From 7e9402b9395cc071bfdb2076149670dab08e6472 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Tue, 17 Mar 2020 22:56:14 +0100 Subject: [PATCH] remove ProfileFunctions dependency --- .../nightscout/androidaps/db/BgReading.java | 4 + .../androidaps/db/CareportalEvent.java | 5 +- .../androidaps/db/TemporaryBasal.java | 14 +- .../dependencyInjection/AppModule.kt | 5 +- .../dependencyInjection/FragmentsModule.kt | 16 +- .../androidaps/dialogs/FillDialog.kt | 10 +- .../androidaps/dialogs/InsulinDialog.kt | 10 +- .../androidaps/dialogs/TreatmentDialog.kt | 4 +- .../androidaps/dialogs/WizardDialog.kt | 2 +- .../plugins/aps/loop/APSResult.java | 12 +- .../configBuilder/ConfigBuilderPlugin.java | 14 +- .../ProfileFunctionImplementation.kt | 71 ++++- .../configBuilder/ProfileFunctions.java | 148 --------- .../plugins/general/nsclient/NSUpload.java | 19 +- .../general/overview/OverviewFragment.java | 4 +- .../general/overview/graphData/GraphData.java | 14 +- .../plugins/pump/combo/ComboFragment.java | 2 +- .../plugins/pump/danaR/DanaRFragment.kt | 2 +- .../pump/medtronic/MedtronicFragment.kt | 2 +- .../plugins/treatments/Treatment.java | 2 +- .../fragments/TreatmentsCareportalFragment.kt | 2 +- .../TreatmentsExtendedBolusesFragment.java | 10 +- .../TreatmentsTemporaryBasalsFragment.java | 6 +- .../elements/SWEditNumberWithUnits.java | 6 +- .../androidaps/utils/ActivityMonitor.kt | 2 +- .../nightscout/androidaps/utils/DateUtil.java | 39 +-- .../androidaps/utils/DecimalFormatter.java | 10 +- .../androidaps/utils/XdripCalibrations.java | 5 +- .../utils/extensions/DoubleToSignedString.kt | 5 +- app/src/test/java/info/AAPSMocker.java | 287 ------------------ app/src/test/java/info/BundleMock.java | 223 -------------- app/src/test/java/info/SPMocker.java | 68 ----- app/src/test/java/info/TestBase.kt | 1 + .../nightscout/androidaps/db/BgReadingTest.kt | 44 +-- .../plugins/aps/loop/APSResultTest.kt | 6 +- .../configBuilder/ConfigBuilderPluginTest.kt | 12 +- .../actions/ActionStartTempTargetTest.kt | 4 +- .../actions/ActionStopTempTargetTest.kt | 2 - .../automation/elements/InputBgTest.kt | 3 - .../triggers/TriggerAutosensValueTest.kt | 3 +- .../triggers/TriggerBolusAgoTest.kt | 3 +- .../triggers/TriggerLocationTest.kt | 4 +- .../triggers/TriggerProfilePercentTest.kt | 3 +- .../triggers/TriggerPumpLastConnectionTest.kt | 3 +- .../triggers/TriggerTempTargetTest.kt | 3 +- .../SmsCommunicatorPluginTest.kt | 7 +- ...DanaRS_Packet_APS_Set_Event_HistoryTest.kt | 9 - .../medtronic/data/dto/BasalProfileUTest.java | 10 +- .../androidaps/utils/DateUtilTest.java | 97 ------ .../androidaps/utils/DateUtilTest.kt | 77 +++++ .../utils/DecimalFormatterTest.java | 12 - .../androidaps/utils/MidnightTimeTest.java | 9 +- 52 files changed, 298 insertions(+), 1037 deletions(-) delete mode 100644 app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ProfileFunctions.java delete mode 100644 app/src/test/java/info/AAPSMocker.java delete mode 100644 app/src/test/java/info/BundleMock.java delete mode 100644 app/src/test/java/info/SPMocker.java delete mode 100644 app/src/test/java/info/nightscout/androidaps/utils/DateUtilTest.java create mode 100644 app/src/test/java/info/nightscout/androidaps/utils/DateUtilTest.kt diff --git a/app/src/main/java/info/nightscout/androidaps/db/BgReading.java b/app/src/main/java/info/nightscout/androidaps/db/BgReading.java index 24b649df6d..b15d92a851 100644 --- a/app/src/main/java/info/nightscout/androidaps/db/BgReading.java +++ b/app/src/main/java/info/nightscout/androidaps/db/BgReading.java @@ -62,6 +62,10 @@ public class BgReading implements DataPointWithLabelInterface { MainApp.instance().androidInjector().inject(this); } + public BgReading(HasAndroidInjector injector) { + injector.androidInjector().inject(this); + } + public BgReading(NSSgv sgv) { date = sgv.getMills(); value = sgv.getMgdl(); diff --git a/app/src/main/java/info/nightscout/androidaps/db/CareportalEvent.java b/app/src/main/java/info/nightscout/androidaps/db/CareportalEvent.java index b7c8091dcd..9912644797 100644 --- a/app/src/main/java/info/nightscout/androidaps/db/CareportalEvent.java +++ b/app/src/main/java/info/nightscout/androidaps/db/CareportalEvent.java @@ -9,7 +9,6 @@ import org.apache.commons.lang3.StringUtils; import org.json.JSONException; import org.json.JSONObject; import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.Collections; @@ -26,7 +25,7 @@ import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.interfaces.Interval; import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; +import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.general.nsclient.data.NSMbg; import info.nightscout.androidaps.plugins.general.overview.OverviewFragment; import info.nightscout.androidaps.plugins.general.overview.graphExtensions.DataPointWithLabelInterface; @@ -168,7 +167,7 @@ public class CareportalEvent implements DataPointWithLabelInterface, Interval { @Override public double getY() { - String units = ProfileFunctions.getSystemUnits(); + String units = ConfigBuilderPlugin.getPlugin().getProfileFunction().getUnits(); if (eventType.equals(MBG)) { double mbg = 0d; try { diff --git a/app/src/main/java/info/nightscout/androidaps/db/TemporaryBasal.java b/app/src/main/java/info/nightscout/androidaps/db/TemporaryBasal.java index 2845fc1145..84aecfb5e5 100644 --- a/app/src/main/java/info/nightscout/androidaps/db/TemporaryBasal.java +++ b/app/src/main/java/info/nightscout/androidaps/db/TemporaryBasal.java @@ -15,8 +15,8 @@ import info.nightscout.androidaps.interfaces.InsulinInterface; import info.nightscout.androidaps.interfaces.Interval; import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; +import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.configBuilder.PluginStore; -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensResult; import info.nightscout.androidaps.plugins.treatments.Treatment; import info.nightscout.androidaps.utils.DateUtil; @@ -95,7 +95,7 @@ public class TemporaryBasal implements Interval, DbObjectBase { } public TemporaryBasal(ExtendedBolus extendedBolus) { - double basal = ProfileFunctions.getInstance().getProfile(extendedBolus.date).getBasal(extendedBolus.date); + double basal = ConfigBuilderPlugin.getPlugin().getProfileFunction().getProfile(extendedBolus.date).getBasal(extendedBolus.date); this.date = extendedBolus.date; this.isValid = extendedBolus.isValid; this.source = extendedBolus.source; @@ -404,7 +404,7 @@ public class TemporaryBasal implements Interval, DbObjectBase { public String toStringFull() { if (isFakeExtended) { - Profile profile = ProfileFunctions.getInstance().getProfile(); + Profile profile = ConfigBuilderPlugin.getPlugin().getProfileFunction().getProfile(); if (profile == null) return "null"; Double currentBasalRate = profile.getBasal(); @@ -428,7 +428,7 @@ public class TemporaryBasal implements Interval, DbObjectBase { double rate; if (isFakeExtended) { - Profile profile = ProfileFunctions.getInstance().getProfile(); + Profile profile = ConfigBuilderPlugin.getPlugin().getProfileFunction().getProfile(); if (profile == null) return "null"; double currentBasalRate = profile.getBasal(); @@ -438,7 +438,7 @@ public class TemporaryBasal implements Interval, DbObjectBase { } if (SP.getBoolean(R.string.key_danar_visualizeextendedaspercentage, false) && SP.getBoolean(R.string.key_danar_useextended, false)) { - Profile profile = ProfileFunctions.getInstance().getProfile(); + Profile profile = ConfigBuilderPlugin.getPlugin().getProfileFunction().getProfile(); if (profile != null) { double basal = profile.getBasal(); if (basal != 0) { @@ -453,7 +453,7 @@ public class TemporaryBasal implements Interval, DbObjectBase { } private String getCalcuatedPercentageIfNeeded() { - Profile profile = ProfileFunctions.getInstance().getProfile(); + Profile profile = ConfigBuilderPlugin.getPlugin().getProfileFunction().getProfile(); if (profile == null) return "null"; @@ -479,7 +479,7 @@ public class TemporaryBasal implements Interval, DbObjectBase { } public String toStringVeryShort() { - Profile profile = ProfileFunctions.getInstance().getProfile(); + Profile profile = ConfigBuilderPlugin.getPlugin().getProfileFunction().getProfile(); if (profile == null) return "null"; diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt index 2109595716..8578605a0f 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt @@ -59,8 +59,8 @@ open class AppModule { @Provides @Singleton - fun provideProfileFunction(sp: SP): ProfileFunction { - return ProfileFunctionImplementation(sp) + fun provideProfileFunction(aapsLogger: AAPSLogger, sp: SP, resourceHelper: ResourceHelper, activePlugin: ActivePluginProvider): ProfileFunction { + return ProfileFunctionImplementation(aapsLogger, sp, resourceHelper, activePlugin) } @Provides @@ -92,6 +92,7 @@ open class AppModule { @ContributesAndroidInjector fun determineBasalResultSMBInjector(): DetermineBasalResultSMB @ContributesAndroidInjector fun determineBasalResultMAInjector(): DetermineBasalResultMA @ContributesAndroidInjector fun determineBasalResultAMAInjector(): DetermineBasalResultAMA + @ContributesAndroidInjector fun determineBasalAdapterSMBJSInjector(): DetermineBasalAdapterSMBJS diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/FragmentsModule.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/FragmentsModule.kt index 60653c6ba5..4c133d9b7d 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/FragmentsModule.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/FragmentsModule.kt @@ -40,6 +40,7 @@ import info.nightscout.androidaps.plugins.source.BGSourceFragment import info.nightscout.androidaps.plugins.treatments.TreatmentsFragment import info.nightscout.androidaps.plugins.treatments.fragments.TreatmentsBolusFragment import info.nightscout.androidaps.plugins.treatments.fragments.TreatmentsCareportalFragment +import info.nightscout.androidaps.plugins.treatments.fragments.TreatmentsExtendedBolusesFragment import info.nightscout.androidaps.plugins.treatments.fragments.TreatmentsProfileSwitchFragment import info.nightscout.androidaps.plugins.treatments.fragments.TreatmentsTempTargetFragment @@ -79,16 +80,11 @@ abstract class FragmentsModule { @ContributesAndroidInjector abstract fun contributesTidepoolFragment(): TidepoolFragment @ContributesAndroidInjector abstract fun contributesTreatmentsFragment(): TreatmentsFragment - @ContributesAndroidInjector - abstract fun contributesTreatmentsBolusFragment(): TreatmentsBolusFragment - @ContributesAndroidInjector - abstract fun contributesTreatmentsTempTargetFragment(): TreatmentsTempTargetFragment - - @ContributesAndroidInjector - abstract fun contributesTreatmentsCareportalFragment(): TreatmentsCareportalFragment - - @ContributesAndroidInjector - abstract fun contributesTreatmentsProfileSwitchFragment(): TreatmentsProfileSwitchFragment + @ContributesAndroidInjector abstract fun contributesTreatmentsBolusFragment(): TreatmentsBolusFragment + @ContributesAndroidInjector abstract fun contributesTreatmentsTempTargetFragment(): TreatmentsTempTargetFragment + @ContributesAndroidInjector abstract fun contributesTreatmentsExtendedBolusesFragment(): TreatmentsExtendedBolusesFragment + @ContributesAndroidInjector abstract fun contributesTreatmentsCareportalFragment(): TreatmentsCareportalFragment + @ContributesAndroidInjector abstract fun contributesTreatmentsProfileSwitchFragment(): TreatmentsProfileSwitchFragment @ContributesAndroidInjector abstract fun contributesVirtualPumpFragment(): VirtualPumpFragment diff --git a/app/src/main/java/info/nightscout/androidaps/dialogs/FillDialog.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/FillDialog.kt index 9cdc906bbf..8f84785963 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/FillDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/FillDialog.kt @@ -58,11 +58,11 @@ class FillDialog : DialogFragmentWithDate() { val maxInsulin = constraintChecker.getMaxBolusAllowed().value() val bolusStep = activePlugin.activePump.pumpDescription.bolusStep fill_insulinamount.setParams(savedInstanceState?.getDouble("fill_insulin_amount") - ?: 0.0, 0.0, maxInsulin, bolusStep, DecimalFormatter.pumpSupportedBolusFormat(), true, ok) + ?: 0.0, 0.0, maxInsulin, bolusStep, DecimalFormatter.pumpSupportedBolusFormat(activePlugin.activePump), true, ok) val amount1 = sp.getDouble("fill_button1", 0.3) if (amount1 > 0) { fill_preset_button1.visibility = View.VISIBLE - fill_preset_button1.text = DecimalFormatter.toPumpSupportedBolus(amount1) // + "U"); + fill_preset_button1.text = DecimalFormatter.toPumpSupportedBolus(amount1, activePlugin.activePump) // + "U"); fill_preset_button1.setOnClickListener { fill_insulinamount.value = amount1 } } else { fill_preset_button1.visibility = View.GONE @@ -70,7 +70,7 @@ class FillDialog : DialogFragmentWithDate() { val amount2 = sp.getDouble("fill_button2", 0.0) if (amount2 > 0) { fill_preset_button2.visibility = View.VISIBLE - fill_preset_button2.text = DecimalFormatter.toPumpSupportedBolus(amount2) // + "U"); + fill_preset_button2.text = DecimalFormatter.toPumpSupportedBolus(amount2, activePlugin.activePump) // + "U"); fill_preset_button2.setOnClickListener { fill_insulinamount.value = amount2 } } else { fill_preset_button2.visibility = View.GONE @@ -78,7 +78,7 @@ class FillDialog : DialogFragmentWithDate() { val amount3 = sp.getDouble("fill_button3", 0.0) if (amount3 > 0) { fill_preset_button3.visibility = View.VISIBLE - fill_preset_button3.text = DecimalFormatter.toPumpSupportedBolus(amount3) // + "U"); + fill_preset_button3.text = DecimalFormatter.toPumpSupportedBolus(amount3, activePlugin.activePump) // + "U"); fill_preset_button3.setOnClickListener { fill_insulinamount.value = amount3 } } else { fill_preset_button3.visibility = View.GONE @@ -94,7 +94,7 @@ class FillDialog : DialogFragmentWithDate() { if (insulinAfterConstraints > 0) { actions.add(resourceHelper.gs(R.string.fillwarning)) actions.add("") - actions.add(resourceHelper.gs(R.string.bolus) + ": " + "" + DecimalFormatter.toPumpSupportedBolus(insulinAfterConstraints) + resourceHelper.gs(R.string.insulin_unit_shortname) + "") + actions.add(resourceHelper.gs(R.string.bolus) + ": " + "" + DecimalFormatter.toPumpSupportedBolus(insulinAfterConstraints, activePlugin.activePump) + resourceHelper.gs(R.string.insulin_unit_shortname) + "") if (abs(insulinAfterConstraints - insulin) > 0.01) actions.add(resourceHelper.gs(R.string.bolusconstraintappliedwarning, resourceHelper.gc(R.color.warning), insulin, insulinAfterConstraints)) } diff --git a/app/src/main/java/info/nightscout/androidaps/dialogs/InsulinDialog.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/InsulinDialog.kt index 37f5da3bdd..8c3d10bb32 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/InsulinDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/InsulinDialog.kt @@ -91,21 +91,21 @@ class InsulinDialog : DialogFragmentWithDate() { overview_insulin_time.setParams(savedInstanceState?.getDouble("overview_insulin_time") ?: 0.0, -12 * 60.0, 12 * 60.0, 5.0, DecimalFormat("0"), false, ok, textWatcher) overview_insulin_amount.setParams(savedInstanceState?.getDouble("overview_insulin_amount") - ?: 0.0, 0.0, maxInsulin, activePlugin.activePump.pumpDescription.bolusStep, DecimalFormatter.pumpSupportedBolusFormat(), false, ok, textWatcher) + ?: 0.0, 0.0, maxInsulin, activePlugin.activePump.pumpDescription.bolusStep, DecimalFormatter.pumpSupportedBolusFormat(activePlugin.activePump), false, ok, textWatcher) - overview_insulin_plus05.text = sp.getDouble(resourceHelper.gs(R.string.key_insulin_button_increment_1), PLUS1_DEFAULT).toSignedString() + overview_insulin_plus05.text = sp.getDouble(resourceHelper.gs(R.string.key_insulin_button_increment_1), PLUS1_DEFAULT).toSignedString(activePlugin.activePump) overview_insulin_plus05.setOnClickListener { overview_insulin_amount.value = max(0.0, overview_insulin_amount.value + sp.getDouble(resourceHelper.gs(R.string.key_insulin_button_increment_1), PLUS1_DEFAULT)) validateInputs() } - overview_insulin_plus10.text = sp.getDouble(resourceHelper.gs(R.string.key_insulin_button_increment_2), PLUS2_DEFAULT).toSignedString() + overview_insulin_plus10.text = sp.getDouble(resourceHelper.gs(R.string.key_insulin_button_increment_2), PLUS2_DEFAULT).toSignedString(activePlugin.activePump) overview_insulin_plus10.setOnClickListener { overview_insulin_amount.value = max(0.0, overview_insulin_amount.value + sp.getDouble(resourceHelper.gs(R.string.key_insulin_button_increment_2), PLUS2_DEFAULT)) validateInputs() } - overview_insulin_plus20.text = sp.getDouble(resourceHelper.gs(R.string.key_insulin_button_increment_3), PLUS3_DEFAULT).toSignedString() + overview_insulin_plus20.text = sp.getDouble(resourceHelper.gs(R.string.key_insulin_button_increment_3), PLUS3_DEFAULT).toSignedString(activePlugin.activePump) overview_insulin_plus20.setOnClickListener { overview_insulin_amount.value = max(0.0, overview_insulin_amount.value + sp.getDouble(resourceHelper.gs(R.string.key_insulin_button_increment_3), PLUS3_DEFAULT)) @@ -129,7 +129,7 @@ class InsulinDialog : DialogFragmentWithDate() { val eatingSoonChecked = overview_insulin_start_eating_soon_tt.isChecked if (insulinAfterConstraints > 0) { - actions.add(resourceHelper.gs(R.string.bolus) + ": " + "" + DecimalFormatter.toPumpSupportedBolus(insulinAfterConstraints) + resourceHelper.gs(R.string.insulin_unit_shortname) + "") + actions.add(resourceHelper.gs(R.string.bolus) + ": " + "" + DecimalFormatter.toPumpSupportedBolus(insulinAfterConstraints, activePlugin.activePump) + resourceHelper.gs(R.string.insulin_unit_shortname) + "") if (recordOnlyChecked) actions.add("" + resourceHelper.gs(R.string.bolusrecordedonly) + "") if (abs(insulinAfterConstraints - insulin) > pumpDescription.pumpType.determineCorrectBolusStepSize(insulinAfterConstraints)) diff --git a/app/src/main/java/info/nightscout/androidaps/dialogs/TreatmentDialog.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/TreatmentDialog.kt index db935b8689..3f729fbf3e 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/TreatmentDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/TreatmentDialog.kt @@ -81,7 +81,7 @@ class TreatmentDialog : DialogFragmentWithDate() { overview_treatment_carbs.setParams(savedInstanceState?.getDouble("overview_treatment_carbs") ?: 0.0, 0.0, maxCarbs, 1.0, DecimalFormat("0"), false, ok, textWatcher) overview_treatment_insulin.setParams(savedInstanceState?.getDouble("overview_treatment_insulin") - ?: 0.0, 0.0, maxInsulin, pumpDescription.bolusStep, DecimalFormatter.pumpSupportedBolusFormat(), false, ok, textWatcher) + ?: 0.0, 0.0, maxInsulin, pumpDescription.bolusStep, DecimalFormatter.pumpSupportedBolusFormat(activePlugin.activePump), false, ok, textWatcher) } override fun submit(): Boolean { @@ -94,7 +94,7 @@ class TreatmentDialog : DialogFragmentWithDate() { val carbsAfterConstraints = constraintChecker.applyCarbsConstraints(Constraint(carbs)).value() if (insulinAfterConstraints > 0) { - actions.add(resourceHelper.gs(R.string.bolus) + ": " + "" + DecimalFormatter.toPumpSupportedBolus(insulinAfterConstraints) + resourceHelper.gs(R.string.insulin_unit_shortname) + "") + actions.add(resourceHelper.gs(R.string.bolus) + ": " + "" + DecimalFormatter.toPumpSupportedBolus(insulinAfterConstraints, activePlugin.activePump) + resourceHelper.gs(R.string.insulin_unit_shortname) + "") if (recordOnlyChecked) actions.add("" + resourceHelper.gs(R.string.bolusrecordedonly) + "") if (abs(insulinAfterConstraints - insulin) > pumpDescription.pumpType.determineCorrectBolusStepSize(insulinAfterConstraints)) diff --git a/app/src/main/java/info/nightscout/androidaps/dialogs/WizardDialog.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/WizardDialog.kt index 805749c4a3..3f2f3ee8f5 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/WizardDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/WizardDialog.kt @@ -111,7 +111,7 @@ class WizardDialog : DaggerDialogFragment() { ?: 0.0, 0.0, maxCarbs.toDouble(), 1.0, DecimalFormat("0"), false, ok, textWatcher) val bolusStep = activePlugin.activePump.pumpDescription.bolusStep treatments_wizard_correction_input.setParams(savedInstanceState?.getDouble("treatments_wizard_correction_input") - ?: 0.0, -maxCorrection, maxCorrection, bolusStep, DecimalFormatter.pumpSupportedBolusFormat(), false, ok, textWatcher) + ?: 0.0, -maxCorrection, maxCorrection, bolusStep, DecimalFormatter.pumpSupportedBolusFormat(activePlugin.activePump), false, ok, textWatcher) treatments_wizard_carb_time_input.setParams(savedInstanceState?.getDouble("treatments_wizard_carb_time_input") ?: 0.0, -60.0, 60.0, 5.0, DecimalFormat("0"), false, ok, textWatcher) initDialog() diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/APSResult.java b/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/APSResult.java index 348cfc7cab..5ca88bfac0 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/APSResult.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/APSResult.java @@ -39,7 +39,7 @@ public class APSResult { @Inject public AAPSLogger aapsLogger; @Inject ConstraintChecker constraintChecker; @Inject SP sp; - @Inject ActivePluginProvider activePluginProvider; + @Inject ActivePluginProvider activePlugin; @Inject TreatmentsPlugin treatmentsPlugin; @Inject ProfileFunction profileFunction; @Inject ResourceHelper resourceHelper; @@ -101,7 +101,7 @@ public class APSResult { @Override public String toString() { - final PumpInterface pump = activePluginProvider.getActivePump(); + final PumpInterface pump = activePlugin.getActivePump(); if (isChangeRequested()) { String ret; // rate @@ -120,7 +120,7 @@ public class APSResult { // smb if (smb != 0) - ret += ("SMB: " + DecimalFormatter.toPumpSupportedBolus(smb) + " U\n"); + ret += ("SMB: " + DecimalFormatter.toPumpSupportedBolus(smb, activePlugin.getActivePump()) + " U\n"); // reason ret += resourceHelper.gs(R.string.reason) + ": " + reason; @@ -130,7 +130,7 @@ public class APSResult { } public Spanned toSpanned() { - final PumpInterface pump = activePluginProvider.getActivePump(); + final PumpInterface pump = activePlugin.getActivePump(); if (isChangeRequested()) { String ret; // rate @@ -149,7 +149,7 @@ public class APSResult { // smb if (smb != 0) - ret += ("" + "SMB" + ": " + DecimalFormatter.toPumpSupportedBolus(smb) + " U
"); + ret += ("" + "SMB" + ": " + DecimalFormatter.toPumpSupportedBolus(smb, activePlugin.getActivePump()) + " U
"); // reason ret += "" + resourceHelper.gs(R.string.reason) + ": " + reason.replace("<", "<").replace(">", ">"); @@ -314,7 +314,7 @@ public class APSResult { long now = System.currentTimeMillis(); TemporaryBasal activeTemp = treatmentsPlugin.getTempBasalFromHistory(now); - PumpInterface pump = activePluginProvider.getActivePump(); + PumpInterface pump = activePlugin.getActivePump(); Profile profile = profileFunction.getProfile(); if (profile == null) { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderPlugin.java index fa1f09937c..b779943cdb 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderPlugin.java @@ -53,17 +53,17 @@ public class ConfigBuilderPlugin extends PluginBase { private final AAPSLogger aapsLogger; private final RxBusWrapper rxBus; private final ResourceHelper resourceHelper; - private final CommandQueueProvider commandQueue; + private final ProfileFunction profileFunction; /** * @deprecated Use dagger to get an instance */ @Deprecated - public CommandQueueProvider getCommandQueue() { - if (commandQueue == null) - throw new IllegalStateException("Accessing commandQueue before first instantiation"); - return commandQueue; + public ProfileFunction getProfileFunction() { + if (profileFunction == null) + throw new IllegalStateException("Accessing profileFunction before first instantiation"); + return profileFunction; } @Deprecated @@ -88,7 +88,7 @@ public class ConfigBuilderPlugin extends PluginBase { RxBusWrapper rxBus, AAPSLogger aapsLogger, ResourceHelper resourceHelper, - CommandQueueProvider commandQueue + ProfileFunction profileFunction ) { super(new PluginDescription() .mainType(PluginType.GENERAL) @@ -106,7 +106,7 @@ public class ConfigBuilderPlugin extends PluginBase { this.rxBus = rxBus; this.aapsLogger = aapsLogger; this.resourceHelper = resourceHelper; - this.commandQueue = commandQueue; + this.profileFunction = profileFunction; configBuilderPlugin = this; // TODO: only while transitioning to Dagger } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ProfileFunctionImplementation.kt b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ProfileFunctionImplementation.kt index dbc9d29e79..13f9fdc8a6 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ProfileFunctionImplementation.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ProfileFunctionImplementation.kt @@ -1,11 +1,19 @@ package info.nightscout.androidaps.plugins.configBuilder +import android.os.Bundle +import com.google.firebase.analytics.FirebaseAnalytics +import info.nightscout.androidaps.BuildConfig import info.nightscout.androidaps.Constants import info.nightscout.androidaps.R import info.nightscout.androidaps.data.Profile import info.nightscout.androidaps.data.ProfileStore import info.nightscout.androidaps.db.ProfileSwitch import info.nightscout.androidaps.db.Source +import info.nightscout.androidaps.interfaces.ActivePluginProvider +import info.nightscout.androidaps.logging.AAPSLogger +import info.nightscout.androidaps.utils.DateUtil +import info.nightscout.androidaps.utils.FabricPrivacy +import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.sharedPreferences.SP import java.security.spec.InvalidParameterSpecException import javax.inject.Inject @@ -13,7 +21,10 @@ import javax.inject.Singleton @Singleton class ProfileFunctionImplementation @Inject constructor( - private val sp: SP + private val aapsLogger: AAPSLogger, + private val sp: SP, + private val resourceHelper: ResourceHelper, + private val activePlugin: ActivePluginProvider ) : ProfileFunction { override fun getProfileName(): String = @@ -22,8 +33,30 @@ class ProfileFunctionImplementation @Inject constructor( override fun getProfileName(customized: Boolean): String = getProfileName(System.currentTimeMillis(), customized, showRemainingTime = false) - override fun getProfileName(time: Long, customized: Boolean, showRemainingTime: Boolean): String = - ProfileFunctions.getInstance().getProfileName(time, customized, showRemainingTime) + override fun getProfileName(time: Long, customized: Boolean, showRemainingTime: Boolean): String { + var profileName = resourceHelper.gs(R.string.noprofileselected) + + val activeTreatments = activePlugin.activeTreatments + val activeProfile = activePlugin.activeProfileInterface + + val profileSwitch = activeTreatments.getProfileSwitchFromHistory(time) + if (profileSwitch != null) { + if (profileSwitch.profileJson != null) { + profileName = if (customized) profileSwitch.customizedName else profileSwitch.profileName + } else { + activeProfile.profile?.let { profileStore -> + val profile = profileStore.getSpecificProfile(profileSwitch.profileName) + if (profile != null) + profileName = profileSwitch.profileName + } + } + + if (showRemainingTime && profileSwitch.durationInMinutes != 0) { + profileName += DateUtil.untilString(profileSwitch.originalEnd(), resourceHelper); + } + } + return profileName; + } override fun getProfileNameWithDuration(): String = getProfileName(System.currentTimeMillis(), customized = true, showRemainingTime = true) @@ -31,12 +64,34 @@ class ProfileFunctionImplementation @Inject constructor( override fun isProfileValid(from: String): Boolean = getProfile()?.isValid(from) ?: false - override fun getProfile(): Profile? { - return ProfileFunctions.getInstance().getProfile() - } + override fun getProfile(): Profile? = + getProfile(System.currentTimeMillis()) - override fun getProfile(time: Long): Profile? = - ProfileFunctions.getInstance().getProfile(System.currentTimeMillis()) + override fun getProfile(time: Long): Profile? { + val activeTreatments = activePlugin.activeTreatments + val activeProfile = activePlugin.activeProfileInterface + + //log.debug("Profile for: " + new Date(time).toLocaleString() + " : " + getProfileName(time)); + val profileSwitch = activeTreatments.getProfileSwitchFromHistory(time) + if (profileSwitch != null) { + if (profileSwitch.profileJson != null) { + return profileSwitch.profileObject + } else if (activeProfile.profile != null) { + val profile = activeProfile.profile!!.getSpecificProfile(profileSwitch.profileName) + if (profile != null) return profile + } + } + if (activeTreatments.profileSwitchesFromHistory.size() > 0) { + val bundle = Bundle() + bundle.putString(FirebaseAnalytics.Param.ITEM_ID, "CatchedError") + bundle.putString(FirebaseAnalytics.Param.ITEM_CATEGORY, BuildConfig.BUILDVERSION) + bundle.putString(FirebaseAnalytics.Param.START_DATE, time.toString()) + bundle.putString(FirebaseAnalytics.Param.VALUE, activeTreatments.profileSwitchesFromHistory.toString()) + FabricPrivacy.getInstance().logCustom(bundle) + } + aapsLogger.error("getProfile at the end: returning null") + return null + } override fun getUnits(): String = sp.getString(R.string.key_units, Constants.MGDL) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ProfileFunctions.java b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ProfileFunctions.java deleted file mode 100644 index a384d2c96e..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ProfileFunctions.java +++ /dev/null @@ -1,148 +0,0 @@ -package info.nightscout.androidaps.plugins.configBuilder; - -import android.os.Bundle; - -import androidx.annotation.Nullable; - -import com.google.firebase.analytics.FirebaseAnalytics; - -import org.jetbrains.annotations.NotNull; -import org.slf4j.Logger; - -import info.nightscout.androidaps.BuildConfig; -import info.nightscout.androidaps.Constants; -import info.nightscout.androidaps.MainApp; -import info.nightscout.androidaps.R; -import info.nightscout.androidaps.data.Profile; -import info.nightscout.androidaps.data.ProfileStore; -import info.nightscout.androidaps.db.ProfileSwitch; -import info.nightscout.androidaps.db.Source; -import info.nightscout.androidaps.interfaces.ProfileInterface; -import info.nightscout.androidaps.interfaces.TreatmentsInterface; -import info.nightscout.androidaps.logging.L; -import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; -import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin; -import info.nightscout.androidaps.utils.DateUtil; -import info.nightscout.androidaps.utils.FabricPrivacy; -import info.nightscout.androidaps.utils.SP; - -public class ProfileFunctions implements ProfileFunction { - private static Logger log = StacktraceLoggerWrapper.getLogger(L.PROFILE); - - private static ProfileFunctions profileFunctions = null; - - @Deprecated - public static ProfileFunctions getInstance() { - if (profileFunctions == null) - profileFunctions = new ProfileFunctions(); - return profileFunctions; - } - - @NotNull - public String getProfileName() { - return getProfileName(System.currentTimeMillis(), true, false); - } - - @NotNull - public String getProfileName(boolean customized) { - return getProfileName(System.currentTimeMillis(), customized, false); - } - - @NotNull - public String getProfileNameWithDuration() { - return getProfileName(System.currentTimeMillis(), true, true); - } - - @NotNull - public String getProfileName(long time, boolean customized, boolean showRemainingTime) { - String profileName = MainApp.gs(R.string.noprofileselected); - - TreatmentsInterface activeTreatments = TreatmentsPlugin.getPlugin(); - ProfileInterface activeProfile = PluginStore.Companion.getInstance().getActiveProfileInterface(); - - ProfileSwitch profileSwitch = activeTreatments.getProfileSwitchFromHistory(time); - if (profileSwitch != null) { - if (profileSwitch.profileJson != null) { - profileName = customized ? profileSwitch.getCustomizedName() : profileSwitch.profileName; - } else { - ProfileStore profileStore = activeProfile.getProfile(); - if (profileStore != null) { - Profile profile = profileStore.getSpecificProfile(profileSwitch.profileName); - if (profile != null) - profileName = profileSwitch.profileName; - } - } - - if (showRemainingTime && profileSwitch.durationInMinutes != 0) { - profileName += DateUtil.untilString(profileSwitch.originalEnd()); - } - return profileName; - } - return profileName; - } - - public boolean isProfileValid(@NotNull String from) { - Profile profile = getProfile(); - return profile != null && profile.isValid(from); - } - - @Nullable - public Profile getProfile() { - return getProfile(System.currentTimeMillis()); - } - - @NotNull - public String getUnits() { - return getSystemUnits(); - } - - @NotNull - @Deprecated - public static String getSystemUnits() { - return SP.getString(R.string.key_units, Constants.MGDL); - } - - @Nullable - public Profile getProfile(long time) { - TreatmentsInterface activeTreatments = TreatmentsPlugin.getPlugin(); - ProfileInterface activeProfile = PluginStore.Companion.getInstance().getActiveProfileInterface(); - - //log.debug("Profile for: " + new Date(time).toLocaleString() + " : " + getProfileName(time)); - ProfileSwitch profileSwitch = activeTreatments.getProfileSwitchFromHistory(time); - if (profileSwitch != null) { - if (profileSwitch.profileJson != null) { - return profileSwitch.getProfileObject(); - } else if (activeProfile.getProfile() != null) { - Profile profile = activeProfile.getProfile().getSpecificProfile(profileSwitch.profileName); - if (profile != null) - return profile; - } - } - if (activeTreatments.getProfileSwitchesFromHistory().size() > 0) { - Bundle bundle = new Bundle(); - bundle.putString(FirebaseAnalytics.Param.ITEM_ID, "CatchedError"); - bundle.putString(FirebaseAnalytics.Param.ITEM_CATEGORY, BuildConfig.BUILDVERSION); - bundle.putString(FirebaseAnalytics.Param.START_DATE, String.valueOf(time)); - bundle.putString(FirebaseAnalytics.Param.VALUE, activeTreatments.getProfileSwitchesFromHistory().toString()); - FabricPrivacy.getInstance().logCustom(bundle); - } - log.error("getProfile at the end: returning null"); - return null; - } - - @NotNull - public ProfileSwitch prepareProfileSwitch(@NotNull final ProfileStore profileStore, @NotNull final String profileName, final int duration, final int percentage, final int timeShift, long date) { - ProfileSwitch profileSwitch = new ProfileSwitch(); - profileSwitch.date = date; - profileSwitch.source = Source.USER; - profileSwitch.profileName = profileName; - profileSwitch.profileJson = profileStore.getSpecificProfile(profileName).getData().toString(); - profileSwitch.profilePlugin = PluginStore.Companion.getInstance().getActiveProfileInterface().getClass().getName(); - profileSwitch.durationInMinutes = duration; - profileSwitch.isCPP = percentage != 100 || timeShift != 0; - profileSwitch.timeshift = timeShift; - profileSwitch.percentage = percentage; - return profileSwitch; - } - -} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSUpload.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSUpload.java index 0c4b4d54e5..c4fd7639a8 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSUpload.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSUpload.java @@ -5,25 +5,21 @@ import android.content.SharedPreferences; import android.content.pm.ResolveInfo; import android.os.Build; import android.os.Bundle; -import androidx.preference.PreferenceManager; import androidx.annotation.Nullable; +import androidx.preference.PreferenceManager; import org.apache.commons.lang3.StringUtils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import java.util.Locale; -import javax.inject.Inject; -import javax.inject.Singleton; - import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.DetailedBolusInfo; @@ -43,7 +39,6 @@ import info.nightscout.androidaps.plugins.aps.loop.DeviceStatus; import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin; import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.configBuilder.PluginStore; -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin; import info.nightscout.androidaps.utils.BatteryLevel; import info.nightscout.androidaps.utils.DateUtil; @@ -78,7 +73,7 @@ public class NSUpload { try { SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext()); boolean useAbsolute = SP.getBoolean("ns_sync_use_absolute", false); - Profile profile = ProfileFunctions.getInstance().getProfile(temporaryBasal.date); + Profile profile = ConfigBuilderPlugin.getPlugin().getProfileFunction().getProfile(temporaryBasal.date); double absoluteRate = 0; if (profile != null) { absoluteRate = profile.getBasal(temporaryBasal.date) * temporaryBasal.percentRate / 100d; @@ -163,8 +158,8 @@ public class NSUpload { } public static void uploadDeviceStatus(LoopPlugin loopPlugin) { - Profile profile = ProfileFunctions.getInstance().getProfile(); - String profileName = ProfileFunctions.getInstance().getProfileName(); + Profile profile = ConfigBuilderPlugin.getPlugin().getProfileFunction().getProfile(); + String profileName = ConfigBuilderPlugin.getPlugin().getProfileFunction().getProfileName(); if (profile == null || profileName == null) { log.error("Profile is null. Skipping upload"); @@ -272,9 +267,9 @@ public class NSUpload { data.put("duration", tempTarget.durationInMinutes); if (tempTarget.low > 0) { data.put("reason", tempTarget.reason); - data.put("targetBottom", Profile.fromMgdlToUnits(tempTarget.low, ProfileFunctions.getSystemUnits())); - data.put("targetTop", Profile.fromMgdlToUnits(tempTarget.high, ProfileFunctions.getSystemUnits())); - data.put("units", ProfileFunctions.getSystemUnits()); + data.put("targetBottom", Profile.fromMgdlToUnits(tempTarget.low, ConfigBuilderPlugin.getPlugin().getProfileFunction().getUnits())); + data.put("targetTop", Profile.fromMgdlToUnits(tempTarget.high, ConfigBuilderPlugin.getPlugin().getProfileFunction().getUnits())); + data.put("units", ConfigBuilderPlugin.getPlugin().getProfileFunction().getUnits()); } data.put("created_at", DateUtil.toISOString(tempTarget.date)); data.put("enteredBy", MainApp.gs(R.string.app_name)); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewFragment.java index 9e9a931eba..8abade4f39 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewFragment.java @@ -1139,7 +1139,7 @@ public class OverviewFragment extends DaggerFragment implements View.OnClickList if (tempTarget != null) { tempTargetView.setTextColor(resourceHelper.gc(R.color.ribbonTextWarning)); tempTargetView.setBackgroundColor(resourceHelper.gc(R.color.ribbonWarning)); - tempTargetView.setText(Profile.toTargetRangeString(tempTarget.low, tempTarget.high, Constants.MGDL, units) + " " + DateUtil.untilString(tempTarget.end())); + tempTargetView.setText(Profile.toTargetRangeString(tempTarget.low, tempTarget.high, Constants.MGDL, units) + " " + DateUtil.untilString(tempTarget.end(), resourceHelper)); } else { tempTargetView.setTextColor(resourceHelper.gc(R.color.ribbonTextDefault)); tempTargetView.setBackgroundColor(resourceHelper.gc(R.color.ribbonDefault)); @@ -1239,7 +1239,7 @@ public class OverviewFragment extends DaggerFragment implements View.OnClickList quickWizardButton.setVisibility(View.VISIBLE); String text = quickWizardEntry.buttonText() + "\n" + DecimalFormatter.to0Decimal(quickWizardEntry.carbs()) + "g"; BolusWizard wizard = quickWizardEntry.doCalc(profile, profileName, lastBG, false); - text += " " + DecimalFormatter.toPumpSupportedBolus(wizard.getCalculatedTotalInsulin()) + "U"; + text += " " + DecimalFormatter.toPumpSupportedBolus(wizard.getCalculatedTotalInsulin(), pump) + "U"; quickWizardButton.setText(text); if (wizard.getCalculatedTotalInsulin() <= 0) quickWizardButton.setVisibility(View.GONE); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphData/GraphData.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphData/GraphData.java index ee0b7bcf9a..c892ab5ad7 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphData/GraphData.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphData/GraphData.java @@ -32,8 +32,8 @@ import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; import info.nightscout.androidaps.plugins.aps.loop.APSResult; import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin; import info.nightscout.androidaps.plugins.aps.openAPSSMB.SMBDefaults; +import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.configBuilder.PluginStore; -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.general.overview.graphExtensions.AreaGraphSeries; import info.nightscout.androidaps.plugins.general.overview.graphExtensions.DataPointWithLabelInterface; import info.nightscout.androidaps.plugins.general.overview.graphExtensions.DoubleDataPoint; @@ -68,7 +68,7 @@ public class GraphData { private IobCobCalculatorPlugin iobCobCalculatorPlugin; public GraphData(GraphView graph, IobCobCalculatorPlugin iobCobCalculatorPlugin) { - units = ProfileFunctions.getSystemUnits(); + units = ConfigBuilderPlugin.getPlugin().getProfileFunction().getUnits(); this.graph = graph; this.iobCobCalculatorPlugin = iobCobCalculatorPlugin; } @@ -151,7 +151,7 @@ public class GraphData { double lastBaseBasal = 0; double lastTempBasal = 0; for (long time = fromTime; time < toTime; time += 60 * 1000L) { - Profile profile = ProfileFunctions.getInstance().getProfile(time); + Profile profile = ConfigBuilderPlugin.getPlugin().getProfileFunction().getProfile(time); if (profile == null) continue; BasalData basalData = iobCobCalculatorPlugin.getBasalData(profile, time); double baseBasalValue = basalData.basal; @@ -263,9 +263,9 @@ public class GraphData { TempTarget tt = TreatmentsPlugin.getPlugin().getTempTargetFromHistory(time); double value; if (tt == null) { - value = Profile.fromMgdlToUnits((profile.getTargetLowMgdl(time) + profile.getTargetHighMgdl(time)) / 2, ProfileFunctions.getSystemUnits()); + value = Profile.fromMgdlToUnits((profile.getTargetLowMgdl(time) + profile.getTargetHighMgdl(time)) / 2, ConfigBuilderPlugin.getPlugin().getProfileFunction().getUnits()); } else { - value = Profile.fromMgdlToUnits(tt.target(), ProfileFunctions.getSystemUnits()); + value = Profile.fromMgdlToUnits(tt.target(), ConfigBuilderPlugin.getPlugin().getProfileFunction().getUnits()); } if (lastTarget != value) { if (lastTarget != -1) @@ -360,7 +360,7 @@ public class GraphData { double maxIAValue = 0; for (long time = fromTime; time <= toTime; time += 5 * 60 * 1000L) { - Profile profile = ProfileFunctions.getInstance().getProfile(time); + Profile profile = ConfigBuilderPlugin.getPlugin().getProfileFunction().getProfile(time); double act = 0d; if (profile == null) continue; total = iobCobCalculatorPlugin.calculateFromTreatmentsAndTempsSynchronized(time, profile); @@ -412,7 +412,7 @@ public class GraphData { Scale iobScale = new Scale(); for (long time = fromTime; time <= toTime; time += 5 * 60 * 1000L) { - Profile profile = ProfileFunctions.getInstance().getProfile(time); + Profile profile = ConfigBuilderPlugin.getPlugin().getProfileFunction().getProfile(time); double iob = 0d; if (profile != null) iob = iobCobCalculatorPlugin.calculateFromTreatmentsAndTempsSynchronized(time, profile).iob; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ComboFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ComboFragment.java index 87c565fa23..7e61ba97a3 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ComboFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ComboFragment.java @@ -222,7 +222,7 @@ public class ComboFragment extends DaggerFragment implements View.OnClickListene } else if (bolusMinAgo < 60) { ago = DateUtil.minAgo(bolus.timestamp); } else { - ago = DateUtil.hourAgo(bolus.timestamp); + ago = DateUtil.hourAgo(bolus.timestamp, resourceHelper); } lastBolusView.setText(resourceHelper.gs(R.string.combo_last_bolus, bolus.amount, unit, ago)); } else { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/DanaRFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/DanaRFragment.kt index 5be012c45c..2e7104c9e1 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/DanaRFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/DanaRFragment.kt @@ -164,7 +164,7 @@ class DanaRFragment : DaggerFragment() { val agoHours = agoMsec.toDouble() / 60.0 / 60.0 / 1000.0 if (agoHours < 6) // max 6h back - danar_lastbolus.text = DateUtil.timeString(pump.lastBolusTime) + " " + DateUtil.sinceString(pump.lastBolusTime) + " " + resourceHelper.gs(R.string.formatinsulinunits, pump.lastBolusAmount) + danar_lastbolus.text = DateUtil.timeString(pump.lastBolusTime) + " " + DateUtil.sinceString(pump.lastBolusTime, resourceHelper) + " " + resourceHelper.gs(R.string.formatinsulinunits, pump.lastBolusAmount) else danar_lastbolus.text = "" } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicFragment.kt index 8768596f50..aede8f4e47 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicFragment.kt @@ -297,7 +297,7 @@ class MedtronicFragment : DaggerFragment() { } else if (bolusMinAgo < 60) { ago = DateUtil.minAgo(pumpStatus.lastBolusTime.time) } else { - ago = DateUtil.hourAgo(pumpStatus.lastBolusTime.time) + ago = DateUtil.hourAgo(pumpStatus.lastBolusTime.time, resourceHelper) } medtronic_lastbolus.text = resourceHelper.gs(R.string.combo_last_bolus, bolus, unit, ago) } else { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/Treatment.java b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/Treatment.java index f863303813..ee99412f77 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/Treatment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/Treatment.java @@ -245,7 +245,7 @@ public class Treatment implements DataPointWithLabelInterface, DbObjectBase { @Override public String getLabel() { String label = ""; - if (insulin > 0) label += DecimalFormatter.toPumpSupportedBolus(insulin) + "U"; + if (insulin > 0) label += DecimalFormatter.toPumpSupportedBolus(insulin, activePlugin.getActivePump()) + "U"; if (carbs > 0) label += "~" + DecimalFormatter.to0Decimal(carbs) + "g"; return label; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsCareportalFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsCareportalFragment.kt index 8786c7247c..46108c045b 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsCareportalFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsCareportalFragment.kt @@ -107,7 +107,7 @@ class TreatmentsCareportalFragment : DaggerFragment() { val careportalEvent = careportalEventList[position] holder.ns.visibility = if (NSUpload.isIdValid(careportalEvent._id)) View.VISIBLE else View.GONE holder.date.text = DateUtil.dateAndTimeString(careportalEvent.date) - holder.duration.text = if (careportalEvent.durationInMsec() == 0L) "" else DateUtil.niceTimeScalar(careportalEvent.durationInMsec()) + holder.duration.text = if (careportalEvent.durationInMsec() == 0L) "" else DateUtil.niceTimeScalar(careportalEvent.durationInMsec(), resourceHelper) holder.note.text = careportalEvent.notes holder.type.text = Translator.translate(careportalEvent.eventType) holder.remove.tag = careportalEvent diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsExtendedBolusesFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsExtendedBolusesFragment.java index 08611be594..2452f40e47 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsExtendedBolusesFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsExtendedBolusesFragment.java @@ -14,6 +14,9 @@ import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; +import javax.inject.Inject; + +import dagger.android.support.DaggerFragment; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.Intervals; @@ -21,6 +24,7 @@ import info.nightscout.androidaps.data.IobTotal; import info.nightscout.androidaps.db.ExtendedBolus; import info.nightscout.androidaps.db.Source; import info.nightscout.androidaps.events.EventExtendedBolusChange; +import info.nightscout.androidaps.interfaces.ActivePluginProvider; import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.general.nsclient.NSUpload; import info.nightscout.androidaps.plugins.general.nsclient.UploadQueue; @@ -34,7 +38,9 @@ import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.CompositeDisposable; -public class TreatmentsExtendedBolusesFragment extends Fragment { +public class TreatmentsExtendedBolusesFragment extends DaggerFragment { + @Inject ActivePluginProvider activePlugin; + private CompositeDisposable disposable = new CompositeDisposable(); private RecyclerView recyclerView; @@ -74,7 +80,7 @@ public class TreatmentsExtendedBolusesFragment extends Fragment { holder.date.setText(DateUtil.dateAndTimeString(extendedBolus.date) + " - " + DateUtil.timeString(extendedBolus.end())); } holder.duration.setText(DecimalFormatter.to0Decimal(extendedBolus.durationInMinutes) + " min"); - holder.insulin.setText(DecimalFormatter.toPumpSupportedBolus(extendedBolus.insulin) + " U"); + holder.insulin.setText(DecimalFormatter.toPumpSupportedBolus(extendedBolus.insulin, activePlugin.getActivePump()) + " U"); holder.realDuration.setText(DecimalFormatter.to0Decimal(extendedBolus.getRealDuration()) + " min"); IobTotal iob = extendedBolus.iobCalc(System.currentTimeMillis()); holder.iob.setText(DecimalFormatter.to2Decimal(iob.iob) + " U"); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsTemporaryBasalsFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsTemporaryBasalsFragment.java index 45b3905150..93ade583b5 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsTemporaryBasalsFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsTemporaryBasalsFragment.java @@ -23,7 +23,7 @@ import info.nightscout.androidaps.db.Source; import info.nightscout.androidaps.db.TemporaryBasal; import info.nightscout.androidaps.events.EventTempBasalChange; import info.nightscout.androidaps.plugins.bus.RxBus; -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; +import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.general.nsclient.NSUpload; import info.nightscout.androidaps.plugins.general.nsclient.UploadQueue; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventAutosensCalculationFinished; @@ -84,7 +84,7 @@ public class TreatmentsTemporaryBasalsFragment extends Fragment { } holder.duration.setText(DecimalFormatter.to0Decimal(tempBasal.durationInMinutes, " min")); if (tempBasal.isAbsolute) { - Profile profile = ProfileFunctions.getInstance().getProfile(tempBasal.date); + Profile profile = ConfigBuilderPlugin.getPlugin().getProfileFunction().getProfile(tempBasal.date); if (profile != null) { holder.absolute.setText(DecimalFormatter.to2Decimal(tempBasal.tempBasalConvertedToAbsolute(tempBasal.date, profile), " U/h")); holder.percent.setText(""); @@ -99,7 +99,7 @@ public class TreatmentsTemporaryBasalsFragment extends Fragment { holder.realDuration.setText(DecimalFormatter.to0Decimal(tempBasal.getRealDuration(), " min")); long now = DateUtil.now(); IobTotal iob = new IobTotal(now); - Profile profile = ProfileFunctions.getInstance().getProfile(now); + Profile profile = ConfigBuilderPlugin.getPlugin().getProfileFunction().getProfile(now); if (profile != null) iob = tempBasal.iobCalc(now, profile); holder.iob.setText(DecimalFormatter.to2Decimal(iob.basaliob, " U")); diff --git a/app/src/main/java/info/nightscout/androidaps/setupwizard/elements/SWEditNumberWithUnits.java b/app/src/main/java/info/nightscout/androidaps/setupwizard/elements/SWEditNumberWithUnits.java index 3023f297d7..1d3f651904 100644 --- a/app/src/main/java/info/nightscout/androidaps/setupwizard/elements/SWEditNumberWithUnits.java +++ b/app/src/main/java/info/nightscout/androidaps/setupwizard/elements/SWEditNumberWithUnits.java @@ -12,7 +12,7 @@ import java.text.DecimalFormat; import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.data.Profile; -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; +import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.setupwizard.SWNumberValidator; import info.nightscout.androidaps.utils.NumberPicker; import info.nightscout.androidaps.utils.SP; @@ -64,10 +64,10 @@ public class SWEditNumberWithUnits extends SWItem { layout.addView(l); double initValue = SP.getDouble(preferenceId, init); - initValue = Profile.toCurrentUnits(ProfileFunctions.getSystemUnits(), initValue); + initValue = Profile.toCurrentUnits(ConfigBuilderPlugin.getPlugin().getProfileFunction().getUnits(), initValue); NumberPicker numberPicker = new NumberPicker(context); - if (ProfileFunctions.getSystemUnits().equals(Constants.MMOL)) + if (ConfigBuilderPlugin.getPlugin().getProfileFunction().getUnits().equals(Constants.MMOL)) numberPicker.setParams(initValue, min, max, 0.1d, new DecimalFormat("0.0"), false, null, watcher); else numberPicker.setParams(initValue, min * 18, max * 18, 1d, new DecimalFormat("0"), false, null, watcher); diff --git a/app/src/main/java/info/nightscout/androidaps/utils/ActivityMonitor.kt b/app/src/main/java/info/nightscout/androidaps/utils/ActivityMonitor.kt index 8dbe0c2b3c..31a9f0dc23 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/ActivityMonitor.kt +++ b/app/src/main/java/info/nightscout/androidaps/utils/ActivityMonitor.kt @@ -63,7 +63,7 @@ class ActivityMonitor @Inject constructor( if (key.startsWith("Monitor") && key.endsWith("total")) { val v = if (value is Long) value else SafeParse.stringToLong(value as String) val activity = key.split("_")[1].replace("Activity", "") - val duration = DateUtil.niceTimeScalar(v as Long) + val duration = DateUtil.niceTimeScalar(v as Long, resourceHelper) val start = sp.getLong(key.replace("total", "start"), 0) val days = T.msecs(DateUtil.now() - start).days() result += "$activity: $duration in $days days
" diff --git a/app/src/main/java/info/nightscout/androidaps/utils/DateUtil.java b/app/src/main/java/info/nightscout/androidaps/utils/DateUtil.java index aa228b96ca..a760f1e57d 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/DateUtil.java +++ b/app/src/main/java/info/nightscout/androidaps/utils/DateUtil.java @@ -21,6 +21,7 @@ import java.util.regex.Pattern; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; +import info.nightscout.androidaps.utils.resources.ResourceHelper; /** * The Class DateUtil. A simple wrapper around SimpleDateFormat to ease the handling of iso date string <-> date obj @@ -185,9 +186,9 @@ public class DateUtil { return (mins > 0 ? "+" : "") + mins.toString(); } - public static String hourAgo(long time) { + public static String hourAgo(long time, ResourceHelper resourceHelper) { double hours = (now() - time) / 1000d / 60 / 60; - return MainApp.gs(R.string.hoursago, hours); + return resourceHelper.gs(R.string.hoursago, hours); } private static LongSparseArray timeStrings = new LongSparseArray<>(); @@ -202,19 +203,19 @@ public class DateUtil { } - public static String timeFrameString(long timeInMillis) { + public static String timeFrameString(long timeInMillis, ResourceHelper resourceHelper) { long remainingTimeMinutes = timeInMillis / (1000 * 60); long remainingTimeHours = remainingTimeMinutes / 60; remainingTimeMinutes = remainingTimeMinutes % 60; - return "(" + ((remainingTimeHours > 0) ? (remainingTimeHours + MainApp.gs(R.string.shorthour) + " ") : "") + remainingTimeMinutes + "')"; + return "(" + ((remainingTimeHours > 0) ? (remainingTimeHours + resourceHelper.gs(R.string.shorthour) + " ") : "") + remainingTimeMinutes + "')"; } - public static String sinceString(long timestamp) { - return timeFrameString(System.currentTimeMillis() - timestamp); + public static String sinceString(long timestamp, ResourceHelper resourceHelper) { + return timeFrameString(System.currentTimeMillis() - timestamp, resourceHelper); } - public static String untilString(long timestamp) { - return timeFrameString(timestamp - System.currentTimeMillis()); + public static String untilString(long timestamp, ResourceHelper resourceHelper) { + return timeFrameString(timestamp - System.currentTimeMillis(), resourceHelper); } public static long now() { @@ -247,26 +248,26 @@ public class DateUtil { return TimeZone.getDefault().getOffset(timestamp) / 60000; } - public static String niceTimeScalar(long t) { - String unit = MainApp.gs(R.string.unit_second); + public static String niceTimeScalar(long t, ResourceHelper resourceHelper) { + String unit = resourceHelper.gs(R.string.unit_second); t = t / 1000; - if (t != 1) unit = MainApp.gs(R.string.unit_seconds); + if (t != 1) unit = resourceHelper.gs(R.string.unit_seconds); if (t > 59) { - unit = MainApp.gs(R.string.unit_minute); + unit = resourceHelper.gs(R.string.unit_minute); t = t / 60; - if (t != 1) unit = MainApp.gs(R.string.unit_minutes); + if (t != 1) unit = resourceHelper.gs(R.string.unit_minutes); if (t > 59) { - unit = MainApp.gs(R.string.unit_hour); + unit = resourceHelper.gs(R.string.unit_hour); t = t / 60; - if (t != 1) unit = MainApp.gs(R.string.unit_hours); + if (t != 1) unit = resourceHelper.gs(R.string.unit_hours); if (t > 24) { - unit = MainApp.gs(R.string.unit_day) + "\""; + unit = resourceHelper.gs(R.string.unit_day) + "\""; t = t / 24; - if (t != 1) unit = MainApp.gs(R.string.unit_days) + "\""; + if (t != 1) unit = resourceHelper.gs(R.string.unit_days) + "\""; if (t > 28) { - unit = MainApp.gs(R.string.unit_week) + "\""; + unit = resourceHelper.gs(R.string.unit_week) + "\""; t = t / 7; - if (t != 1) unit = MainApp.gs(R.string.unit_weeks) + "\""; + if (t != 1) unit = resourceHelper.gs(R.string.unit_weeks) + "\""; } } } diff --git a/app/src/main/java/info/nightscout/androidaps/utils/DecimalFormatter.java b/app/src/main/java/info/nightscout/androidaps/utils/DecimalFormatter.java index c013ed89b8..c4ddfc39a4 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/DecimalFormatter.java +++ b/app/src/main/java/info/nightscout/androidaps/utils/DecimalFormatter.java @@ -2,7 +2,7 @@ package info.nightscout.androidaps.utils; import java.text.DecimalFormat; -import info.nightscout.androidaps.plugins.configBuilder.PluginStore; +import info.nightscout.androidaps.interfaces.PumpInterface; /** * Created by mike on 11.07.2016. @@ -45,14 +45,14 @@ public class DecimalFormatter { return format3dec.format(value) + unit; } - public static String toPumpSupportedBolus(double value) { - return PluginStore.Companion.getInstance().getActivePump().getPumpDescription().bolusStep <= 0.051 + public static String toPumpSupportedBolus(double value, PumpInterface pump) { + return pump.getPumpDescription().bolusStep <= 0.051 ? to2Decimal(value) : to1Decimal(value); } - public static DecimalFormat pumpSupportedBolusFormat() { - return PluginStore.Companion.getInstance().getActivePump().getPumpDescription().bolusStep <= 0.051 + public static DecimalFormat pumpSupportedBolusFormat(PumpInterface pump) { + return pump.getPumpDescription().bolusStep <= 0.051 ? new DecimalFormat("0.00") : new DecimalFormat("0.0"); } diff --git a/app/src/main/java/info/nightscout/androidaps/utils/XdripCalibrations.java b/app/src/main/java/info/nightscout/androidaps/utils/XdripCalibrations.java index 4dcf23529c..2b00d25ee3 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/XdripCalibrations.java +++ b/app/src/main/java/info/nightscout/androidaps/utils/XdripCalibrations.java @@ -6,7 +6,6 @@ import android.content.pm.ResolveInfo; import android.os.Bundle; import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import java.util.List; @@ -14,7 +13,7 @@ import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; +import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.services.Intents; /** @@ -35,7 +34,7 @@ public class XdripCalibrations { Context context = MainApp.instance().getApplicationContext(); Bundle bundle = new Bundle(); bundle.putDouble("glucose_number", bg); - bundle.putString("units", ProfileFunctions.getSystemUnits().equals(Constants.MGDL) ? "mgdl" : "mmol"); + bundle.putString("units", ConfigBuilderPlugin.getPlugin().getProfileFunction().getUnits().equals(Constants.MGDL) ? "mgdl" : "mmol"); bundle.putLong("timestamp", System.currentTimeMillis()); Intent intent = new Intent(Intents.ACTION_REMOTE_CALIBRATION); intent.putExtras(bundle); diff --git a/app/src/main/java/info/nightscout/androidaps/utils/extensions/DoubleToSignedString.kt b/app/src/main/java/info/nightscout/androidaps/utils/extensions/DoubleToSignedString.kt index 496cd6b5b7..af942b871e 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/extensions/DoubleToSignedString.kt +++ b/app/src/main/java/info/nightscout/androidaps/utils/extensions/DoubleToSignedString.kt @@ -1,9 +1,10 @@ package info.nightscout.androidaps.utils.extensions +import info.nightscout.androidaps.interfaces.PumpInterface import info.nightscout.androidaps.utils.DecimalFormatter -fun Double.toSignedString(): String { - val formatted = DecimalFormatter.toPumpSupportedBolus(this) +fun Double.toSignedString(pump: PumpInterface): String { + val formatted = DecimalFormatter.toPumpSupportedBolus(this, pump) return if (this > 0) "+$formatted" else formatted } diff --git a/app/src/test/java/info/AAPSMocker.java b/app/src/test/java/info/AAPSMocker.java deleted file mode 100644 index 4c632c4c1e..0000000000 --- a/app/src/test/java/info/AAPSMocker.java +++ /dev/null @@ -1,287 +0,0 @@ -package info; - -import android.content.Context; -import android.content.pm.PackageManager; -import android.content.res.Resources; - -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Assert; -import org.powermock.api.mockito.PowerMockito; - -import java.util.Locale; - -import info.nightscout.androidaps.Constants; -import info.nightscout.androidaps.MainApp; -import info.nightscout.androidaps.R; -import info.nightscout.androidaps.data.IobTotal; -import info.nightscout.androidaps.data.Profile; -import info.nightscout.androidaps.data.ProfileStore; -import info.nightscout.androidaps.db.DatabaseHelper; -import info.nightscout.androidaps.logging.L; -import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; -import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; -import info.nightscout.androidaps.plugins.general.nsclient.NSUpload; -import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin; -import info.nightscout.androidaps.plugins.treatments.TreatmentService; -import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin; -import info.nightscout.androidaps.queue.CommandQueue; -import info.nightscout.androidaps.utils.SP; - -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyBoolean; -import static org.mockito.ArgumentMatchers.anyInt; -import static org.mockito.ArgumentMatchers.anyLong; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -/** - * Created by mike on 23.03.2018. - */ - -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 CommandQueue queue; - public static ConfigBuilderPlugin configBuilderPlugin; - public static ProfileFunctions profileFunctions; - public static ConstraintChecker constraintChecker; - - public static void mockStrings() { - Locale.setDefault(new Locale("en", "US")); - - when(MainApp.gs(R.string.closed_loop_disabled_on_dev_branch)).thenReturn("Running dev version. Closed loop is disabled."); - when(MainApp.gs(R.string.closedmodedisabledinpreferences)).thenReturn("Closed loop mode disabled in preferences"); - when(MainApp.gs(R.string.objectivenotstarted)).thenReturn("Objective %d not started"); - when(MainApp.gs(R.string.novalidbasalrate)).thenReturn("No valid basal rate read from pump"); - when(MainApp.gs(R.string.autosensdisabledinpreferences)).thenReturn("Autosens disabled in preferences"); - when(MainApp.gs(R.string.smbdisabledinpreferences)).thenReturn("SMB disabled in preferences"); - when(MainApp.gs(R.string.pumplimit)).thenReturn("pump limit"); - when(MainApp.gs(R.string.itmustbepositivevalue)).thenReturn("it must be positive value"); - when(MainApp.gs(R.string.maxvalueinpreferences)).thenReturn("max value in preferences"); - when(MainApp.gs(R.string.maxbasalmultiplier)).thenReturn("max basal multiplier"); - when(MainApp.gs(R.string.maxdailybasalmultiplier)).thenReturn("max daily basal multiplier"); - when(MainApp.gs(R.string.pumplimit)).thenReturn("pump limit"); - when(MainApp.gs(R.string.limitingbolus)).thenReturn("Limiting bolus to %.1f U because of %s"); - when(MainApp.gs(R.string.hardlimit)).thenReturn("hard limit"); - when(MainApp.gs(R.string.key_child)).thenReturn("child"); - when(MainApp.gs(R.string.limitingcarbs)).thenReturn("Limiting carbs to %d g because of %s"); - when(MainApp.gs(R.string.limitingiob)).thenReturn("Limiting IOB to %.1f U because of %s"); - when(MainApp.gs(R.string.pumpisnottempbasalcapable)).thenReturn("Pump is not temp basal capable"); - when(MainApp.gs(R.string.loop)).thenReturn("Loop"); - when(MainApp.gs(R.string.loop_shortname)).thenReturn("LOOP"); - when(MainApp.gs(R.string.smbalwaysdisabled)).thenReturn("SMB always and after carbs disabled because active BG source doesn\\'t support advanced filtering"); - when(MainApp.gs(R.string.smbnotallowedinopenloopmode)).thenReturn("SMB not allowed in open loop mode"); - when(MainApp.gs(R.string.Glimp)).thenReturn("Glimp"); - when(MainApp.gs(R.string.glucose)).thenReturn("Glucose"); - when(MainApp.gs(R.string.delta)).thenReturn("Delta"); - when(MainApp.gs(R.string.short_avgdelta)).thenReturn("Short avg. delta"); - when(MainApp.gs(R.string.long_avgdelta)).thenReturn("Long avg. delta"); - when(MainApp.gs(R.string.zerovalueinprofile)).thenReturn("Invalid profile: %s"); - when(MainApp.gs(R.string.success)).thenReturn("Success"); - when(MainApp.gs(R.string.enacted)).thenReturn("Enacted"); - when(MainApp.gs(R.string.comment)).thenReturn("Comment"); - when(MainApp.gs(R.string.smb_shortname)).thenReturn("SMB"); - when(MainApp.gs(R.string.canceltemp)).thenReturn("Cancel temp basal"); - when(MainApp.gs(R.string.duration)).thenReturn("Duration"); - when(MainApp.gs(R.string.percent)).thenReturn("Percent"); - when(MainApp.gs(R.string.absolute)).thenReturn("Absolute"); - when(MainApp.gs(R.string.waitingforpumpresult)).thenReturn("Waiting for result"); - when(MainApp.gs(R.string.insulin_unit_shortname)).thenReturn("U"); - when(MainApp.gs(R.string.minimalbasalvaluereplaced)).thenReturn("Basal value replaced by minimal supported value: %1$s"); - 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"); - when(MainApp.gs(R.string.configbuilder_insulin)).thenReturn("Insulin"); - when(MainApp.gs(R.string.bolusdelivering)).thenReturn("Delivering 0.0U"); - when(MainApp.gs(R.string.profile_per_unit)).thenReturn("/U"); - when(MainApp.gs(R.string.shortday)).thenReturn("d"); - when(MainApp.gs(R.string.shorthour)).thenReturn("h"); - when(MainApp.gs(R.string.profile_carbs_per_unit)).thenReturn("g/U"); - when(MainApp.gs(R.string.profile_ins_units_per_hour)).thenReturn("U/h"); - when(MainApp.gs(R.string.sms_wrongcode)).thenReturn("Wrong code. Command cancelled."); - when(MainApp.gs(R.string.sms_iob)).thenReturn("IOB:"); - when(MainApp.gs(R.string.sms_lastbg)).thenReturn("Last BG:"); - when(MainApp.gs(R.string.sms_minago)).thenReturn("%1$dmin ago"); - when(MainApp.gs(R.string.smscommunicator_remotecommandnotallowed)).thenReturn("Remote command is not allowed"); - when(MainApp.gs(R.string.smscommunicator_stopsmswithcode)).thenReturn("To disable the SMS Remote Service reply with code %1$s.\\n\\nKeep in mind that you\\'ll able to reactivate it directly from the AAPS master smartphone only."); - when(MainApp.gs(R.string.smscommunicator_mealbolusreplywithcode)).thenReturn("To deliver meal bolus %1$.2fU reply with code %2$s."); - when(MainApp.gs(R.string.smscommunicator_temptargetwithcode)).thenReturn("To set the Temp Target %1$s reply with code %2$s"); - when(MainApp.gs(R.string.smscommunicator_temptargetcancel)).thenReturn("To cancel Temp Target reply with code %1$s"); - when(MainApp.gs(R.string.smscommunicator_stoppedsms)).thenReturn("SMS Remote Service stopped. To reactivate it, use AAPS on master smartphone."); - when(MainApp.gs(R.string.smscommunicator_tt_set)).thenReturn("Target %1$s for %2$d minutes set successfully"); - when(MainApp.gs(R.string.smscommunicator_tt_canceled)).thenReturn("Temp Target canceled successfully"); - when(MainApp.gs(R.string.loopsuspendedfor)).thenReturn("Suspended (%1$d m)"); - when(MainApp.gs(R.string.smscommunicator_loopisdisabled)).thenReturn("Loop is disabled"); - when(MainApp.gs(R.string.smscommunicator_loopisenabled)).thenReturn("Loop is enabled"); - when(MainApp.gs(R.string.wrongformat)).thenReturn("Wrong format"); - when(MainApp.gs(R.string.smscommunicator_loophasbeendisabled)).thenReturn("Loop has been disabled"); - when(MainApp.gs(R.string.smscommunicator_loophasbeenenabled)).thenReturn("Loop has been enabled"); - when(MainApp.gs(R.string.smscommunicator_tempbasalcanceled)).thenReturn("Temp basal canceled"); - when(MainApp.gs(R.string.smscommunicator_loopresumed)).thenReturn("Loop resumed"); - when(MainApp.gs(R.string.smscommunicator_wrongduration)).thenReturn("Wrong duration"); - when(MainApp.gs(R.string.smscommunicator_suspendreplywithcode)).thenReturn("To suspend loop for %1$d minutes reply with code %2$s"); - when(MainApp.gs(R.string.smscommunicator_loopsuspended)).thenReturn("Loop suspended"); - when(MainApp.gs(R.string.smscommunicator_unknowncommand)).thenReturn("Unknown command or wrong reply"); - when(MainApp.gs(R.string.notconfigured)).thenReturn("Not configured"); - when(MainApp.gs(R.string.smscommunicator_profilereplywithcode)).thenReturn("To switch profile to %1$s %2$d%% reply with code %3$s"); - when(MainApp.gs(R.string.profileswitchcreated)).thenReturn("Profile switch created"); - when(MainApp.gs(R.string.smscommunicator_basalstopreplywithcode)).thenReturn("To stop temp basal reply with code %1$s"); - when(MainApp.gs(R.string.smscommunicator_basalpctreplywithcode)).thenReturn("To start basal %1$d%% for %2$d min reply with code %3$s"); - when(MainApp.gs(R.string.smscommunicator_tempbasalset_percent)).thenReturn("Temp basal %1$d%% for %2$d min started successfully"); - when(MainApp.gs(R.string.smscommunicator_basalreplywithcode)).thenReturn("To start basal %1$.2fU/h for %2$d min reply with code %3$s"); - when(MainApp.gs(R.string.smscommunicator_tempbasalset)).thenReturn("Temp basal %1$.2fU/h for %2$d min started successfully"); - when(MainApp.gs(R.string.smscommunicator_extendedstopreplywithcode)).thenReturn("To stop extended bolus reply with code %1$s"); - when(MainApp.gs(R.string.smscommunicator_extendedcanceled)).thenReturn("Extended bolus canceled"); - when(MainApp.gs(R.string.smscommunicator_extendedreplywithcode)).thenReturn("To start extended bolus %1$.2fU for %2$d min reply with code %3$s"); - when(MainApp.gs(R.string.smscommunicator_extendedset)).thenReturn("Extended bolus %1$.2fU for %2$d min started successfully"); - when(MainApp.gs(R.string.smscommunicator_bolusreplywithcode)).thenReturn("To deliver bolus %1$.2fU reply with code %2$s"); - when(MainApp.gs(R.string.smscommunicator_bolusdelivered)).thenReturn("Bolus %1$.2fU delivered successfully"); - when(MainApp.gs(R.string.smscommunicator_remotebolusnotallowed)).thenReturn("Remote bolus not available. Try again later."); - when(MainApp.gs(R.string.smscommunicator_calibrationreplywithcode)).thenReturn("To send calibration %1$.2f reply with code %2$s"); - when(MainApp.gs(R.string.smscommunicator_calibrationsent)).thenReturn("Calibration sent. Receiving must be enabled in xDrip."); - when(MainApp.gs(R.string.pumpsuspended)).thenReturn("Pump suspended"); - when(MainApp.gs(R.string.cob)).thenReturn("COB"); - when(MainApp.gs(R.string.value_unavailable_short)).thenReturn("n/a"); - when(MainApp.gs(R.string.starttemptarget)).thenReturn("Start temp target"); - when(MainApp.gs(R.string.stoptemptarget)).thenReturn("Stop temp target"); - when(MainApp.gs(R.string.disableloop)).thenReturn("Disable loop"); - when(MainApp.gs(R.string.enableloop)).thenReturn("Enable loop"); - when(MainApp.gs(R.string.resumeloop)).thenReturn("Resume loop"); - when(MainApp.gs(R.string.suspendloop)).thenReturn("Suspend loop"); - when(MainApp.gs(R.string.pumpNotInitialized)).thenReturn("Pump not initialized!"); - when(MainApp.gs(R.string.increasingmaxbasal)).thenReturn("Increasing max basal value because setting is lower than your max basal in profile"); - when(MainApp.gs(R.string.overview_bolusprogress_delivered)).thenReturn("Delivered"); - when(MainApp.gs(R.string.smscommunicator_mealbolusreplywithcode)).thenReturn("To deliver meal bolus %1$.2fU reply with code %2$s"); - when(MainApp.gs(R.string.smscommunicator_mealbolusdelivered)).thenReturn("Meal Bolus %1$.2fU delivered successfully"); - when(MainApp.gs(R.string.smscommunicator_mealbolusdelivered_tt)).thenReturn("Target %1$s for %2$d minutes"); - when(MainApp.gs(R.string.smscommunicator_carbsreplywithcode)).thenReturn("To enter %1$dg at %2$s reply with code %3$s"); - when(MainApp.gs(R.string.smscommunicator_carbsset)).thenReturn("Carbs %1$dg entered successfully"); - } - - public static MainApp mockMainApp() { - System.setProperty("disableFirebase", "true"); - PowerMockito.mockStatic(MainApp.class); - MainApp mainApp = mock(MainApp.class); - when(MainApp.instance()).thenReturn(mainApp); - - return mainApp; - } - - public static void mockConfigBuilder() { - PowerMockito.mockStatic(ConfigBuilderPlugin.class); - configBuilderPlugin = mock(ConfigBuilderPlugin.class); - when(ConfigBuilderPlugin.getPlugin()).thenReturn(configBuilderPlugin); - } - - public static void mockSP() { - PowerMockito.mockStatic(SP.class); - when(SP.getLong(anyInt(), anyLong())).thenReturn(0L); - when(SP.getBoolean(anyInt(), anyBoolean())).thenReturn(false); - when(SP.getInt(anyInt(), anyInt())).thenReturn(0); - when(SP.getString(anyInt(), anyString())).thenReturn(""); - } - - public static void mockL() { - PowerMockito.mockStatic(L.class); - when(L.isEnabled(any())).thenReturn(true); - } - - public static void mockNSUpload() { - PowerMockito.mockStatic(NSUpload.class); - } - - public static void mockApplicationContext() { - Context mockedContext = mock(Context.class); - Resources mResources = mock(Resources.class); - when(MainApp.instance().getApplicationContext()).thenReturn(mockedContext); - when(mockedContext.getResources()).thenReturn(mResources); - PackageManager packageManager = mock(PackageManager.class); - when(mockedContext.getPackageManager()).thenReturn(packageManager); - } - - public static DatabaseHelper mockDatabaseHelper() { - DatabaseHelper databaseHelper = mock(DatabaseHelper.class); - when(MainApp.getDbHelper()).thenReturn(databaseHelper); - return databaseHelper; - } - - public static void mockCommandQueue() { - queue = mock(CommandQueue.class); - when(ConfigBuilderPlugin.getPlugin().getCommandQueue()).thenReturn(queue); - } - - public static TreatmentsPlugin mockTreatmentPlugin() { - PowerMockito.mockStatic(TreatmentsPlugin.class); - TreatmentsPlugin treatmentsPlugin = PowerMockito.mock(TreatmentsPlugin.class); - when(TreatmentsPlugin.getPlugin()).thenReturn(treatmentsPlugin); - when(treatmentsPlugin.getLastCalculationTreatments()).thenReturn(new IobTotal(0)); - when(treatmentsPlugin.getLastCalculationTempBasals()).thenReturn(new IobTotal(0)); - - TreatmentService treatmentService = PowerMockito.mock(TreatmentService.class); - when(treatmentsPlugin.getService()).thenReturn(treatmentService); - return treatmentsPlugin; - } - - public static void mockTreatmentService() { - TreatmentService treatmentService = PowerMockito.mock(TreatmentService.class); - try { - PowerMockito.whenNew(TreatmentService.class).withNoArguments().thenReturn(treatmentService); - } catch (Exception e) { - } - - } - - /* - public static Profile getValidProfile() { - try { - if (profile == null) - profile = new Profile(new JSONObject(validProfile), Constants.MGDL); - } catch (JSONException ignored) { - } - 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; - } - - public static void mockProfileFunctions() { - PowerMockito.mockStatic(ProfileFunctions.class); - profileFunctions = PowerMockito.mock(ProfileFunctions.class); - PowerMockito.when(ProfileFunctions.getSystemUnits()).thenReturn(Constants.MGDL); - PowerMockito.when(ProfileFunctions.getInstance()).thenReturn(profileFunctions); - profile = getValidProfile(); - PowerMockito.when(ProfileFunctions.getInstance().getProfile()).thenReturn(profile); - PowerMockito.when(ProfileFunctions.getInstance().getProfileName()).thenReturn(TESTPROFILENAME); - } - */ - public static IobCobCalculatorPlugin mockIobCobCalculatorPlugin() { - PowerMockito.mockStatic(IobCobCalculatorPlugin.class); - IobCobCalculatorPlugin iobCobCalculatorPlugin = PowerMockito.mock(IobCobCalculatorPlugin.class); - PowerMockito.when(IobCobCalculatorPlugin.getPlugin()).thenReturn(iobCobCalculatorPlugin); - Object dataLock = new Object(); - PowerMockito.when(iobCobCalculatorPlugin.getDataLock()).thenReturn(dataLock); - return iobCobCalculatorPlugin; - } - -} diff --git a/app/src/test/java/info/BundleMock.java b/app/src/test/java/info/BundleMock.java deleted file mode 100644 index 62b4f28db6..0000000000 --- a/app/src/test/java/info/BundleMock.java +++ /dev/null @@ -1,223 +0,0 @@ -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()); - } - - public static Bundle mock(final HashMap 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 get = new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - return map.get(invocation.getArguments()[0]); - } - }; - Answer getOrDefault = new Answer() { - @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; - } -} \ No newline at end of file diff --git a/app/src/test/java/info/SPMocker.java b/app/src/test/java/info/SPMocker.java deleted file mode 100644 index cfed7f6b11..0000000000 --- a/app/src/test/java/info/SPMocker.java +++ /dev/null @@ -1,68 +0,0 @@ -package info; - -import org.junit.Assert; -import org.mockito.ArgumentMatchers; -import org.powermock.api.mockito.PowerMockito; - -import java.util.HashMap; - -import info.nightscout.androidaps.utils.SP; - -public class SPMocker { - - static HashMap data = new HashMap<>(); - - public static void prepareMock() { - PowerMockito.mockStatic(SP.class); - - try { - 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); - System.out.print("putString " + key + " " + value + "\n"); - return null; - }); - - 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: " + e.getMessage()); - } - - } - -} diff --git a/app/src/test/java/info/TestBase.kt b/app/src/test/java/info/TestBase.kt index 89cc1cc71c..2153d6d753 100644 --- a/app/src/test/java/info/TestBase.kt +++ b/app/src/test/java/info/TestBase.kt @@ -35,6 +35,7 @@ open class TestBase { @Before fun setupLocale() { Locale.setDefault(Locale.ENGLISH) + System.setProperty("disableFirebase", "true") } // Workaround for Kotlin nullability. diff --git a/app/src/test/java/info/nightscout/androidaps/db/BgReadingTest.kt b/app/src/test/java/info/nightscout/androidaps/db/BgReadingTest.kt index 5769b15c8f..792b85f515 100644 --- a/app/src/test/java/info/nightscout/androidaps/db/BgReadingTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/db/BgReadingTest.kt @@ -2,7 +2,6 @@ package info.nightscout.androidaps.db import dagger.android.AndroidInjector import dagger.android.HasAndroidInjector -import info.AAPSMocker import info.TestBase import info.nightscout.androidaps.Constants import info.nightscout.androidaps.MainApp @@ -21,6 +20,7 @@ import org.mockito.ArgumentMatchers import org.mockito.Mock import org.mockito.Mockito import org.mockito.Mockito.`when` +import org.powermock.api.mockito.PowerMockito import org.powermock.core.classloader.annotations.PrepareForTest import org.powermock.modules.junit4.PowerMockRunner import java.util.* @@ -48,7 +48,7 @@ class BgReadingTest : TestBase() { @Test fun valueToUnits() { - val bgReading = BgReading() + val bgReading = BgReading(injector) bgReading.value = 18.0 Assert.assertEquals(18.0, bgReading.valueToUnits(Constants.MGDL) * 1, 0.01) Assert.assertEquals(1.0, bgReading.valueToUnits(Constants.MMOL) * 1, 0.01) @@ -56,7 +56,7 @@ class BgReadingTest : TestBase() { @Test fun directionToSymbol() { - val bgReading = BgReading() + val bgReading = BgReading(injector) bgReading.direction = "DoubleDown" Assert.assertEquals("\u21ca", bgReading.directionToSymbol()) bgReading.direction = "SingleDown" @@ -76,7 +76,7 @@ class BgReadingTest : TestBase() { } @Test fun dateTest() { - val bgReading = BgReading() + val bgReading = BgReading(injector) val now = System.currentTimeMillis() bgReading.date = now val nowDate = Date(now) @@ -85,14 +85,17 @@ class BgReadingTest : TestBase() { } @Test fun valueTest() { - val bgReading = BgReading() + val bgReading = BgReading(injector) val valueToSet = 81.0 // 4.5 mmol Assert.assertEquals(81.0, bgReading.value(valueToSet).value, 0.01) } @Test fun copyFromTest() { - val bgReading = BgReading() - val copy = BgReading() + val databaseHelper = Mockito.mock(DatabaseHelper::class.java) + `when`(MainApp.getDbHelper()).thenReturn(databaseHelper) + setReadings(72, 0) + val bgReading = BgReading(injector) + val copy = BgReading(injector) bgReading.value = 81.0 val now = System.currentTimeMillis() bgReading.date = now @@ -105,21 +108,22 @@ class BgReadingTest : TestBase() { @Test fun isEqualTest() { - val bgReading = BgReading() - val copy = BgReading() + val bgReading = BgReading(injector) + val copy = BgReading(injector) bgReading.value = 81.0 val now = System.currentTimeMillis() bgReading.date = now copy.date = now copy.copyFrom(bgReading) Assert.assertTrue(copy.isEqual(bgReading)) - Assert.assertFalse(copy.isEqual(BgReading())) + Assert.assertFalse(copy.isEqual(BgReading(injector))) } @Test fun calculateDirection() { - val bgReading = BgReading() + val bgReading = BgReading(injector) val bgReadingsList: List? = null - AAPSMocker.mockDatabaseHelper() + val databaseHelper = Mockito.mock(DatabaseHelper::class.java) + `when`(MainApp.getDbHelper()).thenReturn(databaseHelper) `when`(MainApp.getDbHelper().getAllBgreadingsDataFromTime(ArgumentMatchers.anyLong(), ArgumentMatchers.anyBoolean())).thenReturn(bgReadingsList) Assert.assertEquals("NONE", bgReading.calculateDirection()) setReadings(72, 0) @@ -140,19 +144,19 @@ class BgReadingTest : TestBase() { @Before fun prepareMock() { - val mainApp = AAPSMocker.mockMainApp() - AAPSMocker.mockApplicationContext() - AAPSMocker.mockSP() - AAPSMocker.mockL() - AAPSMocker.mockDatabaseHelper() - `when`(mainApp.androidInjector()).thenReturn(injector.androidInjector()) + val mainApp = PowerMockito.mockStatic(MainApp::class.java) +// AAPSMocker.mockApplicationContext() +// AAPSMocker.mockSP() +// AAPSMocker.mockL() +// AAPSMocker.mockDatabaseHelper() +// `when`(mainApp.androidInjector()).thenReturn(injector.androidInjector()) } fun setReadings(current_value: Int, previous_value: Int) { - val now = BgReading() + val now = BgReading(injector) now.value = current_value.toDouble() now.date = System.currentTimeMillis() - val previous = BgReading() + val previous = BgReading(injector) previous.value = previous_value.toDouble() previous.date = System.currentTimeMillis() - 6 * 60 * 1000L val bgReadings: MutableList = mutableListOf() diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/aps/loop/APSResultTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/aps/loop/APSResultTest.kt index c4c06d6449..ba1dc347be 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/aps/loop/APSResultTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/aps/loop/APSResultTest.kt @@ -49,7 +49,7 @@ class APSResultTest : TestBase() { it.aapsLogger = aapsLogger it.constraintChecker = constraintChecker it.sp = sp - it.activePluginProvider = activePluginProvider + it.activePlugin = activePluginProvider it.treatmentsPlugin = treatmentsPlugin it.profileFunction = profileFunction it.resourceHelper = resourceHelper @@ -170,7 +170,7 @@ class APSResultTest : TestBase() { it.aapsLogger = aapsLogger it.constraintChecker = constraintChecker it.sp = sp - it.activePluginProvider = activePluginProvider + it.activePlugin = activePluginProvider it.treatmentsPlugin = treatmentsPlugin it.profileFunction = profileFunction it.resourceHelper = resourceHelper @@ -187,7 +187,7 @@ class APSResultTest : TestBase() { it.aapsLogger = aapsLogger it.constraintChecker = constraintChecker it.sp = sp - it.activePluginProvider = activePluginProvider + it.activePlugin = activePluginProvider it.treatmentsPlugin = treatmentsPlugin it.profileFunction = profileFunction it.resourceHelper = resourceHelper diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderPluginTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderPluginTest.kt index 40825ca2b4..24d35c5139 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderPluginTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderPluginTest.kt @@ -8,12 +8,8 @@ import info.nightscout.androidaps.interfaces.ActivePluginProvider import info.nightscout.androidaps.interfaces.CommandQueueProvider import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.plugins.bus.RxBusWrapper -import info.nightscout.androidaps.plugins.insulin.InsulinOrefRapidActingPlugin -import info.nightscout.androidaps.plugins.profile.local.LocalProfilePlugin import info.nightscout.androidaps.plugins.profile.ns.NSProfilePlugin import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin -import info.nightscout.androidaps.plugins.sensitivity.SensitivityOref0Plugin -import info.nightscout.androidaps.plugins.sensitivity.SensitivityOref1Plugin import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.sharedPreferences.SP @@ -25,21 +21,17 @@ import org.powermock.core.classloader.annotations.PrepareForTest import org.powermock.modules.junit4.PowerMockRunner @RunWith(PowerMockRunner::class) -@PrepareForTest(NSProfilePlugin::class) class ConfigBuilderPluginTest : TestBase() { - @Mock lateinit var insulinOrefRapidActingPlugin: Lazy - @Mock lateinit var localProfilePlugin: Lazy @Mock lateinit var virtualPumpPlugin: Lazy @Mock lateinit var treatmentsPlugin: Lazy - @Mock lateinit var sensitivityOref0Plugin: Lazy - @Mock lateinit var sensitivityOref1Plugin: Lazy @Mock lateinit var sp: SP @Mock lateinit var aapsLogger: AAPSLogger @Mock lateinit var resourceHelper: ResourceHelper @Mock lateinit var commandQueue: CommandQueueProvider @Mock lateinit var activePlugin: ActivePluginProvider + @Mock lateinit var profileFunction: ProfileFunction lateinit var configBuilderPlugin: ConfigBuilderPlugin @@ -56,6 +48,6 @@ class ConfigBuilderPluginTest : TestBase() { @Before fun prepareMock() { - configBuilderPlugin = ConfigBuilderPlugin(activePlugin, injector, sp, RxBusWrapper(), aapsLogger, resourceHelper, commandQueue) + configBuilderPlugin = ConfigBuilderPlugin(activePlugin, injector, sp, RxBusWrapper(), aapsLogger, resourceHelper, profileFunction) } } \ No newline at end of file diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionStartTempTargetTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionStartTempTargetTest.kt index 46c885bf99..fe4abf1d7c 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionStartTempTargetTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionStartTempTargetTest.kt @@ -1,6 +1,5 @@ package info.nightscout.androidaps.plugins.general.automation.actions -import info.AAPSMocker import info.nightscout.androidaps.Constants import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.R @@ -13,6 +12,7 @@ import org.junit.Test import org.junit.runner.RunWith import org.mockito.Mockito import org.mockito.Mockito.`when` +import org.powermock.api.mockito.PowerMockito import org.powermock.core.classloader.annotations.PrepareForTest import org.powermock.modules.junit4.PowerMockRunner @@ -24,7 +24,7 @@ class ActionStartTempTargetTest : ActionsTestBase() { @Before fun setup() { - AAPSMocker.mockMainApp() + PowerMockito.mockStatic(MainApp::class.java) `when`(resourceHelper.gs(R.string.starttemptarget)).thenReturn("Start temp target") sut = ActionStartTempTarget(injector) diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionStopTempTargetTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionStopTempTargetTest.kt index ae4bd63747..069d06cfbe 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionStopTempTargetTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionStopTempTargetTest.kt @@ -1,6 +1,5 @@ package info.nightscout.androidaps.plugins.general.automation.actions -import info.AAPSMocker import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.R import info.nightscout.androidaps.queue.Callback @@ -21,7 +20,6 @@ class ActionStopTempTargetTest : ActionsTestBase() { @Before fun setup() { - AAPSMocker.mockMainApp() `when`(resourceHelper.gs(R.string.stoptemptarget)).thenReturn("Stop temp target") sut = ActionStopTempTarget(injector) diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/elements/InputBgTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/elements/InputBgTest.kt index 848cb0b6c9..d565a4a13a 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/elements/InputBgTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/elements/InputBgTest.kt @@ -1,18 +1,15 @@ package info.nightscout.androidaps.plugins.general.automation.elements import info.nightscout.androidaps.Constants -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions import info.nightscout.androidaps.plugins.general.automation.triggers.TriggerTestBase import org.junit.Assert import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.mockito.Mockito.`when` -import org.powermock.core.classloader.annotations.PrepareForTest import org.powermock.modules.junit4.PowerMockRunner @RunWith(PowerMockRunner::class) -@PrepareForTest(ProfileFunctions::class) class InputBgTest : TriggerTestBase() { @Test diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerAutosensValueTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerAutosensValueTest.kt index 4a5fdd4842..a91fcf6d06 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerAutosensValueTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerAutosensValueTest.kt @@ -2,7 +2,6 @@ package info.nightscout.androidaps.plugins.general.automation.triggers import com.google.common.base.Optional import info.nightscout.androidaps.R -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions import info.nightscout.androidaps.plugins.general.automation.elements.Comparator import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensData import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin @@ -20,7 +19,7 @@ import org.powermock.core.classloader.annotations.PrepareForTest import org.powermock.modules.junit4.PowerMockRunner @RunWith(PowerMockRunner::class) -@PrepareForTest(ProfileFunctions::class, DateUtil::class, IobCobCalculatorPlugin::class) +@PrepareForTest(DateUtil::class, IobCobCalculatorPlugin::class) class TriggerAutosensValueTest : TriggerTestBase() { var now = 1514766900000L diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerBolusAgoTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerBolusAgoTest.kt index 7971bbc7ef..fbc4cd8a8b 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerBolusAgoTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerBolusAgoTest.kt @@ -2,7 +2,6 @@ package info.nightscout.androidaps.plugins.general.automation.triggers import com.google.common.base.Optional import info.nightscout.androidaps.R -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions import info.nightscout.androidaps.plugins.general.automation.elements.Comparator import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin import info.nightscout.androidaps.utils.DateUtil @@ -18,7 +17,7 @@ import org.powermock.core.classloader.annotations.PrepareForTest import org.powermock.modules.junit4.PowerMockRunner @RunWith(PowerMockRunner::class) -@PrepareForTest(ProfileFunctions::class, DateUtil::class, TreatmentsPlugin::class) +@PrepareForTest(DateUtil::class, TreatmentsPlugin::class) class TriggerBolusAgoTest : TriggerTestBase() { var now = 1514766900000L diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerLocationTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerLocationTest.kt index e3c40047a7..30e6081b29 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerLocationTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerLocationTest.kt @@ -3,7 +3,6 @@ package info.nightscout.androidaps.plugins.general.automation.triggers import android.location.Location import com.google.common.base.Optional import info.nightscout.androidaps.R -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions import info.nightscout.androidaps.plugins.general.automation.elements.InputLocationMode import info.nightscout.androidaps.services.LocationService import info.nightscout.androidaps.utils.DateUtil @@ -19,7 +18,7 @@ import org.powermock.core.classloader.annotations.PrepareForTest import org.powermock.modules.junit4.PowerMockRunner @RunWith(PowerMockRunner::class) -@PrepareForTest(ProfileFunctions::class, DateUtil::class, LocationService::class) +@PrepareForTest(DateUtil::class, LocationService::class) class TriggerLocationTest : TriggerTestBase() { var now = 1514766900000L @@ -30,7 +29,6 @@ class TriggerLocationTest : TriggerTestBase() { `when`(DateUtil.now()).thenReturn(now) PowerMockito.spy(LocationService::class.java) `when`(locationDataContainer.lastLocation).thenReturn(mockedLocation()) -// MockitoAnnotations.initMocks(this) } @Test fun copyConstructorTest() { diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerProfilePercentTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerProfilePercentTest.kt index 85af485a26..9a03087c4e 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerProfilePercentTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerProfilePercentTest.kt @@ -2,7 +2,6 @@ package info.nightscout.androidaps.plugins.general.automation.triggers import com.google.common.base.Optional import info.nightscout.androidaps.R -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions import info.nightscout.androidaps.plugins.general.automation.elements.Comparator import info.nightscout.androidaps.utils.DateUtil import org.json.JSONException @@ -17,7 +16,7 @@ import org.powermock.core.classloader.annotations.PrepareForTest import org.powermock.modules.junit4.PowerMockRunner @RunWith(PowerMockRunner::class) -@PrepareForTest(ProfileFunctions::class, DateUtil::class) +@PrepareForTest(DateUtil::class) class TriggerProfilePercentTest : TriggerTestBase() { private val now = 1514766900000L diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerPumpLastConnectionTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerPumpLastConnectionTest.kt index eba694fbdd..d834fcd642 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerPumpLastConnectionTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerPumpLastConnectionTest.kt @@ -2,7 +2,6 @@ package info.nightscout.androidaps.plugins.general.automation.triggers import com.google.common.base.Optional import info.nightscout.androidaps.R -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions import info.nightscout.androidaps.plugins.general.automation.elements.Comparator import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin import info.nightscout.androidaps.utils.DateUtil @@ -17,7 +16,7 @@ import org.powermock.core.classloader.annotations.PrepareForTest import org.powermock.modules.junit4.PowerMockRunner @RunWith(PowerMockRunner::class) -@PrepareForTest(ProfileFunctions::class, DateUtil::class, VirtualPumpPlugin::class) +@PrepareForTest(DateUtil::class, VirtualPumpPlugin::class) class TriggerPumpLastConnectionTest : TriggerTestBase() { @Mock lateinit var virtualPumpPlugin: VirtualPumpPlugin diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTempTargetTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTempTargetTest.kt index 7cf3110b04..9632e3aa78 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTempTargetTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTempTargetTest.kt @@ -3,7 +3,6 @@ package info.nightscout.androidaps.plugins.general.automation.triggers import com.google.common.base.Optional import info.nightscout.androidaps.R import info.nightscout.androidaps.db.TempTarget -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions import info.nightscout.androidaps.plugins.general.automation.elements.ComparatorExists import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin import info.nightscout.androidaps.utils.DateUtil @@ -18,7 +17,7 @@ import org.powermock.core.classloader.annotations.PrepareForTest import org.powermock.modules.junit4.PowerMockRunner @RunWith(PowerMockRunner::class) -@PrepareForTest(ProfileFunctions::class, DateUtil::class, TreatmentsPlugin::class) +@PrepareForTest(DateUtil::class, TreatmentsPlugin::class) class TriggerTempTargetTest : TriggerTestBase() { var now = 1514766900000L diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPluginTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPluginTest.kt index 801066498d..f16ebbed09 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPluginTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPluginTest.kt @@ -3,7 +3,6 @@ package info.nightscout.androidaps.plugins.general.smsCommunicator import android.telephony.SmsManager import dagger.android.AndroidInjector import dagger.android.HasAndroidInjector -import info.AAPSMocker import info.TestBase import info.nightscout.androidaps.Constants import info.nightscout.androidaps.MainApp @@ -53,7 +52,6 @@ import java.util.* @RunWith(PowerMockRunner::class) @PrepareForTest(ConstraintChecker::class, FabricPrivacy::class, VirtualPumpPlugin::class, XdripCalibrations::class, SmsManager::class, RxBusWrapper::class, CommandQueue::class, LocalProfilePlugin::class, DateUtil::class, IobCobCalculatorPlugin::class, MainApp::class) -//@PrepareForTest(L::class, SP::class, resourceHelper::class, DateUtil::class, ProfileFunctions::class, TreatmentsPlugin::class, IobCobCalculatorPlugin::class, CommandQueue::class, ConfigBuilderPlugin::class, NSUpload::class, ProfileInterface::class, LocalProfilePlugin::class, VirtualPumpPlugin::class, LoopPlugin::class) class SmsCommunicatorPluginTest : TestBase() { @Mock lateinit var aapsLogger: AAPSLogger @@ -101,11 +99,8 @@ class SmsCommunicatorPluginTest : TestBase() { private var hasBeenRun = false @Before fun prepareTests() { - val mainApp = AAPSMocker.mockMainApp() - `when`(mainApp.androidInjector()).thenReturn(injector.androidInjector()) - rxBus = RxBusWrapper() - val reading = BgReading() + val reading = BgReading(injector) reading.value = 100.0 val bgList: MutableList = ArrayList() bgList.add(reading) diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_APS_Set_Event_HistoryTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_APS_Set_Event_HistoryTest.kt index 4c293eb5fa..33e343ee08 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_APS_Set_Event_HistoryTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_APS_Set_Event_HistoryTest.kt @@ -1,19 +1,10 @@ package info.nightscout.androidaps.plugins.pump.danaRS.comm -import info.AAPSMocker -import info.nightscout.androidaps.interfaces.ActivePluginProvider -import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump -import info.nightscout.androidaps.plugins.pump.danaRS.DanaRSPlugin import info.nightscout.androidaps.utils.DateUtil -import info.nightscout.androidaps.utils.resources.ResourceHelper import org.junit.Assert -import org.junit.Before import org.junit.Test import org.junit.runner.RunWith -import org.mockito.Mock -import org.powermock.api.mockito.PowerMockito import org.powermock.core.classloader.annotations.PrepareForTest import org.powermock.modules.junit4.PowerMockRunner diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/pump/medtronic/data/dto/BasalProfileUTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/pump/medtronic/data/dto/BasalProfileUTest.java index 2c0e00b963..6511117e9b 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/pump/medtronic/data/dto/BasalProfileUTest.java +++ b/app/src/test/java/info/nightscout/androidaps/plugins/pump/medtronic/data/dto/BasalProfileUTest.java @@ -7,8 +7,6 @@ import org.junit.Ignore; import org.junit.Test; import org.powermock.api.mockito.PowerMockito; -import info.AAPSMocker; -import info.SPMocker; import info.nightscout.androidaps.interfaces.PumpDescription; import info.nightscout.androidaps.plugins.pump.common.defs.PumpType; import info.nightscout.androidaps.plugins.pump.medtronic.driver.MedtronicPumpStatus; @@ -29,11 +27,11 @@ public class BasalProfileUTest { // MainApp mainApp = new MainApp(); @Before public void initMocking() { - AAPSMocker.mockMainApp(); - AAPSMocker.mockStrings(); - AAPSMocker.mockDatabaseHelper(); +// AAPSMocker.mockMainApp(); +// AAPSMocker.mockStrings(); +// AAPSMocker.mockDatabaseHelper(); - SPMocker.prepareMock(); +// SPMocker.prepareMock(); PowerMockito.mockStatic(DateUtil.class); when(DateUtil.now()).thenReturn(1514766900000L + T.mins(1).msecs()); diff --git a/app/src/test/java/info/nightscout/androidaps/utils/DateUtilTest.java b/app/src/test/java/info/nightscout/androidaps/utils/DateUtilTest.java deleted file mode 100644 index 4346023695..0000000000 --- a/app/src/test/java/info/nightscout/androidaps/utils/DateUtilTest.java +++ /dev/null @@ -1,97 +0,0 @@ -package info.nightscout.androidaps.utils; - - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; - -import java.util.Date; - -import info.AAPSMocker; -import info.nightscout.androidaps.MainApp; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -/** - * Created by mike on 20.11.2017. - */ -@RunWith(PowerMockRunner.class) -@PrepareForTest({MainApp.class}) -public class DateUtilTest { - - @Test - public void fromISODateStringTest() throws Exception { - assertEquals(1511124634417L, DateUtil.fromISODateString("2017-11-19T22:50:34.417+0200").getTime()); - assertEquals(1511124634000L, DateUtil.fromISODateString("2017-11-19T22:50:34+0200").getTime()); - assertEquals(1512317365000L, DateUtil.fromISODateString("2017-12-03T16:09:25.000Z").getTime()); - assertEquals(1513902750000L, DateUtil.fromISODateString("2017-12-22T00:32:30Z").getTime()); - } - - @Test - public void toISOStringTest() throws Exception { - assertEquals("2017-12-22T00:32:30Z", DateUtil.toISOString(new Date(1513902750000L))); - assertEquals("2017-12-22T00:32:30Z", DateUtil.toISOString(1513902750000L)); - } - - @Test - public void toDateTest() { - assertTrue(DateUtil.toDate((int) (T.hours(1).secs() + T.mins(1).secs() + 1)).toString().contains("01:01:00")); - } - - @Test - public void toSecondsTest() { - Assert.assertEquals(3600, DateUtil.toSeconds("01:00")); - Assert.assertEquals(3600, DateUtil.toSeconds("01:00 a.m.")); - Assert.assertEquals(3600, DateUtil.toSeconds("01:00 AM")); - } - - @Test - public void dateStringTest() { - assertTrue(DateUtil.dateString(new Date(1513902750000L)).contains("22")); - assertTrue(DateUtil.dateString(1513902750000L).contains("22")); - } - - @Test - public void timeStringTest() { - assertTrue(DateUtil.timeString(new Date(1513902750000L)).contains("32")); - assertTrue(DateUtil.timeString(1513902750000L).contains("32")); - } - - @Test - public void dateAndTimeStringTest() { - assertTrue(DateUtil.dateAndTimeString(1513902750000L).contains("22")); - assertTrue(DateUtil.dateAndTimeString(1513902750000L).contains("32")); - assertTrue(DateUtil.dateAndTimeString(new Date(1513902750000L)).contains("22")); - assertTrue(DateUtil.dateAndTimeString(new Date(1513902750000L)).contains("32")); - } - - @Test - public void dateAndTimeRangeStringTest() { - assertTrue(DateUtil.dateAndTimeRangeString(1513902750000L, 1513902750000L).contains("22")); - assertTrue(DateUtil.dateAndTimeRangeString(1513902750000L, 1513902750000L).contains("32")); - assertTrue(DateUtil.dateAndTimeRangeString(1513902750000L, 1513902750000L).contains("22")); - assertTrue(DateUtil.dateAndTimeRangeString(1513902750000L, 1513902750000L).contains("32")); - } - - /* - @Test - public void timeStringFromSecondsTest() { - Assert.assertEquals("1:00 AM", DateUtil.timeStringFromSeconds((int) T.hours(1).secs())); - } - */ - - @Test - public void timeFrameStringTest() { - Assert.assertEquals("(1h 1')", DateUtil.timeFrameString((T.hours(1).msecs() + T.mins(1).msecs()))); - } - - @Before - public void prepareMock() { - AAPSMocker.mockMainApp(); - AAPSMocker.mockStrings(); - } -} diff --git a/app/src/test/java/info/nightscout/androidaps/utils/DateUtilTest.kt b/app/src/test/java/info/nightscout/androidaps/utils/DateUtilTest.kt new file mode 100644 index 0000000000..d8899d07ed --- /dev/null +++ b/app/src/test/java/info/nightscout/androidaps/utils/DateUtilTest.kt @@ -0,0 +1,77 @@ +package info.nightscout.androidaps.utils + +import info.TestBase +import info.nightscout.androidaps.R +import info.nightscout.androidaps.utils.resources.ResourceHelper +import org.junit.Assert +import org.junit.Test +import org.junit.runner.RunWith +import org.mockito.Mock +import org.mockito.Mockito.`when` +import org.powermock.modules.junit4.PowerMockRunner +import java.util.* + +@RunWith(PowerMockRunner::class) +class DateUtilTest : TestBase() { + + @Mock lateinit var resourceHelper: ResourceHelper + + @Test + fun fromISODateStringTest() { + Assert.assertEquals(1511124634417L, DateUtil.fromISODateString("2017-11-19T22:50:34.417+0200").time) + Assert.assertEquals(1511124634000L, DateUtil.fromISODateString("2017-11-19T22:50:34+0200").time) + Assert.assertEquals(1512317365000L, DateUtil.fromISODateString("2017-12-03T16:09:25.000Z").time) + Assert.assertEquals(1513902750000L, DateUtil.fromISODateString("2017-12-22T00:32:30Z").time) + } + + @Test + fun toISOStringTest() { + Assert.assertEquals("2017-12-22T00:32:30Z", DateUtil.toISOString(Date(1513902750000L))) + Assert.assertEquals("2017-12-22T00:32:30Z", DateUtil.toISOString(1513902750000L)) + } + + @Test fun toDateTest() { + Assert.assertTrue(DateUtil.toDate((T.hours(1).secs() + T.mins(1).secs() + 1).toInt()).toString().contains("01:01:00")) + } + + @Test fun toSecondsTest() { + Assert.assertEquals(3600, DateUtil.toSeconds("01:00").toLong()) + Assert.assertEquals(3600, DateUtil.toSeconds("01:00 a.m.").toLong()) + Assert.assertEquals(3600, DateUtil.toSeconds("01:00 AM").toLong()) + } + + @Test fun dateStringTest() { + Assert.assertTrue(DateUtil.dateString(Date(1513902750000L)).contains("22")) + Assert.assertTrue(DateUtil.dateString(1513902750000L).contains("22")) + } + + @Test fun timeStringTest() { + Assert.assertTrue(DateUtil.timeString(Date(1513902750000L)).contains("32")) + Assert.assertTrue(DateUtil.timeString(1513902750000L).contains("32")) + } + + @Test fun dateAndTimeStringTest() { + Assert.assertTrue(DateUtil.dateAndTimeString(1513902750000L).contains("22")) + Assert.assertTrue(DateUtil.dateAndTimeString(1513902750000L).contains("32")) + Assert.assertTrue(DateUtil.dateAndTimeString(Date(1513902750000L)).contains("22")) + Assert.assertTrue(DateUtil.dateAndTimeString(Date(1513902750000L)).contains("32")) + } + + @Test fun dateAndTimeRangeStringTest() { + Assert.assertTrue(DateUtil.dateAndTimeRangeString(1513902750000L, 1513902750000L).contains("22")) + Assert.assertTrue(DateUtil.dateAndTimeRangeString(1513902750000L, 1513902750000L).contains("32")) + Assert.assertTrue(DateUtil.dateAndTimeRangeString(1513902750000L, 1513902750000L).contains("22")) + Assert.assertTrue(DateUtil.dateAndTimeRangeString(1513902750000L, 1513902750000L).contains("32")) + } + + /* + @Test + public void timeStringFromSecondsTest() { + Assert.assertEquals("1:00 AM", DateUtil.timeStringFromSeconds((int) T.hours(1).secs())); + } + */ + @Test fun timeFrameStringTest() { + `when`(resourceHelper.gs(R.string.shorthour)).thenReturn("h") + Assert.assertEquals("(1h 1')", DateUtil.timeFrameString(T.hours(1).msecs() + T.mins(1).msecs(), resourceHelper)) + } +} \ No newline at end of file diff --git a/app/src/test/java/info/nightscout/androidaps/utils/DecimalFormatterTest.java b/app/src/test/java/info/nightscout/androidaps/utils/DecimalFormatterTest.java index ca1bc84e78..e02e5fe28b 100644 --- a/app/src/test/java/info/nightscout/androidaps/utils/DecimalFormatterTest.java +++ b/app/src/test/java/info/nightscout/androidaps/utils/DecimalFormatterTest.java @@ -1,17 +1,11 @@ package info.nightscout.androidaps.utils; import org.junit.Assert; -import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; -import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; -import info.AAPSMocker; -import info.nightscout.androidaps.MainApp; - @RunWith(PowerMockRunner.class) -@PrepareForTest({MainApp.class}) public class DecimalFormatterTest { @Test @@ -45,10 +39,4 @@ public class DecimalFormatterTest { @Test public void pumpSupportedBolusFormat() { } - - @Before - public void prepareMock() { - AAPSMocker.mockMainApp(); - AAPSMocker.mockStrings(); - } } \ No newline at end of file diff --git a/app/src/test/java/info/nightscout/androidaps/utils/MidnightTimeTest.java b/app/src/test/java/info/nightscout/androidaps/utils/MidnightTimeTest.java index 823653c5ab..28a6b1cc31 100644 --- a/app/src/test/java/info/nightscout/androidaps/utils/MidnightTimeTest.java +++ b/app/src/test/java/info/nightscout/androidaps/utils/MidnightTimeTest.java @@ -2,20 +2,12 @@ package info.nightscout.androidaps.utils; import org.junit.Assert; -import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import java.util.Calendar; -import java.util.Date; - -import info.AAPSMocker; -import info.nightscout.androidaps.MainApp; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; /** * Created by mike on 20.11.2017. @@ -60,6 +52,7 @@ public class MidnightTimeTest { MidnightTime.resetCache(); Assert.assertEquals(0, MidnightTime.times.size()); } + @Test public void log() { long now = DateUtil.now();