Merge pull request #348 from nightscout/jacoco2

Jacoco, tests and gradle cleanup
This commit is contained in:
Milos Kozak 2021-02-19 19:53:24 +01:00 committed by GitHub
commit 051cbe7870
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
237 changed files with 1535 additions and 1567 deletions

2
.gitignore vendored
View file

@ -2,7 +2,7 @@
.gradle .gradle
/local.properties /local.properties
.DS_Store .DS_Store
app/jacoco.exec */jacoco.exec
/build /build
/captures /captures
*.apk *.apk

View file

@ -1,23 +1,18 @@
buildscript {
repositories {
maven { url "https://plugins.gradle.org/m2/" } // jacoco 0.2
}
dependencies {
//classpath 'com.dicedmelon.gradle:jacoco-android:0.1.4'
classpath 'com.hiya:jacoco-android:0.2'
}
}
apply plugin: 'com.android.application' apply plugin: 'com.android.application'
apply plugin: 'kotlin-android' apply plugin: 'kotlin-android'
apply plugin: 'kotlin-kapt' apply plugin: 'kotlin-kapt'
apply plugin: 'com.google.gms.google-services' apply plugin: 'com.google.gms.google-services'
//apply plugin: 'jacoco-android'
apply plugin: 'com.hiya.jacoco-android' apply plugin: 'com.hiya.jacoco-android'
apply plugin: 'com.google.firebase.crashlytics' apply plugin: 'com.google.firebase.crashlytics'
apply from: "${project.rootDir}/gradle/android_dependencies.gradle"
jacoco { jacoco {
toolVersion = "0.8.3" toolVersion = "0.8.6"
}
tasks.withType(Test) {
jacoco.includeNoLocationClasses = true
} }
repositories { repositories {
@ -109,12 +104,9 @@ tasks.matching { it instanceof Test }.all {
} }
android { android {
compileSdkVersion 28
ndkVersion "21.1.6352462" ndkVersion "21.1.6352462"
defaultConfig { defaultConfig {
minSdkVersion 26
targetSdkVersion 28
multiDexEnabled true multiDexEnabled true
versionCode 1500 versionCode 1500
version "2.8.2.1-dev-b" version "2.8.2.1-dev-b"
@ -123,37 +115,9 @@ android {
buildConfigField "String", "REMOTE", '"' + generateGitRemote() + '"' buildConfigField "String", "REMOTE", '"' + generateGitRemote() + '"'
buildConfigField "String", "HEAD", '"' + generateGitBuild() + '"' buildConfigField "String", "HEAD", '"' + generateGitBuild() + '"'
buildConfigField "String", "COMMITTED", '"' + allCommitted() + '"' buildConfigField "String", "COMMITTED", '"' + allCommitted() + '"'
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
// if you change minSdkVersion to less than 11, you need to change executeTask for wear
ndk {
moduleName "BleCommandUtil"
}
}
kotlinOptions {
jvmTarget = '1.8'
}
buildFeatures {
viewBinding true
}
lintOptions {
checkReleaseBuilds false
disable 'MissingTranslation'
disable 'ExtraTranslation'
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
debug {
testCoverageEnabled(project.hasProperty('coverage'))
}
firebaseDisable {
System.setProperty("disableFirebase", "true")
ext.enableCrashlytics = false
}
} }
flavorDimensions "standard" flavorDimensions "standard"
productFlavors { productFlavors {
full { full {
@ -197,25 +161,8 @@ android {
] ]
} }
} }
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
testOptions {
unitTests {
returnDefaultValues = true
includeAndroidResources = true
all {
maxParallelForks = 10
forkEvery = 20
}
}
}
useLibrary "org.apache.http.legacy" useLibrary "org.apache.http.legacy"
} }
allprojects { allprojects {
@ -241,24 +188,6 @@ dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs') implementation fileTree(include: ['*.jar'], dir: 'libs')
testImplementation "junit:junit:$junit_version"
testImplementation 'org.json:json:20201115'
testImplementation "org.mockito:mockito-core:${mockitoVersion}"
testImplementation "org.powermock:powermock-api-mockito2:${powermockVersion}"
testImplementation "org.powermock:powermock-module-junit4-rule-agent:${powermockVersion}"
testImplementation "org.powermock:powermock-module-junit4-rule:${powermockVersion}"
testImplementation "org.powermock:powermock-module-junit4:${powermockVersion}"
testImplementation "joda-time:joda-time:$jodatime_version"
testImplementation('com.google.truth:truth:1.1.2') {
exclude group: "com.google.guava", module: "guava"
}
testImplementation "org.skyscreamer:jsonassert:1.5.0"
testImplementation "org.hamcrest:hamcrest-all:1.3"
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0-alpha04'
androidTestImplementation "androidx.test.ext:junit:$androidx_junit"
androidTestImplementation "androidx.test:rules:$androidx_rules"
/* Dagger2 - We are going to use dagger.android which includes /* Dagger2 - We are going to use dagger.android which includes
* support for Activity and fragment injection so we need to include * support for Activity and fragment injection so we need to include
* the following dependencies */ * the following dependencies */
@ -270,10 +199,11 @@ dependencies {
/* Dagger2 - default dependency */ /* Dagger2 - default dependency */
kapt "com.google.dagger:dagger-compiler:$dagger_version" kapt "com.google.dagger:dagger-compiler:$dagger_version"
androidTestImplementation 'androidx.test.uiautomator:uiautomator:2.2.0'
} }
apply from: "${project.rootDir}/gradle/test_dependencies.gradle"
/* /*
// Run 'adb' shell command to clear application data of main app for 'debug' variant // Run 'adb' shell command to clear application data of main app for 'debug' variant
task clearMainAppData(type: Exec) { task clearMainAppData(type: Exec) {

View file

@ -75,8 +75,12 @@
<activity android:name=".activities.StatsActivity" /> <activity android:name=".activities.StatsActivity" />
<activity <activity
android:name="com.google.firebase.auth.internal.FederatedSignInActivity" android:name="com.google.firebase.auth.internal.FederatedSignInActivity"
tools:replace="android:launchMode" android:excludeFromRecents="true"
android:launchMode="standard" /> android:exported="true"
android:launchMode="singleInstance"
android:permission="com.google.firebase.auth.api.gms.permission.LAUNCH_FEDERATED_SIGN_IN"
android:theme="@android:style/Theme.Translucent.NoTitleBar"
tools:replace="android:launchMode" />
<!-- Receive new BG readings from other local apps --> <!-- Receive new BG readings from other local apps -->
<receiver <receiver

View file

@ -15,7 +15,6 @@ import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensResult import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensResult
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin
import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.FabricPrivacy
import info.nightscout.androidaps.utils.HardLimits import info.nightscout.androidaps.utils.HardLimits
@ -36,7 +35,7 @@ open class OpenAPSAMAPlugin @Inject constructor(
private val profileFunction: ProfileFunction, private val profileFunction: ProfileFunction,
private val context: Context, private val context: Context,
private val activePlugin: ActivePluginProvider, private val activePlugin: ActivePluginProvider,
private val treatmentsPlugin: TreatmentsPlugin, private val treatmentsPlugin: TreatmentsInterface,
private val iobCobCalculatorPlugin: IobCobCalculatorPlugin, private val iobCobCalculatorPlugin: IobCobCalculatorPlugin,
private val hardLimits: HardLimits, private val hardLimits: HardLimits,
private val profiler: Profiler, private val profiler: Profiler,

View file

@ -17,7 +17,6 @@ import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensResult import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensResult
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin
import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.HardLimits import info.nightscout.androidaps.utils.HardLimits
import info.nightscout.androidaps.utils.Profiler import info.nightscout.androidaps.utils.Profiler
@ -37,7 +36,7 @@ open class OpenAPSSMBPlugin @Inject constructor(
private val profileFunction: ProfileFunction, private val profileFunction: ProfileFunction,
private val context: Context, private val context: Context,
private val activePlugin: ActivePluginProvider, private val activePlugin: ActivePluginProvider,
private val treatmentsPlugin: TreatmentsPlugin, private val treatmentsPlugin: TreatmentsInterface,
private val iobCobCalculatorPlugin: IobCobCalculatorPlugin, private val iobCobCalculatorPlugin: IobCobCalculatorPlugin,
private val hardLimits: HardLimits, private val hardLimits: HardLimits,
private val profiler: Profiler, private val profiler: Profiler,

View file

@ -13,7 +13,6 @@ import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker
import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification
import info.nightscout.androidaps.plugins.general.overview.notifications.Notification import info.nightscout.androidaps.plugins.general.overview.notifications.Notification
import info.nightscout.androidaps.plugins.sensitivity.SensitivityOref1Plugin import info.nightscout.androidaps.plugins.sensitivity.SensitivityOref1Plugin
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin
import info.nightscout.androidaps.utils.DecimalFormatter import info.nightscout.androidaps.utils.DecimalFormatter
import info.nightscout.androidaps.utils.HardLimits import info.nightscout.androidaps.utils.HardLimits
import info.nightscout.androidaps.utils.Round import info.nightscout.androidaps.utils.Round
@ -38,7 +37,7 @@ class SafetyPlugin @Inject constructor(
private val activePlugin: ActivePluginProvider, private val activePlugin: ActivePluginProvider,
private val hardLimits: HardLimits, private val hardLimits: HardLimits,
private val buildHelper: BuildHelper, private val buildHelper: BuildHelper,
private val treatmentsPlugin: TreatmentsPlugin, private val treatmentsPlugin: TreatmentsInterface,
private val config: Config private val config: Config
) : PluginBase(PluginDescription() ) : PluginBase(PluginDescription()
.mainType(PluginType.CONSTRAINTS) .mainType(PluginType.CONSTRAINTS)

View file

@ -11,15 +11,15 @@ import com.google.common.base.Optional
import dagger.android.HasAndroidInjector import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.R import info.nightscout.androidaps.R
import info.nightscout.androidaps.interfaces.ActivePluginProvider import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.interfaces.TreatmentsInterface
import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.plugins.general.automation.dialogs.ChooseTriggerDialog import info.nightscout.androidaps.plugins.general.automation.dialogs.ChooseTriggerDialog
import info.nightscout.androidaps.plugins.general.automation.events.EventTriggerChanged import info.nightscout.androidaps.plugins.general.automation.events.EventTriggerChanged
import info.nightscout.androidaps.plugins.general.automation.events.EventTriggerClone import info.nightscout.androidaps.plugins.general.automation.events.EventTriggerClone
import info.nightscout.androidaps.plugins.general.automation.events.EventTriggerRemove import info.nightscout.androidaps.plugins.general.automation.events.EventTriggerRemove
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin
import info.nightscout.androidaps.services.LastLocationDataContainer import info.nightscout.androidaps.services.LastLocationDataContainer
import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.sharedPreferences.SP import info.nightscout.androidaps.utils.sharedPreferences.SP
@ -29,13 +29,14 @@ import javax.inject.Inject
import kotlin.reflect.full.primaryConstructor import kotlin.reflect.full.primaryConstructor
abstract class Trigger(val injector: HasAndroidInjector) { abstract class Trigger(val injector: HasAndroidInjector) {
@Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var aapsLogger: AAPSLogger
@Inject lateinit var rxBus: RxBusWrapper @Inject lateinit var rxBus: RxBusWrapper
@Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var resourceHelper: ResourceHelper
@Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var profileFunction: ProfileFunction
@Inject lateinit var sp: SP @Inject lateinit var sp: SP
@Inject lateinit var locationDataContainer: LastLocationDataContainer @Inject lateinit var locationDataContainer: LastLocationDataContainer
@Inject lateinit var treatmentsPlugin: TreatmentsPlugin @Inject lateinit var treatmentsInterface: TreatmentsInterface
@Inject lateinit var activePlugin: ActivePluginProvider @Inject lateinit var activePlugin: ActivePluginProvider
@Inject lateinit var iobCobCalculatorPlugin: IobCobCalculatorPlugin @Inject lateinit var iobCobCalculatorPlugin: IobCobCalculatorPlugin
@ -53,6 +54,7 @@ abstract class Trigger(val injector: HasAndroidInjector) {
abstract fun duplicate(): Trigger abstract fun duplicate(): Trigger
companion object { companion object {
@JvmStatic @JvmStatic
fun scanForActivity(cont: Context?): AppCompatActivity? { fun scanForActivity(cont: Context?): AppCompatActivity? {
when (cont) { when (cont) {

View file

@ -35,7 +35,7 @@ class TriggerBolusAgo(injector: HasAndroidInjector) : Trigger(injector) {
} }
override fun shouldRun(): Boolean { override fun shouldRun(): Boolean {
val lastBolusTime = treatmentsPlugin.getLastBolusTime(true) val lastBolusTime = treatmentsInterface.getLastBolusTime(true)
if (lastBolusTime == 0L) if (lastBolusTime == 0L)
return if (comparator.value == Comparator.Compare.IS_NOT_AVAILABLE) { return if (comparator.value == Comparator.Compare.IS_NOT_AVAILABLE) {
aapsLogger.debug(LTag.AUTOMATION, "Ready for execution: " + friendlyDescription()) aapsLogger.debug(LTag.AUTOMATION, "Ready for execution: " + friendlyDescription())

View file

@ -28,7 +28,7 @@ class TriggerTempTarget(injector: HasAndroidInjector) : Trigger(injector) {
} }
override fun shouldRun(): Boolean { override fun shouldRun(): Boolean {
val tt = treatmentsPlugin.tempTargetFromHistory val tt = treatmentsInterface.tempTargetFromHistory
if (tt == null && comparator.value == ComparatorExists.Compare.NOT_EXISTS) { if (tt == null && comparator.value == ComparatorExists.Compare.NOT_EXISTS) {
aapsLogger.debug(LTag.AUTOMATION, "Ready for execution: " + friendlyDescription()) aapsLogger.debug(LTag.AUTOMATION, "Ready for execution: " + friendlyDescription())
return true return true

View file

@ -363,7 +363,7 @@ class OpenHumansUploader @Inject constructor(
copyDisposable = Completable.fromCallable { MainApp.getDbHelper().clearOpenHumansQueue() } copyDisposable = Completable.fromCallable { MainApp.getDbHelper().clearOpenHumansQueue() }
.andThen(Single.defer { Single.just(MainApp.getDbHelper().countOfAllRows + treatmentsPlugin.service.count()) }) .andThen(Single.defer { Single.just(MainApp.getDbHelper().countOfAllRows + treatmentsPlugin.service.count()) })
.doOnSuccess { maxProgress = it } .doOnSuccess { maxProgress = it }
.flatMapObservable { Observable.defer { Observable.fromIterable(treatmentsPlugin.service.treatmentData) } } .flatMapObservable { Observable.defer { Observable.fromIterable(treatmentsPlugin.service.getTreatmentData()) } }
.map { enqueueTreatment(it); increaseCounter() } .map { enqueueTreatment(it); increaseCounter() }
.ignoreElements() .ignoreElements()
.andThen(Observable.defer { Observable.fromIterable(repository.compatGetBgReadingsDataFromTime(0, true).blockingGet()) }) .andThen(Observable.defer { Observable.fromIterable(repository.compatGetBgReadingsDataFromTime(0, true).blockingGet()) })

View file

@ -450,7 +450,7 @@ class SmsCommunicatorPlugin @Inject constructor(
private fun processTREATMENTS(divided: Array<String>, receivedSms: Sms) { private fun processTREATMENTS(divided: Array<String>, receivedSms: Sms) {
if (divided[1].toUpperCase(Locale.getDefault()) == "REFRESH") { if (divided[1].toUpperCase(Locale.getDefault()) == "REFRESH") {
(activePlugin.activeTreatments as TreatmentsPlugin).service.resetTreatments() activePlugin.activeTreatments.service.resetTreatments()
rxBus.send(EventNSClientRestart()) rxBus.send(EventNSClientRestart())
sendSMS(Sms(receivedSms.phoneNumber, "TREATMENTS REFRESH SENT")) sendSMS(Sms(receivedSms.phoneNumber, "TREATMENTS REFRESH SENT"))
receivedSms.processed = true receivedSms.processed = true

View file

@ -41,6 +41,7 @@ import info.nightscout.androidaps.interfaces.ProfileFunction;
import info.nightscout.androidaps.interfaces.PumpDescription; import info.nightscout.androidaps.interfaces.PumpDescription;
import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.interfaces.PumpPluginBase; import info.nightscout.androidaps.interfaces.PumpPluginBase;
import info.nightscout.androidaps.interfaces.TreatmentsInterface;
import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.AAPSLogger;
import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.logging.LTag;
import info.nightscout.androidaps.plugins.bus.RxBusWrapper; import info.nightscout.androidaps.plugins.bus.RxBusWrapper;
@ -80,7 +81,7 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
private final ResourceHelper resourceHelper; private final ResourceHelper resourceHelper;
private final ProfileFunction profileFunction; private final ProfileFunction profileFunction;
private final TreatmentsPlugin treatmentsPlugin; private final TreatmentsInterface treatmentsPlugin;
private final info.nightscout.androidaps.utils.sharedPreferences.SP sp; private final info.nightscout.androidaps.utils.sharedPreferences.SP sp;
private RxBusWrapper rxBus; private RxBusWrapper rxBus;
private final CommandQueueProvider commandQueue; private final CommandQueueProvider commandQueue;
@ -136,7 +137,7 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
RxBusWrapper rxBus, RxBusWrapper rxBus,
ResourceHelper resourceHelper, ResourceHelper resourceHelper,
ProfileFunction profileFunction, ProfileFunction profileFunction,
TreatmentsPlugin treatmentsPlugin, TreatmentsInterface treatmentsPlugin,
SP sp, SP sp,
CommandQueueProvider commandQueue, CommandQueueProvider commandQueue,
Context context Context context

View file

@ -49,6 +49,7 @@ import info.nightscout.androidaps.interfaces.ProfileFunction;
import info.nightscout.androidaps.interfaces.PumpDescription; import info.nightscout.androidaps.interfaces.PumpDescription;
import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.interfaces.PumpPluginBase; import info.nightscout.androidaps.interfaces.PumpPluginBase;
import info.nightscout.androidaps.interfaces.TreatmentsInterface;
import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.AAPSLogger;
import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.logging.LTag;
import info.nightscout.androidaps.plugins.bus.RxBusWrapper; import info.nightscout.androidaps.plugins.bus.RxBusWrapper;
@ -129,7 +130,6 @@ import info.nightscout.androidaps.plugins.pump.insight.exceptions.app_layer_erro
import info.nightscout.androidaps.plugins.pump.insight.exceptions.app_layer_errors.NoActiveTBRToCanceLException; import info.nightscout.androidaps.plugins.pump.insight.exceptions.app_layer_errors.NoActiveTBRToCanceLException;
import info.nightscout.androidaps.plugins.pump.insight.utils.ExceptionTranslator; import info.nightscout.androidaps.plugins.pump.insight.utils.ExceptionTranslator;
import info.nightscout.androidaps.plugins.pump.insight.utils.ParameterBlockUtil; import info.nightscout.androidaps.plugins.pump.insight.utils.ParameterBlockUtil;
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin;
import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.DateUtil;
import info.nightscout.androidaps.utils.TimeChangeType; import info.nightscout.androidaps.utils.TimeChangeType;
import info.nightscout.androidaps.utils.resources.ResourceHelper; import info.nightscout.androidaps.utils.resources.ResourceHelper;
@ -141,7 +141,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface,
private final AAPSLogger aapsLogger; private final AAPSLogger aapsLogger;
private final RxBusWrapper rxBus; private final RxBusWrapper rxBus;
private final ResourceHelper resourceHelper; private final ResourceHelper resourceHelper;
private final TreatmentsPlugin treatmentsPlugin; private final TreatmentsInterface treatmentsPlugin;
private final SP sp; private final SP sp;
private final CommandQueueProvider commandQueue; private final CommandQueueProvider commandQueue;
private final ProfileFunction profileFunction; private final ProfileFunction profileFunction;
@ -203,7 +203,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface,
AAPSLogger aapsLogger, AAPSLogger aapsLogger,
RxBusWrapper rxBus, RxBusWrapper rxBus,
ResourceHelper resourceHelper, ResourceHelper resourceHelper,
TreatmentsPlugin treatmentsPlugin, TreatmentsInterface treatmentsPlugin,
SP sp, SP sp,
CommandQueueProvider commandQueue, CommandQueueProvider commandQueue,
ProfileFunction profileFunction, ProfileFunction profileFunction,

View file

@ -16,6 +16,7 @@ import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils; import com.j256.ormlite.table.TableUtils;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.json.JSONException; import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
@ -39,6 +40,8 @@ import info.nightscout.androidaps.events.EventNsTreatment;
import info.nightscout.androidaps.events.EventReloadTreatmentData; import info.nightscout.androidaps.events.EventReloadTreatmentData;
import info.nightscout.androidaps.events.EventTreatmentChange; import info.nightscout.androidaps.events.EventTreatmentChange;
import info.nightscout.androidaps.interfaces.DatabaseHelperInterface; import info.nightscout.androidaps.interfaces.DatabaseHelperInterface;
import info.nightscout.androidaps.interfaces.TreatmentServiceInterface;
import info.nightscout.androidaps.interfaces.UpdateReturn;
import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.AAPSLogger;
import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.logging.LTag;
import info.nightscout.androidaps.plugins.bus.RxBusWrapper; import info.nightscout.androidaps.plugins.bus.RxBusWrapper;
@ -57,7 +60,7 @@ import io.reactivex.disposables.CompositeDisposable;
* Created by mike on 24.09.2017. * Created by mike on 24.09.2017.
*/ */
public class TreatmentService extends OrmLiteBaseService<DatabaseHelper> { public class TreatmentService extends OrmLiteBaseService<DatabaseHelper> implements TreatmentServiceInterface {
@Inject AAPSLogger aapsLogger; @Inject AAPSLogger aapsLogger;
@Inject FabricPrivacy fabricPrivacy; @Inject FabricPrivacy fabricPrivacy;
@ -471,7 +474,7 @@ public class TreatmentService extends OrmLiteBaseService<DatabaseHelper> {
} }
public UpdateReturn createOrUpdateMedtronic(Treatment treatment, boolean fromNightScout) { @NotNull public UpdateReturn createOrUpdateMedtronic(@NotNull Treatment treatment, boolean fromNightScout) {
if (MedtronicHistoryData.doubleBolusDebug) if (MedtronicHistoryData.doubleBolusDebug)
aapsLogger.debug(LTag.DATATREATMENTS, "DoubleBolusDebug: createOrUpdateMedtronic:: originalTreatment={}, fromNightScout={}", treatment, fromNightScout); aapsLogger.debug(LTag.DATATREATMENTS, "DoubleBolusDebug: createOrUpdateMedtronic:: originalTreatment={}, fromNightScout={}", treatment, fromNightScout);
@ -821,22 +824,4 @@ public class TreatmentService extends OrmLiteBaseService<DatabaseHelper> {
return null; return null;
} }
public class UpdateReturn {
public UpdateReturn(boolean success, boolean newRecord) {
this.success = success;
this.newRecord = newRecord;
}
boolean newRecord;
boolean success;
@Override
public String toString() {
return "UpdateReturn [" +
"newRecord=" + newRecord +
", success=" + success +
']';
}
}
} }

View file

@ -46,7 +46,9 @@ import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.interfaces.ProfileFunction; import info.nightscout.androidaps.interfaces.ProfileFunction;
import info.nightscout.androidaps.interfaces.ProfileStore; import info.nightscout.androidaps.interfaces.ProfileStore;
import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.interfaces.TreatmentServiceInterface;
import info.nightscout.androidaps.interfaces.TreatmentsInterface; import info.nightscout.androidaps.interfaces.TreatmentsInterface;
import info.nightscout.androidaps.interfaces.UpdateReturn;
import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.AAPSLogger;
import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.logging.LTag;
import info.nightscout.androidaps.plugins.bus.RxBusWrapper; import info.nightscout.androidaps.plugins.bus.RxBusWrapper;
@ -82,7 +84,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface
private final CompositeDisposable disposable = new CompositeDisposable(); private final CompositeDisposable disposable = new CompositeDisposable();
protected TreatmentService service; protected TreatmentServiceInterface service;
private IobTotal lastTreatmentCalculation; private IobTotal lastTreatmentCalculation;
private IobTotal lastTempBasalsCalculation; private IobTotal lastTempBasalsCalculation;
@ -180,7 +182,8 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface
super.onStop(); super.onStop();
} }
public TreatmentService getService() { @Override
public TreatmentServiceInterface getService() {
return this.service; return this.service;
} }
@ -620,9 +623,9 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface
} }
public TreatmentUpdateReturn createOrUpdateMedtronic(Treatment treatment, boolean fromNightScout) { public TreatmentUpdateReturn createOrUpdateMedtronic(Treatment treatment, boolean fromNightScout) {
TreatmentService.UpdateReturn resultRecord = getService().createOrUpdateMedtronic(treatment, fromNightScout); UpdateReturn resultRecord = getService().createOrUpdateMedtronic(treatment, fromNightScout);
return new TreatmentUpdateReturn(resultRecord.success, resultRecord.newRecord); return new TreatmentUpdateReturn(resultRecord.getSuccess(), resultRecord.getNewRecord());
} }
// return true if new record is created // return true if new record is created
@ -643,7 +646,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface
treatment.carbs = detailedBolusInfo.carbs; treatment.carbs = detailedBolusInfo.carbs;
treatment.mealBolus = treatment.carbs > 0; treatment.mealBolus = treatment.carbs > 0;
treatment.boluscalc = detailedBolusInfo.boluscalc != null ? detailedBolusInfo.boluscalc.toString() : null; treatment.boluscalc = detailedBolusInfo.boluscalc != null ? detailedBolusInfo.boluscalc.toString() : null;
TreatmentService.UpdateReturn creatOrUpdateResult; UpdateReturn creatOrUpdateResult;
getAapsLogger().debug(medtronicPump && MedtronicHistoryData.doubleBolusDebug, LTag.DATATREATMENTS, "DoubleBolusDebug: addToHistoryTreatment::treatment={} " + treatment); getAapsLogger().debug(medtronicPump && MedtronicHistoryData.doubleBolusDebug, LTag.DATATREATMENTS, "DoubleBolusDebug: addToHistoryTreatment::treatment={} " + treatment);
@ -652,7 +655,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface
else else
creatOrUpdateResult = getService().createOrUpdateMedtronic(treatment, false); creatOrUpdateResult = getService().createOrUpdateMedtronic(treatment, false);
boolean newRecordCreated = creatOrUpdateResult.newRecord; boolean newRecordCreated = creatOrUpdateResult.getNewRecord();
//log.debug("Adding new Treatment record" + treatment.toString()); //log.debug("Adding new Treatment record" + treatment.toString());
if (detailedBolusInfo.carbTime != 0) { if (detailedBolusInfo.carbTime != 0) {
@ -673,7 +676,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface
if (newRecordCreated && detailedBolusInfo.isValid) if (newRecordCreated && detailedBolusInfo.isValid)
nsUpload.uploadTreatmentRecord(detailedBolusInfo); nsUpload.uploadTreatmentRecord(detailedBolusInfo);
if (!allowUpdate && !creatOrUpdateResult.success) { if (!allowUpdate && !creatOrUpdateResult.getSuccess()) {
getAapsLogger().error("Treatment could not be added to DB", new Exception()); getAapsLogger().error("Treatment could not be added to DB", new Exception());
String status = String.format(resourceHelper.gs(R.string.error_adding_treatment_message), treatment.insulin, (int) treatment.carbs, dateUtil.dateAndTimeString(treatment.date)); String status = String.format(resourceHelper.gs(R.string.error_adding_treatment_message), treatment.insulin, (int) treatment.carbs, dateUtil.dateAndTimeString(treatment.date));

View file

@ -125,69 +125,6 @@
<item>YpsoPump</item> <item>YpsoPump</item>
</string-array> </string-array>
<string-array name="medtronicPumpTypeArray">
<item>Other (unsupported)</item>
<item>512</item>
<item>712</item>
<item>515</item>
<item>715</item>
<item>522</item>
<item>722</item>
<item>523 (Fw 2.4A or lower)</item>
<item>723 (Fw 2.4A or lower)</item>
<item>554 (EU Fw. &lt;= 2.6A)</item>
<item>754 (EU Fw. &lt;= 2.6A)</item>
<item>554 (CA Fw. &lt;= 2.7A)</item>
<item>754 (CA Fw. &lt;= 2.7A)</item>
</string-array>
<string-array name="medtronicPumpFreqArray">
<item>@string/medtronic_pump_frequency_us_ca</item>
<item>@string/medtronic_pump_frequency_worldwide</item>
</string-array>
<string-array name="medtronicPumpFreqValues">
<item>@string/key_medtronic_pump_frequency_us_ca</item>
<item>@string/key_medtronic_pump_frequency_worldwide</item>
</string-array>
<string-array name="medtronicBolusDelay">
<item>5</item>
<item>10</item>
<item>15</item>
</string-array>
<string-array name="medtronicEncoding">
<item>@string/medtronic_pump_encoding_4b6b_local</item>
<item>@string/medtronic_pump_encoding_4b6b_rileylink</item>
</string-array>
<string-array name="onOff">
<item>@string/common_on</item>
<item>@string/common_off</item>
</string-array>
<string-array name="medtronicEncodingValues">
<item>@string/key_medtronic_pump_encoding_4b6b_local</item>
<item>@string/key_medtronic_pump_encoding_4b6b_rileylink</item>
</string-array>
<string-array name="medtronicBatteryType">
<item>@string/medtronic_pump_battery_no</item>
<item>@string/medtronic_pump_battery_alkaline</item>
<item>@string/medtronic_pump_battery_lithium</item>
<item>@string/medtronic_pump_battery_nizn</item>
<item>@string/medtronic_pump_battery_nimh</item>
</string-array>
<string-array name="medtronicBatteryTypeValues">
<item>@string/key_medtronic_pump_battery_no</item>
<item>@string/key_medtronic_pump_battery_alkaline</item>
<item>@string/key_medtronic_pump_battery_lithium</item>
<item>@string/key_medtronic_pump_battery_nizn</item>
<item>@string/key_medtronic_pump_battery_nimh</item>
</string-array>
<string-array name="smbMaxMinutes"> <string-array name="smbMaxMinutes">
<item>15</item> <item>15</item>
<item>30</item> <item>30</item>

View file

@ -65,7 +65,4 @@
<color name="splashBackground">#2E2E2E</color> <color name="splashBackground">#2E2E2E</color>
<color name="importListFileName">#FFFFFF</color>
<color name="importListAdditionalInfo">#BBBBBB</color>
</resources> </resources>

View file

@ -1251,7 +1251,6 @@
<string name="key_snoozedTo" translatable="false">snoozedTo</string> <string name="key_snoozedTo" translatable="false">snoozedTo</string>
<string name="key_snooze_dst_in24h" translatable="false">snooze_dst_in24h</string> <string name="key_snooze_dst_in24h" translatable="false">snooze_dst_in24h</string>
<string name="key_snooze_loopdisabled" translatable="false">snooze_loopdisabled</string> <string name="key_snooze_loopdisabled" translatable="false">snooze_loopdisabled</string>
<string name="sixdigitnumber" translatable="false">^\\d{6}</string>
<string name="ebstopsloop">Use of Extended bolus feature will stop closed loop mode for the time of running extended bolus. Do you really want it?</string> <string name="ebstopsloop">Use of Extended bolus feature will stop closed loop mode for the time of running extended bolus. Do you really want it?</string>
<string name="closed_loop_disabled_with_eb">Closed loop disabled because of running Extended bolus</string> <string name="closed_loop_disabled_with_eb">Closed loop disabled because of running Extended bolus</string>
<string name="phonechecker">\"PhoneChecker\"</string> <string name="phonechecker">\"PhoneChecker\"</string>

View file

@ -22,16 +22,6 @@
<item name="colorAccent">@color/colorAccent</item> <item name="colorAccent">@color/colorAccent</item>
</style> </style>
<style name="Theme.AppCompat.NoTitle" parent="Theme.AppCompat.NoActionBar">
<item name="android:windowNoTitle">true</item>
<item name="android:windowBackground">@android:color/transparent</item>
<item name="android:colorBackgroundCacheHint">@null</item>
<item name="android:windowIsTranslucent">false</item>
<item name="android:windowAnimationStyle">@android:style/Animation</item>
</style>
<style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />
<style name="section_header_label"> <style name="section_header_label">
<item name="android:layout_width">match_parent</item> <item name="android:layout_width">match_parent</item>
<item name="android:layout_height">wrap_content</item> <item name="android:layout_height">wrap_content</item>

View file

@ -3,33 +3,35 @@ package info.nightscout.androidaps
import dagger.android.AndroidInjector import dagger.android.AndroidInjector
import dagger.android.HasAndroidInjector import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.data.Profile import info.nightscout.androidaps.data.Profile
import info.nightscout.androidaps.interfaces.ProfileStore
import info.nightscout.androidaps.db.ProfileSwitch import info.nightscout.androidaps.db.ProfileSwitch
import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.db.Treatment import info.nightscout.androidaps.db.Treatment
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.interfaces.ConfigInterface
import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.interfaces.ProfileStore
import info.nightscout.androidaps.interfaces.TreatmentsInterface
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.DefaultValueHelper import info.nightscout.androidaps.utils.DefaultValueHelper
import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.FabricPrivacy
import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.rx.AapsSchedulers
import info.nightscout.androidaps.utils.rx.TestAapsSchedulers
import org.json.JSONObject import org.json.JSONObject
import org.junit.Before import org.junit.Before
import org.mockito.Mock import org.mockito.Mock
import org.powermock.core.classloader.annotations.PrepareForTest import org.powermock.core.classloader.annotations.PrepareForTest
@Suppress("SpellCheckingInspection")
@PrepareForTest(FabricPrivacy::class) @PrepareForTest(FabricPrivacy::class)
open class TestBaseWithProfile : TestBase() { open class TestBaseWithProfile : TestBase() {
@Mock lateinit var activePluginProvider: ActivePluginProvider @Mock lateinit var activePluginProvider: ActivePluginProvider
@Mock lateinit var resourceHelper: ResourceHelper @Mock lateinit var resourceHelper: ResourceHelper
@Mock lateinit var treatmentsPlugin: TreatmentsPlugin @Mock lateinit var treatmentsInterface: TreatmentsInterface
@Mock lateinit var fabricPrivacy: FabricPrivacy @Mock lateinit var fabricPrivacy: FabricPrivacy
@Mock lateinit var profileFunction: ProfileFunction @Mock lateinit var profileFunction: ProfileFunction
@Mock lateinit var defaultValueHelper: DefaultValueHelper @Mock lateinit var defaultValueHelper: DefaultValueHelper
@Mock lateinit var dateUtil: DateUtil @Mock lateinit var dateUtil: DateUtil
@Mock lateinit var configInterface: ConfigInterface
val rxBus = RxBusWrapper(aapsSchedulers) val rxBus = RxBusWrapper(aapsSchedulers)
@ -41,10 +43,10 @@ open class TestBaseWithProfile : TestBase() {
it.resourceHelper = resourceHelper it.resourceHelper = resourceHelper
it.rxBus = rxBus it.rxBus = rxBus
it.fabricPrivacy = fabricPrivacy it.fabricPrivacy = fabricPrivacy
it.configInterface = Config() it.configInterface = configInterface
} }
if (it is ProfileSwitch) { if (it is ProfileSwitch) {
it.treatmentsPlugin = treatmentsPlugin it.treatmentsPlugin = treatmentsInterface
it.aapsLogger = aapsLogger it.aapsLogger = aapsLogger
it.rxBus = rxBus it.rxBus = rxBus
it.resourceHelper = resourceHelper it.resourceHelper = resourceHelper
@ -61,7 +63,7 @@ open class TestBaseWithProfile : TestBase() {
private lateinit var validProfileJSON: String private lateinit var validProfileJSON: String
lateinit var validProfile: Profile lateinit var validProfile: Profile
val TESTPROFILENAME = "someProfile" @Suppress("PropertyName") val TESTPROFILENAME = "someProfile"
@Before @Before
fun prepareMock() { fun prepareMock() {

View file

@ -123,13 +123,13 @@ class ConstraintsCheckerTest : TestBaseWithProfile() {
danaPump = DanaPump(aapsLogger, sp, injector) danaPump = DanaPump(aapsLogger, sp, injector)
hardLimits = HardLimits(aapsLogger, rxBus, sp, resourceHelper, context, nsUpload) hardLimits = HardLimits(aapsLogger, rxBus, sp, resourceHelper, context, nsUpload)
objectivesPlugin = ObjectivesPlugin(injector, aapsLogger, resourceHelper, activePlugin, sp, Config(), uel) objectivesPlugin = ObjectivesPlugin(injector, aapsLogger, resourceHelper, activePlugin, sp, Config(), uel)
comboPlugin = ComboPlugin(injector, aapsLogger, rxBus, resourceHelper, profileFunction, treatmentsPlugin, sp, commandQueue, context) comboPlugin = ComboPlugin(injector, aapsLogger, rxBus, resourceHelper, profileFunction, treatmentsInterface, sp, commandQueue, context)
danaRPlugin = DanaRPlugin(injector, aapsLogger, aapsSchedulers, rxBus, context, resourceHelper, constraintChecker, activePlugin, sp, commandQueue, danaPump, dateUtil, fabricPrivacy) danaRPlugin = DanaRPlugin(injector, aapsLogger, aapsSchedulers, rxBus, context, resourceHelper, constraintChecker, activePlugin, sp, commandQueue, danaPump, dateUtil, fabricPrivacy)
danaRSPlugin = DanaRSPlugin(injector, aapsLogger, aapsSchedulers, rxBus, context, resourceHelper, constraintChecker, profileFunction, activePluginProvider, sp, commandQueue, danaPump, detailedBolusInfoStorage, fabricPrivacy, dateUtil) danaRSPlugin = DanaRSPlugin(injector, aapsLogger, aapsSchedulers, rxBus, context, resourceHelper, constraintChecker, profileFunction, activePluginProvider, sp, commandQueue, danaPump, detailedBolusInfoStorage, fabricPrivacy, dateUtil)
insightPlugin = LocalInsightPlugin(injector, aapsLogger, rxBus, resourceHelper, treatmentsPlugin, sp, commandQueue, profileFunction, nsUpload, context, uploadQueue, Config(), dateUtil) insightPlugin = LocalInsightPlugin(injector, aapsLogger, rxBus, resourceHelper, treatmentsInterface, sp, commandQueue, profileFunction, nsUpload, context, uploadQueue, Config(), dateUtil)
openAPSSMBPlugin = OpenAPSSMBPlugin(injector, aapsLogger, rxBus, constraintChecker, resourceHelper, profileFunction, context, activePlugin, treatmentsPlugin, iobCobCalculatorPlugin, hardLimits, profiler, sp) openAPSSMBPlugin = OpenAPSSMBPlugin(injector, aapsLogger, rxBus, constraintChecker, resourceHelper, profileFunction, context, activePlugin, treatmentsInterface, iobCobCalculatorPlugin, hardLimits, profiler, sp)
openAPSAMAPlugin = OpenAPSAMAPlugin(injector, aapsLogger, rxBus, constraintChecker, resourceHelper, profileFunction, context, activePlugin, treatmentsPlugin, iobCobCalculatorPlugin, hardLimits, profiler, fabricPrivacy) openAPSAMAPlugin = OpenAPSAMAPlugin(injector, aapsLogger, rxBus, constraintChecker, resourceHelper, profileFunction, context, activePlugin, treatmentsInterface, iobCobCalculatorPlugin, hardLimits, profiler, fabricPrivacy)
safetyPlugin = SafetyPlugin(injector, aapsLogger, resourceHelper, sp, rxBus, constraintChecker, openAPSAMAPlugin, openAPSSMBPlugin, sensitivityOref1Plugin, activePlugin, hardLimits, BuildHelper(Config(), loggerUtils), treatmentsPlugin, Config()) safetyPlugin = SafetyPlugin(injector, aapsLogger, resourceHelper, sp, rxBus, constraintChecker, openAPSAMAPlugin, openAPSSMBPlugin, sensitivityOref1Plugin, activePlugin, hardLimits, BuildHelper(Config(), loggerUtils), treatmentsInterface, Config())
val constraintsPluginsList = ArrayList<PluginBase>() val constraintsPluginsList = ArrayList<PluginBase>()
constraintsPluginsList.add(safetyPlugin) constraintsPluginsList.add(safetyPlugin)
constraintsPluginsList.add(objectivesPlugin) constraintsPluginsList.add(objectivesPlugin)

View file

@ -43,7 +43,7 @@ class APSResultTest : TestBaseWithProfile() {
it.constraintChecker = constraintChecker it.constraintChecker = constraintChecker
it.sp = sp it.sp = sp
it.activePlugin = activePluginProvider it.activePlugin = activePluginProvider
it.treatmentsPlugin = treatmentsPlugin it.treatmentsPlugin = treatmentsInterface
it.profileFunction = profileFunction it.profileFunction = profileFunction
it.resourceHelper = resourceHelper it.resourceHelper = resourceHelper
} }
@ -56,7 +56,7 @@ class APSResultTest : TestBaseWithProfile() {
// closed loop mode return original request // closed loop mode return original request
closedLoopEnabled.set(aapsLogger, true) closedLoopEnabled.set(aapsLogger, true)
`when`(treatmentsPlugin.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(null) `when`(treatmentsInterface.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(null)
apsResult.tempBasalRequested(false) apsResult.tempBasalRequested(false)
Assert.assertEquals(false, apsResult.isChangeRequested) Assert.assertEquals(false, apsResult.isChangeRequested)
apsResult.tempBasalRequested(true).percent(200).duration(30) apsResult.tempBasalRequested(true).percent(200).duration(30)
@ -65,46 +65,46 @@ class APSResultTest : TestBaseWithProfile() {
// open loop // open loop
closedLoopEnabled.set(aapsLogger, false) closedLoopEnabled.set(aapsLogger, false)
// no change requested // no change requested
`when`(treatmentsPlugin.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(null) `when`(treatmentsInterface.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(null)
apsResult.tempBasalRequested(false) apsResult.tempBasalRequested(false)
Assert.assertEquals(false, apsResult.isChangeRequested) Assert.assertEquals(false, apsResult.isChangeRequested)
// request 100% when no temp is running // request 100% when no temp is running
`when`(treatmentsPlugin.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(null) `when`(treatmentsInterface.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(null)
apsResult.tempBasalRequested(true).percent(100).duration(30) apsResult.tempBasalRequested(true).percent(100).duration(30)
Assert.assertEquals(false, apsResult.isChangeRequested) Assert.assertEquals(false, apsResult.isChangeRequested)
// request equal temp // request equal temp
`when`(treatmentsPlugin.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal(injector).percent(70).duration(30)) `when`(treatmentsInterface.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal(injector).percent(70).duration(30))
apsResult.tempBasalRequested(true).percent(70).duration(30) apsResult.tempBasalRequested(true).percent(70).duration(30)
Assert.assertEquals(false, apsResult.isChangeRequested) Assert.assertEquals(false, apsResult.isChangeRequested)
// request zero temp // request zero temp
`when`(treatmentsPlugin.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal(injector).percent(10).duration(30)) `when`(treatmentsInterface.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal(injector).percent(10).duration(30))
apsResult.tempBasalRequested(true).percent(0).duration(30) apsResult.tempBasalRequested(true).percent(0).duration(30)
Assert.assertEquals(true, apsResult.isChangeRequested) Assert.assertEquals(true, apsResult.isChangeRequested)
// request high temp // request high temp
`when`(treatmentsPlugin.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal(injector).percent(190).duration(30)) `when`(treatmentsInterface.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal(injector).percent(190).duration(30))
apsResult.tempBasalRequested(true).percent(200).duration(30) apsResult.tempBasalRequested(true).percent(200).duration(30)
Assert.assertEquals(true, apsResult.isChangeRequested) Assert.assertEquals(true, apsResult.isChangeRequested)
// request slightly different temp // request slightly different temp
`when`(treatmentsPlugin.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal(injector).percent(70).duration(30)) `when`(treatmentsInterface.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal(injector).percent(70).duration(30))
apsResult.tempBasalRequested(true).percent(80).duration(30) apsResult.tempBasalRequested(true).percent(80).duration(30)
Assert.assertEquals(false, apsResult.isChangeRequested) Assert.assertEquals(false, apsResult.isChangeRequested)
// request different temp // request different temp
`when`(treatmentsPlugin.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal(injector).percent(70).duration(30)) `when`(treatmentsInterface.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal(injector).percent(70).duration(30))
apsResult.tempBasalRequested(true).percent(120).duration(30) apsResult.tempBasalRequested(true).percent(120).duration(30)
Assert.assertEquals(true, apsResult.isChangeRequested) Assert.assertEquals(true, apsResult.isChangeRequested)
// it should work with absolute temps too // it should work with absolute temps too
// request different temp // request different temp
`when`(treatmentsPlugin.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal(injector).absolute(1.0).duration(30)) `when`(treatmentsInterface.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal(injector).absolute(1.0).duration(30))
apsResult.tempBasalRequested(true).percent(100).duration(30) apsResult.tempBasalRequested(true).percent(100).duration(30)
Assert.assertEquals(false, apsResult.isChangeRequested) Assert.assertEquals(false, apsResult.isChangeRequested)
`when`(treatmentsPlugin.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal(injector).absolute(2.0).duration(30)) `when`(treatmentsInterface.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal(injector).absolute(2.0).duration(30))
apsResult.tempBasalRequested(true).percent(50).duration(30) apsResult.tempBasalRequested(true).percent(50).duration(30)
Assert.assertEquals(true, apsResult.isChangeRequested) Assert.assertEquals(true, apsResult.isChangeRequested)
@ -115,44 +115,44 @@ class APSResultTest : TestBaseWithProfile() {
// open loop // open loop
closedLoopEnabled.set(aapsLogger, false) closedLoopEnabled.set(aapsLogger, false)
// request 100% when no temp is running // request 100% when no temp is running
`when`(treatmentsPlugin.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(null) `when`(treatmentsInterface.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(null)
apsResult.tempBasalRequested(true).rate(1.0).duration(30) apsResult.tempBasalRequested(true).rate(1.0).duration(30)
Assert.assertEquals(false, apsResult.isChangeRequested) Assert.assertEquals(false, apsResult.isChangeRequested)
// request equal temp // request equal temp
`when`(treatmentsPlugin.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal(injector).absolute(2.0).duration(30)) `when`(treatmentsInterface.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal(injector).absolute(2.0).duration(30))
apsResult.tempBasalRequested(true).rate(2.0).duration(30) apsResult.tempBasalRequested(true).rate(2.0).duration(30)
Assert.assertEquals(false, apsResult.isChangeRequested) Assert.assertEquals(false, apsResult.isChangeRequested)
`when`(treatmentsPlugin.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal(injector).percent(200).duration(30)) `when`(treatmentsInterface.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal(injector).percent(200).duration(30))
apsResult.tempBasalRequested(true).rate(2.0).duration(30) apsResult.tempBasalRequested(true).rate(2.0).duration(30)
Assert.assertEquals(false, apsResult.isChangeRequested) Assert.assertEquals(false, apsResult.isChangeRequested)
// request zero temp // request zero temp
`when`(treatmentsPlugin.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal(injector).absolute(0.1).duration(30)) `when`(treatmentsInterface.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal(injector).absolute(0.1).duration(30))
apsResult.tempBasalRequested(true).rate(0.0).duration(30) apsResult.tempBasalRequested(true).rate(0.0).duration(30)
Assert.assertEquals(true, apsResult.isChangeRequested) Assert.assertEquals(true, apsResult.isChangeRequested)
// request high temp // request high temp
`when`(treatmentsPlugin.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal(injector).absolute(34.9).duration(30)) `when`(treatmentsInterface.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal(injector).absolute(34.9).duration(30))
apsResult.tempBasalRequested(true).rate(35.0).duration(30) apsResult.tempBasalRequested(true).rate(35.0).duration(30)
Assert.assertEquals(true, apsResult.isChangeRequested) Assert.assertEquals(true, apsResult.isChangeRequested)
// request slightly different temp // request slightly different temp
`when`(treatmentsPlugin.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal(injector).absolute(1.1).duration(30)) `when`(treatmentsInterface.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal(injector).absolute(1.1).duration(30))
apsResult.tempBasalRequested(true).rate(1.2).duration(30) apsResult.tempBasalRequested(true).rate(1.2).duration(30)
Assert.assertEquals(false, apsResult.isChangeRequested) Assert.assertEquals(false, apsResult.isChangeRequested)
// request different temp // request different temp
`when`(treatmentsPlugin.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal(injector).absolute(1.1).duration(30)) `when`(treatmentsInterface.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal(injector).absolute(1.1).duration(30))
apsResult.tempBasalRequested(true).rate(1.5).duration(30) apsResult.tempBasalRequested(true).rate(1.5).duration(30)
Assert.assertEquals(true, apsResult.isChangeRequested) Assert.assertEquals(true, apsResult.isChangeRequested)
// it should work with percent temps too // it should work with percent temps too
// request different temp // request different temp
`when`(treatmentsPlugin.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal(injector).percent(110).duration(30)) `when`(treatmentsInterface.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal(injector).percent(110).duration(30))
apsResult.tempBasalRequested(true).rate(1.1).duration(30) apsResult.tempBasalRequested(true).rate(1.1).duration(30)
Assert.assertEquals(false, apsResult.isChangeRequested) Assert.assertEquals(false, apsResult.isChangeRequested)
`when`(treatmentsPlugin.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal(injector).percent(200).duration(30)) `when`(treatmentsInterface.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal(injector).percent(200).duration(30))
apsResult.tempBasalRequested(true).rate(0.5).duration(30) apsResult.tempBasalRequested(true).rate(0.5).duration(30)
Assert.assertEquals(true, apsResult.isChangeRequested) Assert.assertEquals(true, apsResult.isChangeRequested)
} }
@ -164,7 +164,7 @@ class APSResultTest : TestBaseWithProfile() {
it.constraintChecker = constraintChecker it.constraintChecker = constraintChecker
it.sp = sp it.sp = sp
it.activePlugin = activePluginProvider it.activePlugin = activePluginProvider
it.treatmentsPlugin = treatmentsPlugin it.treatmentsPlugin = treatmentsInterface
it.profileFunction = profileFunction it.profileFunction = profileFunction
it.resourceHelper = resourceHelper it.resourceHelper = resourceHelper
} }
@ -181,7 +181,7 @@ class APSResultTest : TestBaseWithProfile() {
it.constraintChecker = constraintChecker it.constraintChecker = constraintChecker
it.sp = sp it.sp = sp
it.activePlugin = activePluginProvider it.activePlugin = activePluginProvider
it.treatmentsPlugin = treatmentsPlugin it.treatmentsPlugin = treatmentsInterface
it.profileFunction = profileFunction it.profileFunction = profileFunction
it.resourceHelper = resourceHelper it.resourceHelper = resourceHelper
} }

View file

@ -76,7 +76,7 @@ class SafetyPluginTest : TestBaseWithProfile() {
`when`(activePlugin.activePump).thenReturn(virtualPumpPlugin) `when`(activePlugin.activePump).thenReturn(virtualPumpPlugin)
`when`(virtualPumpPlugin.pumpDescription).thenReturn(pumpDescription) `when`(virtualPumpPlugin.pumpDescription).thenReturn(pumpDescription)
hardLimits = HardLimits(aapsLogger, rxBus, sp, resourceHelper, context, nsUpload) hardLimits = HardLimits(aapsLogger, rxBus, sp, resourceHelper, context, nsUpload)
safetyPlugin = SafetyPlugin(injector, aapsLogger, resourceHelper, sp, rxBus, constraintChecker, openAPSAMAPlugin, openAPSSMBPlugin, sensitivityOref1Plugin, activePlugin, hardLimits, buildHelper, treatmentsPlugin, Config()) safetyPlugin = SafetyPlugin(injector, aapsLogger, resourceHelper, sp, rxBus, constraintChecker, openAPSAMAPlugin, openAPSSMBPlugin, sensitivityOref1Plugin, activePlugin, hardLimits, buildHelper, treatmentsInterface, Config())
} }
@Test fun pumpDescriptionShouldLimitLoopInvocation() { @Test fun pumpDescriptionShouldLimitLoopInvocation() {

View file

@ -20,7 +20,7 @@ class ActionProfileSwitchPercentTest : ActionsTestBase() {
@Before @Before
fun setup() { fun setup() {
`when`(activePlugin.activeTreatments).thenReturn(treatmentsPlugin) `when`(activePlugin.activeTreatments).thenReturn(treatmentsInterface)
`when`(resourceHelper.gs(R.string.startprofileforever)).thenReturn("Start profile %d%%") `when`(resourceHelper.gs(R.string.startprofileforever)).thenReturn("Start profile %d%%")
`when`(resourceHelper.gs(R.string.startprofile)).thenReturn("Start profile %d%% for %d min") `when`(resourceHelper.gs(R.string.startprofile)).thenReturn("Start profile %d%% for %d min")
@ -49,7 +49,7 @@ class ActionProfileSwitchPercentTest : ActionsTestBase() {
Assert.assertTrue(result.success) Assert.assertTrue(result.success)
} }
}) })
Mockito.verify(treatmentsPlugin, Mockito.times(1)).doProfileSwitch(30, 110, 0) Mockito.verify(treatmentsInterface, Mockito.times(1)).doProfileSwitch(30, 110, 0)
} }
@Test fun hasDialogTest() { @Test fun hasDialogTest() {

View file

@ -26,7 +26,7 @@ class ActionProfileSwitchTest : ActionsTestBase() {
private val stringJson = "{\"data\":{\"profileToSwitchTo\":\"Test\"},\"type\":\"info.nightscout.androidaps.plugins.general.automation.actions.ActionProfileSwitch\"}" private val stringJson = "{\"data\":{\"profileToSwitchTo\":\"Test\"},\"type\":\"info.nightscout.androidaps.plugins.general.automation.actions.ActionProfileSwitch\"}"
@Before fun setUp() { @Before fun setUp() {
`when`(activePlugin.activeTreatments).thenReturn(treatmentsPlugin) `when`(activePlugin.activeTreatments).thenReturn(treatmentsInterface)
`when`(resourceHelper.gs(R.string.profilename)).thenReturn("Change profile to") `when`(resourceHelper.gs(R.string.profilename)).thenReturn("Change profile to")
`when`(resourceHelper.gs(ArgumentMatchers.eq(R.string.changengetoprofilename), ArgumentMatchers.anyString())).thenReturn("Change profile to %s") `when`(resourceHelper.gs(ArgumentMatchers.eq(R.string.changengetoprofilename), ArgumentMatchers.anyString())).thenReturn("Change profile to %s")
`when`(resourceHelper.gs(R.string.alreadyset)).thenReturn("Already set") `when`(resourceHelper.gs(R.string.alreadyset)).thenReturn("Already set")
@ -97,7 +97,7 @@ class ActionProfileSwitchTest : ActionsTestBase() {
Assert.assertEquals("OK", result.comment) Assert.assertEquals("OK", result.comment)
} }
}) })
Mockito.verify(treatmentsPlugin, Mockito.times(1)).doProfileSwitch(anyObject(), anyString(), anyInt(), anyInt(), anyInt(), anyLong()) Mockito.verify(treatmentsInterface, Mockito.times(1)).doProfileSwitch(anyObject(), anyString(), anyInt(), anyInt(), anyInt(), anyLong())
} }
@Test fun hasDialogTest() { @Test fun hasDialogTest() {

View file

@ -12,7 +12,6 @@ import org.junit.Test
import org.junit.runner.RunWith import org.junit.runner.RunWith
import org.mockito.Mockito import org.mockito.Mockito
import org.mockito.Mockito.`when` import org.mockito.Mockito.`when`
import org.powermock.api.mockito.PowerMockito
import org.powermock.core.classloader.annotations.PrepareForTest import org.powermock.core.classloader.annotations.PrepareForTest
import org.powermock.modules.junit4.PowerMockRunner import org.powermock.modules.junit4.PowerMockRunner
@ -45,13 +44,13 @@ class ActionStartTempTargetTest : ActionsTestBase() {
} }
@Test fun doActionTest() { @Test fun doActionTest() {
`when`(activePlugin.activeTreatments).thenReturn(treatmentsPlugin) `when`(activePlugin.activeTreatments).thenReturn(treatmentsInterface)
sut.doAction(object : Callback() { sut.doAction(object : Callback() {
override fun run() { override fun run() {
Assert.assertTrue(result.success) Assert.assertTrue(result.success)
} }
}) })
Mockito.verify(treatmentsPlugin, Mockito.times(1)).addToHistoryTempTarget(anyObject()) Mockito.verify(treatmentsInterface, Mockito.times(1)).addToHistoryTempTarget(anyObject())
} }
@Test fun hasDialogTest() { @Test fun hasDialogTest() {

View file

@ -38,13 +38,13 @@ class ActionStopTempTargetTest : ActionsTestBase() {
} }
@Test fun doActionTest() { @Test fun doActionTest() {
`when`(activePlugin.activeTreatments).thenReturn(treatmentsPlugin) `when`(activePlugin.activeTreatments).thenReturn(treatmentsInterface)
sut.doAction(object : Callback() { sut.doAction(object : Callback() {
override fun run() { override fun run() {
Assert.assertTrue(result.success) Assert.assertTrue(result.success)
} }
}) })
Mockito.verify(treatmentsPlugin, Mockito.times(1)).addToHistoryTempTarget(anyObject()) Mockito.verify(treatmentsInterface, Mockito.times(1)).addToHistoryTempTarget(anyObject())
} }
@Test fun hasDialogTest() { @Test fun hasDialogTest() {

View file

@ -9,19 +9,21 @@ import org.junit.Test
import org.junit.runner.RunWith import org.junit.runner.RunWith
import org.powermock.modules.junit4.PowerMockRunner import org.powermock.modules.junit4.PowerMockRunner
@Suppress("SpellCheckingInspection")
@RunWith(PowerMockRunner::class) @RunWith(PowerMockRunner::class)
class TriggerBTDeviceTest : TriggerTestBase() { class TriggerBTDeviceTest : TriggerTestBase() {
var now = 1514766900000L var now = 1514766900000L
var someName = "Headset" private var someName = "Headset"
var btJson = "{\"data\":{\"comparator\":\"ON_CONNECT\",\"name\":\"Headset\"},\"type\":\"info.nightscout.androidaps.plugins.general.automation.triggers.TriggerBTDevice\"}" private var btJson = "{\"data\":{\"comparator\":\"ON_CONNECT\",\"name\":\"Headset\"},\"type\":\"info.nightscout.androidaps.plugins.general.automation.triggers.TriggerBTDevice\"}"
@Test fun shouldRun() { @Test fun shouldRun() {
val t: TriggerBTDevice = TriggerBTDevice(injector) @Suppress("UNUSED_VARIABLE")
val t = TriggerBTDevice(injector)
} }
@Test fun toJSON() { @Test fun toJSON() {
val t: TriggerBTDevice = TriggerBTDevice(injector) val t = TriggerBTDevice(injector)
t.btDevice.value = someName t.btDevice.value = someName
Assert.assertEquals(btJson, t.toJSON()) Assert.assertEquals(btJson, t.toJSON())
} }

View file

@ -30,7 +30,7 @@ class TriggerBolusAgoTest : TriggerTestBase() {
@Test @Test
fun shouldRunTest() { fun shouldRunTest() {
`when`(treatmentsPlugin.getLastBolusTime(true)).thenReturn(now) // Set last bolus time to now `when`(treatmentsInterface.getLastBolusTime(true)).thenReturn(now) // Set last bolus time to now
`when`(DateUtil.now()).thenReturn(now + 10 * 60 * 1000) // set current time to now + 10 min `when`(DateUtil.now()).thenReturn(now + 10 * 60 * 1000) // set current time to now + 10 min
var t = TriggerBolusAgo(injector).setValue(110).comparator(Comparator.Compare.IS_EQUAL) var t = TriggerBolusAgo(injector).setValue(110).comparator(Comparator.Compare.IS_EQUAL)
Assert.assertEquals(110, t.minutesAgo.value) Assert.assertEquals(110, t.minutesAgo.value)
@ -53,7 +53,7 @@ class TriggerBolusAgoTest : TriggerTestBase() {
Assert.assertTrue(t.shouldRun()) Assert.assertTrue(t.shouldRun())
t = TriggerBolusAgo(injector).setValue(390).comparator(Comparator.Compare.IS_EQUAL_OR_LESSER) t = TriggerBolusAgo(injector).setValue(390).comparator(Comparator.Compare.IS_EQUAL_OR_LESSER)
Assert.assertTrue(t.shouldRun()) Assert.assertTrue(t.shouldRun())
PowerMockito.`when`(treatmentsPlugin.getLastBolusTime(true)).thenReturn(0L) // Set last bolus time to 0 PowerMockito.`when`(treatmentsInterface.getLastBolusTime(true)).thenReturn(0L) // Set last bolus time to 0
t = TriggerBolusAgo(injector).comparator(Comparator.Compare.IS_NOT_AVAILABLE) t = TriggerBolusAgo(injector).comparator(Comparator.Compare.IS_NOT_AVAILABLE)
Assert.assertTrue(t.shouldRun()) Assert.assertTrue(t.shouldRun())
} }

View file

@ -28,12 +28,12 @@ class TriggerTempTargetTest : TriggerTestBase() {
} }
@Test fun shouldRunTest() { @Test fun shouldRunTest() {
`when`(treatmentsPlugin.tempTargetFromHistory).thenReturn(null) `when`(treatmentsInterface.tempTargetFromHistory).thenReturn(null)
var t: TriggerTempTarget = TriggerTempTarget(injector).comparator(ComparatorExists.Compare.EXISTS) var t: TriggerTempTarget = TriggerTempTarget(injector).comparator(ComparatorExists.Compare.EXISTS)
Assert.assertFalse(t.shouldRun()) Assert.assertFalse(t.shouldRun())
t = TriggerTempTarget(injector).comparator(ComparatorExists.Compare.NOT_EXISTS) t = TriggerTempTarget(injector).comparator(ComparatorExists.Compare.NOT_EXISTS)
Assert.assertTrue(t.shouldRun()) Assert.assertTrue(t.shouldRun())
PowerMockito.`when`(treatmentsPlugin.tempTargetFromHistory).thenReturn(TempTarget()) PowerMockito.`when`(treatmentsInterface.tempTargetFromHistory).thenReturn(TempTarget())
t = TriggerTempTarget(injector).comparator(ComparatorExists.Compare.NOT_EXISTS) t = TriggerTempTarget(injector).comparator(ComparatorExists.Compare.NOT_EXISTS)
Assert.assertFalse(t.shouldRun()) Assert.assertFalse(t.shouldRun())
t = TriggerTempTarget(injector).comparator(ComparatorExists.Compare.EXISTS) t = TriggerTempTarget(injector).comparator(ComparatorExists.Compare.EXISTS)

View file

@ -45,7 +45,7 @@ open class TriggerTestBase : TestBaseWithProfile() {
it.profileFunction = profileFunction it.profileFunction = profileFunction
it.sp = sp it.sp = sp
it.locationDataContainer = locationDataContainer it.locationDataContainer = locationDataContainer
it.treatmentsPlugin = treatmentsPlugin it.treatmentsInterface = treatmentsInterface
it.activePlugin = activePlugin it.activePlugin = activePlugin
it.iobCobCalculatorPlugin = iobCobCalculatorPlugin it.iobCobCalculatorPlugin = iobCobCalculatorPlugin
} }

View file

@ -6,7 +6,6 @@ import info.nightscout.androidaps.plugins.general.maintenance.formats.Prefs
import info.nightscout.androidaps.testing.utils.SingleStringStorage import info.nightscout.androidaps.testing.utils.SingleStringStorage
import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.sharedPreferences.SP import info.nightscout.androidaps.utils.sharedPreferences.SP
import org.hamcrest.CoreMatchers
import org.junit.Assert import org.junit.Assert
import org.junit.Test import org.junit.Test
import org.junit.runner.RunWith import org.junit.runner.RunWith
@ -32,9 +31,9 @@ class ClassicPrefsFormatTest : TestBase() {
val classicFormat = ClassicPrefsFormat(resourceHelper, SingleStringStorage(test)) val classicFormat = ClassicPrefsFormat(resourceHelper, SingleStringStorage(test))
val prefs = classicFormat.loadPreferences(getMockedFile(), "") val prefs = classicFormat.loadPreferences(getMockedFile(), "")
Assert.assertThat(prefs.values.size, CoreMatchers.`is`(2)) Assert.assertEquals(prefs.values.size, 2)
Assert.assertThat(prefs.values["key1"], CoreMatchers.`is`("val1")) Assert.assertEquals(prefs.values["key1"], "val1")
Assert.assertThat(prefs.values["keyB"], CoreMatchers.`is`("valB")) Assert.assertEquals(prefs.values["keyB"], "valB")
Assert.assertNull(prefs.values["key3"]) Assert.assertNull(prefs.values["key3"])
} }

View file

@ -4,11 +4,11 @@ import info.nightscout.androidaps.TestBase
import info.nightscout.androidaps.plugins.general.maintenance.formats.* import info.nightscout.androidaps.plugins.general.maintenance.formats.*
import info.nightscout.androidaps.testing.utils.SingleStringStorage import info.nightscout.androidaps.testing.utils.SingleStringStorage
import info.nightscout.androidaps.utils.CryptoUtil import info.nightscout.androidaps.utils.CryptoUtil
import info.nightscout.androidaps.utils.assumeAES256isSupported
import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.sharedPreferences.SP import info.nightscout.androidaps.utils.sharedPreferences.SP
import org.hamcrest.CoreMatchers import org.hamcrest.CoreMatchers
import org.junit.Assert import org.junit.Assert
import org.junit.Assume
import org.junit.Before import org.junit.Before
import org.junit.Test import org.junit.Test
import org.junit.runner.RunWith import org.junit.runner.RunWith
@ -20,6 +20,7 @@ import org.powermock.core.classloader.annotations.PrepareForTest
import org.powermock.modules.junit4.PowerMockRunner import org.powermock.modules.junit4.PowerMockRunner
import java.io.File import java.io.File
@Suppress("SpellCheckingInspection")
@PowerMockIgnore("javax.crypto.*") @PowerMockIgnore("javax.crypto.*")
@RunWith(PowerMockRunner::class) @RunWith(PowerMockRunner::class)
@PrepareForTest(File::class) @PrepareForTest(File::class)
@ -32,6 +33,16 @@ class EncryptedPrefsFormatTest : TestBase() {
private var cryptoUtil: CryptoUtil = CryptoUtil(aapsLogger) private var cryptoUtil: CryptoUtil = CryptoUtil(aapsLogger)
// https://stackoverflow.com/questions/52344522/joseexception-couldnt-create-aes-gcm-nopadding-cipher-illegal-key-size
// https://stackoverflow.com/questions/47708951/can-aes-256-work-on-android-devices-with-api-level-26
// Java prior to Oracle Java 8u161 does not have policy for 256 bit AES - but Android support it
// when test is run in Vanilla JVM without policy - Invalid key size exception is thrown
private fun assumeAES256isSupported(cryptoUtil: CryptoUtil) {
cryptoUtil.lastException?.message?.let { exceptionMessage ->
Assume.assumeThat("Upgrade your testing environment Java (OpenJDK or Java 8u161) and JAVA_HOME - AES 256 is supported by Android so this exception should not happen!", exceptionMessage, CoreMatchers.not(CoreMatchers.containsString("key size")))
}
}
@Before @Before
fun mock() { fun mock() {
Mockito.`when`(resourceHelper.gs(ArgumentMatchers.anyInt())).thenReturn("mock translation") Mockito.`when`(resourceHelper.gs(ArgumentMatchers.anyInt())).thenReturn("mock translation")
@ -57,13 +68,13 @@ class EncryptedPrefsFormatTest : TestBase() {
assumeAES256isSupported(cryptoUtil) assumeAES256isSupported(cryptoUtil)
Assert.assertThat(prefs.values.size, CoreMatchers.`is`(2)) Assert.assertEquals(prefs.values.size, 2)
Assert.assertThat(prefs.values["key1"], CoreMatchers.`is`("A")) Assert.assertEquals(prefs.values["key1"], "A")
Assert.assertThat(prefs.values["keyB"], CoreMatchers.`is`("2")) Assert.assertEquals(prefs.values["keyB"], "2")
Assert.assertThat(prefs.metadata[PrefsMetadataKey.FILE_FORMAT]?.status, CoreMatchers.`is`(PrefsStatus.OK)) Assert.assertEquals(prefs.metadata[PrefsMetadataKey.FILE_FORMAT]?.status, PrefsStatus.OK)
Assert.assertThat(prefs.metadata[PrefsMetadataKey.FILE_FORMAT]?.value, CoreMatchers.`is`(EncryptedPrefsFormat.FORMAT_KEY_ENC)) Assert.assertEquals(prefs.metadata[PrefsMetadataKey.FILE_FORMAT]?.value, EncryptedPrefsFormat.FORMAT_KEY_ENC)
Assert.assertThat(prefs.metadata[PrefsMetadataKey.ENCRYPTION]?.status, CoreMatchers.`is`(PrefsStatus.OK)) Assert.assertEquals(prefs.metadata[PrefsMetadataKey.ENCRYPTION]?.status, PrefsStatus.OK)
} }
@Test @Test
@ -101,13 +112,13 @@ class EncryptedPrefsFormatTest : TestBase() {
assumeAES256isSupported(cryptoUtil) assumeAES256isSupported(cryptoUtil)
Assert.assertThat(prefsOut.values.size, CoreMatchers.`is`(2)) Assert.assertEquals(prefsOut.values.size, 2)
Assert.assertThat(prefsOut.values["testpref1"], CoreMatchers.`is`("--1--")) Assert.assertEquals(prefsOut.values["testpref1"], "--1--")
Assert.assertThat(prefsOut.values["testpref2"], CoreMatchers.`is`("another")) Assert.assertEquals(prefsOut.values["testpref2"], "another")
Assert.assertThat(prefsOut.metadata[PrefsMetadataKey.FILE_FORMAT]?.status, CoreMatchers.`is`(PrefsStatus.OK)) Assert.assertEquals(prefsOut.metadata[PrefsMetadataKey.FILE_FORMAT]?.status, PrefsStatus.OK)
Assert.assertThat(prefsOut.metadata[PrefsMetadataKey.FILE_FORMAT]?.value, CoreMatchers.`is`(EncryptedPrefsFormat.FORMAT_KEY_ENC)) Assert.assertEquals(prefsOut.metadata[PrefsMetadataKey.FILE_FORMAT]?.value, EncryptedPrefsFormat.FORMAT_KEY_ENC)
Assert.assertThat(prefsOut.metadata[PrefsMetadataKey.ENCRYPTION]?.status, CoreMatchers.`is`(PrefsStatus.OK)) Assert.assertEquals(prefsOut.metadata[PrefsMetadataKey.ENCRYPTION]?.status, PrefsStatus.OK)
} }
@Test @Test
@ -128,11 +139,11 @@ class EncryptedPrefsFormatTest : TestBase() {
val encryptedFormat = EncryptedPrefsFormat(resourceHelper, cryptoUtil, storage) val encryptedFormat = EncryptedPrefsFormat(resourceHelper, cryptoUtil, storage)
val prefs = encryptedFormat.loadPreferences(getMockedFile(), "it-is-NOT-right-secret") val prefs = encryptedFormat.loadPreferences(getMockedFile(), "it-is-NOT-right-secret")
Assert.assertThat(prefs.values.size, CoreMatchers.`is`(0)) Assert.assertEquals(prefs.values.size, 0)
Assert.assertThat(prefs.metadata[PrefsMetadataKey.FILE_FORMAT]?.status, CoreMatchers.`is`(PrefsStatus.OK)) Assert.assertEquals(prefs.metadata[PrefsMetadataKey.FILE_FORMAT]?.status, PrefsStatus.OK)
Assert.assertThat(prefs.metadata[PrefsMetadataKey.FILE_FORMAT]?.value, CoreMatchers.`is`(EncryptedPrefsFormat.FORMAT_KEY_ENC)) Assert.assertEquals(prefs.metadata[PrefsMetadataKey.FILE_FORMAT]?.value, EncryptedPrefsFormat.FORMAT_KEY_ENC)
Assert.assertThat(prefs.metadata[PrefsMetadataKey.ENCRYPTION]?.status, CoreMatchers.`is`(PrefsStatus.ERROR)) Assert.assertEquals(prefs.metadata[PrefsMetadataKey.ENCRYPTION]?.status, PrefsStatus.ERROR)
} }
@Test @Test
@ -158,10 +169,10 @@ class EncryptedPrefsFormatTest : TestBase() {
assumeAES256isSupported(cryptoUtil) assumeAES256isSupported(cryptoUtil)
// contents were not tampered and we can decrypt them // contents were not tampered and we can decrypt them
Assert.assertThat(prefs.values.size, CoreMatchers.`is`(2)) Assert.assertEquals(prefs.values.size, 2)
// but checksum fails on metadata, so overall security fails // but checksum fails on metadata, so overall security fails
Assert.assertThat(prefs.metadata[PrefsMetadataKey.ENCRYPTION]?.status, CoreMatchers.`is`(PrefsStatus.ERROR)) Assert.assertEquals(prefs.metadata[PrefsMetadataKey.ENCRYPTION]?.status, PrefsStatus.ERROR)
} }
@Test @Test
@ -182,8 +193,8 @@ class EncryptedPrefsFormatTest : TestBase() {
val encryptedFormat = EncryptedPrefsFormat(resourceHelper, cryptoUtil, storage) val encryptedFormat = EncryptedPrefsFormat(resourceHelper, cryptoUtil, storage)
val prefs = encryptedFormat.loadPreferences(getMockedFile(), "sikret") val prefs = encryptedFormat.loadPreferences(getMockedFile(), "sikret")
Assert.assertThat(prefs.values.size, CoreMatchers.`is`(0)) Assert.assertEquals(prefs.values.size, 0)
Assert.assertThat(prefs.metadata[PrefsMetadataKey.ENCRYPTION]?.status, CoreMatchers.`is`(PrefsStatus.ERROR)) Assert.assertEquals(prefs.metadata[PrefsMetadataKey.ENCRYPTION]?.status, PrefsStatus.ERROR)
} }
@Test @Test
@ -197,8 +208,8 @@ class EncryptedPrefsFormatTest : TestBase() {
val encryptedFormat = EncryptedPrefsFormat(resourceHelper, cryptoUtil, storage) val encryptedFormat = EncryptedPrefsFormat(resourceHelper, cryptoUtil, storage)
val prefs = encryptedFormat.loadPreferences(getMockedFile(), "sikret") val prefs = encryptedFormat.loadPreferences(getMockedFile(), "sikret")
Assert.assertThat(prefs.values.size, CoreMatchers.`is`(0)) Assert.assertEquals(prefs.values.size, 0)
Assert.assertThat(prefs.metadata[PrefsMetadataKey.FILE_FORMAT]?.status, CoreMatchers.`is`(PrefsStatus.ERROR)) Assert.assertEquals(prefs.metadata[PrefsMetadataKey.FILE_FORMAT]?.status, PrefsStatus.ERROR)
} }
@Test(expected = PrefFormatError::class) @Test(expected = PrefFormatError::class)

View file

@ -154,16 +154,16 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() {
}.`when`(commandQueue).extendedBolus(ArgumentMatchers.anyDouble(), ArgumentMatchers.anyInt(), ArgumentMatchers.any(Callback::class.java)) }.`when`(commandQueue).extendedBolus(ArgumentMatchers.anyDouble(), ArgumentMatchers.anyInt(), ArgumentMatchers.any(Callback::class.java))
`when`(activePlugin.activePump).thenReturn(virtualPumpPlugin) `when`(activePlugin.activePump).thenReturn(virtualPumpPlugin)
`when`(activePlugin.activeTreatments).thenReturn(treatmentsPlugin) `when`(activePlugin.activeTreatments).thenReturn(treatmentsInterface)
`when`(virtualPumpPlugin.shortStatus(ArgumentMatchers.anyBoolean())).thenReturn("Virtual Pump") `when`(virtualPumpPlugin.shortStatus(ArgumentMatchers.anyBoolean())).thenReturn("Virtual Pump")
`when`(virtualPumpPlugin.isSuspended()).thenReturn(false) `when`(virtualPumpPlugin.isSuspended()).thenReturn(false)
`when`(virtualPumpPlugin.pumpDescription).thenReturn(PumpDescription()) `when`(virtualPumpPlugin.pumpDescription).thenReturn(PumpDescription())
`when`(virtualPumpPlugin.model()).thenReturn(PumpType.GenericAAPS) `when`(virtualPumpPlugin.model()).thenReturn(PumpType.GenericAAPS)
`when`(treatmentsPlugin.lastCalculationTreatments).thenReturn(IobTotal(0)) `when`(treatmentsInterface.lastCalculationTreatments).thenReturn(IobTotal(0))
`when`(treatmentsPlugin.lastCalculationTempBasals).thenReturn(IobTotal(0)) `when`(treatmentsInterface.lastCalculationTempBasals).thenReturn(IobTotal(0))
`when`(treatmentsPlugin.service).thenReturn(treatmentService) `when`(treatmentsInterface.service).thenReturn(treatmentService)
`when`(activePlugin.activeProfileInterface).thenReturn(localProfilePlugin) `when`(activePlugin.activeProfileInterface).thenReturn(localProfilePlugin)

View file

@ -2,23 +2,22 @@ package info.nightscout.androidaps.plugins.pump.common.utils;
import android.util.Log; import android.util.Log;
import junit.framework.Assert; import org.junit.Assert;
import org.junit.Test; import org.junit.Test;
public class DateTimeUtilUTest { public class DateTimeUtilUTest {
@Test @Test
public void getATechDateDiferenceAsMinutes() { public void getATechDateDifferenceAsMinutes() {
long dt1 = 20191001182301L; long dt1 = 20191001182301L;
long dt2 = 20191001192805L; long dt2 = 20191001192805L;
int aTechDateDiferenceAsMinutes = DateTimeUtil.getATechDateDiferenceAsMinutes(dt1, dt2); int aTechDateDifferenceAsMinutes = DateTimeUtil.getATechDateDiferenceAsMinutes(dt1, dt2);
Assert.assertEquals(65, aTechDateDiferenceAsMinutes); Assert.assertEquals(65, aTechDateDifferenceAsMinutes);
Log.d("DateTimeUtilUTest", "Time difference: " + aTechDateDiferenceAsMinutes); Log.d("DateTimeUtilUTest", "Time difference: " + aTechDateDifferenceAsMinutes);
} }
} }

View file

@ -25,6 +25,7 @@ import org.powermock.api.mockito.PowerMockito
import org.powermock.core.classloader.annotations.PrepareForTest import org.powermock.core.classloader.annotations.PrepareForTest
import org.powermock.modules.junit4.PowerMockRunner import org.powermock.modules.junit4.PowerMockRunner
@Suppress("SpellCheckingInspection")
@RunWith(PowerMockRunner::class) @RunWith(PowerMockRunner::class)
@PrepareForTest(FabricPrivacy::class, MainApp::class, DatabaseHelper::class) @PrepareForTest(FabricPrivacy::class, MainApp::class, DatabaseHelper::class)
class TreatmentsPluginTest : TestBaseWithProfile() { class TreatmentsPluginTest : TestBaseWithProfile() {
@ -47,8 +48,8 @@ class TreatmentsPluginTest : TestBaseWithProfile() {
} }
} }
lateinit var insulinOrefRapidActingPlugin: InsulinOrefRapidActingPlugin private lateinit var insulinOrefRapidActingPlugin: InsulinOrefRapidActingPlugin
lateinit var sot: TreatmentsPlugin private lateinit var sot: TreatmentsPlugin
@Before @Before
fun prepare() { fun prepare() {
@ -77,7 +78,7 @@ class TreatmentsPluginTest : TestBaseWithProfile() {
} }
@Test @Test
fun `90% TBR and should produce less absolute insulin`() { fun `90pct TBR and should produce less absolute insulin`() {
val now = DateUtil.now() val now = DateUtil.now()
val tbrs: MutableList<TemporaryBasal> = ArrayList() val tbrs: MutableList<TemporaryBasal> = ArrayList()
`when`(databaseHelper.getTemporaryBasalsDataFromTime(ArgumentMatchers.anyLong(), ArgumentMatchers.anyBoolean())).thenReturn(tbrs) `when`(databaseHelper.getTemporaryBasalsDataFromTime(ArgumentMatchers.anyLong(), ArgumentMatchers.anyBoolean())).thenReturn(tbrs)
@ -91,7 +92,7 @@ class TreatmentsPluginTest : TestBaseWithProfile() {
} }
@Test @Test
fun `110% TBR and should produce 10% more absolute insulin`() { fun `110pct TBR and should produce 10pct more absolute insulin`() {
val now = DateUtil.now() val now = DateUtil.now()
val tbrs: MutableList<TemporaryBasal> = ArrayList() val tbrs: MutableList<TemporaryBasal> = ArrayList()
`when`(databaseHelper.getTemporaryBasalsDataFromTime(ArgumentMatchers.anyLong(), ArgumentMatchers.anyBoolean())).thenReturn(tbrs) `when`(databaseHelper.getTemporaryBasalsDataFromTime(ArgumentMatchers.anyLong(), ArgumentMatchers.anyBoolean())).thenReturn(tbrs)

View file

@ -107,8 +107,8 @@ class CommandQueueTest : TestBaseWithProfile() {
`when`(context.getSystemService(Context.POWER_SERVICE)).thenReturn(powerManager) `when`(context.getSystemService(Context.POWER_SERVICE)).thenReturn(powerManager)
`when`(lazyActivePlugin.get()).thenReturn(activePlugin) `when`(lazyActivePlugin.get()).thenReturn(activePlugin)
`when`(activePlugin.activePump).thenReturn(testPumpPlugin) `when`(activePlugin.activePump).thenReturn(testPumpPlugin)
`when`(activePlugin.activeTreatments).thenReturn(treatmentsPlugin) `when`(activePlugin.activeTreatments).thenReturn(treatmentsInterface)
`when`(treatmentsPlugin.lastBolusTime).thenReturn(Calendar.getInstance().also { it.set(2000, 0, 1) }.timeInMillis) `when`(treatmentsInterface.lastBolusTime).thenReturn(Calendar.getInstance().also { it.set(2000, 0, 1) }.timeInMillis)
`when`(profileFunction.getProfile()).thenReturn(validProfile) `when`(profileFunction.getProfile()).thenReturn(validProfile)
val bolusConstraint = Constraint(0.0) val bolusConstraint = Constraint(0.0)

View file

@ -72,8 +72,8 @@ class QueueThreadTest : TestBaseWithProfile() {
Mockito.`when`(context.getSystemService(Context.POWER_SERVICE)).thenReturn(powerManager) Mockito.`when`(context.getSystemService(Context.POWER_SERVICE)).thenReturn(powerManager)
Mockito.`when`(lazyActivePlugin.get()).thenReturn(activePlugin) Mockito.`when`(lazyActivePlugin.get()).thenReturn(activePlugin)
Mockito.`when`(activePlugin.activePump).thenReturn(pumpPlugin) Mockito.`when`(activePlugin.activePump).thenReturn(pumpPlugin)
Mockito.`when`(activePlugin.activeTreatments).thenReturn(treatmentsPlugin) Mockito.`when`(activePlugin.activeTreatments).thenReturn(treatmentsInterface)
Mockito.`when`(treatmentsPlugin.lastBolusTime).thenReturn(Calendar.getInstance().also { it.set(2000, 0, 1) }.timeInMillis) Mockito.`when`(treatmentsInterface.lastBolusTime).thenReturn(Calendar.getInstance().also { it.set(2000, 0, 1) }.timeInMillis)
Mockito.`when`(profileFunction.getProfile()).thenReturn(validProfile) Mockito.`when`(profileFunction.getProfile()).thenReturn(validProfile)
val bolusConstraint = Constraint(0.0) val bolusConstraint = Constraint(0.0)

View file

@ -1,158 +0,0 @@
package info.nightscout.androidaps.testing.mocks;
import android.content.SharedPreferences;
import androidx.annotation.Nullable;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class SharedPreferencesMock implements SharedPreferences {
private final EditorInternals editor = new EditorInternals();
class EditorInternals implements Editor {
Map<String, Object> innerMap = new HashMap<>();
@Override
public Editor putString(String k, @Nullable String v) {
innerMap.put(k, v);
return this;
}
@Override
public Editor putStringSet(String k, @Nullable Set<String> set) {
innerMap.put(k, set);
return this;
}
@Override
public Editor putInt(String k, int i) {
innerMap.put(k, i);
return this;
}
@Override
public Editor putLong(String k, long l) {
innerMap.put(k, l);
return this;
}
@Override
public Editor putFloat(String k, float v) {
innerMap.put(k, v);
return this;
}
@Override
public Editor putBoolean(String k, boolean b) {
innerMap.put(k, b);
return this;
}
@Override
public Editor remove(String k) {
innerMap.remove(k);
return this;
}
@Override
public Editor clear() {
innerMap.clear();
return this;
}
@Override
public boolean commit() {
return true;
}
@Override
public void apply() {
}
}
@Override
public Map<String, ?> getAll() {
return editor.innerMap;
}
@Nullable
@Override
public String getString(String k, @Nullable String s) {
if (editor.innerMap.containsKey(k)) {
return (String) editor.innerMap.get(k);
} else {
return s;
}
}
@Nullable
@Override
public Set<String> getStringSet(String k, @Nullable Set<String> set) {
if (editor.innerMap.containsKey(k)) {
return (Set<String>) editor.innerMap.get(k);
} else {
return set;
}
}
@Override
public int getInt(String k, int i) {
if (editor.innerMap.containsKey(k)) {
return (Integer) editor.innerMap.get(k);
} else {
return i;
}
}
@Override
public long getLong(String k, long l) {
if (editor.innerMap.containsKey(k)) {
return (Long) editor.innerMap.get(k);
} else {
return l;
}
}
@Override
public float getFloat(String k, float v) {
if (editor.innerMap.containsKey(k)) {
return (Float) editor.innerMap.get(k);
} else {
return v;
}
}
@Override
public boolean getBoolean(String k, boolean b) {
if (editor.innerMap.containsKey(k)) {
return (Boolean) editor.innerMap.get(k);
} else {
return b;
}
}
@Override
public boolean contains(String k) {
return editor.innerMap.containsKey(k);
}
@Override
public Editor edit() {
return editor;
}
@Override
public void registerOnSharedPreferenceChangeListener(OnSharedPreferenceChangeListener onSharedPreferenceChangeListener) {
}
@Override
public void unregisterOnSharedPreferenceChangeListener(OnSharedPreferenceChangeListener onSharedPreferenceChangeListener) {
}
}

View file

@ -1,42 +0,0 @@
package info.nightscout.androidaps.utils;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.modules.junit4.PowerMockRunner;
@RunWith(PowerMockRunner.class)
public class DecimalFormatterTest {
@Test
public void to0DecimalTest() {
Assert.assertEquals("1", DecimalFormatter.to0Decimal(1.33d).replace(",", "."));
Assert.assertEquals("1U", DecimalFormatter.to0Decimal(1.33d, "U").replace(",", "."));
}
@Test
public void to1DecimalTest() {
Assert.assertEquals("1.3", DecimalFormatter.to1Decimal(1.33d).replace(",", "."));
Assert.assertEquals("1.3U", DecimalFormatter.to1Decimal(1.33d, "U").replace(",", "."));
}
@Test
public void to2DecimalTest() {
Assert.assertEquals("1.33", DecimalFormatter.to2Decimal(1.3333d).replace(",", "."));
Assert.assertEquals("1.33U", DecimalFormatter.to2Decimal(1.3333d, "U").replace(",", "."));
}
@Test
public void to3DecimalTest() {
Assert.assertEquals("1.333", DecimalFormatter.to3Decimal(1.3333d).replace(",", "."));
Assert.assertEquals("1.333U", DecimalFormatter.to3Decimal(1.3333d, "U").replace(",", "."));
}
@Test
public void toPumpSupportedBolus() {
}
@Test
public void pumpSupportedBolusFormat() {
}
}

View file

@ -1,93 +0,0 @@
package info.nightscout.androidaps.utils;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
/**
* Created by mike on 12.03.2018.
*/
public class JsonHelperTest {
private String jsonString = "{\"d\":\"3.0\",\"i\":\"4\",\"s\":\"5\",\"b\":\"true\",\"j\":{\"a\": \"1\"}}";
@Test
public void safeGetObjectTest() throws JSONException {
JSONObject object = new JSONObject(jsonString);
Object o = new Object();
assertEquals(o, JsonHelper.safeGetObject(null, "x", o));
assertEquals(o, JsonHelper.safeGetObject(object, "x", o));
assertNotEquals(o, JsonHelper.safeGetObject(object, "d", o));
}
@Test
public void safeGetJSONObjectTest() throws JSONException {
JSONObject object = new JSONObject(jsonString);
JSONObject o = new JSONObject();
assertEquals(o, JsonHelper.safeGetJSONObject(null, "x", o));
assertTrue(JsonHelper.safeGetJSONObject(object, "j", o).has("a"));
assertEquals(o, JsonHelper.safeGetJSONObject(object, "d", o));
}
@Test
public void safeGetStringTest() throws JSONException {
JSONObject object = new JSONObject(jsonString);
Object o = new Object();
assertNull(JsonHelper.safeGetString(null, "s"));
assertNull(JsonHelper.safeGetString(object, "notexisting"));
assertEquals("5", JsonHelper.safeGetString(object, "s"));
assertEquals("default", JsonHelper.safeGetString(null, "notexisting", "default"));
assertEquals("default", JsonHelper.safeGetString(object, "notexisting", "default"));
assertEquals("5", JsonHelper.safeGetString(object, "s", "default"));
assertEquals("default", JsonHelper.safeGetStringAllowNull(null, "notexisting", "default"));
assertEquals("default", JsonHelper.safeGetStringAllowNull(object, "notexisting", "default"));
assertNull(JsonHelper.safeGetStringAllowNull(object, "notexisting", null));
assertEquals("5", JsonHelper.safeGetStringAllowNull(object, "s", "default"));
}
@Test
public void safeGetDoubleTest() throws JSONException {
JSONObject object = new JSONObject(jsonString);
assertEquals(0.0d, JsonHelper.safeGetDouble(object, "notexisting"), 0.0d);
assertEquals(0.0d, JsonHelper.safeGetDouble(null, "notexisting"), 0.0d);
assertEquals(3.0d, JsonHelper.safeGetDouble(object, "d"), 0.000001d);
assertEquals(6d, JsonHelper.safeGetDouble(null, "notexisting", 6d), 0.0d);
assertEquals(6d, JsonHelper.safeGetDouble(object, "notexisting", 6d), 0.0d);
assertEquals(3d, JsonHelper.safeGetDouble(object, "d", 6d), 0.0d);
}
@Test
public void safeGetLntTest() throws JSONException {
JSONObject object = new JSONObject(jsonString);
assertEquals(0, JsonHelper.safeGetInt(null, "notexisting"));
assertEquals(0, JsonHelper.safeGetInt(object, "notexisting"));
assertEquals(4, JsonHelper.safeGetInt(object, "i"));
}
@Test
public void safeGetLongTest() throws JSONException {
JSONObject object = new JSONObject(jsonString);
assertEquals(0, JsonHelper.safeGetInt(null, "notexisting"));
assertEquals(0, JsonHelper.safeGetInt(object, "notexisting"));
assertEquals(4, JsonHelper.safeGetInt(object, "i"));
}
@Test
public void safeGetBooleanTest() throws JSONException {
JSONObject object = new JSONObject(jsonString);
assertFalse(JsonHelper.safeGetBoolean(null, "notexisting"));
assertFalse(JsonHelper.safeGetBoolean(object, "notexisting"));
assertTrue(JsonHelper.safeGetBoolean(object, "b"));
}
}

View file

@ -1,41 +0,0 @@
package info.nightscout.androidaps.utils;
import org.junit.Test;
import static org.junit.Assert.*;
public class RoundTest {
public RoundTest(){
super();
}
@Test
public void roundToTest() throws Exception {
assertEquals( 0.55d, Round.roundTo(0.54d, 0.05d), 0.00000000000000000001d );
assertEquals( -3.26d, Round.roundTo(-3.2553715764602713d, 0.01d), 0.00000000000000000001d );
assertEquals( 0.816d, Round.roundTo(0.8156666666666667d, 0.001d), 0.00000000000000000001d );
assertEquals( 0.235d, Round.roundTo(0.235d, 0.001d), 0.00000000000000000001d );
assertEquals( 0.3d, Round.roundTo(0.3d, 0.1d), 0.00000000000000001d );
assertEquals( 0.0017d, Round.roundTo(0.0016960652144170627d, 0.0001d), 0.00000000000000000001d );
assertEquals( 0.0078d, Round.roundTo(0.007804436682291013d, 0.0001d), 0.00000000000000000001d );
assertEquals( 0.6d, Round.roundTo(0.6d, 0.05d), 0.00000000000000000001d );
assertEquals( 1d, Round.roundTo(1.49d, 1d), 0.00000000000000000001d );
assertEquals( 0d, Round.roundTo(0d, 1d), 0.00000000000000000001d );
}
@Test
public void floorToTest() throws Exception {
assertEquals( 0.5d, Round.floorTo(0.54d, 0.05d), 0.00000001d );
assertEquals( 1d, Round.floorTo(1.59d, 1d), 0.00000001d );
assertEquals( 0d, Round.floorTo(0d, 1d), 0.00000001d );
}
@Test
public void ceilToTest() throws Exception {
assertEquals( 0.6d, Round.ceilTo(0.54d, 0.1d), 0.00000001d );
assertEquals( 2d, Round.ceilTo(1.49999d, 1d), 0.00000001d );
assertEquals( 0d, Round.ceilTo(0d, 1d), 0.00000001d );
}
}

View file

@ -1,22 +0,0 @@
package info.nightscout.androidaps.utils;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class StringUtilsTest {
@Test
public void removeSurroundingQuotesTest() {
String compareString = "test";
assertEquals(compareString, StringUtils.removeSurroundingQuotes(compareString));
assertEquals(compareString, StringUtils.removeSurroundingQuotes("\"" + compareString + "\""));
assertEquals("\"" + compareString, StringUtils.removeSurroundingQuotes("\"" + compareString));
compareString = "te\"st";
assertEquals(compareString, StringUtils.removeSurroundingQuotes(compareString));
assertEquals(compareString, StringUtils.removeSurroundingQuotes("\"" + compareString + "\""));
assertEquals("\"" + compareString, StringUtils.removeSurroundingQuotes("\"" + compareString));
}
}

View file

@ -1,49 +0,0 @@
package info.nightscout.androidaps.utils;
import org.junit.Assert;
import org.junit.Test;
/**
* Created by mike on 26.03.2018.
*/
//@RunWith(PowerMockRunner.class)
public class TTest {
@Test
public void toUnits() {
Assert.assertEquals(1, T.msecs(1000).secs());
Assert.assertEquals(1, T.secs(60).mins());
Assert.assertEquals(1, T.mins(60).hours());
Assert.assertEquals(1, T.hours(24).days());
Assert.assertEquals(24, T.days(1).hours());
Assert.assertEquals(60000, T.mins(1).msecs());
}
@Test
public void now() {
Assert.assertTrue(Math.abs(T.now().msecs() - System.currentTimeMillis()) < 5000);
}
@Test
public void additions() {
long nowMsecs = System.currentTimeMillis();
T now = T.msecs(nowMsecs);
Assert.assertEquals(now.plus(T.secs(5)).msecs(), nowMsecs + 5 * 1000);
Assert.assertEquals(now.plus(T.mins(5)).msecs(), nowMsecs + 5 * 60 * 1000);
Assert.assertEquals(now.plus(T.hours(5)).msecs(), nowMsecs + 5 * 60 * 60 * 1000);
Assert.assertEquals(now.plus(T.days(5)).msecs(), nowMsecs + 5 * 24 * 60 * 60 * 1000);
}
@Test
public void subtractions() {
long nowMsecs = System.currentTimeMillis();
T now = T.msecs(nowMsecs);
Assert.assertEquals(now.minus(T.secs(5)).msecs(), nowMsecs - 5 * 1000);
Assert.assertEquals(now.minus(T.mins(5)).msecs(), nowMsecs - 5 * 60 * 1000);
Assert.assertEquals(now.minus(T.hours(5)).msecs(), nowMsecs - 5 * 60 * 60 * 1000);
Assert.assertEquals(now.minus(T.days(5)).msecs(), nowMsecs - 5 * 24 * 60 * 60 * 1000);
}
}

View file

@ -42,6 +42,7 @@ buildscript {
includeModule("org.jetbrains.trove4j", "trove4j") includeModule("org.jetbrains.trove4j", "trove4j")
} }
} }
maven { url "https://plugins.gradle.org/m2/" } // jacoco 0.2
} }
dependencies { dependencies {
classpath 'com.android.tools.build:gradle:4.0.1' classpath 'com.android.tools.build:gradle:4.0.1'
@ -52,6 +53,7 @@ buildscript {
// in the individual module build.gradle files // in the individual module build.gradle files
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath 'com.hiya:jacoco-android:0.2'
} }
} }

View file

@ -2,48 +2,21 @@ apply plugin: 'com.android.library'
apply plugin: 'kotlin-android' apply plugin: 'kotlin-android'
apply plugin: 'kotlin-kapt' apply plugin: 'kotlin-kapt'
apply plugin: 'kotlin-parcelize' apply plugin: 'kotlin-parcelize'
apply plugin: 'com.hiya.jacoco-android'
apply from: 'core_dependencies.gradle'
apply from: "${project.rootDir}/gradle/android_dependencies.gradle"
apply from: "${project.rootDir}/gradle/android_module_dependencies.gradle"
apply from: "${project.rootDir}/gradle/test_dependencies.gradle"
android { android {
compileSdkVersion 28
defaultConfig { defaultConfig {
minSdkVersion 26
targetSdkVersion 28
versionCode 1 versionCode 1
versionName "1.0" versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
consumerProguardFiles 'consumer-rules.pro'
}
kotlinOptions {
jvmTarget = '1.8'
}
buildFeatures {
viewBinding true
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
debug {
testCoverageEnabled(project.hasProperty('coverage'))
}
firebaseDisable {
System.setProperty("disableFirebase", "true")
ext.enableCrashlytics = false
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
} }
} }
dependencies { dependencies {
implementation project(':database') implementation project(':database')
} }
apply from: 'core_dependencies.gradle'

View file

@ -22,10 +22,6 @@ dependencies {
api "com.google.dagger:dagger-android:$dagger_version" api "com.google.dagger:dagger-android:$dagger_version"
api "com.google.dagger:dagger-android-support:$dagger_version" api "com.google.dagger:dagger-android-support:$dagger_version"
annotationProcessor "com.google.dagger:dagger-compiler:$dagger_version"
annotationProcessor "com.google.dagger:dagger-android-processor:$dagger_version"
kapt "com.google.dagger:dagger-android-processor:$dagger_version"
kapt "com.google.dagger:dagger-compiler:$dagger_version"
//Logger //Logger
api 'org.slf4j:slf4j-api:1.7.30' api 'org.slf4j:slf4j-api:1.7.30'
@ -105,10 +101,8 @@ dependencies {
api 'com.github.kenglxn.QRGen:android:2.6.0' api 'com.github.kenglxn.QRGen:android:2.6.0'
api 'com.eatthepath:java-otp:0.2.0' api 'com.eatthepath:java-otp:0.2.0'
api "commons-codec:commons-codec:$commonscodec_version"
// Phone checker // Phone checker
api 'com.scottyab:rootbeer-lib:0.0.8' api 'com.scottyab:rootbeer-lib:0.0.8'
testImplementation "junit:junit:$junit_version"
androidTestImplementation "androidx.test.ext:junit:$androidx_junit"
androidTestImplementation "androidx.test:rules:$androidx_rules"
} }

View file

@ -0,0 +1,18 @@
package info.nightscout.androidaps.interfaces
import info.nightscout.androidaps.db.Treatment
interface TreatmentServiceInterface {
fun getTreatmentDataFromTime(mills: Long, ascending: Boolean): List<Treatment>
fun getTreatmentDataFromTime(from: Long, to: Long, ascending: Boolean): List<Treatment>
fun getTreatmentData(): List<Treatment>
fun getLastBolus(excludeSMB: Boolean): Treatment?
fun getLastCarb(): Treatment?
fun createOrUpdateMedtronic(treatment: Treatment, fromNightScout: Boolean): UpdateReturn
fun createOrUpdate(treatment: Treatment): UpdateReturn
fun resetTreatments()
fun delete(data: Treatment)
fun update(data: Treatment)
fun count(): Long
}

View file

@ -21,6 +21,8 @@ import info.nightscout.androidaps.plugins.treatments.TreatmentUpdateReturn;
*/ */
public interface TreatmentsInterface { public interface TreatmentsInterface {
TreatmentServiceInterface getService();
void updateTotalIOBTreatments(); void updateTotalIOBTreatments();
void updateTotalIOBTempBasals(); void updateTotalIOBTempBasals();
@ -40,6 +42,7 @@ public interface TreatmentsInterface {
List<Treatment> getTreatmentsFromHistoryAfterTimestamp(long timestamp); List<Treatment> getTreatmentsFromHistoryAfterTimestamp(long timestamp);
long getLastBolusTime(); long getLastBolusTime();
long getLastBolusTime(boolean excludeSMB);
// real basals (not faked by extended bolus) // real basals (not faked by extended bolus)
boolean isInHistoryRealTempBasalInProgress(); boolean isInHistoryRealTempBasalInProgress();

View file

@ -0,0 +1,11 @@
package info.nightscout.androidaps.interfaces
class UpdateReturn(var success: Boolean, var newRecord: Boolean) {
override fun toString(): String {
return "UpdateReturn [" +
"newRecord=" + newRecord +
", success=" + success +
']'
}
}

View file

@ -1,5 +1,6 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android" <androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:card_view="http://schemas.android.com/apk/res-auto" xmlns:card_view="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools" xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/careportal_cardview" android:id="@+id/careportal_cardview"
@ -29,7 +30,7 @@
android:layout_marginEnd="6dp" android:layout_marginEnd="6dp"
android:layout_marginBottom="1dp" android:layout_marginBottom="1dp"
card_view:srcCompat="@drawable/ic_meta_format" card_view:srcCompat="@drawable/ic_meta_format"
android:tint="@color/importListFileName" /> app:tint="@color/importListFileName" />
<TextView <TextView
android:id="@+id/filelist_name" android:id="@+id/filelist_name"
@ -90,7 +91,7 @@
android:layout_marginEnd="8dp" android:layout_marginEnd="8dp"
android:layout_marginBottom="1dp" android:layout_marginBottom="1dp"
card_view:srcCompat="@drawable/ic_meta_name" card_view:srcCompat="@drawable/ic_meta_name"
android:tint="@color/importListAdditionalInfo" /> app:tint="@color/importListAdditionalInfo" />
<TextView <TextView
android:id="@+id/meta_device_name" android:id="@+id/meta_device_name"
@ -122,7 +123,7 @@
android:layout_marginEnd="8dp" android:layout_marginEnd="8dp"
android:layout_marginBottom="1dp" android:layout_marginBottom="1dp"
card_view:srcCompat="@drawable/ic_meta_date" card_view:srcCompat="@drawable/ic_meta_date"
android:tint="@color/importListAdditionalInfo" /> app:tint="@color/importListAdditionalInfo" />
<TextView <TextView
android:id="@+id/meta_date_time" android:id="@+id/meta_date_time"

View file

@ -85,5 +85,9 @@
<color name="metadataTextWarning">#FF8C00</color> <color name="metadataTextWarning">#FF8C00</color>
<color name="metadataTextError">#FF5555</color> <color name="metadataTextError">#FF5555</color>
<!-- Import/Export -->
<color name="importListAdditionalInfo">#BBBBBB</color>
<color name="importListFileName">#FFFFFF</color>
</resources> </resources>

View file

@ -18,6 +18,16 @@
<item name="android:windowAnimationStyle">@android:style/Animation</item> <item name="android:windowAnimationStyle">@android:style/Animation</item>
</style> </style>
<style name="Theme.AppCompat.NoTitle" parent="Theme.AppCompat.NoActionBar">
<item name="android:windowNoTitle">true</item>
<item name="android:windowBackground">@android:color/transparent</item>
<item name="android:colorBackgroundCacheHint">@null</item>
<item name="android:windowIsTranslucent">false</item>
<item name="android:windowAnimationStyle">@android:style/Animation</item>
</style>
<style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />
<style name="AppThemeWarningDialog" parent="AppTheme"> <style name="AppThemeWarningDialog" parent="AppTheme">
<item name="alertDialogTheme">@style/AppThemeWarningDialogTheme</item> <item name="alertDialogTheme">@style/AppThemeWarningDialogTheme</item>
<item name="dialogTitleBackground">@color/warningAlertBackground</item> <item name="dialogTitleBackground">@color/warningAlertBackground</item>

View file

@ -0,0 +1,40 @@
package info.nightscout.androidaps
import info.nightscout.androidaps.logging.AAPSLoggerTest
import info.nightscout.androidaps.utils.rx.AapsSchedulers
import info.nightscout.androidaps.utils.rx.TestAapsSchedulers
import org.junit.Before
import org.junit.Rule
import org.mockito.Mockito
import org.mockito.junit.MockitoJUnit
import org.mockito.junit.MockitoRule
import java.util.*
@Suppress("SpellCheckingInspection")
open class TestBase {
val aapsLogger = AAPSLoggerTest()
val aapsSchedulers: AapsSchedulers = TestAapsSchedulers()
// Add a JUnit rule that will setup the @Mock annotated vars and log.
// Another possibility would be to add `MockitoAnnotations.initMocks(this) to the setup method.
@get:Rule
val mockitoRule: MockitoRule = MockitoJUnit.rule()
@Before
fun setupLocale() {
Locale.setDefault(Locale.ENGLISH)
System.setProperty("disableFirebase", "true")
}
// Workaround for Kotlin nullability.
// https://medium.com/@elye.project/befriending-kotlin-and-mockito-1c2e7b0ef791
// https://stackoverflow.com/questions/30305217/is-it-possible-to-use-mockito-in-kotlin
fun <T> anyObject(): T {
Mockito.any<T>()
return uninitialized()
}
@Suppress("Unchecked_Cast")
fun <T> uninitialized(): T = null as T
}

View file

@ -20,11 +20,12 @@ fun assumeAES256isSupported(cryptoUtil: CryptoUtil) {
} }
} }
@Suppress("SpellCheckingInspection")
@PowerMockIgnore("javax.crypto.*") @PowerMockIgnore("javax.crypto.*")
@RunWith(PowerMockRunner::class) @RunWith(PowerMockRunner::class)
class CryptoUtilTest: TestBase() { class CryptoUtilTest: TestBase() {
var cryptoUtil: CryptoUtil = CryptoUtil(aapsLogger) private var cryptoUtil: CryptoUtil = CryptoUtil(aapsLogger)
@Test @Test
fun testFixedSaltCrypto() { fun testFixedSaltCrypto() {

View file

@ -2,7 +2,7 @@ package info.nightscout.androidaps.utils
import android.content.Context import android.content.Context
import info.nightscout.androidaps.TestBase import info.nightscout.androidaps.TestBase
import info.nightscout.androidaps.R import info.nightscout.androidaps.core.R
import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.resources.ResourceHelper
import org.junit.Assert import org.junit.Assert
import org.junit.Test import org.junit.Test

View file

@ -0,0 +1,30 @@
package info.nightscout.androidaps.utils
import org.junit.Assert
import org.junit.Test
import org.junit.runner.RunWith
import org.powermock.modules.junit4.PowerMockRunner
@RunWith(PowerMockRunner::class)
class DecimalFormatterTest {
@Test fun to0DecimalTest() {
Assert.assertEquals("1", DecimalFormatter.to0Decimal(1.33).replace(",", "."))
Assert.assertEquals("1U", DecimalFormatter.to0Decimal(1.33, "U").replace(",", "."))
}
@Test fun to1DecimalTest() {
Assert.assertEquals("1.3", DecimalFormatter.to1Decimal(1.33).replace(",", "."))
Assert.assertEquals("1.3U", DecimalFormatter.to1Decimal(1.33, "U").replace(",", "."))
}
@Test fun to2DecimalTest() {
Assert.assertEquals("1.33", DecimalFormatter.to2Decimal(1.3333).replace(",", "."))
Assert.assertEquals("1.33U", DecimalFormatter.to2Decimal(1.3333, "U").replace(",", "."))
}
@Test fun to3DecimalTest() {
Assert.assertEquals("1.333", DecimalFormatter.to3Decimal(1.3333).replace(",", "."))
Assert.assertEquals("1.333U", DecimalFormatter.to3Decimal(1.3333, "U").replace(",", "."))
}
}

View file

@ -0,0 +1,82 @@
package info.nightscout.androidaps.utils
import org.json.JSONObject
import org.junit.Assert
import org.junit.Test
import org.junit.runner.RunWith
import org.powermock.modules.junit4.PowerMockRunner
@Suppress("SpellCheckingInspection")
@RunWith(PowerMockRunner::class)
class JsonHelperTest {
private val jsonString = "{\"d\":\"3.0\",\"i\":\"4\",\"s\":\"5\",\"b\":\"true\",\"j\":{\"a\": \"1\"}}"
@Test
fun safeGetObjectTest() {
val json = JSONObject(jsonString)
val o = Any()
Assert.assertEquals(o, JsonHelper.safeGetObject(null, "x", o))
Assert.assertEquals(o, JsonHelper.safeGetObject(json, "x", o))
Assert.assertNotEquals(o, JsonHelper.safeGetObject(json, "d", o))
}
@Test
fun safeGetJSONObjectTest() {
val json = JSONObject(jsonString)
val o = JSONObject()
Assert.assertEquals(o, JsonHelper.safeGetJSONObject(null, "x", o))
Assert.assertTrue(JsonHelper.safeGetJSONObject(json, "j", o)!!.has("a"))
Assert.assertEquals(o, JsonHelper.safeGetJSONObject(json, "d", o))
}
@Test
fun safeGetStringTest() {
val json = JSONObject(jsonString)
Assert.assertNull(JsonHelper.safeGetString(null, "s"))
Assert.assertNull(JsonHelper.safeGetString(json, "notexisting"))
Assert.assertEquals("5", JsonHelper.safeGetString(json, "s"))
Assert.assertEquals("default", JsonHelper.safeGetString(null, "notexisting", "default"))
Assert.assertEquals("default", JsonHelper.safeGetString(json, "notexisting", "default"))
Assert.assertEquals("5", JsonHelper.safeGetString(json, "s", "default"))
Assert.assertEquals("default", JsonHelper.safeGetStringAllowNull(null, "notexisting", "default"))
Assert.assertEquals("default", JsonHelper.safeGetStringAllowNull(json, "notexisting", "default"))
Assert.assertNull(JsonHelper.safeGetStringAllowNull(json, "notexisting", null))
Assert.assertEquals("5", JsonHelper.safeGetStringAllowNull(json, "s", "default"))
}
@Test
fun safeGetDoubleTest() {
val json = JSONObject(jsonString)
Assert.assertEquals(0.0, JsonHelper.safeGetDouble(json, "notexisting"), 0.0)
Assert.assertEquals(0.0, JsonHelper.safeGetDouble(null, "notexisting"), 0.0)
Assert.assertEquals(3.0, JsonHelper.safeGetDouble(json, "d"), 0.000001)
Assert.assertEquals(6.0, JsonHelper.safeGetDouble(null, "notexisting", 6.0), 0.0)
Assert.assertEquals(6.0, JsonHelper.safeGetDouble(json, "notexisting", 6.0), 0.0)
Assert.assertEquals(3.0, JsonHelper.safeGetDouble(json, "d", 6.0), 0.0)
}
@Test
fun safeGetLntTest() {
val json = JSONObject(jsonString)
Assert.assertEquals(0, JsonHelper.safeGetInt(null, "notexisting").toLong())
Assert.assertEquals(0, JsonHelper.safeGetInt(json, "notexisting").toLong())
Assert.assertEquals(4, JsonHelper.safeGetInt(json, "i").toLong())
}
@Test
fun safeGetLongTest() {
val json = JSONObject(jsonString)
Assert.assertEquals(0, JsonHelper.safeGetInt(null, "notexisting").toLong())
Assert.assertEquals(0, JsonHelper.safeGetInt(json, "notexisting").toLong())
Assert.assertEquals(4, JsonHelper.safeGetInt(json, "i").toLong())
}
@Test
fun safeGetBooleanTest() {
val json = JSONObject(jsonString)
Assert.assertFalse(JsonHelper.safeGetBoolean(null, "notexisting"))
Assert.assertFalse(JsonHelper.safeGetBoolean(json, "notexisting"))
Assert.assertTrue(JsonHelper.safeGetBoolean(json, "b"))
}
}

View file

@ -0,0 +1,40 @@
package info.nightscout.androidaps.utils
import org.junit.Assert
import org.junit.Test
class RoundTest {
@Test
fun roundToTest() {
Assert.assertEquals(0.55, Round.roundTo(0.54, 0.05), 0.00000000000000000001)
Assert.assertEquals(-3.26, Round.roundTo(-3.2553715764602713, 0.01), 0.00000000000000000001)
Assert.assertEquals(0.816, Round.roundTo(0.8156666666666667, 0.001), 0.00000000000000000001)
Assert.assertEquals(0.235, Round.roundTo(0.235, 0.001), 0.00000000000000000001)
Assert.assertEquals(0.3, Round.roundTo(0.3, 0.1), 0.00000000000000001)
Assert.assertEquals(0.0017, Round.roundTo(0.0016960652144170627, 0.0001), 0.00000000000000000001)
Assert.assertEquals(0.0078, Round.roundTo(0.007804436682291013, 0.0001), 0.00000000000000000001)
Assert.assertEquals(0.6, Round.roundTo(0.6, 0.05), 0.00000000000000000001)
Assert.assertEquals(1.0, Round.roundTo(1.49, 1.0), 0.00000000000000000001)
Assert.assertEquals(0.0, Round.roundTo(0.0, 1.0), 0.00000000000000000001)
}
@Test
fun floorToTest() {
Assert.assertEquals(0.5, Round.floorTo(0.54, 0.05), 0.00000001)
Assert.assertEquals(1.0, Round.floorTo(1.59, 1.0), 0.00000001)
Assert.assertEquals(0.0, Round.floorTo(0.0, 1.0), 0.00000001)
}
@Test
fun ceilToTest() {
Assert.assertEquals(0.6, Round.ceilTo(0.54, 0.1), 0.00000001)
Assert.assertEquals(2.0, Round.ceilTo(1.49999, 1.0), 0.00000001)
Assert.assertEquals(0.0, Round.ceilTo(0.0, 1.0), 0.00000001)
}
@Test
fun isSameTest() {
Assert.assertTrue(Round.isSame(0.54, 0.54))
}
}

View file

@ -0,0 +1,18 @@
package info.nightscout.androidaps.utils
import org.junit.Assert
import org.junit.Test
class StringUtilsTest {
@Test fun removeSurroundingQuotesTest() {
var compareString = "test"
Assert.assertEquals(compareString, StringUtils.removeSurroundingQuotes(compareString))
Assert.assertEquals(compareString, StringUtils.removeSurroundingQuotes("\"" + compareString + "\""))
Assert.assertEquals("\"" + compareString, StringUtils.removeSurroundingQuotes("\"" + compareString))
compareString = "te\"st"
Assert.assertEquals(compareString, StringUtils.removeSurroundingQuotes(compareString))
Assert.assertEquals(compareString, StringUtils.removeSurroundingQuotes("\"" + compareString + "\""))
Assert.assertEquals("\"" + compareString, StringUtils.removeSurroundingQuotes("\"" + compareString))
}
}

View file

@ -0,0 +1,40 @@
package info.nightscout.androidaps.utils
import org.junit.Assert
import org.junit.Test
import kotlin.math.abs
@Suppress("SpellCheckingInspection")
class TTest {
@Test fun toUnits() {
Assert.assertEquals(1, T.msecs(1000).secs())
Assert.assertEquals(1, T.secs(60).mins())
Assert.assertEquals(1, T.mins(60).hours())
Assert.assertEquals(1, T.hours(24).days())
Assert.assertEquals(24, T.days(1).hours())
Assert.assertEquals(60000, T.mins(1).msecs())
}
@Test fun now() {
Assert.assertTrue(abs(T.now().msecs() - System.currentTimeMillis()) < 5000)
}
@Test fun additions() {
val nowMsecs = System.currentTimeMillis()
val now = T.msecs(nowMsecs)
Assert.assertEquals(now.plus(T.secs(5)).msecs(), nowMsecs + 5 * 1000)
Assert.assertEquals(now.plus(T.mins(5)).msecs(), nowMsecs + 5 * 60 * 1000)
Assert.assertEquals(now.plus(T.hours(5)).msecs(), nowMsecs + 5 * 60 * 60 * 1000)
Assert.assertEquals(now.plus(T.days(5)).msecs(), nowMsecs + 5 * 24 * 60 * 60 * 1000)
}
@Test fun subtractions() {
val nowMsecs = System.currentTimeMillis()
val now = T.msecs(nowMsecs)
Assert.assertEquals(now.minus(T.secs(5)).msecs(), nowMsecs - 5 * 1000)
Assert.assertEquals(now.minus(T.mins(5)).msecs(), nowMsecs - 5 * 60 * 1000)
Assert.assertEquals(now.minus(T.hours(5)).msecs(), nowMsecs - 5 * 60 * 60 * 1000)
Assert.assertEquals(now.minus(T.days(5)).msecs(), nowMsecs - 5 * 24 * 60 * 60 * 1000)
}
}

View file

@ -1,56 +1,20 @@
apply plugin: 'com.android.library' apply plugin: 'com.android.library'
apply plugin: 'kotlin-android' apply plugin: 'kotlin-android'
apply plugin: 'kotlin-kapt' apply plugin: 'kotlin-kapt'
apply plugin: 'com.hiya.jacoco-android'
apply from: "${project.rootDir}/gradle/android_dependencies.gradle"
apply from: "${project.rootDir}/gradle/android_module_dependencies.gradle"
apply from: "${project.rootDir}/gradle/test_dependencies.gradle"
android { android {
compileSdkVersion 28
defaultConfig { defaultConfig {
minSdkVersion 24
targetSdkVersion 28
versionCode 1 versionCode 1
versionName "1.0" versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
consumerProguardFiles 'consumer-rules.pro'
}
kotlinOptions {
jvmTarget = '1.8'
}
buildFeatures {
viewBinding true
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
debug {
testCoverageEnabled(project.hasProperty('coverage'))
}
firebaseDisable {
System.setProperty("disableFirebase", "true")
ext.enableCrashlytics = false
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
} }
} }
dependencies { dependencies {
implementation project(':core') implementation project(':core')
implementation fileTree(dir: 'libs', include: ['*.jar'])
annotationProcessor "com.google.dagger:dagger-compiler:$dagger_version"
annotationProcessor "com.google.dagger:dagger-android-processor:$dagger_version"
kapt "com.google.dagger:dagger-android-processor:$dagger_version"
kapt "com.google.dagger:dagger-compiler:$dagger_version"
testImplementation "junit:junit:$junit_version"
androidTestImplementation "androidx.test.ext:junit:$androidx_junit"
androidTestImplementation "androidx.test:rules:$androidx_rules"
} }

View file

@ -1,25 +0,0 @@
package info.nightscout.androidaps.dana
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("info.nightscout.androidaps.dana.test", appContext.packageName)
}
}

View file

@ -0,0 +1,39 @@
package info.nightscout.androidaps
import info.nightscout.androidaps.logging.AAPSLoggerTest
import info.nightscout.androidaps.utils.rx.AapsSchedulers
import info.nightscout.androidaps.utils.rx.TestAapsSchedulers
import org.junit.Before
import org.junit.Rule
import org.mockito.Mockito
import org.mockito.junit.MockitoJUnit
import org.mockito.junit.MockitoRule
import java.util.*
open class TestBase {
val aapsLogger = AAPSLoggerTest()
val aapsSchedulers: AapsSchedulers = TestAapsSchedulers()
// Add a JUnit rule that will setup the @Mock annotated vars and log.
// Another possibility would be to add `MockitoAnnotations.initMocks(this) to the setup method.
@get:Rule
val mockitoRule: MockitoRule = MockitoJUnit.rule()
@Before
fun setupLocale() {
Locale.setDefault(Locale.ENGLISH)
System.setProperty("disableFirebase", "true")
}
// Workaround for Kotlin nullability.
// https://medium.com/@elye.project/befriending-kotlin-and-mockito-1c2e7b0ef791
// https://stackoverflow.com/questions/30305217/is-it-possible-to-use-mockito-in-kotlin
fun <T> anyObject(): T {
Mockito.any<T>()
return uninitialized()
}
@Suppress("Unchecked_Cast")
fun <T> uninitialized(): T = null as T
}

View file

@ -0,0 +1,82 @@
package info.nightscout.androidaps
import dagger.android.AndroidInjector
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.data.Profile
import info.nightscout.androidaps.db.ProfileSwitch
import info.nightscout.androidaps.db.Treatment
import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.interfaces.ConfigInterface
import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.interfaces.ProfileStore
import info.nightscout.androidaps.interfaces.TreatmentsInterface
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.DefaultValueHelper
import info.nightscout.androidaps.utils.FabricPrivacy
import info.nightscout.androidaps.utils.resources.ResourceHelper
import org.json.JSONObject
import org.junit.Before
import org.mockito.Mock
import org.powermock.core.classloader.annotations.PrepareForTest
@Suppress("SpellCheckingInspection")
@PrepareForTest(FabricPrivacy::class)
open class TestBaseWithProfile : TestBase() {
@Mock lateinit var activePluginProvider: ActivePluginProvider
@Mock lateinit var resourceHelper: ResourceHelper
@Mock lateinit var treatmentsInterface: TreatmentsInterface
@Mock lateinit var fabricPrivacy: FabricPrivacy
@Mock lateinit var profileFunction: ProfileFunction
@Mock lateinit var defaultValueHelper: DefaultValueHelper
@Mock lateinit var dateUtil: DateUtil
@Mock lateinit var configInterface: ConfigInterface
val rxBus = RxBusWrapper(aapsSchedulers)
val profileInjector = HasAndroidInjector {
AndroidInjector {
if (it is Profile) {
it.aapsLogger = aapsLogger
it.activePlugin = activePluginProvider
it.resourceHelper = resourceHelper
it.rxBus = rxBus
it.fabricPrivacy = fabricPrivacy
it.configInterface = configInterface
}
if (it is ProfileSwitch) {
it.treatmentsPlugin = treatmentsInterface
it.aapsLogger = aapsLogger
it.rxBus = rxBus
it.resourceHelper = resourceHelper
it.dateUtil = dateUtil
}
if (it is Treatment) {
it.activePlugin = activePluginProvider
it.profileFunction = profileFunction
it.defaultValueHelper = defaultValueHelper
it.resourceHelper = resourceHelper
}
}
}
private lateinit var validProfileJSON: String
lateinit var validProfile: Profile
@Suppress("PropertyName") val TESTPROFILENAME = "someProfile"
@Before
fun prepareMock() {
validProfileJSON = "{\"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\"}"
validProfile = Profile(profileInjector, JSONObject(validProfileJSON), Constants.MGDL)
}
fun getValidProfileStore(): ProfileStore {
val json = JSONObject()
val store = JSONObject()
store.put(TESTPROFILENAME, JSONObject(validProfileJSON))
json.put("defaultProfile", TESTPROFILENAME)
json.put("store", store)
return ProfileStore(profileInjector, json)
}
}

View file

@ -0,0 +1,29 @@
package info.nightscout.androidaps.dana
import info.nightscout.androidaps.TestBaseWithProfile
import info.nightscout.androidaps.utils.sharedPreferences.SP
import org.junit.Assert
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mock
import org.powermock.modules.junit4.PowerMockRunner
@RunWith(PowerMockRunner::class)
class DanaPumpTest : TestBaseWithProfile() {
@Mock lateinit var sp: SP
private lateinit var sut: DanaPump
@Before
fun setup() {
sut = DanaPump(aapsLogger, sp, profileInjector)
}
@Test
fun detectDanaRS() {
sut.hwModel = 0x05
Assert.assertTrue(sut.modelFriendlyName().contains("DanaRS"))
}
}

View file

@ -1,18 +0,0 @@
package info.nightscout.androidaps.dana
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
}

View file

@ -1,58 +1,20 @@
apply plugin: 'com.android.library' apply plugin: 'com.android.library'
apply plugin: 'kotlin-android' apply plugin: 'kotlin-android'
apply plugin: 'kotlin-kapt' apply plugin: 'kotlin-kapt'
apply plugin: 'com.hiya.jacoco-android'
apply from: "${project.rootDir}/gradle/android_dependencies.gradle"
apply from: "${project.rootDir}/gradle/android_module_dependencies.gradle"
apply from: "${project.rootDir}/gradle/test_dependencies.gradle"
android { android {
compileSdkVersion 28
defaultConfig { defaultConfig {
minSdkVersion 24
targetSdkVersion 28
versionCode 1 versionCode 1
versionName "1.0" versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
consumerProguardFiles 'consumer-rules.pro'
} }
kotlinOptions {
jvmTarget = '1.8'
}
buildFeatures {
viewBinding true
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
debug {
testCoverageEnabled(project.hasProperty('coverage'))
}
firebaseDisable {
System.setProperty("disableFirebase", "true")
ext.enableCrashlytics = false
}
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
}
} }
dependencies { dependencies {
implementation project(':core') implementation project(':core')
implementation project(':dana') implementation project(':dana')
implementation fileTree(dir: 'libs', include: ['*.jar'])
annotationProcessor "com.google.dagger:dagger-compiler:$dagger_version"
annotationProcessor "com.google.dagger:dagger-android-processor:$dagger_version"
kapt "com.google.dagger:dagger-android-processor:$dagger_version"
kapt "com.google.dagger:dagger-compiler:$dagger_version"
testImplementation "junit:junit:$junit_version"
androidTestImplementation "androidx.test.ext:junit:$androidx_junit"
androidTestImplementation "androidx.test:rules:$androidx_rules"
} }

View file

@ -0,0 +1,40 @@
package info.nightscout.androidaps
import info.nightscout.androidaps.logging.AAPSLoggerTest
import info.nightscout.androidaps.utils.rx.AapsSchedulers
import info.nightscout.androidaps.utils.rx.TestAapsSchedulers
import org.junit.Before
import org.junit.Rule
import org.mockito.Mockito
import org.mockito.junit.MockitoJUnit
import org.mockito.junit.MockitoRule
import java.util.*
@Suppress("SpellCheckingInspection")
open class TestBase {
val aapsLogger = AAPSLoggerTest()
val aapsSchedulers: AapsSchedulers = TestAapsSchedulers()
// Add a JUnit rule that will setup the @Mock annotated vars and log.
// Another possibility would be to add `MockitoAnnotations.initMocks(this) to the setup method.
@get:Rule
val mockitoRule: MockitoRule = MockitoJUnit.rule()
@Before
fun setupLocale() {
Locale.setDefault(Locale.ENGLISH)
System.setProperty("disableFirebase", "true")
}
// Workaround for Kotlin nullability.
// https://medium.com/@elye.project/befriending-kotlin-and-mockito-1c2e7b0ef791
// https://stackoverflow.com/questions/30305217/is-it-possible-to-use-mockito-in-kotlin
fun <T> anyObject(): T {
Mockito.any<T>()
return uninitialized()
}
@Suppress("Unchecked_Cast")
fun <T> uninitialized(): T = null as T
}

View file

@ -0,0 +1,82 @@
package info.nightscout.androidaps
import dagger.android.AndroidInjector
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.data.Profile
import info.nightscout.androidaps.db.ProfileSwitch
import info.nightscout.androidaps.db.Treatment
import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.interfaces.ConfigInterface
import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.interfaces.ProfileStore
import info.nightscout.androidaps.interfaces.TreatmentsInterface
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.DefaultValueHelper
import info.nightscout.androidaps.utils.FabricPrivacy
import info.nightscout.androidaps.utils.resources.ResourceHelper
import org.json.JSONObject
import org.junit.Before
import org.mockito.Mock
import org.powermock.core.classloader.annotations.PrepareForTest
@Suppress("SpellCheckingInspection")
@PrepareForTest(FabricPrivacy::class)
open class TestBaseWithProfile : TestBase() {
@Mock lateinit var activePluginProvider: ActivePluginProvider
@Mock lateinit var resourceHelper: ResourceHelper
@Mock lateinit var treatmentsInterface: TreatmentsInterface
@Mock lateinit var fabricPrivacy: FabricPrivacy
@Mock lateinit var profileFunction: ProfileFunction
@Mock lateinit var defaultValueHelper: DefaultValueHelper
@Mock lateinit var dateUtil: DateUtil
@Mock lateinit var configInterface: ConfigInterface
val rxBus = RxBusWrapper(aapsSchedulers)
val profileInjector = HasAndroidInjector {
AndroidInjector {
if (it is Profile) {
it.aapsLogger = aapsLogger
it.activePlugin = activePluginProvider
it.resourceHelper = resourceHelper
it.rxBus = rxBus
it.fabricPrivacy = fabricPrivacy
it.configInterface = configInterface
}
if (it is ProfileSwitch) {
it.treatmentsPlugin = treatmentsInterface
it.aapsLogger = aapsLogger
it.rxBus = rxBus
it.resourceHelper = resourceHelper
it.dateUtil = dateUtil
}
if (it is Treatment) {
it.activePlugin = activePluginProvider
it.profileFunction = profileFunction
it.defaultValueHelper = defaultValueHelper
it.resourceHelper = resourceHelper
}
}
}
private lateinit var validProfileJSON: String
lateinit var validProfile: Profile
@Suppress("PropertyName") val TESTPROFILENAME = "someProfile"
@Before
fun prepareMock() {
validProfileJSON = "{\"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\"}"
validProfile = Profile(profileInjector, JSONObject(validProfileJSON), Constants.MGDL)
}
fun getValidProfileStore(): ProfileStore {
val json = JSONObject()
val store = JSONObject()
store.put(TESTPROFILENAME, JSONObject(validProfileJSON))
json.put("defaultProfile", TESTPROFILENAME)
json.put("store", store)
return ProfileStore(profileInjector, json)
}
}

View file

@ -0,0 +1,67 @@
package info.nightscout.androidaps
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.data.DetailedBolusInfo
import info.nightscout.androidaps.data.Profile
import info.nightscout.androidaps.data.PumpEnactResult
import info.nightscout.androidaps.interfaces.PumpDescription
import info.nightscout.androidaps.interfaces.PumpInterface
import info.nightscout.androidaps.plugins.common.ManufacturerType
import info.nightscout.androidaps.plugins.pump.common.defs.PumpType
import info.nightscout.androidaps.utils.TimeChangeType
import org.json.JSONObject
@Suppress("MemberVisibilityCanBePrivate")
class TestPumpPlugin(val injector: HasAndroidInjector) : PumpInterface {
var connected = false
var isProfileSet = true
override fun isConnected() = connected
override fun isConnecting() = false
override fun isHandshakeInProgress() = false
val lastData = 0L
val baseBasal = 0.0
override val pumpDescription = PumpDescription()
override fun isInitialized(): Boolean = true
override fun isSuspended(): Boolean = false
override fun isBusy(): Boolean = false
override fun connect(reason: String) {
connected = true
}
override fun disconnect(reason: String) {
connected = false
}
override fun stopConnecting() {
connected = false
}
override fun waitForDisconnectionInSeconds(): Int = 0
override fun getPumpStatus(reason: String) {}
override fun setNewBasalProfile(profile: Profile): PumpEnactResult = PumpEnactResult(injector)
override fun isThisProfileSet(profile: Profile): Boolean = isProfileSet
override fun lastDataTime(): Long = lastData
override val baseBasalRate: Double = baseBasal
override val reservoirLevel: Double = 0.0
override val batteryLevel: Int = 0
override fun deliverTreatment(detailedBolusInfo: DetailedBolusInfo): PumpEnactResult = PumpEnactResult(injector).success(true)
override fun stopBolusDelivering() {}
override fun setTempBasalAbsolute(absoluteRate: Double, durationInMinutes: Int, profile: Profile, enforceNew: Boolean): PumpEnactResult = PumpEnactResult(injector).success(true)
override fun setTempBasalPercent(percent: Int, durationInMinutes: Int, profile: Profile, enforceNew: Boolean): PumpEnactResult = PumpEnactResult(injector).success(true)
override fun setExtendedBolus(insulin: Double, durationInMinutes: Int): PumpEnactResult = PumpEnactResult(injector).success(true)
override fun cancelTempBasal(enforceNew: Boolean): PumpEnactResult = PumpEnactResult(injector).success(true)
override fun cancelExtendedBolus(): PumpEnactResult = PumpEnactResult(injector).success(true)
override fun getJSONStatus(profile: Profile, profileName: String, version: String): JSONObject = JSONObject()
override fun manufacturer(): ManufacturerType = ManufacturerType.AndroidAPS
override fun model(): PumpType = PumpType.GenericAAPS
override fun serialNumber(): String = "1"
override fun shortStatus(veryShort: Boolean): String = ""
override val isFakingTempsByExtendedBoluses: Boolean = false
override fun loadTDDs(): PumpEnactResult = PumpEnactResult(injector).success(true)
override fun canHandleDST(): Boolean = true
override fun timezoneOrDSTChanged(timeChangeType: TimeChangeType) {}
}

View file

@ -4,10 +4,10 @@ import android.content.Context
import dagger.android.AndroidInjector import dagger.android.AndroidInjector
import dagger.android.HasAndroidInjector import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.Constants import info.nightscout.androidaps.Constants
import info.nightscout.androidaps.R
import info.nightscout.androidaps.TestBaseWithProfile import info.nightscout.androidaps.TestBaseWithProfile
import info.nightscout.androidaps.dana.DanaPump import info.nightscout.androidaps.dana.DanaPump
import info.nightscout.androidaps.danar.DanaRPlugin import info.nightscout.androidaps.danar.DanaRPlugin
import info.nightscout.androidaps.danar.R
import info.nightscout.androidaps.interfaces.CommandQueueProvider import info.nightscout.androidaps.interfaces.CommandQueueProvider
import info.nightscout.androidaps.interfaces.Constraint import info.nightscout.androidaps.interfaces.Constraint
import info.nightscout.androidaps.interfaces.PluginType import info.nightscout.androidaps.interfaces.PluginType
@ -45,7 +45,7 @@ class DanaRPluginTest : TestBaseWithProfile() {
`when`(resourceHelper.gs(R.string.pumplimit)).thenReturn("pump limit") `when`(resourceHelper.gs(R.string.pumplimit)).thenReturn("pump limit")
`when`(resourceHelper.gs(R.string.limitingbasalratio)).thenReturn("Limiting max basal rate to %1\$.2f U/h because of %2\$s") `when`(resourceHelper.gs(R.string.limitingbasalratio)).thenReturn("Limiting max basal rate to %1\$.2f U/h because of %2\$s")
`when`(resourceHelper.gs(R.string.limitingpercentrate)).thenReturn("Limiting max percent rate to %1\$d%% because of %2\$s") `when`(resourceHelper.gs(R.string.limitingpercentrate)).thenReturn("Limiting max percent rate to %1\$d%% because of %2\$s")
danaPump = info.nightscout.androidaps.dana.DanaPump(aapsLogger, sp, injector) danaPump = DanaPump(aapsLogger, sp, injector)
danaRPlugin = DanaRPlugin(injector, aapsLogger, aapsSchedulers, rxBus, context, resourceHelper, constraintChecker, activePluginProvider, sp, commandQueue, danaPump, dateUtil, fabricPrivacy) danaRPlugin = DanaRPlugin(injector, aapsLogger, aapsSchedulers, rxBus, context, resourceHelper, constraintChecker, activePluginProvider, sp, commandQueue, danaPump, dateUtil, fabricPrivacy)
} }

View file

@ -3,6 +3,7 @@ package info.nightscout.androidaps.plugins.pump.danaR.comm
import dagger.android.AndroidInjector import dagger.android.AndroidInjector
import dagger.android.HasAndroidInjector import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.TestBase import info.nightscout.androidaps.TestBase
import info.nightscout.androidaps.TestPumpPlugin
import info.nightscout.androidaps.dana.DanaPump import info.nightscout.androidaps.dana.DanaPump
import info.nightscout.androidaps.danaRKorean.DanaRKoreanPlugin import info.nightscout.androidaps.danaRKorean.DanaRKoreanPlugin
import info.nightscout.androidaps.danaRv2.DanaRv2Plugin import info.nightscout.androidaps.danaRv2.DanaRv2Plugin
@ -20,9 +21,11 @@ import info.nightscout.androidaps.utils.sharedPreferences.SP
import org.junit.Before import org.junit.Before
import org.mockito.Mock import org.mockito.Mock
import org.mockito.Mockito.`when` import org.mockito.Mockito.`when`
import org.mockito.Mockito.anyBoolean
import org.mockito.Mockito.doNothing
import org.powermock.core.classloader.annotations.PrepareForTest import org.powermock.core.classloader.annotations.PrepareForTest
@PrepareForTest(DetailedBolusInfoStorage::class, ConstraintChecker::class) @PrepareForTest(DetailedBolusInfoStorage::class, ConstraintChecker::class, DanaRKoreanPlugin::class, DanaRPlugin::class)
open class DanaRTestBase : TestBase() { open class DanaRTestBase : TestBase() {
@Mock lateinit var sp: SP @Mock lateinit var sp: SP
@ -41,9 +44,16 @@ open class DanaRTestBase : TestBase() {
@Mock lateinit var constraintChecker: ConstraintChecker @Mock lateinit var constraintChecker: ConstraintChecker
@Mock lateinit var nsUpload: NSUpload @Mock lateinit var nsUpload: NSUpload
lateinit var testPumpPlugin: TestPumpPlugin
@Before @Before
fun prepareMock() { fun setup() {
danaPump = DanaPump(aapsLogger, sp, injector)
testPumpPlugin = TestPumpPlugin(injector)
`when`(activePluginProvider.activeTreatments).thenReturn(treatmentsInterface) `when`(activePluginProvider.activeTreatments).thenReturn(treatmentsInterface)
`when`(activePluginProvider.activePump).thenReturn(testPumpPlugin)
doNothing().`when`(danaRKoreanPlugin).setPluginEnabled(anyObject(), anyBoolean())
doNothing().`when`(danaRPlugin).setPluginEnabled(anyObject(), anyBoolean())
} }
val injector = HasAndroidInjector { val injector = HasAndroidInjector {
@ -102,9 +112,4 @@ open class DanaRTestBase : TestBase() {
array[6 + position] = value array[6 + position] = value
return array return array
} }
@Before
fun setup() {
danaPump = info.nightscout.androidaps.dana.DanaPump(aapsLogger, sp, injector)
}
} }

View file

@ -2,21 +2,15 @@ package info.nightscout.androidaps.plugins.pump.danaR.comm
import info.nightscout.androidaps.danar.comm.MessageHashTableR import info.nightscout.androidaps.danar.comm.MessageHashTableR
import info.nightscout.androidaps.interfaces.Constraint import info.nightscout.androidaps.interfaces.Constraint
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin
import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker
import info.nightscout.androidaps.plugins.pump.common.bolusInfo.DetailedBolusInfoStorage
import org.junit.Assert import org.junit.Assert
import org.junit.Test import org.junit.Test
import org.junit.runner.RunWith import org.junit.runner.RunWith
import org.mockito.Mockito import org.mockito.Mockito
import org.powermock.core.classloader.annotations.PrepareForTest
import org.powermock.modules.junit4.PowerMockRunner import org.powermock.modules.junit4.PowerMockRunner
@RunWith(PowerMockRunner::class) @RunWith(PowerMockRunner::class)
@PrepareForTest(ConstraintChecker::class, DetailedBolusInfoStorage::class, ConfigBuilderPlugin::class)
class MessageHashTableRTest : DanaRTestBase() { class MessageHashTableRTest : DanaRTestBase() {
@Test fun runTest() { @Test fun runTest() {
Mockito.`when`(constraintChecker.applyBolusConstraints(anyObject())).thenReturn(Constraint(0.0)) Mockito.`when`(constraintChecker.applyBolusConstraints(anyObject())).thenReturn(Constraint(0.0))
val messageHashTable = MessageHashTableR(injector) val messageHashTable = MessageHashTableR(injector)

View file

@ -2,7 +2,7 @@ package info.nightscout.androidaps.plugins.pump.danaR.comm
import dagger.android.AndroidInjector import dagger.android.AndroidInjector
import dagger.android.HasAndroidInjector import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.R import info.nightscout.androidaps.danar.R
import info.nightscout.androidaps.danar.comm.MsgBolusProgress import info.nightscout.androidaps.danar.comm.MsgBolusProgress
import info.nightscout.androidaps.db.Treatment import info.nightscout.androidaps.db.Treatment
import org.junit.Assert import org.junit.Assert
@ -15,7 +15,6 @@ import org.powermock.modules.junit4.PowerMockRunner
@RunWith(PowerMockRunner::class) @RunWith(PowerMockRunner::class)
class MsgBolusProgressTest : DanaRTestBase() { class MsgBolusProgressTest : DanaRTestBase() {
@Test fun runTest() { @Test fun runTest() {
`when`(resourceHelper.gs(ArgumentMatchers.eq(R.string.bolusdelivering), ArgumentMatchers.anyDouble())).thenReturn("Delivering %1\$.2fU") `when`(resourceHelper.gs(ArgumentMatchers.eq(R.string.bolusdelivering), ArgumentMatchers.anyDouble())).thenReturn("Delivering %1\$.2fU")
danaPump.bolusingTreatment = Treatment(HasAndroidInjector { AndroidInjector { } }) danaPump.bolusingTreatment = Treatment(HasAndroidInjector { AndroidInjector { } })

View file

@ -2,7 +2,7 @@ package info.nightscout.androidaps.plugins.pump.danaR.comm
import dagger.android.AndroidInjector import dagger.android.AndroidInjector
import dagger.android.HasAndroidInjector import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.R import info.nightscout.androidaps.danar.R
import info.nightscout.androidaps.danar.comm.MsgBolusStop import info.nightscout.androidaps.danar.comm.MsgBolusStop
import info.nightscout.androidaps.db.Treatment import info.nightscout.androidaps.db.Treatment
import org.junit.Assert import org.junit.Assert

View file

@ -1,20 +1,15 @@
package info.nightscout.androidaps.plugins.pump.danaR.comm package info.nightscout.androidaps.plugins.pump.danaR.comm
import info.nightscout.androidaps.danar.comm.MsgError import info.nightscout.androidaps.danar.comm.MsgError
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload
import org.junit.Assert import org.junit.Assert
import org.junit.Test import org.junit.Test
import org.junit.runner.RunWith import org.junit.runner.RunWith
import org.powermock.api.mockito.PowerMockito
import org.powermock.core.classloader.annotations.PrepareForTest
import org.powermock.modules.junit4.PowerMockRunner import org.powermock.modules.junit4.PowerMockRunner
@RunWith(PowerMockRunner::class) @RunWith(PowerMockRunner::class)
@PrepareForTest(NSUpload::class)
class MsgErrorTest : DanaRTestBase() { class MsgErrorTest : DanaRTestBase() {
@Test fun runTest() { @Test fun runTest() {
PowerMockito.mockStatic(NSUpload::class.java)
val packet = MsgError(injector) val packet = MsgError(injector)
// test message decoding // test message decoding

View file

@ -9,6 +9,7 @@ import org.powermock.modules.junit4.PowerMockRunner
class MsgHistoryAlarmTest : DanaRTestBase() { class MsgHistoryAlarmTest : DanaRTestBase() {
@Test fun runTest() { @Test fun runTest() {
@Suppress("UNUSED_VARIABLE")
val packet = MsgHistoryAlarm(injector) val packet = MsgHistoryAlarm(injector)
// nothing left to test // nothing left to test
} }

View file

@ -1,14 +1,9 @@
package info.nightscout.androidaps.plugins.pump.danaR.comm package info.nightscout.androidaps.plugins.pump.danaR.comm
import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.danar.comm.MsgHistoryAll import info.nightscout.androidaps.danar.comm.MsgHistoryAll
import info.nightscout.androidaps.db.DatabaseHelper
import org.junit.Assert import org.junit.Assert
import org.junit.Test import org.junit.Test
import org.junit.runner.RunWith import org.junit.runner.RunWith
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 org.powermock.modules.junit4.PowerMockRunner
@RunWith(PowerMockRunner::class) @RunWith(PowerMockRunner::class)

View file

@ -9,6 +9,7 @@ import org.powermock.modules.junit4.PowerMockRunner
class MsgHistoryBasalHourTest : DanaRTestBase() { class MsgHistoryBasalHourTest : DanaRTestBase() {
@Test fun runTest() { @Test fun runTest() {
@Suppress("UNUSED_VARIABLE")
val packet = MsgHistoryBasalHour(injector) val packet = MsgHistoryBasalHour(injector)
// nothing left to test // nothing left to test
} }

View file

@ -9,6 +9,7 @@ import org.powermock.modules.junit4.PowerMockRunner
class MsgHistoryBolusTest : DanaRTestBase() { class MsgHistoryBolusTest : DanaRTestBase() {
@Test fun runTest() { @Test fun runTest() {
@Suppress("UNUSED_VARIABLE")
val packet = MsgHistoryBolus(injector) val packet = MsgHistoryBolus(injector)
// nothing left to test // nothing left to test
} }

View file

@ -9,6 +9,7 @@ import org.powermock.modules.junit4.PowerMockRunner
class MsgHistoryCarboTest : DanaRTestBase() { class MsgHistoryCarboTest : DanaRTestBase() {
@Test fun runTest() { @Test fun runTest() {
@Suppress("UNUSED_VARIABLE")
val packet = MsgHistoryCarbo(injector) val packet = MsgHistoryCarbo(injector)
// nothing left to test // nothing left to test
} }

View file

@ -9,6 +9,7 @@ import org.powermock.modules.junit4.PowerMockRunner
class MsgHistoryDailyInsulinTest : DanaRTestBase() { class MsgHistoryDailyInsulinTest : DanaRTestBase() {
@Test fun runTest() { @Test fun runTest() {
@Suppress("UNUSED_VARIABLE")
val packet = MsgHistoryDailyInsulin(injector) val packet = MsgHistoryDailyInsulin(injector)
// nothing left to test // nothing left to test
} }

View file

@ -9,6 +9,7 @@ import org.powermock.modules.junit4.PowerMockRunner
class MsgHistoryDoneTest : DanaRTestBase() { class MsgHistoryDoneTest : DanaRTestBase() {
@Test fun runTest() { @Test fun runTest() {
@Suppress("UNUSED_VARIABLE")
val packet = MsgHistoryDone(injector) val packet = MsgHistoryDone(injector)
// nothing left to test // nothing left to test
} }

View file

@ -9,6 +9,7 @@ import org.powermock.modules.junit4.PowerMockRunner
class MsgHistoryErrorTest : DanaRTestBase() { class MsgHistoryErrorTest : DanaRTestBase() {
@Test fun runTest() { @Test fun runTest() {
@Suppress("UNUSED_VARIABLE")
val packet = MsgHistoryError(injector) val packet = MsgHistoryError(injector)
// nothing left to test // nothing left to test
} }

View file

@ -9,6 +9,7 @@ import org.powermock.modules.junit4.PowerMockRunner
class MsgHistoryGlucoseTest : DanaRTestBase() { class MsgHistoryGlucoseTest : DanaRTestBase() {
@Test fun runTest() { @Test fun runTest() {
@Suppress("UNUSED_VARIABLE")
val packet = MsgHistoryGlucose(injector) val packet = MsgHistoryGlucose(injector)
// nothing left to test // nothing left to test
} }

Some files were not shown because too many files have changed in this diff Show more