Merge pull request #891 from MilosKozak/carbsgen0418

Dana Queue for Carbs Generator
This commit is contained in:
Milos Kozak 2018-04-18 17:00:13 +02:00 committed by GitHub
commit 2af47d4b83
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
29 changed files with 734 additions and 240 deletions

View file

@ -2,7 +2,6 @@ package info.nightscout.androidaps.plugins.Careportal.Dialogs;
import android.app.Activity;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog;
@ -15,7 +14,6 @@ import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
@ -70,7 +68,7 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick
private static String event;
Profile profile;
ProfileStore profileStore;
public ProfileStore profileStore;
String units = Constants.MGDL;
TextView eventTypeText;
@ -109,14 +107,14 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick
public void setOptions(OptionsToShow options, int event) {
this.options = options;
this.event = MainApp.sResources.getString(event);
this.event = MainApp.gs(event);
}
public NewNSTreatmentDialog() {
super();
if (seconds == null) {
seconds = new Double(Math.random() * 59).intValue();
seconds = Double.valueOf(Math.random() * 59).intValue();
}
}
@ -136,7 +134,7 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (options == null) return null;
getDialog().setTitle(getString(options.eventName));
getDialog().setTitle(MainApp.gs(options.eventName));
setStyle(DialogFragment.STYLE_NORMAL, getTheme());
View view = inflater.inflate(R.layout.careportal_newnstreatment_dialog, container, false);
@ -193,32 +191,29 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick
final Double bg = Profile.fromMgdlToUnits(GlucoseStatus.getGlucoseStatusData() != null ? GlucoseStatus.getGlucoseStatusData().glucose : 0d, units);
// temp target
final ArrayList<CharSequence> reasonList = new ArrayList<CharSequence>();
reasonList.add(MainApp.sResources.getString(R.string.manual));
reasonList.add(MainApp.sResources.getString(R.string.eatingsoon));
reasonList.add(MainApp.sResources.getString(R.string.activity));
ArrayAdapter<CharSequence> adapterReason = new ArrayAdapter<CharSequence>(getContext(),
final ArrayList<CharSequence> reasonList = new ArrayList<>();
reasonList.add(MainApp.gs(R.string.manual));
reasonList.add(MainApp.gs(R.string.eatingsoon));
reasonList.add(MainApp.gs(R.string.activity));
ArrayAdapter<CharSequence> adapterReason = new ArrayAdapter<>(getContext(),
R.layout.spinner_centered, reasonList);
reasonSpinner.setAdapter(adapterReason);
reasonSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
double defaultDuration = 0;
double defaultDuration;
double defaultTarget = 0;
if (profile != null) {
defaultTarget = bg.doubleValue();
defaultTarget = bg;
}
boolean erase = false;
if (MainApp.sResources.getString(R.string.eatingsoon).equals(reasonList.get(position))) {
if (MainApp.gs(R.string.eatingsoon).equals(reasonList.get(position))) {
defaultDuration = SP.getDouble(R.string.key_eatingsoon_duration, 0d);
defaultTarget = SP.getDouble(R.string.key_eatingsoon_target, 0d);
;
} else if (MainApp.sResources.getString(R.string.activity).equals(reasonList.get(position))) {
} else if (MainApp.gs(R.string.activity).equals(reasonList.get(position))) {
defaultDuration = SP.getDouble(R.string.key_activity_duration, 0d);
;
defaultTarget = SP.getDouble(R.string.key_activity_target, 0d);
;
} else {
defaultDuration = 0;
erase = true;
@ -267,12 +262,9 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick
editBg.setParams(bg, 0d, 500d, 1d, new DecimalFormat("0"), false, bgTextWatcher);
editTemptarget.setParams(bg, 0d, 500d, 1d, new DecimalFormat("0"), false);
}
sensorRadioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Double bg = Profile.fromMgdlToUnits(GlucoseStatus.getGlucoseStatusData() != null ? GlucoseStatus.getGlucoseStatusData().glucose : 0d, profile.getUnits());
editBg.setValue(bg);
}
sensorRadioButton.setOnCheckedChangeListener((buttonView, isChecked) -> {
Double bg1 = Profile.fromMgdlToUnits(GlucoseStatus.getGlucoseStatusData() != null ? GlucoseStatus.getGlucoseStatusData().glucose : 0d, profile.getUnits());
editBg.setValue(bg1);
});
Integer maxCarbs = MainApp.getConstraintChecker().getMaxCarbsAllowed().value();
@ -408,7 +400,7 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick
tpd.show(context.getFragmentManager(), "Timepickerdialog");
break;
case R.id.ok:
createNSTreatment();
confirmNSTreatmentCreation();
dismiss();
break;
case R.id.cancel:
@ -572,127 +564,126 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick
String buildConfirmText(JSONObject data) {
String ret = "";
try {
if (data.has("eventType")) {
ret += getString(R.string.careportal_newnstreatment_eventtype);
ret += MainApp.gs(R.string.careportal_newnstreatment_eventtype);
ret += ": ";
ret += Translator.translate(data.getString("eventType"));
ret += Translator.translate(JsonHelper.safeGetString(data, "eventType", ""));
ret += "\n";
}
if (data.has("glucose")) {
ret += getString(R.string.treatments_wizard_bg_label);
ret += MainApp.gs(R.string.treatments_wizard_bg_label);
ret += ": ";
ret += data.get("glucose");
ret += JsonHelper.safeGetObject(data, "glucose", "");
ret += " " + units + "\n";
}
if (data.has("glucoseType")) {
ret += getString(R.string.careportal_newnstreatment_glucosetype);
ret += MainApp.gs(R.string.careportal_newnstreatment_glucosetype);
ret += ": ";
ret += Translator.translate(data.getString("glucoseType"));
ret += Translator.translate(JsonHelper.safeGetString(data, "glucoseType", ""));
ret += "\n";
}
if (data.has("carbs")) {
ret += getString(R.string.careportal_newnstreatment_carbs_label);
ret += MainApp.gs(R.string.careportal_newnstreatment_carbs_label);
ret += ": ";
ret += data.get("carbs");
ret += JsonHelper.safeGetObject(data, "carbs", "");
ret += " g\n";
}
if (data.has("insulin")) {
ret += getString(R.string.careportal_newnstreatment_insulin_label);
ret += MainApp.gs(R.string.careportal_newnstreatment_insulin_label);
ret += ": ";
ret += data.get("insulin");
ret += JsonHelper.safeGetObject(data, "insulin", "");
ret += " U\n";
}
if (data.has("duration")) {
ret += getString(R.string.careportal_newnstreatment_duration_label);
ret += MainApp.gs(R.string.careportal_newnstreatment_duration_label);
ret += ": ";
ret += data.get("duration");
ret += JsonHelper.safeGetObject(data, "duration", "");
ret += " min\n";
}
if (data.has("percent")) {
ret += getString(R.string.careportal_newnstreatment_percent_label);
ret += MainApp.gs(R.string.careportal_newnstreatment_percent_label);
ret += ": ";
ret += data.get("percent");
ret += JsonHelper.safeGetObject(data, "percent", "");
ret += " %\n";
}
if (data.has("absolute")) {
ret += getString(R.string.careportal_newnstreatment_absolute_label);
ret += MainApp.gs(R.string.careportal_newnstreatment_absolute_label);
ret += ": ";
ret += data.get("absolute");
ret += JsonHelper.safeGetObject(data, "absolute", "");
ret += " U/h\n";
}
if (data.has("preBolus")) {
ret += getString(R.string.careportal_newnstreatment_carbtime_label);
ret += MainApp.gs(R.string.careportal_newnstreatment_carbtime_label);
ret += ": ";
ret += data.get("preBolus");
ret += JsonHelper.safeGetObject(data, "preBolus", "");
ret += " min\n";
}
if (data.has("notes")) {
ret += getString(R.string.careportal_newnstreatment_notes_label);
ret += MainApp.gs(R.string.careportal_newnstreatment_notes_label);
ret += ": ";
ret += data.get("notes");
ret += JsonHelper.safeGetObject(data, "notes", "");
ret += "\n";
}
if (data.has("profile")) {
ret += getString(R.string.careportal_newnstreatment_profile_label);
ret += MainApp.gs(R.string.careportal_newnstreatment_profile_label);
ret += ": ";
ret += data.get("profile");
ret += JsonHelper.safeGetObject(data, "profile", "");
ret += "\n";
}
if (data.has("percentage")) {
ret += getString(R.string.careportal_newnstreatment_percentage_label);
ret += MainApp.gs(R.string.careportal_newnstreatment_percentage_label);
ret += ": ";
ret += data.get("percentage");
ret += JsonHelper.safeGetObject(data, "percentage", "");
ret += " %\n";
}
if (data.has("timeshift")) {
ret += getString(R.string.careportal_newnstreatment_timeshift_label);
ret += MainApp.gs(R.string.careportal_newnstreatment_timeshift_label);
ret += ": ";
ret += data.get("timeshift");
ret += JsonHelper.safeGetObject(data, "timeshift", "");
ret += " h\n";
}
if (data.has("targetBottom") && data.has("targetTop")) {
ret += getString(R.string.target_range);
ret += MainApp.gs(R.string.target_range);
ret += " ";
ret += data.get("targetBottom");
ret += JsonHelper.safeGetObject(data, "targetBottom", "");
ret += " - ";
ret += data.get("targetTop");
ret += JsonHelper.safeGetObject(data, "targetTop", "");
ret += "\n";
}
if (data.has("created_at")) {
ret += getString(R.string.careportal_newnstreatment_eventtime_label);
ret += MainApp.gs(R.string.careportal_newnstreatment_eventtime_label);
ret += ": ";
ret += eventTime.toLocaleString();
ret += "\n";
}
if (data.has("enteredBy")) {
ret += getString(R.string.careportal_newnstreatment_enteredby_title);
ret += MainApp.gs(R.string.careportal_newnstreatment_enteredby_title);
ret += ": ";
ret += data.get("enteredBy");
ret += JsonHelper.safeGetObject(data, "enteredBy", "");
ret += "\n";
}
} catch (JSONException e) {
log.error("Unhandled exception", e);
}
return ret;
}
void createNSTreatment() {
void confirmNSTreatmentCreation() {
if (context != null) {
final JSONObject data = gatherData();
String confirmText = buildConfirmText(data);
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle(getContext().getString(R.string.confirmation));
final String confirmText = buildConfirmText(data);
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle(MainApp.gs(R.string.confirmation));
builder.setMessage(confirmText);
builder.setPositiveButton(getContext().getString(R.string.ok), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
builder.setPositiveButton(MainApp.gs(R.string.ok), (dialog, id) -> createNSTreatment(data));
builder.setNegativeButton(MainApp.gs(R.string.cancel), null);
builder.show();
}
}
public void createNSTreatment(JSONObject data) {
if (options.executeProfileSwitch) {
if (data.has("profile")) {
try {
doProfileSwitch(profileStore, data.getString("profile"), data.getInt("duration"), data.getInt("percentage"), data.getInt("timeshift"));
} catch (JSONException e) {
log.error("Unhandled exception", e);
}
doProfileSwitch(profileStore, JsonHelper.safeGetString(data, "profile"), JsonHelper.safeGetInt(data, "duration"), JsonHelper.safeGetInt(data, "percentage"), JsonHelper.safeGetInt(data, "timeshift"));
}
} else if (options.executeTempTarget) {
final int duration = JsonHelper.safeGetInt(data, "duration");
@ -719,10 +710,6 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick
FabricPrivacy.getInstance().logCustom(new CustomEvent("NSTreatment"));
}
}
});
builder.setNegativeButton(getContext().getString(R.string.cancel), null);
builder.show();
}
public static void doProfileSwitch(final ProfileStore profileStore, final String profileName, final int duration, final int percentage, final int timeshift) {
ProfileSwitch profileSwitch = new ProfileSwitch();

View file

@ -85,37 +85,52 @@ public class ObjectivesFragment extends SubscriberFragment {
}
});
Long now = System.currentTimeMillis();
if (position > 0 && objectives.get(position - 1).accomplished.getTime() == 0) {
long prevObjectiveAccomplishedTime = position > 0 ?
objectives.get(position - 1).accomplished.getTime() : -1;
int phase = modifyVisibility(position, prevObjectiveAccomplishedTime,
o.started.getTime(), o.durationInDays,
o.accomplished.getTime(), requirementsMet.done, enableFake.isChecked());
switch (phase) {
case 0:
// Phase 0: previous not completed
holder.startedLayout.setVisibility(View.GONE);
holder.durationLayout.setVisibility(View.GONE);
holder.progressLayout.setVisibility(View.GONE);
holder.verifyLayout.setVisibility(View.GONE);
} else if (o.started.getTime() == 0) {
break;
case 1:
// Phase 1: not started
holder.durationLayout.setVisibility(View.GONE);
holder.progressLayout.setVisibility(View.GONE);
holder.verifyLayout.setVisibility(View.GONE);
holder.started.setVisibility(View.GONE);
} else if (o.started.getTime() > 0 && !enableFake.isChecked() && o.accomplished.getTime() == 0 && !(o.started.getTime() + o.durationInDays * 24 * 60 * 60 * 1000 < now && requirementsMet.done)) {
break;
case 2:
// Phase 2: started, waiting for duration and met requirements
holder.startButton.setEnabled(false);
holder.verifyLayout.setVisibility(View.GONE);
} else if (o.accomplished.getTime() == 0) {
break;
case 3:
// Phase 3: started, after duration, requirements met
holder.startButton.setEnabled(false);
holder.accomplished.setVisibility(View.INVISIBLE);
} else {
break;
case 4:
// Phase 4: verified
holder.gateLayout.setVisibility(View.GONE);
holder.startedLayout.setVisibility(View.GONE);
holder.durationLayout.setVisibility(View.GONE);
holder.progressLayout.setVisibility(View.GONE);
holder.verifyButton.setVisibility(View.INVISIBLE);
break;
default:
// should not happen
}
}
@Override
public int getItemCount() {
return objectives.size();
@ -164,6 +179,40 @@ public class ObjectivesFragment extends SubscriberFragment {
}
}
/**
* returns an int, which represents the phase the current objective is at.
*
* this is mainly used for unit-testing the conditions
*
* @param currentPosition
* @param prevObjectiveAccomplishedTime
* @param objectiveStartedTime
* @param durationInDays
* @param objectiveAccomplishedTime
* @param requirementsMet
* @return
*/
public int modifyVisibility(int currentPosition,
long prevObjectiveAccomplishedTime,
long objectiveStartedTime, int durationInDays,
long objectiveAccomplishedTime, boolean requirementsMet,
boolean enableFakeValue) {
Long now = System.currentTimeMillis();
if (currentPosition > 0 && prevObjectiveAccomplishedTime == 0) {
return 0;
} else if (objectiveStartedTime == 0) {
return 1;
} else if (objectiveStartedTime > 0 && !enableFakeValue
&& objectiveAccomplishedTime == 0
&& !(objectiveStartedTime + durationInDays * 24 * 60 * 60 * 1000 >= now && requirementsMet)) {
return 2;
} else if (objectiveAccomplishedTime == 0) {
return 3;
} else {
return 4;
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
@ -205,6 +254,7 @@ public class ObjectivesFragment extends SubscriberFragment {
ObjectivesPlugin.objectives.get(3).gate = MainApp.sResources.getString(R.string.objectives_3_gate);
ObjectivesPlugin.objectives.get(4).gate = MainApp.sResources.getString(R.string.objectives_4_gate);
ObjectivesPlugin.objectives.get(5).gate = MainApp.sResources.getString(R.string.objectives_5_gate);
updateGUI();
return view;

View file

@ -1,7 +1,5 @@
package info.nightscout.androidaps.plugins.ProfileLocal;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import org.json.JSONArray;
@ -70,18 +68,15 @@ public class LocalProfilePlugin extends PluginBase implements ProfileInterface {
}
public synchronized void storeSettings() {
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext());
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean(LOCAL_PROFILE + "mmol", mmol);
editor.putBoolean(LOCAL_PROFILE + "mgdl", mgdl);
editor.putString(LOCAL_PROFILE + "dia", dia.toString());
editor.putString(LOCAL_PROFILE + "ic", ic.toString());
editor.putString(LOCAL_PROFILE + "isf", isf.toString());
editor.putString(LOCAL_PROFILE + "basal", basal.toString());
editor.putString(LOCAL_PROFILE + "targetlow", targetLow.toString());
editor.putString(LOCAL_PROFILE + "targethigh", targetHigh.toString());
SP.putBoolean(LOCAL_PROFILE + "mmol", mmol);
SP.putBoolean(LOCAL_PROFILE + "mgdl", mgdl);
SP.putString(LOCAL_PROFILE + "dia", dia.toString());
SP.putString(LOCAL_PROFILE + "ic", ic.toString());
SP.putString(LOCAL_PROFILE + "isf", isf.toString());
SP.putString(LOCAL_PROFILE + "basal", basal.toString());
SP.putString(LOCAL_PROFILE + "targetlow", targetLow.toString());
SP.putString(LOCAL_PROFILE + "targethigh", targetHigh.toString());
editor.apply();
createAndStoreConvertedProfile();
edited = false;
if (Config.logPrefsChange)

View file

@ -166,6 +166,10 @@ public class CommandQueue {
public boolean bolus(DetailedBolusInfo detailedBolusInfo, Callback callback) {
Command.CommandType type = detailedBolusInfo.isSMB ? Command.CommandType.SMB_BOLUS : Command.CommandType.BOLUS;
if(type.equals(Command.CommandType.BOLUS) && detailedBolusInfo.carbs > 0 && detailedBolusInfo.insulin == 0){
type = Command.CommandType.CARBS_ONLY_TREATMENT;
//Carbs only can be added in parallel as they can be "in the future".
} else {
if (isRunning(type)) {
if (callback != null)
callback.result(executingNowError()).run();
@ -174,6 +178,7 @@ public class CommandQueue {
// remove all unfinished boluses
removeAll(type);
}
// apply constraints
detailedBolusInfo.insulin = MainApp.getConstraintChecker().applyBolusConstraints(new Constraint<>(detailedBolusInfo.insulin)).value();
@ -183,13 +188,15 @@ public class CommandQueue {
if (detailedBolusInfo.isSMB) {
add(new CommandSMBBolus(detailedBolusInfo, callback));
} else {
add(new CommandBolus(detailedBolusInfo, callback));
add(new CommandBolus(detailedBolusInfo, callback, type));
if(type.equals(Command.CommandType.BOLUS)) {
// Bring up bolus progress dialog (start here, so the dialog is shown when the bolus is requested,
// not when the Bolus command is starting. The command closes the dialog upon completion).
showBolusProgressDialog(detailedBolusInfo.insulin, detailedBolusInfo.context);
// Notify Wear about upcoming bolus
MainApp.bus().post(new EventBolusRequested(detailedBolusInfo.insulin));
}
}
notifyAboutNewCommand();

View file

@ -12,6 +12,7 @@ public abstract class Command {
public enum CommandType {
BOLUS,
SMB_BOLUS,
CARBS_ONLY_TREATMENT,
TEMPBASAL,
EXTENDEDBOLUS,
BASALPROFILE,

View file

@ -16,8 +16,8 @@ import info.nightscout.utils.DecimalFormatter;
public class CommandBolus extends Command {
DetailedBolusInfo detailedBolusInfo;
public CommandBolus(DetailedBolusInfo detailedBolusInfo, Callback callback) {
commandType = CommandType.BOLUS;
public CommandBolus(DetailedBolusInfo detailedBolusInfo, Callback callback, CommandType type) {
commandType = type;
this.detailedBolusInfo = detailedBolusInfo;
this.callback = callback;
}

View file

@ -1,5 +1,7 @@
package info.nightscout.utils;
import android.support.annotation.Nullable;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
@ -17,6 +19,20 @@ public class JsonHelper {
private JsonHelper() {};
public static Object safeGetObject(JSONObject json, String fieldName, Object defaultValue) {
Object result = defaultValue;
if (json.has(fieldName)) {
try {
result = json.get(fieldName);
} catch (JSONException ignored) {
}
}
return result;
}
@Nullable
public static String safeGetString(JSONObject json, String fieldName) {
String result = null;

View file

@ -24,7 +24,7 @@ public class SP {
return sharedPreferences.getString(key, defaultValue);
}
static public boolean getBoolean(int resourceID, boolean defaultValue) {
static public boolean getBoolean(int resourceID, Boolean defaultValue) {
try {
return sharedPreferences.getBoolean(MainApp.sResources.getString(resourceID), defaultValue);
} catch (Exception e) {
@ -32,7 +32,7 @@ public class SP {
}
}
static public boolean getBoolean(String key, boolean defaultValue) {
static public boolean getBoolean(String key, Boolean defaultValue) {
try {
return sharedPreferences.getBoolean(key, defaultValue);
} catch (Exception e) {

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 963 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 912 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 881 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 692 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 619 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

View file

@ -151,7 +151,7 @@
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:text="@string/activate_profile"
android:textColor="@color/colorProfileSwitchButton" />
android:drawableLeft="@drawable/icon_local_activate" />
<LinearLayout
android:layout_width="wrap_content"
@ -172,7 +172,7 @@
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:text="@string/reset"
android:textColor="@color/colorProfileSwitchButton" />
android:drawableLeft="@drawable/icon_local_reset" />
<Button
android:id="@+id/localprofile_save"
@ -188,7 +188,7 @@
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:text="@string/save"
android:textColor="@color/colorProfileSwitchButton" />
android:drawableLeft="@drawable/icon_local_save" />
</LinearLayout>
</LinearLayout>
</ScrollView>

View file

@ -1,11 +1,13 @@
package info;
import android.content.Context;
import android.content.Intent;
import com.squareup.otto.Bus;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.Assert;
import org.powermock.api.mockito.PowerMockito;
import java.util.Locale;
@ -15,8 +17,10 @@ import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.ConstraintChecker;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.data.ProfileStore;
import info.nightscout.androidaps.db.DatabaseHelper;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.Treatments.TreatmentService;
import info.nightscout.androidaps.queue.CommandQueue;
import info.nightscout.utils.SP;
@ -33,6 +37,10 @@ import static org.mockito.Mockito.when;
public class AAPSMocker {
private static String validProfile = "{\"dia\":\"3\",\"carbratio\":[{\"time\":\"00:00\",\"value\":\"30\"}],\"carbs_hr\":\"20\",\"delay\":\"20\",\"sens\":[{\"time\":\"00:00\",\"value\":\"100\"},{\"time\":\"2:00\",\"value\":\"110\"}],\"timezone\":\"UTC\",\"basal\":[{\"time\":\"00:00\",\"value\":\"1\"}],\"target_low\":[{\"time\":\"00:00\",\"value\":\"4\"}],\"target_high\":[{\"time\":\"00:00\",\"value\":\"5\"}],\"startDate\":\"1970-01-01T00:00:00.000Z\",\"units\":\"mmol\"}";
private static Profile profile;
private static ProfileStore profileStore;
public static final String TESTPROFILENAME = "someProfile";
public static Intent intentSent = null;
public static void mockStrings() {
Locale.setDefault(new Locale("en", "US"));
@ -81,6 +89,7 @@ public class AAPSMocker {
when(MainApp.gs(R.string.basalprofilenotaligned)).thenReturn("Basal values not aligned to hours: %s");
when(MainApp.gs(R.string.minago)).thenReturn("%d min ago");
when(MainApp.gs(R.string.hoursago)).thenReturn("%.1fh ago");
when(MainApp.gs(R.string.careportal_profileswitch)).thenReturn("Profile Switch");
}
public static MainApp mockMainApp() {
@ -128,6 +137,11 @@ public class AAPSMocker {
when(ConfigBuilderPlugin.getCommandQueue()).thenReturn(queue);
}
public static void mockTreatmentService() throws Exception {
TreatmentService treatmentService = PowerMockito.mock(TreatmentService.class);
PowerMockito.whenNew(TreatmentService.class).withNoArguments().thenReturn(treatmentService);
}
public static Profile getValidProfile() {
try {
if (profile == null)
@ -137,6 +151,24 @@ public class AAPSMocker {
return profile;
}
public static ProfileStore getValidProfileStore() {
try {
if (profileStore == null) {
JSONObject json = new JSONObject();
JSONObject store = new JSONObject();
JSONObject profile = new JSONObject(validProfile);
json.put("defaultProfile", TESTPROFILENAME);
json.put("store", store);
store.put(TESTPROFILENAME, profile);
profileStore = new ProfileStore(json);
}
} catch (JSONException ignored) {
Assert.fail("getValidProfileStore() failed");
}
return profileStore;
}
private static MockedBus bus = new MockedBus();
public static void prepareMockedBus() {

View file

@ -0,0 +1,223 @@
package info;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.SparseArray;
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyBoolean;
import static org.mockito.Matchers.anyByte;
import static org.mockito.Matchers.anyChar;
import static org.mockito.Matchers.anyDouble;
import static org.mockito.Matchers.anyFloat;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.anyLong;
import static org.mockito.Matchers.anyShort;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.when;
public final class BundleMock {
public static Bundle mock() {
return mock(new HashMap<String, Object>());
}
public static Bundle mock(final HashMap<String, Object> map) {
Answer unsupported = new Answer() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
throw new UnsupportedOperationException();
}
};
Answer put = new Answer() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
map.put((String)invocation.getArguments()[0], invocation.getArguments()[1]);
return null;
}
};
Answer<Object> get = new Answer<Object>() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
return map.get(invocation.getArguments()[0]);
}
};
Answer<Object> getOrDefault = new Answer<Object>() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
Object key = invocation.getArguments()[0];
return map.containsKey(key) ? map.get(key) : invocation.getArguments()[1];
}
};
Bundle bundle = Mockito.mock(Bundle.class);
doAnswer(new Answer() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
return map.size();
}
}).when(bundle).size();
doAnswer(new Answer() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
return map.isEmpty();
}
}).when(bundle).isEmpty();
doAnswer(new Answer() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
map.clear();
return null;
}
}).when(bundle).clear();
doAnswer(new Answer() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
return map.containsKey(invocation.getArguments()[0]);
}
}).when(bundle).containsKey(anyString());
doAnswer(new Answer() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
return map.get(invocation.getArguments()[0]);
}
}).when(bundle).get(anyString());
doAnswer(new Answer() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
map.remove(invocation.getArguments()[0]);
return null;
}
}).when(bundle).remove(anyString());
doAnswer(new Answer() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
return map.keySet();
}
}).when(bundle).keySet();
doAnswer(new Answer() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
return BundleMock.class.getSimpleName() + "{map=" + map.toString() + "}";
}
}).when(bundle).toString();
doAnswer(put).when(bundle).putBoolean(anyString(), anyBoolean());
when(bundle.getBoolean(anyString())).thenAnswer(get);
when(bundle.getBoolean(anyString(), anyBoolean())).thenAnswer(getOrDefault);
doAnswer(put).when(bundle).putByte(anyString(), anyByte());
when(bundle.getByte(anyString())).thenAnswer(get);
when(bundle.getByte(anyString(), anyByte())).thenAnswer(getOrDefault);
doAnswer(put).when(bundle).putChar(anyString(), anyChar());
when(bundle.getChar(anyString())).thenAnswer(get);
when(bundle.getChar(anyString(), anyChar())).thenAnswer(getOrDefault);
doAnswer(put).when(bundle).putInt(anyString(), anyShort());
when(bundle.getShort(anyString())).thenAnswer(get);
when(bundle.getShort(anyString(), anyShort())).thenAnswer(getOrDefault);
doAnswer(put).when(bundle).putLong(anyString(), anyLong());
when(bundle.getLong(anyString())).thenAnswer(get);
when(bundle.getLong(anyString(), anyLong())).thenAnswer(getOrDefault);
doAnswer(put).when(bundle).putFloat(anyString(), anyFloat());
when(bundle.getFloat(anyString())).thenAnswer(get);
when(bundle.getFloat(anyString(), anyFloat())).thenAnswer(getOrDefault);
doAnswer(put).when(bundle).putDouble(anyString(), anyDouble());
when(bundle.getDouble(anyString())).thenAnswer(get);
when(bundle.getDouble(anyString(), anyDouble())).thenAnswer(getOrDefault);
doAnswer(put).when(bundle).putString(anyString(), anyString());
when(bundle.getString(anyString())).thenAnswer(get);
when(bundle.getString(anyString(), anyString())).thenAnswer(getOrDefault);
doAnswer(put).when(bundle).putBooleanArray(anyString(), any(boolean[].class));
when(bundle.getBooleanArray(anyString())).thenAnswer(get);
doAnswer(put).when(bundle).putLongArray(anyString(), any(long[].class));
when(bundle.getLongArray(anyString())).thenAnswer(get);
doAnswer(put).when(bundle).putDoubleArray(anyString(), any(double[].class));
when(bundle.getDoubleArray(anyString())).thenAnswer(get);
doAnswer(put).when(bundle).putIntArray(anyString(), any(int[].class));
when(bundle.getIntArray(anyString())).thenAnswer(get);
doAnswer(put).when(bundle).putInt(anyString(), anyInt());
when(bundle.getInt(anyString())).thenAnswer(get);
when(bundle.getInt(anyString(), anyInt())).thenAnswer(getOrDefault);
doAnswer(unsupported).when(bundle).putAll(any(Bundle.class));
when(bundle.hasFileDescriptors()).thenAnswer(unsupported);
doAnswer(put).when(bundle).putShort(anyString(), anyShort());
when(bundle.getShort(anyString())).thenAnswer(get);
when(bundle.getShort(anyString(), anyShort())).thenAnswer(getOrDefault);
doAnswer(put).when(bundle).putFloat(anyString(), anyFloat());
when(bundle.getFloat(anyString())).thenAnswer(get);
when(bundle.getFloat(anyString(), anyFloat())).thenAnswer(getOrDefault);
doAnswer(put).when(bundle).putCharSequence(anyString(), any(CharSequence.class));
when(bundle.getCharSequence(anyString())).thenAnswer(get);
when(bundle.getCharSequence(anyString(), any(CharSequence.class))).thenAnswer(getOrDefault);
doAnswer(put).when(bundle).putBundle(anyString(), any(Bundle.class));
when(bundle.getBundle(anyString())).thenAnswer(get);
doAnswer(put).when(bundle).putParcelable(anyString(), any(Parcelable.class));
when(bundle.getParcelable(anyString())).thenAnswer(get);
doAnswer(put).when(bundle).putParcelableArray(anyString(), any(Parcelable[].class));
when(bundle.getParcelableArray(anyString())).thenAnswer(get);
doAnswer(put).when(bundle).putParcelableArrayList(anyString(), any(ArrayList.class));
when(bundle.getParcelableArrayList(anyString())).thenAnswer(get);
doAnswer(put).when(bundle).putSparseParcelableArray(anyString(), any(SparseArray.class));
when(bundle.getSparseParcelableArray(anyString())).thenAnswer(get);
doAnswer(put).when(bundle).putSerializable(anyString(), any(Serializable.class));
when(bundle.getSerializable(anyString())).thenAnswer(get);
doAnswer(put).when(bundle).putIntegerArrayList(anyString(), any(ArrayList.class));
when(bundle.getIntegerArrayList(anyString())).thenAnswer(get);
doAnswer(put).when(bundle).putStringArrayList(anyString(), any(ArrayList.class));
when(bundle.getStringArrayList(anyString())).thenAnswer(get);
doAnswer(put).when(bundle).putCharSequenceArrayList(anyString(), any(ArrayList.class));
when(bundle.getCharSequenceArrayList(anyString())).thenAnswer(get);
doAnswer(put).when(bundle).putCharArray(anyString(), any(char[].class));
when(bundle.getCharArray(anyString())).thenAnswer(get);
doAnswer(put).when(bundle).putByteArray(anyString(), any(byte[].class));
when(bundle.getByteArray(anyString())).thenAnswer(get);
doAnswer(put).when(bundle).putShortArray(anyString(), any(short[].class));
when(bundle.getShortArray(anyString())).thenAnswer(get);
doAnswer(put).when(bundle).putFloatArray(anyString(), any(float[].class));
when(bundle.getFloatArray(anyString())).thenAnswer(get);
doAnswer(put).when(bundle).putCharSequenceArray(anyString(), any(CharSequence[].class));
when(bundle.getCharSequenceArray(anyString())).thenAnswer(get);
return bundle;
}
}

View file

@ -2,17 +2,12 @@ package info;
import org.junit.Assert;
import org.mockito.ArgumentMatchers;
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.powermock.api.mockito.PowerMockito;
import java.util.HashMap;
import info.nightscout.utils.SP;
import static org.powermock.api.mockito.PowerMockito.when;
public class SPMocker {
static HashMap<String, Object> data = new HashMap<>();
@ -24,20 +19,48 @@ public class SPMocker {
PowerMockito.when(SP.class, "putString", ArgumentMatchers.anyString(), ArgumentMatchers.anyString()).then(invocation -> {
String key = invocation.getArgument(0);
String value = invocation.getArgument(1);
data.put(key,value);
data.put(key, value);
System.out.print("putString " + key + " " + value + "\n");
return null;
});
PowerMockito.when(SP.class, "getString", ArgumentMatchers.anyString(), ArgumentMatchers.anyString()).then(invocation -> {
PowerMockito.when(SP.class, "getString", ArgumentMatchers.anyString(), ArgumentMatchers.any()).then(invocation -> {
String key = invocation.getArgument(0);
String def = invocation.getArgument(1);
String value = (String) data.get(key);
if (value == null) value = def;
System.out.print("getString " + key + " " + value + "\n");
return value;
});
PowerMockito.when(SP.class, "putBoolean", ArgumentMatchers.anyString(), ArgumentMatchers.anyBoolean()).then(invocation -> {
String key = invocation.getArgument(0);
Boolean value = invocation.getArgument(1);
data.put(key, value);
System.out.print("putBoolean " + key + " " + value + "\n");
return null;
});
PowerMockito.when(SP.class, "getBoolean", ArgumentMatchers.anyString(), ArgumentMatchers.any()).then(invocation -> {
String key = invocation.getArgument(0);
Boolean def = invocation.getArgument(1);
Boolean value = (Boolean) data.get(key);
if (value == null) value = def;
System.out.print("getBoolean " + key + " " + value + "\n");
return value;
});
PowerMockito.when(SP.class, "getDouble", ArgumentMatchers.anyString(), ArgumentMatchers.any()).then(invocation -> {
String key = invocation.getArgument(0);
Double def = invocation.getArgument(1);
Double value = (Double) data.get(key);
if (value == null) value = def;
System.out.print("getDouble " + key + " " + value + "\n");
return value;
});
} catch (Exception e) {
Assert.fail("Unable to mock the construction of "
+ "the SP object");
Assert.fail("Unable to mock the construction of the SP object: " + e.getMessage());
}
}

View file

@ -0,0 +1,89 @@
package info.nightscout.androidaps.plugins.Careportal.Dialogs;
import android.content.Context;
import org.json.JSONObject;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentMatchers;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import info.AAPSMocker;
import info.SPMocker;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.db.DatabaseHelper;
import info.nightscout.androidaps.db.ProfileSwitch;
import info.nightscout.androidaps.plugins.Careportal.Dialogs.NewNSTreatmentDialog;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.ProfileNS.NSProfilePlugin;
import info.nightscout.androidaps.plugins.Treatments.TreatmentService;
import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin;
import info.nightscout.utils.NSUpload;
import info.nightscout.utils.SP;
import static info.nightscout.androidaps.plugins.Careportal.CareportalFragment.PROFILESWITCH;
import static org.powermock.api.mockito.PowerMockito.doAnswer;
import static org.powermock.api.mockito.PowerMockito.when;
@RunWith(PowerMockRunner.class)
@PrepareForTest({SP.class, MainApp.class, ConfigBuilderPlugin.class, Context.class, NSUpload.class, TreatmentsPlugin.class, TreatmentService.class, DatabaseHelper.class})
public class NewNSTreatmentDialogTest {
NewNSTreatmentDialog dialog;
ProfileSwitch profileSwitchUpload = null;
@Test
public void createNSTreatmentTest() throws Exception {
// Test profile creation
doAnswer(invocation -> {
ProfileSwitch ps = invocation.getArgument(0);
profileSwitchUpload = ps;
return null;
}).when(NSUpload.class, "uploadProfileSwitch", ArgumentMatchers.any());
PROFILESWITCH.executeProfileSwitch = true;
dialog.setOptions(PROFILESWITCH, R.string.careportal_profileswitch);
dialog.profileStore = AAPSMocker.getValidProfileStore();
JSONObject data = new JSONObject();
data.put("profile", AAPSMocker.TESTPROFILENAME);
data.put("duration", 0);
data.put("percentage", 110);
data.put("timeshift", 0);
dialog.createNSTreatment(data);
// Profile should be sent to NS
Assert.assertEquals(AAPSMocker.TESTPROFILENAME, profileSwitchUpload.profileName);
}
@Test
public void doProfileSwitch() {
}
@Test
public void doProfileSwitch1() {
}
@Before
public void prepareMock() throws Exception {
AAPSMocker.mockMainApp();
SPMocker.prepareMock();
SP.putString("profile", AAPSMocker.getValidProfileStore().getData().toString());
AAPSMocker.mockConfigBuilder();
AAPSMocker.mockApplicationContext();
AAPSMocker.mockStrings();
PowerMockito.mockStatic(NSUpload.class);
AAPSMocker.mockTreatmentService();
AAPSMocker.mockBus();
AAPSMocker.mockDatabaseHelper();
NSProfilePlugin profilePlugin = NSProfilePlugin.getPlugin();
when(MainApp.getConfigBuilder().getActiveProfileInterface())
.thenReturn(profilePlugin);
dialog = new NewNSTreatmentDialog();
}
}

View file

@ -0,0 +1,71 @@
package info.nightscout.androidaps.plugins.ConstraintsObjectives;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class ObjectivesFragmentTest {
@Test
public void testModifyVisibility() {
ObjectivesFragment fragment = new ObjectivesFragment();
int currentPosition = 1;
long prevObjectiveAccomplishedTime = 0;
long objectiveStartedTime = 0;
int durationInDays = 0;
long objectiveAccomplishedTime = 0;
boolean requirementsMet = false;
boolean enableFakeValue = false;
// previous objective is not accomplished yet
assertEquals(0, fragment.modifyVisibility(currentPosition, prevObjectiveAccomplishedTime,
objectiveStartedTime, durationInDays, objectiveAccomplishedTime, requirementsMet, enableFakeValue));
// not started yet
prevObjectiveAccomplishedTime = 4711;
assertEquals(1, fragment.modifyVisibility(currentPosition, prevObjectiveAccomplishedTime,
objectiveStartedTime, durationInDays, objectiveAccomplishedTime, requirementsMet, enableFakeValue));
// started
// time calculation is true, requirements met is false
objectiveStartedTime = Long.MAX_VALUE;
durationInDays = 0;
assertEquals(2, fragment.modifyVisibility(currentPosition, prevObjectiveAccomplishedTime,
objectiveStartedTime, durationInDays, objectiveAccomplishedTime, requirementsMet, enableFakeValue));
// started
// time calculation is false, requirements met is false
objectiveStartedTime = 10;
durationInDays = 0;
requirementsMet = true;
assertEquals(2, fragment.modifyVisibility(currentPosition, prevObjectiveAccomplishedTime,
objectiveStartedTime, durationInDays, objectiveAccomplishedTime, requirementsMet, enableFakeValue));
// started
// time calculation is false, requirements met is true
objectiveStartedTime = 10;
durationInDays = 999999;
requirementsMet = true;
assertEquals(2, fragment.modifyVisibility(currentPosition, prevObjectiveAccomplishedTime,
objectiveStartedTime, durationInDays, objectiveAccomplishedTime, requirementsMet, enableFakeValue));
// started, after duration, requirements met --> show verify
objectiveStartedTime = Long.MAX_VALUE;
durationInDays = 0;
requirementsMet = true;
assertEquals(3, fragment.modifyVisibility(currentPosition, prevObjectiveAccomplishedTime,
objectiveStartedTime, durationInDays, objectiveAccomplishedTime, requirementsMet, enableFakeValue));
// finished
objectiveStartedTime = Long.MAX_VALUE;
durationInDays = 0;
requirementsMet = true;
objectiveAccomplishedTime = Long.MAX_VALUE;
assertEquals(4, fragment.modifyVisibility(currentPosition, prevObjectiveAccomplishedTime,
objectiveStartedTime, durationInDays, objectiveAccomplishedTime, requirementsMet, enableFakeValue));
}
}