[#2210][#728] Tests for complications related, formating, perisitence, utils and data-model code of wear module

This commit is contained in:
dlvoy 2019-11-26 09:24:41 +01:00
parent 1042e8aab8
commit 48aa7a887a
21 changed files with 2510 additions and 0 deletions

View file

@ -0,0 +1,113 @@
package info.nightscout.androidaps.data;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import java.util.HashSet;
import java.util.Set;
import info.nightscout.androidaps.interaction.utils.Constants;
import info.nightscout.androidaps.interaction.utils.WearUtil;
import info.nightscout.androidaps.testing.mockers.WearUtilMocker;
import static org.hamcrest.number.OrderingComparison.comparesEqualTo;
import static org.hamcrest.number.OrderingComparison.greaterThan;
import static org.hamcrest.number.OrderingComparison.lessThan;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
@RunWith(PowerMockRunner.class)
@PrepareForTest( { WearUtil.class } )
public class BgWatchDataTest {
@Before
public void mock() {
WearUtilMocker.prepareMockNoReal();
}
@Test
public void bgWatchDataHashTest() {
// GIVEN
BgWatchData inserted = new BgWatchData(
88.0, 160.0, 90.0,
WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS*4*1, 1
);
Set<BgWatchData> set = new HashSet<>();
// THEN
assertFalse(set.contains(inserted));
set.add(inserted);
assertTrue(set.contains(inserted));
}
/**
* BgWatchData has BIZARRE equals - only timestamp and color are checked!
*/
@Test
public void bgWatchDataEqualsTest() {
// GIVEN
BgWatchData item1 = new BgWatchData(
88.0, 160.0, 90.0,
WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS, 1
);
BgWatchData item2sameTimeSameColor = new BgWatchData(
123.0, 190, 90.0,
WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS, 1
);
BgWatchData item3sameTimeSameDiffColor = new BgWatchData(
96.0, 190, 90.0,
WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS, 0
);
BgWatchData item4differentTime = new BgWatchData(
88.0, 160.0, 90.0,
WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS*2, 1
);
// THEN
assertEquals(item1, item2sameTimeSameColor);
assertNotEquals(item1, item3sameTimeSameDiffColor);
assertNotEquals(item1, item4differentTime);
assertFalse(item1.equals("aa bbb"));
}
/**
* BgWatchData is ordered by timestamp, reverse order
*/
@Test
public void bgWatchDataCompareTest() {
// GIVEN
BgWatchData item1 = new BgWatchData(
85, 160.0, 90.0,
WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS*2, 1
);
BgWatchData item2 = new BgWatchData(
80, 190, 90.0,
WearUtilMocker.REF_NOW, 1
);
BgWatchData item3 = new BgWatchData(
80, 190, 50.0,
WearUtilMocker.REF_NOW + Constants.MINUTE_IN_MS*5, 0
);
BgWatchData item4 = new BgWatchData(
160, 140, 70.0,
WearUtilMocker.REF_NOW, 0
);
// THEN
assertThat(item2, lessThan(item1));
assertThat(item2, greaterThan(item3));
assertThat(item2, comparesEqualTo(item4));
}
}

View file

@ -0,0 +1,265 @@
package info.nightscout.androidaps.data;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import com.google.android.gms.wearable.DataMap;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import java.util.ArrayList;
import info.nightscout.androidaps.aaps;
import info.nightscout.androidaps.interaction.utils.Constants;
import info.nightscout.androidaps.interaction.utils.Persistence;
import info.nightscout.androidaps.interaction.utils.WearUtil;
import info.nightscout.androidaps.testing.mockers.AAPSMocker;
import info.nightscout.androidaps.testing.mockers.AndroidMocker;
import info.nightscout.androidaps.testing.mockers.WearUtilMocker;
import info.nightscout.androidaps.testing.mocks.BundleMock;
import info.nightscout.androidaps.testing.mocks.IntentMock;
import info.nightscout.androidaps.testing.utils.BasalWatchDataExt;
import info.nightscout.androidaps.testing.utils.BgWatchDataExt;
import info.nightscout.androidaps.testing.utils.BolusWatchDataExt;
import info.nightscout.androidaps.testing.utils.TempWatchDataExt;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
@RunWith(PowerMockRunner.class)
@PrepareForTest( { WearUtil.class, Log.class, SharedPreferences.class, Context.class, aaps.class, android.util.Base64.class, Intent.class } )
public class DisplayRawDataBasalsTest {
@Before
public void mock() {
AAPSMocker.prepareMock();
AAPSMocker.resetMockedSharedPrefs();
AndroidMocker.mockBase64();
WearUtilMocker.prepareMockNoReal();
}
//==============================================================================================
// BASALS for chart
//==============================================================================================
private DataMap dataMapForBasals() {
DataMap dataMap = new DataMap();
ArrayList<DataMap> temps = new ArrayList<>();
DataMap temp = new DataMap();
temp.putLong("starttime", WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS*20);
temp.putDouble("startBasal", 1.5);
temp.putLong("endtime", WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS*10);
temp.putDouble("endbasal", 1.5);
temp.putDouble("amount", 1.8);
temps.add(temp);
DataMap temp2 = new DataMap();
temp2.putLong("starttime", WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS*10);
temp2.putDouble("startBasal", 1.3);
temp2.putLong("endtime", WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS*2);
temp2.putDouble("endbasal", 1.3);
temp2.putDouble("amount", 2.3);
temps.add(temp2);
dataMap.putDataMapArrayList("temps", temps);
ArrayList<DataMap> basals = new ArrayList<>();
DataMap basal = new DataMap();
basal.putLong("starttime", WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS*20);
basal.putLong("endtime", WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS*2);
basal.putDouble("amount", 1.2);
basals.add(basal);
dataMap.putDataMapArrayList("basals", basals);
ArrayList<DataMap> boluses = new ArrayList<>();
DataMap bolus = new DataMap();
bolus.putLong("date", WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS*17);
bolus.putDouble("bolus", 5.5);
bolus.putDouble("carbs", 20.0);
bolus.putBoolean("isSMB", false);
bolus.putBoolean("isValid", true);
boluses.add(bolus);
DataMap bolus2 = new DataMap();
bolus2.putLong("date", WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS*11);
bolus2.putDouble("bolus", 3.0);
bolus2.putDouble("carbs", 0.0);
bolus2.putBoolean("isSMB", false);
bolus2.putBoolean("isValid", true);
boluses.add(bolus2);
DataMap bolus3 = new DataMap();
bolus3.putLong("date", WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS*3);
bolus3.putDouble("bolus", 0.0);
bolus3.putDouble("carbs", 15.0);
bolus3.putBoolean("isSMB", true);
bolus3.putBoolean("isValid", false);
boluses.add(bolus3);
dataMap.putDataMapArrayList("boluses", boluses);
ArrayList<DataMap> predictions = new ArrayList<>();
for (int i=0; i<10; i++) {
DataMap prediction = new DataMap();
prediction.putLong("timestamp", WearUtilMocker.REF_NOW + Constants.MINUTE_IN_MS*i);
prediction.putDouble("sgv", 160-4*i);
prediction.putInt("color", 0);
predictions.add(prediction);
}
dataMap.putDataMapArrayList("predictions", predictions);
return dataMap;
}
private void assertBasalsEmpty(DisplayRawData newRaw) {
assertThat(newRaw.tempWatchDataList.size(), is(0));
assertThat(newRaw.basalWatchDataList.size(), is(0));
assertThat(newRaw.bolusWatchDataList.size(), is(0));
assertThat(newRaw.predictionList.size(), is(0));
}
private void assertBasalsOk(DisplayRawData newRaw) {
assertThat(newRaw.tempWatchDataList.size(), is(2));
assertThat(newRaw.basalWatchDataList.size(), is(1));
assertThat(newRaw.bolusWatchDataList.size(), is(3));
assertThat(newRaw.predictionList.size(), is(10));
assertThat(new TempWatchDataExt(newRaw.tempWatchDataList.get(0)), is(TempWatchDataExt.build(
WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS*20,
1.5,
WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS*10,
1.5,
1.8
)));
assertThat(new TempWatchDataExt(newRaw.tempWatchDataList.get(1)), is(TempWatchDataExt.build(
WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS*10,
1.3,
WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS*2,
1.3,
2.3
)));
assertThat(new BasalWatchDataExt(newRaw.basalWatchDataList.get(0)), is(BasalWatchDataExt.build(
WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS*20,
WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS*2,
1.2
)));
assertThat(new BolusWatchDataExt(newRaw.bolusWatchDataList.get(0)), is(BolusWatchDataExt.build(
WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS*17,
5.5,
20,
false,
true
)));
assertThat(new BolusWatchDataExt(newRaw.bolusWatchDataList.get(1)), is(BolusWatchDataExt.build(
WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS*11,
3,
0,
false,
true
)));
assertThat(new BolusWatchDataExt(newRaw.bolusWatchDataList.get(2)), is(BolusWatchDataExt.build(
WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS*3,
0,
15,
true,
false
)));
assertThat(new BgWatchDataExt(newRaw.predictionList.get(3)), is(BgWatchDataExt.build(
160-4*3,
WearUtilMocker.REF_NOW + Constants.MINUTE_IN_MS*3,
0
)));
assertThat(new BgWatchDataExt(newRaw.predictionList.get(7)), is(BgWatchDataExt.build(
160-4*7,
WearUtilMocker.REF_NOW + Constants.MINUTE_IN_MS*7,
0
)));
}
@Test
public void updateBasalsFromEmptyPersistenceTest() {
// GIVEN
Persistence persistence = new Persistence();
DisplayRawData newRaw = new DisplayRawData();
// WHEN
newRaw.updateFromPersistence(persistence);
// THEN
assertBasalsEmpty(newRaw);
}
@Test
public void updateBasalsFromPersistenceTest() {
// GIVEN
Persistence persistence = new Persistence();
DisplayRawData newRaw = new DisplayRawData();
// WHEN
Persistence.storeDataMap(DisplayRawData.BASALS_PERSISTENCE_KEY, dataMapForBasals());
newRaw.updateFromPersistence(persistence);
// THEN
assertBasalsOk(newRaw);
}
@Test
public void partialUpdateBasalsFromPersistenceTest() {
// GIVEN
Persistence persistence = new Persistence();
DisplayRawData newRaw = new DisplayRawData();
// WHEN
Persistence.storeDataMap(DisplayRawData.BASALS_PERSISTENCE_KEY, dataMapForBasals());
newRaw.partialUpdateFromPersistence(persistence);
// THEN
assertBasalsEmpty(newRaw);
}
@Test
public void updateBasalsFromMessageTest() {
// GIVEN
Intent intent = IntentMock.mock();
Bundle bundle = BundleMock.mock(dataMapForBasals());
intent.putExtra("basals", bundle);
DisplayRawData newRaw = new DisplayRawData();
// WHEN
newRaw.updateBasalsFromMessage(intent, null);
// THEN
assertBasalsOk(newRaw);
}
@Test
public void updateBasalsFromEmptyMessageTest() {
// GIVEN
Intent intent = IntentMock.mock();
DisplayRawData newRaw = new DisplayRawData();
// WHEN
newRaw.updateBasalsFromMessage(intent, null);
// THEN
assertBasalsEmpty(newRaw);
}
}

View file

@ -0,0 +1,146 @@
package info.nightscout.androidaps.data;
import com.google.android.gms.wearable.DataMap;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import java.util.ArrayList;
import info.nightscout.androidaps.interaction.utils.Constants;
import info.nightscout.androidaps.interaction.utils.WearUtil;
import info.nightscout.androidaps.testing.mockers.WearUtilMocker;
import info.nightscout.androidaps.testing.utils.BgWatchDataExt;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
@RunWith(PowerMockRunner.class)
@PrepareForTest( { WearUtil.class } )
public class DisplayRawDataBgEntriesTest {
@Before
public void mock() {
WearUtilMocker.prepareMockNoReal();
}
//==============================================================================================
// ENTRIES for chart
//==============================================================================================
private DataMap dataMapForEntries() {
DataMap dataMap = new DataMap();
ArrayList<DataMap> entries = new ArrayList<>();
for (int i=0; i<12; i++) {
DataMap entry = new DataMap();
entry.putLong("timestamp", WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS*4*(16-i));
entry.putDouble("sgvDouble", 145.0-5*i);
entry.putDouble("high", 170.0);
entry.putDouble("low", 80.0);
entry.putInt("color", 0);
entries.add(entry);
}
dataMap.putDataMapArrayList("entries", entries);
return dataMap;
}
private DataMap dataMapForEntries(long timestamp, double sgv) {
DataMap entry = new DataMap();
entry.putLong("timestamp", timestamp);
entry.putDouble("sgvDouble", sgv);
entry.putDouble("high", 160.0);
entry.putDouble("low", 90.0);
entry.putInt("color", 1);
return entry;
}
@Test
public void addToWatchSetTest() {
// GIVEN
DisplayRawData newRaw = new DisplayRawData();
DataMap multipleEntries = dataMapForEntries();
DataMap singleEntry1 = dataMapForEntries(WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS*4*2,92);
DataMap singleEntry2 = dataMapForEntries(WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS*4*1,88);
// WHEN, THEN
// add list
newRaw.addToWatchSet(multipleEntries);
assertThat(newRaw.bgDataList.size(), is(12));
assertThat(new BgWatchDataExt(newRaw.bgDataList.get(5)),
is(new BgWatchDataExt(new BgWatchData(
120.0, 170.0, 80.0,
WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS*4*(16-5), 0
))));
assertThat(new BgWatchDataExt(newRaw.bgDataList.get(11)),
is(new BgWatchDataExt(new BgWatchData(
90.0, 170.0, 80.0,
WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS*4*(16-11), 0
))));
// add single entries
newRaw.addToWatchSet(singleEntry1);
newRaw.addToWatchSet(singleEntry2);
assertThat(newRaw.bgDataList.size(), is(14));
assertThat(new BgWatchDataExt(newRaw.bgDataList.get(12)),
is(new BgWatchDataExt(new BgWatchData(
92.0, 160.0, 90.0,
WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS*4*2, 1
))));
assertThat(new BgWatchDataExt(newRaw.bgDataList.get(13)),
is(new BgWatchDataExt(new BgWatchData(
88.0, 160.0, 90.0,
WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS*4*1, 1
))));
// ignore duplicates
newRaw.addToWatchSet(singleEntry2);
assertThat(newRaw.bgDataList.size(), is(14));
}
@Test
public void addToWatchSetCleanupOldTest() {
DisplayRawData newRaw = new DisplayRawData();
newRaw.addToWatchSet(dataMapForEntries(WearUtil.timestamp(),125));
assertThat(newRaw.bgDataList.size(), is(1));
WearUtilMocker.progressClock(Constants.HOUR_IN_MS*2);
newRaw.addToWatchSet(dataMapForEntries(WearUtil.timestamp(),140));
assertThat(newRaw.bgDataList.size(), is(2));
WearUtilMocker.progressClock(Constants.HOUR_IN_MS*1);
newRaw.addToWatchSet(dataMapForEntries(WearUtil.timestamp(),150));
WearUtilMocker.progressClock(Constants.HOUR_IN_MS*1 +Constants.MINUTE_IN_MS*30);
newRaw.addToWatchSet(dataMapForEntries(WearUtil.timestamp(),101));
assertThat(newRaw.bgDataList.size(), is(4));
WearUtilMocker.progressClock(Constants.MINUTE_IN_MS*30);
newRaw.addToWatchSet(dataMapForEntries(WearUtil.timestamp(),90));
assertThat(newRaw.bgDataList.size(), is(5));
WearUtilMocker.progressClock(Constants.HOUR_IN_MS*1 +Constants.MINUTE_IN_MS*30);
newRaw.addToWatchSet(dataMapForEntries(WearUtil.timestamp(),80));
assertThat(newRaw.bgDataList.size(), is(5));
WearUtilMocker.progressClock(Constants.HOUR_IN_MS*4);
newRaw.addToWatchSet(dataMapForEntries(WearUtil.timestamp(),92));
assertThat(newRaw.bgDataList.size(), is(2));
WearUtilMocker.progressClock(Constants.HOUR_IN_MS*5 +Constants.MINUTE_IN_MS*30);
newRaw.addToWatchSet(dataMapForEntries(WearUtil.timestamp(),107));
assertThat(newRaw.bgDataList.size(), is(1));
WearUtilMocker.progressClock(Constants.HOUR_IN_MS*6 +Constants.MINUTE_IN_MS*30);
newRaw.addToWatchSet(dataMapForEntries(WearUtil.timestamp()-Constants.HOUR_IN_MS*6,138));
assertThat(newRaw.bgDataList.size(), is(0));
}
}

View file

@ -0,0 +1,148 @@
package info.nightscout.androidaps.data;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import com.google.android.gms.wearable.DataMap;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import info.nightscout.androidaps.aaps;
import info.nightscout.androidaps.interaction.utils.Constants;
import info.nightscout.androidaps.interaction.utils.Persistence;
import info.nightscout.androidaps.interaction.utils.WearUtil;
import info.nightscout.androidaps.testing.mockers.AAPSMocker;
import info.nightscout.androidaps.testing.mockers.AndroidMocker;
import info.nightscout.androidaps.testing.mockers.WearUtilMocker;
import info.nightscout.androidaps.testing.mocks.BundleMock;
import info.nightscout.androidaps.testing.mocks.IntentMock;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
@RunWith(PowerMockRunner.class)
@PrepareForTest( { WearUtil.class, Log.class, SharedPreferences.class, Context.class, aaps.class, android.util.Base64.class, Intent.class } )
public class DisplayRawDataSgvDataTest {
@Before
public void mock() {
AAPSMocker.prepareMock();
AAPSMocker.resetMockedSharedPrefs();
AndroidMocker.mockBase64();
WearUtilMocker.prepareMockNoReal();
}
//==============================================================================================
// SGV DATA
//==============================================================================================
private DataMap dataMapForData() {
DataMap dataMap = new DataMap();
dataMap.putLong("sgvLevel", 1L);
dataMap.putLong("timestamp", WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS);
dataMap.putString("sgvString", "106");
dataMap.putString("slopeArrow", "");
dataMap.putString("delta", "5.4");
dataMap.putString("avgDelta", "3.7");
dataMap.putString("glucoseUnits", "mg/dl");
return dataMap;
}
private void assertDataEmpty(DisplayRawData newRaw) {
assertThat(newRaw.sgvLevel, is(0L));
assertThat(newRaw.datetime, is(0L));
assertThat(newRaw.sSgv, is("---"));
assertThat(newRaw.sDirection, is("--"));
assertThat(newRaw.sDelta, is("--"));
assertThat(newRaw.sAvgDelta, is("--"));
assertThat(newRaw.sUnits, is("-"));
}
private void assertDataOk(DisplayRawData newRaw) {
assertThat(newRaw.sgvLevel, is(1L));
assertThat(newRaw.datetime, is(WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS));
assertThat(newRaw.sSgv, is("106"));
assertThat(newRaw.sDirection, is(""));
assertThat(newRaw.sDelta, is("5.4"));
assertThat(newRaw.sAvgDelta, is("3.7"));
assertThat(newRaw.sUnits, is("mg/dl"));
}
@Test
public void updateDataFromEmptyPersistenceTest() {
// GIVEN
Persistence persistence = new Persistence();
DisplayRawData newRaw = new DisplayRawData();
// WHEN
newRaw.updateFromPersistence(persistence);
// THEN
assertDataEmpty(newRaw);
}
@Test
public void updateDataFromPersistenceTest() {
// GIVEN
Persistence persistence = new Persistence();
DisplayRawData newRaw = new DisplayRawData();
// WHEN
Persistence.storeDataMap(DisplayRawData.DATA_PERSISTENCE_KEY, dataMapForData());
newRaw.updateFromPersistence(persistence);
// THEN
assertDataOk(newRaw);
}
@Test
public void partialUpdateDataFromPersistenceTest() {
// GIVEN
Persistence persistence = new Persistence();
DisplayRawData newRaw = new DisplayRawData();
// WHEN
Persistence.storeDataMap(DisplayRawData.DATA_PERSISTENCE_KEY, dataMapForData());
newRaw.partialUpdateFromPersistence(persistence);
// THEN
assertDataOk(newRaw);
}
@Test
public void updateDataFromMessageTest() {
// GIVEN
Intent intent = IntentMock.mock();
Bundle bundle = BundleMock.mock(dataMapForData());
intent.putExtra("data", bundle);
DisplayRawData newRaw = new DisplayRawData();
// WHEN
newRaw.updateDataFromMessage(intent, null);
// THEN
assertDataOk(newRaw);
}
@Test
public void updateDataFromEmptyMessageTest() {
// GIVEN
Intent intent = IntentMock.mock();
DisplayRawData newRaw = new DisplayRawData();
// WHEN
newRaw.updateDataFromMessage(intent, null);
// THEN
assertDataEmpty(newRaw);
}
}

View file

@ -0,0 +1,176 @@
package info.nightscout.androidaps.data;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import com.google.android.gms.wearable.DataMap;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import info.nightscout.androidaps.aaps;
import info.nightscout.androidaps.interaction.utils.Constants;
import info.nightscout.androidaps.interaction.utils.Persistence;
import info.nightscout.androidaps.interaction.utils.WearUtil;
import info.nightscout.androidaps.testing.mockers.AAPSMocker;
import info.nightscout.androidaps.testing.mockers.AndroidMocker;
import info.nightscout.androidaps.testing.mockers.RawDataMocker;
import info.nightscout.androidaps.testing.mockers.WearUtilMocker;
import info.nightscout.androidaps.testing.mocks.BundleMock;
import info.nightscout.androidaps.testing.mocks.IntentMock;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
@RunWith(PowerMockRunner.class)
@PrepareForTest( { WearUtil.class, Log.class, SharedPreferences.class, Context.class, aaps.class, android.util.Base64.class, Intent.class } )
public class DisplayRawDataStatusTest {
@Before
public void mock() {
AAPSMocker.prepareMock();
AAPSMocker.resetMockedSharedPrefs();
AndroidMocker.mockBase64();
WearUtilMocker.prepareMockNoReal();
}
@Test
public void toDebugStringTest() {
DisplayRawData raw = RawDataMocker.rawDelta(5, "1.5");
raw.externalStatusString = "placeholder-here";
assertThat(raw.datetime, is(WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS*5));
assertThat(raw.toDebugString(), containsString("placeholder-here"));
}
//==============================================================================================
// STATUS
//==============================================================================================
private DataMap dataMapForStatus() {
DataMap dataMap = new DataMap();
dataMap.putString("currentBasal", "120%");
dataMap.putString("battery", "76");
dataMap.putString("rigBattery", "40%");
dataMap.putBoolean("detailedIob", true);
dataMap.putString("iobSum", "12.5") ;
dataMap.putString("iobDetail","(11,2|1,3)");
dataMap.putString("cob","5(10)g");
dataMap.putString("bgi", "13");
dataMap.putBoolean("showBgi", false);
dataMap.putString("externalStatusString", "");
dataMap.putInt("batteryLevel", 1);
dataMap.putLong("openApsStatus", WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS*2);
return dataMap;
}
private void assertStatusEmpty(DisplayRawData newRaw) {
assertThat(newRaw.sBasalRate, is("-.--U/h"));
assertThat(newRaw.sUploaderBattery, is("--"));
assertThat(newRaw.sRigBattery, is("--"));
assertThat(newRaw.detailedIOB, is(false));
assertThat(newRaw.sIOB1, is("IOB"));
assertThat(newRaw.sIOB2, is("-.--"));
assertThat(newRaw.sCOB1, is("Carb"));
assertThat(newRaw.sCOB2, is("--g"));
assertThat(newRaw.sBgi, is("--"));
assertThat(newRaw.showBGI, is(false));
assertThat(newRaw.externalStatusString, is("no status"));
assertThat(newRaw.batteryLevel, is(1));
assertThat(newRaw.openApsStatus, is(-1L));
}
private void assertStatusOk(DisplayRawData newRaw) {
assertThat(newRaw.sBasalRate, is("120%"));
assertThat(newRaw.sUploaderBattery, is("76"));
assertThat(newRaw.sRigBattery, is("40%"));
assertThat(newRaw.detailedIOB, is(true));
assertThat(newRaw.sIOB1, is("12.5U"));
assertThat(newRaw.sIOB2, is("(11,2|1,3)"));
assertThat(newRaw.sCOB1, is("Carb"));
assertThat(newRaw.sCOB2, is("5(10)g"));
assertThat(newRaw.sBgi, is("13"));
assertThat(newRaw.showBGI, is(false));
assertThat(newRaw.externalStatusString, is(""));
assertThat(newRaw.batteryLevel, is(1));
assertThat(newRaw.openApsStatus, is(WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS*2));
}
@Test
public void updateStatusFromEmptyPersistenceTest() {
// GIVEN
Persistence persistence = new Persistence();
DisplayRawData newRaw = new DisplayRawData();
// WHEN
newRaw.updateFromPersistence(persistence);
// THEN
assertStatusEmpty(newRaw);
}
@Test
public void updateStatusFromPersistenceTest() {
// GIVEN
Persistence persistence = new Persistence();
DisplayRawData newRaw = new DisplayRawData();
// WHEN
Persistence.storeDataMap(DisplayRawData.STATUS_PERSISTENCE_KEY, dataMapForStatus());
newRaw.updateFromPersistence(persistence);
// THEN
assertStatusOk(newRaw);
}
@Test
public void partialUpdateStatusFromPersistenceTest() {
// GIVEN
Persistence persistence = new Persistence();
DisplayRawData newRaw = new DisplayRawData();
// WHEN
Persistence.storeDataMap(DisplayRawData.STATUS_PERSISTENCE_KEY, dataMapForStatus());
newRaw.partialUpdateFromPersistence(persistence);
// THEN
assertStatusOk(newRaw);
}
@Test
public void updateStatusFromMessageTest() {
// GIVEN
Intent intent = IntentMock.mock();
Bundle bundle = BundleMock.mock(dataMapForStatus());
intent.putExtra("status", bundle);
DisplayRawData newRaw = new DisplayRawData();
// WHEN
newRaw.updateStatusFromMessage(intent, null);
// THEN
assertStatusOk(newRaw);
}
@Test
public void updateStatusFromEmptyMessageTest() {
// GIVEN
Intent intent = IntentMock.mock();
DisplayRawData newRaw = new DisplayRawData();
// WHEN
newRaw.updateStatusFromMessage(intent, null);
// THEN
assertStatusEmpty(newRaw);
}
}

View file

@ -0,0 +1,204 @@
package info.nightscout.androidaps.interaction.utils;
import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import info.nightscout.androidaps.aaps;
import info.nightscout.androidaps.data.DisplayRawData;
import info.nightscout.androidaps.testing.mockers.AAPSMocker;
import info.nightscout.androidaps.testing.mockers.WearUtilMocker;
import static info.nightscout.androidaps.testing.mockers.RawDataMocker.rawCob;
import static info.nightscout.androidaps.testing.mockers.RawDataMocker.rawCobIobBr;
import static info.nightscout.androidaps.testing.mockers.RawDataMocker.rawDelta;
import static info.nightscout.androidaps.testing.mockers.RawDataMocker.rawIob;
import static info.nightscout.androidaps.testing.mockers.RawDataMocker.rawSgv;
import static info.nightscout.androidaps.testing.mockers.WearUtilMocker.backInTime;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
/**
* This test covers DisplayFormat class (directly)
* but also SmallestDoubleString - due to carefully chosen input data to format
*/
@RunWith(PowerMockRunner.class)
@PrepareForTest( { WearUtil.class, Log.class, SharedPreferences.class, Context.class, aaps.class } )
public class DisplayFormatTest {
@Before
public void mock() {
WearUtilMocker.prepareMock();
AAPSMocker.prepareMock();
AAPSMocker.resetMockedSharedPrefs();
}
@Test
public void shortTimeSinceTest() {
assertThat(DisplayFormat.shortTimeSince(backInTime(0,0,0,0)), is("0'"));
assertThat(DisplayFormat.shortTimeSince(backInTime(0,0,0,5)), is("0'"));
assertThat(DisplayFormat.shortTimeSince(backInTime(0,0,0,55)), is("0'"));
assertThat(DisplayFormat.shortTimeSince(backInTime(0,0,1,0)), is("1'"));
assertThat(DisplayFormat.shortTimeSince(backInTime(0,0,1,59)), is("1'"));
assertThat(DisplayFormat.shortTimeSince(backInTime(0,0,2,0)), is("2'"));
assertThat(DisplayFormat.shortTimeSince(backInTime(0,0,3,0)), is("3'"));
assertThat(DisplayFormat.shortTimeSince(backInTime(0,0,4,0)), is("4'"));
assertThat(DisplayFormat.shortTimeSince(backInTime(0,0,10,0)), is("10'"));
assertThat(DisplayFormat.shortTimeSince(backInTime(0,0,30,0)), is("30'"));
assertThat(DisplayFormat.shortTimeSince(backInTime(0,0,59,0)), is("59'"));
assertThat(DisplayFormat.shortTimeSince(backInTime(0,0,59,59)), is("59'"));
assertThat(DisplayFormat.shortTimeSince(backInTime(0,1,0,0)), is("1h"));
assertThat(DisplayFormat.shortTimeSince(backInTime(0,1,30,0)), is("1h"));
assertThat(DisplayFormat.shortTimeSince(backInTime(0,1,59,59)), is("1h"));
assertThat(DisplayFormat.shortTimeSince(backInTime(0,2,0,0)), is("2h"));
assertThat(DisplayFormat.shortTimeSince(backInTime(0,3,0,0)), is("3h"));
assertThat(DisplayFormat.shortTimeSince(backInTime(0,4,0,0)), is("4h"));
assertThat(DisplayFormat.shortTimeSince(backInTime(0,5,0,0)), is("5h"));
assertThat(DisplayFormat.shortTimeSince(backInTime(0,12,0,0)), is("12h"));
assertThat(DisplayFormat.shortTimeSince(backInTime(0,18,0,0)), is("18h"));
assertThat(DisplayFormat.shortTimeSince(backInTime(0,23,59,59)), is("23h"));
assertThat(DisplayFormat.shortTimeSince(backInTime(1,0,0,0)), is("1d"));
assertThat(DisplayFormat.shortTimeSince(backInTime(1,12,0,0)), is("1d"));
assertThat(DisplayFormat.shortTimeSince(backInTime(1,23,59,59)), is("1d"));
assertThat(DisplayFormat.shortTimeSince(backInTime(2,0,0,0)), is("2d"));
assertThat(DisplayFormat.shortTimeSince(backInTime(3,0,0,0)), is("3d"));
assertThat(DisplayFormat.shortTimeSince(backInTime(4,0,0,0)), is("4d"));
assertThat(DisplayFormat.shortTimeSince(backInTime(5,0,0,0)), is("5d"));
assertThat(DisplayFormat.shortTimeSince(backInTime(6,0,0,0)), is("6d"));
assertThat(DisplayFormat.shortTimeSince(backInTime(6,23,59,59)), is("6d"));
assertThat(DisplayFormat.shortTimeSince(backInTime(7,0,0,0)), is("1w"));
assertThat(DisplayFormat.shortTimeSince(backInTime(8,0,0,0)), is("1w"));
assertThat(DisplayFormat.shortTimeSince(backInTime(9,0,0,0)), is("1w"));
assertThat(DisplayFormat.shortTimeSince(backInTime(13,23,59,59)), is("1w"));
assertThat(DisplayFormat.shortTimeSince(backInTime(14,0,0,0)), is("2w"));
assertThat(DisplayFormat.shortTimeSince(backInTime(21,0,0,0)), is("3w"));
assertThat(DisplayFormat.shortTimeSince(backInTime(28,0,0,0)), is("4w"));
assertThat(DisplayFormat.shortTimeSince(backInTime(31,0,0,0)), is("4w"));
assertThat(DisplayFormat.shortTimeSince(backInTime(32,0,0,0)), is("4w"));
assertThat(DisplayFormat.shortTimeSince(backInTime(35,0,0,0)), is("5w"));
assertThat(DisplayFormat.shortTimeSince(backInTime(100,0,0,0)), is("14w"));
assertThat(DisplayFormat.shortTimeSince(backInTime(200,0,0,0)), is("28w"));
assertThat(DisplayFormat.shortTimeSince(backInTime(365,0,0,0)), is("52w"));
assertThat(DisplayFormat.shortTimeSince(backInTime(366,0,0,0)), is("52w"));
assertThat(DisplayFormat.shortTimeSince(backInTime(367,0,0,0)), is("52w"));
}
@Test
public void shortTrendTest() {
DisplayRawData raw = new DisplayRawData();
assertThat(DisplayFormat.shortTrend(raw), is("-- Δ--"));
raw.datetime = backInTime(0, 0, 2, 0);
assertThat(DisplayFormat.shortTrend(raw), is("2' Δ--"));
AAPSMocker.setMockedUnicodeComplicationsOn(true);
// shortening
assertThat(DisplayFormat.shortTrend(rawDelta(2, "1.2")), is("2' Δ1.2"));
assertThat(DisplayFormat.shortTrend(rawDelta(11,"1.2")), is("11' 1.2"));
assertThat(DisplayFormat.shortTrend(rawDelta(12,"0.7")), is("12' Δ.7"));
assertThat(DisplayFormat.shortTrend(rawDelta(10,"1.0")), is("10' Δ1"));
assertThat(DisplayFormat.shortTrend(rawDelta(14,"-5.0")), is("14' Δ-5"));
assertThat(DisplayFormat.shortTrend(rawDelta(13,"-5.1")), is("13' -5"));
assertThat(DisplayFormat.shortTrend(rawDelta(15,"0.87")), is("15' .87"));
assertThat(DisplayFormat.shortTrend(rawDelta(10,"-1.78")), is("10' -2"));
assertThat(DisplayFormat.shortTrend(rawDelta(3, "2.549")), is("3' 2.55"));
assertThat(DisplayFormat.shortTrend(rawDelta(1, "-1.563")), is("1' -1.6"));
// preserving separator
assertThat(DisplayFormat.shortTrend(rawDelta(2, "1,2")), is("2' Δ1,2"));
assertThat(DisplayFormat.shortTrend(rawDelta(15,"0,87")), is("15' ,87"));
assertThat(DisplayFormat.shortTrend(rawDelta(3, "+2,549")), is("3' 2,55"));
assertThat(DisplayFormat.shortTrend(rawDelta(1, "-1,563")), is("1' -1,6"));
// UTF-off mode - without delta symbol
AAPSMocker.setMockedUnicodeComplicationsOn(false);
assertThat(DisplayFormat.shortTrend(rawDelta(2, "1.2")), is("2' 1.2"));
assertThat(DisplayFormat.shortTrend(rawDelta(12,"0.7")), is("12' 0.7"));
assertThat(DisplayFormat.shortTrend(rawDelta(10,"1.0")), is("10' 1.0"));
assertThat(DisplayFormat.shortTrend(rawDelta(14,"-5.0")), is("14' -5"));
}
@Test
public void longGlucoseLine() {
assertThat(DisplayFormat.longGlucoseLine(rawSgv("125",2, "1.2")), is("125→ Δ1.2 (2')"));
assertThat(DisplayFormat.longGlucoseLine(rawSgv("97",11, "5.2")), is("97↗ Δ5.2 (11')"));
assertThat(DisplayFormat.longGlucoseLine(rawSgv("110",12,"0.7")), is("110→ Δ.7 (12')"));
assertThat(DisplayFormat.longGlucoseLine(rawSgv("65",10,"7.0")), is("65↗ Δ7 (10')"));
assertThat(DisplayFormat.longGlucoseLine(rawSgv("215",14,"-5.0")), is("215↘ Δ-5 (14')"));
assertThat(DisplayFormat.longGlucoseLine(rawSgv("8.3",13,"-5.1")), is("8.3↘ Δ-5.1 (13')"));
assertThat(DisplayFormat.longGlucoseLine(rawSgv("6.8",15,"10.83")), is("6.8↑ Δ10.83 (15')"));
assertThat(DisplayFormat.longGlucoseLine(rawSgv("13.2",10,"-11.78")), is("13.2↓ Δ-11.78 (10')"));
assertThat(DisplayFormat.longGlucoseLine(rawSgv("3.9",3, "2.549")), is("3.9→ Δ2.549 (3')"));
assertThat(DisplayFormat.longGlucoseLine(rawSgv("11.1",1, "-15.563")), is("11.1↓ Δ-15.563 (1')"));
}
@Test
public void longDetailsLineTest() {
AAPSMocker.setMockedUnicodeComplicationsOn(true);
assertThat(DisplayFormat.longDetailsLine(rawCobIobBr("0g", "0U", "3.5U/h")), is("0g ⁞ 0U ⁞ ⎍3.5U/h"));
assertThat(DisplayFormat.longDetailsLine(rawCobIobBr("50g", "7.56U", "0%")), is("50g ⁞ 7.56U ⁞ ⎍0%"));
assertThat(DisplayFormat.longDetailsLine(rawCobIobBr("12g", "3.23U", "120%")), is("12g ⁞ 3.23U ⁞ 120%"));
assertThat(DisplayFormat.longDetailsLine(rawCobIobBr("2(40)g", "-1.5U", "0.55U/h")), is("2(40)g ⁞ -2U ⁞ 0.55U/h"));
assertThat(DisplayFormat.longDetailsLine(rawCobIobBr("0(24)g", "0.05U", "160%")), is("0(24)g ⁞ 0.05U ⁞ 160%"));
assertThat(DisplayFormat.longDetailsLine(rawCobIobBr("47g", "13.87U", "220%")), is("47g ⁞ 13.87U ⁞ 220%"));
assertThat(DisplayFormat.longDetailsLine(rawCobIobBr("13(5)g", "5.90U", "300%")), is("13(5)g ⁞ 5.90U ⁞ 300%"));
assertThat(DisplayFormat.longDetailsLine(rawCobIobBr("11(50)g", "0U", "70%")), is("11(50)g ⁞ 0U ⁞ 70%"));
assertThat(DisplayFormat.longDetailsLine(rawCobIobBr("7g", "0.54U", "30%")), is("7g ⁞ 0.54U ⁞ ⎍30%"));
assertThat(DisplayFormat.longDetailsLine(rawCobIobBr("19(38)g", "35.545U", "12.9U/h")), is("19g ⁞ 36U ⁞ 12.9U/h"));
assertThat(DisplayFormat.longDetailsLine(rawCobIobBr("100(1)g", "12.345U", "6.98647U/h")), is("100g 12U 6.98647U/h"));
AAPSMocker.setMockedUnicodeComplicationsOn(false);
assertThat(DisplayFormat.longDetailsLine(rawCobIobBr("0g", "0U", "3.5U/h")), is("0g | 0U | 3.5U/h"));
assertThat(DisplayFormat.longDetailsLine(rawCobIobBr("50g", "7.56U", "0%")), is("50g | 7.56U | 0%"));
assertThat(DisplayFormat.longDetailsLine(rawCobIobBr("12g", "3.23U", "120%")), is("12g | 3.23U | 120%"));
assertThat(DisplayFormat.longDetailsLine(rawCobIobBr("7g", "0.54U", "30%")), is("7g | 0.54U | 30%"));
assertThat(DisplayFormat.longDetailsLine(rawCobIobBr("19(38)g", "35.545U", "12.9U/h")), is("19g | 36U | 12.9U/h"));
}
@Test
public void detailedIobTest() {
assertThat(DisplayFormat.detailedIob(rawIob("-1.29U", "(0,910|-2,20)")), is(Pair.create("-1.29U", ",91 -2")));
assertThat(DisplayFormat.detailedIob(rawIob("3.50U", "")), is(Pair.create("3.50U", "")));
assertThat(DisplayFormat.detailedIob(rawIob("12.5U", "(+1,4|-4.78)")), is(Pair.create("12.5U", "1,4 -5")));
assertThat(DisplayFormat.detailedIob(rawIob("0.67U", "some junks")), is(Pair.create(".67U", "")));
assertThat(DisplayFormat.detailedIob(rawIob("-11.0U", "(broken|data)")), is(Pair.create("-11U", "-- --")));
assertThat(DisplayFormat.detailedIob(rawIob("5.52U", "(0,5439|wrong)")), is(Pair.create("5.52U", ",54 --")));
assertThat(DisplayFormat.detailedIob(rawIob("-8.1U", "(|-8,1)")), is(Pair.create("-8.1U", "-- -8")));
assertThat(DisplayFormat.detailedIob(rawIob("-8.1U", "(|-8,1)")), is(Pair.create("-8.1U", "-- -8")));
assertThat(DisplayFormat.detailedIob(rawIob("7.6U", "(malformed)")), is(Pair.create("7.6U", "")));
assertThat(DisplayFormat.detailedIob(rawIob("-4.26U", "(6,97|1,3422|too much)")), is(Pair.create("-4.26U", "7 1,3")));
}
@Test
public void detailedCobTest() {
assertThat(DisplayFormat.detailedCob(rawCob("0g")), is(Pair.create("0g", "")));
assertThat(DisplayFormat.detailedCob(rawCob("50g")), is(Pair.create("50g", "")));
assertThat(DisplayFormat.detailedCob(rawCob("2(40)g")), is(Pair.create("2g", "40g")));
assertThat(DisplayFormat.detailedCob(rawCob("0(24)g")), is(Pair.create("0g", "24g")));
assertThat(DisplayFormat.detailedCob(rawCob("13(5)g")), is(Pair.create("13g", "5g")));
assertThat(DisplayFormat.detailedCob(rawCob("11(50)g")), is(Pair.create("11g", "50g")));
assertThat(DisplayFormat.detailedCob(rawCob("19(38)g")), is(Pair.create("19g", "38g")));
assertThat(DisplayFormat.detailedCob(rawCob("100(1)g")), is(Pair.create("100g", "1g")));
}
}

View file

@ -0,0 +1,68 @@
package info.nightscout.androidaps.interaction.utils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.modules.junit4.PowerMockRunner;
import java.util.HashSet;
import java.util.Set;
import static org.hamcrest.CoreMatchers.containsString;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
@RunWith(PowerMockRunner.class)
public class PairTest {
@Test
public void pairEqualsTest() {
// GIVEN
Pair left = Pair.create("aa", "bbb");
Pair right = Pair.create("ccc", "dd");
Pair another = Pair.create("aa", "bbb");
Pair samePos1 = Pair.create("aa", "d");
Pair samePos2 = Pair.create("zzzzz", "bbb");
Pair no1 = Pair.create(12, 345L);
Pair no2 = Pair.create(-943, 42);
Pair no3 = Pair.create(12L, 345);
Pair no4 = Pair.create(12, 345L);
// THEN
assertNotEquals(left, right);
assertEquals(left, another);
assertNotEquals(left, samePos1);
assertNotEquals(left, samePos2);
assertNotEquals(no1, no2);
assertNotEquals(no1, no3);
assertEquals(no1, no4);
assertFalse(left.equals("aa bbb"));
}
@Test
public void pairHashTest() {
// GIVEN
Pair inserted = Pair.create("aa", "bbb");
Set<Pair> set = new HashSet<>();
// THEN
assertFalse(set.contains(inserted));
set.add(inserted);
assertTrue(set.contains(inserted));
}
@Test
public void toStringTest() {
// GIVEN
Pair pair = Pair.create("the-first", "2nd");
assertThat(pair.toString(), containsString("the-first"));
assertThat(pair+"", containsString("2nd"));
}
}

View file

@ -0,0 +1,189 @@
package info.nightscout.androidaps.interaction.utils;
import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;
import com.google.android.gms.wearable.DataMap;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import java.util.Set;
import info.nightscout.androidaps.aaps;
import info.nightscout.androidaps.testing.mockers.AAPSMocker;
import info.nightscout.androidaps.testing.mockers.AndroidMocker;
import info.nightscout.androidaps.testing.mockers.LogMocker;
import info.nightscout.androidaps.testing.mockers.WearUtilMocker;
import static info.nightscout.androidaps.testing.mockers.WearUtilMocker.REF_NOW;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
@RunWith(PowerMockRunner.class)
@PrepareForTest( { WearUtil.class, Log.class, SharedPreferences.class, Context.class, aaps.class, android.util.Base64.class} )
public class PersistenceTest {
@Before
public void mock() {
WearUtilMocker.prepareMock();
LogMocker.prepareMock();
AAPSMocker.prepareMock();
AAPSMocker.resetMockedSharedPrefs();
AndroidMocker.mockBase64();
}
@Test
public void putStringTest() {
// GIVEN
Persistence persistence = new Persistence();
// WHEN
final String emptyGot = persistence.getString("test-key", "default-value");
persistence.putString("test-key", "newValue");
final String updatedGot = persistence.getString("test-key", "another-default-value");
// THEN
assertThat(emptyGot, is("default-value"));
assertThat(updatedGot, is("newValue"));
}
@Test
public void putBooleanTest() {
// GIVEN
Persistence persistence = new Persistence();
// WHEN
final boolean emptyGot = persistence.getBoolean("test-key", false);
persistence.putBoolean("test-key", true);
final boolean updatedGot = persistence.getBoolean("test-key", false);
// THEN
assertFalse(emptyGot);
assertTrue(updatedGot);
}
@Test
public void whenDataUpdatedTest() {
// GIVEN
Persistence persistence = new Persistence();
DataMap map = new DataMap();
// WHEN
final long whenNotUpdated = persistence.whenDataUpdated();
Persistence.storeDataMap("data-map", map);
final long whenUpdatedFirst = persistence.whenDataUpdated();
WearUtilMocker.progressClock(60000);
Persistence.storeDataMap("data-map", map);
final long whenUpdatedNext = persistence.whenDataUpdated();
// THEN
assertThat(0L, is(whenNotUpdated));
assertThat(REF_NOW, is(whenUpdatedFirst));
assertThat(REF_NOW + 60000, is(whenUpdatedNext));
}
@Test
public void getDataMapTest() {
// GIVEN
Persistence persistence = new Persistence();
DataMap map = new DataMap();
map.putByteArray("test-key", new byte[]{9, 42, 127, -5});
// WHEN
DataMap notExisting = persistence.getDataMap("not-there");
Persistence.storeDataMap("data-map", map);
DataMap restoredMap = persistence.getDataMap("data-map");
byte[] restoredMapContents = restoredMap.getByteArray("test-key");
// THEN
assertNull(notExisting);
assertNotNull(restoredMap);
assertTrue(restoredMap.containsKey("test-key"));
assertThat(restoredMapContents.length, is(4));
assertThat(restoredMapContents[0], is((byte)9));
assertThat(restoredMapContents[1], is((byte)42));
assertThat(restoredMapContents[2], is((byte)127));
assertThat(restoredMapContents[3], is((byte)-5));
}
@Test
public void brokenDataMapTest() {
// GIVEN
Persistence persistence = new Persistence();
// WHEN
persistence.putString("data-map", "ZmFrZSBkYXRh");
DataMap restoredMap = persistence.getDataMap("data-map");
// THEN
assertNull(restoredMap);
}
@Test
public void setsTest() {
// GIVEN
Persistence persistence = new Persistence();
// WHEN
Set<String> emptySet = persistence.getSetOf("some fake id");
persistence.addToSet("test-set", "element1");
persistence.addToSet("test-set", "second-elem");
persistence.addToSet("test-set", "3rd");
persistence.addToSet("test-set", "czwarty");
persistence.addToSet("test-set", "V");
persistence.addToSet("test-set", "6");
Set<String> initialSet = persistence.getSetOf("test-set");
Set<String> sameInitialSet = Persistence.setOf("test-set");
persistence.addToSet("test-set", "second-elem");
persistence.addToSet("test-set", "new-one");
Set<String> extendedSet = persistence.getSetOf("test-set");
persistence.removeFromSet("test-set", "czwarty");
persistence.removeFromSet("test-set", "6");
persistence.removeFromSet("test-set", "3rd");
Set<String> reducedSet = persistence.getSetOf("test-set");
// THEN
assertThat(emptySet.size(), is(0));
assertThat(initialSet.size(), is(6));
assertTrue(initialSet.contains("element1"));
assertTrue(initialSet.contains("second-elem"));
assertTrue(initialSet.contains("3rd"));
assertTrue(initialSet.contains("czwarty"));
assertTrue(initialSet.contains("V"));
assertTrue(initialSet.contains("6"));
assertThat(initialSet, is(sameInitialSet));
assertThat(extendedSet.size(), is(7));
assertTrue(extendedSet.contains("new-one"));
assertThat(reducedSet.size(), is(4));
assertTrue(reducedSet.contains("element1"));
assertTrue(reducedSet.contains("second-elem"));
assertFalse(reducedSet.contains("3rd"));
assertFalse(reducedSet.contains("czwarty"));
assertTrue(reducedSet.contains("V"));
assertFalse(reducedSet.contains("6"));
assertTrue(reducedSet.contains("new-one"));
}
}

View file

@ -0,0 +1,186 @@
package info.nightscout.androidaps.interaction.utils;
import android.os.Bundle;
import android.util.Log;
import com.google.android.gms.wearable.DataMap;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import java.util.HashSet;
import java.util.Set;
import info.nightscout.androidaps.testing.mockers.LogMocker;
import info.nightscout.androidaps.testing.mockers.WearUtilMocker;
import info.nightscout.androidaps.testing.mocks.BundleMock;
import static info.nightscout.androidaps.testing.mockers.WearUtilMocker.REF_NOW;
import static org.hamcrest.CoreMatchers.both;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.lessThan;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
/**
* Created by dlvoy on 22.11.2019.
*/
@RunWith(PowerMockRunner.class)
@PrepareForTest( { WearUtil.class, Log.class} )
public class WearUtilTest {
@Before
public void mock() {
WearUtilMocker.prepareMock();
LogMocker.prepareMock();
}
@Test
public void timestampAndTimeDiffsTest() {
// smoke for mocks - since we freeze "now" to get stable tests
assertThat(REF_NOW, is(WearUtil.timestamp()));
assertThat(0L, is(WearUtil.msTill(REF_NOW)));
assertThat(3456L, is(WearUtil.msTill(REF_NOW+3456L)));
assertThat(-6294L, is(WearUtil.msTill(REF_NOW-6294L)));
assertThat(0L, is(WearUtil.msTill(REF_NOW)));
assertThat(-3456L, is(WearUtil.msSince(REF_NOW+3456L)));
assertThat(6294L, is(WearUtil.msSince(REF_NOW-6294L)));
}
@Test
public void joinSetTest() {
// GIVEN
Set<String> refSet = new HashSet<>();
refSet.add("element1");
refSet.add("second-elem");
refSet.add("3rd");
// WHEN
String joined = WearUtil.joinSet(refSet, "|");
// THEN
// we cannot guarantee order of items in joined string
// but all items have to be there
assertThat(joined.length(), is("element1".length() + "second-elem".length() + "3rd".length() + "|".length()*2 ));
assertThat("|"+joined+"|", containsString("|"+"element1"+"|"));
assertThat("|"+joined+"|", containsString("|"+"second-elem"+"|"));
assertThat("|"+joined+"|", containsString("|"+"3rd"+"|"));
}
@Test
public void explodeSetTest() {
// GIVEN
String serializedSet = "second-elem:element1:3rd";
// WHEN
Set<String> set = WearUtil.explodeSet(serializedSet, ":");
// THEN
assertThat(set.size(), is(3));
assertTrue(set.contains("element1"));
assertTrue(set.contains("second-elem"));
assertTrue(set.contains("3rd"));
}
@Test
public void explodeSetEmptyElemsTest() {
// GIVEN
String serializedSet = ",,,,real,,,another,,,";
// WHEN
Set<String> set = WearUtil.explodeSet(serializedSet, ",");
// THEN
assertThat(set.size(), is(2));
assertThat(true, is(set.contains("real")));
assertThat(true, is(set.contains("another")));
}
@Test
public void joinExplodeStabilityTest() {
// GIVEN
Set<String> refSet = new HashSet<>();
refSet.add("element1");
refSet.add("second-elem");
refSet.add("3rd");
refSet.add("czwarty");
refSet.add("V");
refSet.add("6");
// WHEN
String joinedSet = WearUtil.joinSet(refSet, "#");
final Set<String> explodedSet = WearUtil.explodeSet(joinedSet, "#");
// THEN
assertThat(explodedSet, is(refSet));
}
@Test
public void threadSleepTest() {
// GIVEN
final long testStart = System.currentTimeMillis();
final long requestedSleepDuration = 85L;
final long measuringMargin = 100L;
// WHEN
WearUtil.threadSleep(requestedSleepDuration);
final long measuredSleepDuration = System.currentTimeMillis() - testStart;
// THEN
// we cannot guarantee to be exact to the millisecond - we add some margin of error
assertThat(measuredSleepDuration, is(both(greaterThan(60L)).and(lessThan(requestedSleepDuration+measuringMargin))));
}
@Test
public void rateLimitTest() {
// WHEN
final boolean firstCall = WearUtil.rateLimit("test-limit", 3);
final boolean callAfterward = WearUtil.rateLimit("test-limit", 3);
WearUtilMocker.progressClock(500L);
final boolean callTooSoon = WearUtil.rateLimit("test-limit", 3);
WearUtilMocker.progressClock(3100L);
final boolean callAfterRateLimit = WearUtil.rateLimit("test-limit", 3);
// THEN
assertTrue(firstCall);
assertFalse(callAfterward);
assertFalse(callTooSoon);
assertTrue(callAfterRateLimit);
}
/**
* It tests if mock for bundleToDataMap is sane,
* because original impl. of bundleToDataMap
* uses DataMap.fromBundle which need Android SDK runtime
*/
@Test
public void bundleToDataMapTest() {
// GIVEN
DataMap refMap = new DataMap();
refMap.putString("ala", "ma kota");
refMap.putInt("why", 42);
refMap.putFloatArray("list", new float[]{0.45f, 3.2f, 6.8f});
// WHEN
WearUtilMocker.prepareMockNoReal();
Bundle bundle = BundleMock.mock(refMap);
DataMap gotMap = WearUtil.bundleToDataMap(bundle);
// THEN
assertThat(gotMap, is(refMap));
}
}

View file

@ -0,0 +1,63 @@
package info.nightscout.androidaps.testing.mockers;
import android.content.Context;
import android.content.SharedPreferences;
import org.junit.Assert;
import org.mockito.ArgumentMatchers;
import org.mockito.invocation.InvocationOnMock;
import org.powermock.api.mockito.PowerMockito;
import java.util.HashMap;
import java.util.Map;
import info.nightscout.androidaps.aaps;
import info.nightscout.androidaps.testing.mocks.SharedPreferencesMock;
import static org.mockito.Mockito.mock;
import static org.powermock.api.mockito.PowerMockito.mockStatic;
public class AAPSMocker {
private static final Map<String, SharedPreferences> mockedSharedPrefs = new HashMap<>();
private static boolean unicodeComplicationsOn = true;
public static void prepareMock() {
Context mockedContext = mock(Context.class);
mockStatic(aaps.class, InvocationOnMock::callRealMethod);
try {
PowerMockito.when(aaps.class, "getAppContext").thenReturn(mockedContext);
PowerMockito.when(mockedContext, "getSharedPreferences", ArgumentMatchers.anyString(), ArgumentMatchers.anyInt()).thenAnswer(invocation -> {
final String key = invocation.getArgument(0);
if (mockedSharedPrefs.containsKey(key)) {
return mockedSharedPrefs.get(key);
} else {
SharedPreferencesMock newPrefs = new SharedPreferencesMock();
mockedSharedPrefs.put(key, newPrefs);
return newPrefs;
}
});
PowerMockito.when(aaps.class, "areComplicationsUnicode").thenAnswer(invocation -> unicodeComplicationsOn);
} catch (Exception e) {
Assert.fail("Unable to mock objects: " + e.getMessage());
}
setMockedUnicodeComplicationsOn(true);
resetMockedSharedPrefs();
}
public static void resetMockedSharedPrefs() {
mockedSharedPrefs.clear();
}
public static void resetMockedSharedPrefs(String forKey) {
mockedSharedPrefs.remove(forKey);
}
public static void setMockedUnicodeComplicationsOn(boolean setUnicodeOn) {
unicodeComplicationsOn = setUnicodeOn;
}
}

View file

@ -0,0 +1,40 @@
package info.nightscout.androidaps.testing.mockers;
import org.junit.Assert;
import org.powermock.api.mockito.PowerMockito;
import java.util.Base64;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyString;
import static org.powermock.api.mockito.PowerMockito.mockStatic;
public class AndroidMocker {
public static void mockBase64() {
mockStatic(android.util.Base64.class);
try {
PowerMockito.when(android.util.Base64.class, "decode", anyString(), anyInt()).thenAnswer(invocation -> {
final String payload = invocation.getArgument(0);
try {
return Base64.getDecoder().decode(payload);
} catch (java.lang.IllegalArgumentException ex) {
return null;
}
});
PowerMockito.when(android.util.Base64.class, "encodeToString", any(), anyInt()).thenAnswer(invocation -> {
final byte[] payload = invocation.getArgument(0);
return Base64.getEncoder().encodeToString(payload);
});
} catch (Exception e) {
Assert.fail("Unable to mock objects: " + e.getMessage());
}
}
}

View file

@ -0,0 +1,11 @@
package info.nightscout.androidaps.testing.mockers;
import android.util.Log;
import static org.powermock.api.mockito.PowerMockito.mockStatic;
public class LogMocker {
public static void prepareMock() {
mockStatic(Log.class);
}
}

View file

@ -0,0 +1,65 @@
package info.nightscout.androidaps.testing.mockers;
import info.nightscout.androidaps.data.DisplayRawData;
import info.nightscout.androidaps.interaction.utils.SafeParse;
import static info.nightscout.androidaps.testing.mockers.WearUtilMocker.backInTime;
public class RawDataMocker {
public static DisplayRawData rawSgv(String sgv, int m, String deltaString) {
DisplayRawData raw = new DisplayRawData();
raw.datetime = backInTime(0, 0, m, 0);
raw.sDelta = deltaString;
raw.sSgv = sgv;
double delta = SafeParse.stringToDouble(deltaString);
if (delta <= (-3.5 * 5)) {
raw.sDirection = "\u21ca";
} else if (delta <= (-2 * 5)) {
raw.sDirection = "\u2193";
} else if (delta <= (-1 * 5)) {
raw.sDirection = "\u2198";
} else if (delta <= (1 * 5)) {
raw.sDirection = "\u2192";
} else if (delta <= (2 * 5)) {
raw.sDirection = "\u2197";
} else if (delta <= (3.5 * 5)) {
raw.sDirection = "\u2191";
} else {
raw.sDirection = "\u21c8";
}
return raw;
}
public static DisplayRawData rawDelta(int m, String delta) {
DisplayRawData raw = new DisplayRawData();
raw.datetime = backInTime(0, 0, m, 0);
raw.sDelta = delta;
return raw;
}
public static DisplayRawData rawCobIobBr(String cob, String iob, String br) {
DisplayRawData raw = new DisplayRawData();
raw.sCOB2 = cob;
raw.sIOB1 = iob;
raw.sBasalRate = br;
return raw;
}
public static DisplayRawData rawIob(String iob, String iob2) {
DisplayRawData raw = new DisplayRawData();
raw.sIOB1 = iob;
raw.sIOB2 = iob2;
return raw;
}
public static DisplayRawData rawCob(String cob) {
DisplayRawData raw = new DisplayRawData();
raw.sCOB2 = cob;
return raw;
}
}

View file

@ -0,0 +1,104 @@
package info.nightscout.androidaps.testing.mockers;
import android.os.Bundle;
import com.google.android.gms.wearable.Asset;
import com.google.android.gms.wearable.DataMap;
import org.junit.Assert;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.powermock.api.mockito.PowerMockito;
import java.util.ArrayList;
import info.nightscout.androidaps.interaction.utils.Constants;
import info.nightscout.androidaps.interaction.utils.WearUtil;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyString;
import static org.powermock.api.mockito.PowerMockito.mockStatic;
public class WearUtilMocker {
public static final long REF_NOW = 1572610530000L;
private static long clockMsDiff = 0L;
public static void prepareMock() {
resetClock();
mockStatic(WearUtil.class, InvocationOnMock::callRealMethod);
try {
// because we cleverly used timestamp() by implementation, we can mock it
// and control the time in tests
PowerMockito.when(WearUtil.class, "timestamp").then(invocation -> (REF_NOW + clockMsDiff));
} catch (Exception e) {
Assert.fail("Unable to mock the construction of the WearUtil object: " + e.getMessage());
}
}
public static void prepareMockNoReal() {
resetClock();
mockStatic(WearUtil.class);
try {
PowerMockito.when(WearUtil.class, "timestamp").then(invocation -> REF_NOW + clockMsDiff);
PowerMockito.when(WearUtil.class, "getWakeLock", anyString(), anyInt()).then(invocation -> null);
PowerMockito.when(WearUtil.class, "bundleToDataMap", any(Bundle.class)).then(bundleToDataMapMock);
} catch (Exception e) {
Assert.fail("Unable to mock the construction of the WearUtil object: " + e.getMessage());
}
}
public static void resetClock() {
clockMsDiff = 0L;
}
public static void progressClock(long byMilliseconds) {
clockMsDiff = clockMsDiff + byMilliseconds;
}
public static void setClock(long atMillisecondsSinceEpoch) {
clockMsDiff = atMillisecondsSinceEpoch - REF_NOW;
}
public static long backInTime(int d, int h, int m, int s) {
return REF_NOW - (Constants.DAY_IN_MS * d + Constants.HOUR_IN_MS * h + Constants.MINUTE_IN_MS * m + Constants.SECOND_IN_MS * s);
}
private static Answer bundleToDataMapMock = invocation -> {
DataMap map = new DataMap();
Bundle bundle = invocation.getArgument(0);
for(String key: bundle.keySet()) {
Object v = bundle.get(key);
if (v instanceof Asset) map.putAsset(key, (Asset)v);
if (v instanceof Boolean) map.putBoolean(key, (Boolean)v);
if (v instanceof Byte) map.putByte(key, (Byte)v);
if (v instanceof byte[]) map.putByteArray(key, (byte[])v);
if (v instanceof DataMap) map.putDataMap(key, (DataMap)v);
if (v instanceof Double) map.putDouble(key, (Double)v);
if (v instanceof Float) map.putFloat(key, (Float)v);
if (v instanceof float[]) map.putFloatArray(key, (float[])v);
if (v instanceof Integer) map.putInt(key, (Integer)v);
if (v instanceof Long) map.putLong(key, (Long)v);
if (v instanceof long[]) map.putLongArray(key, (long[])v);
if (v instanceof String) map.putString(key, (String)v);
if (v instanceof String[]) map.putStringArray(key, (String[])v);
if (v instanceof ArrayList) {
if (!((ArrayList)v).isEmpty()) {
if (((ArrayList) v).get(0) instanceof Integer) {
map.putIntegerArrayList(key, (ArrayList<Integer>)v);
}
if (((ArrayList) v).get(0) instanceof String) {
map.putStringArrayList(key, (ArrayList<String>)v);
}
if (((ArrayList) v).get(0) instanceof DataMap) {
map.putDataMapArrayList(key, (ArrayList<DataMap>)v);
}
}
}
}
return map;
};
}

View file

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

View file

@ -0,0 +1,39 @@
package info.nightscout.androidaps.testing.mocks;
import android.content.Intent;
import android.os.Bundle;
import org.mockito.Mockito;
import org.mockito.stubbing.Answer;
import java.util.HashMap;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.when;
public final class IntentMock {
public static Intent mock() {
return mock(new HashMap<String, Object>());
}
public static Intent mock(final HashMap<String, Object> map) {
Answer put = invocation -> {
map.put((String)invocation.getArguments()[0], invocation.getArguments()[1]);
return null;
};
Answer<Object> get = invocation -> map.get(invocation.getArguments()[0]);
Intent intent = Mockito.mock(Intent.class);
when(intent.putExtra(anyString(), any(Bundle.class))).thenAnswer(put);
when(intent.getBundleExtra(anyString())).thenAnswer(get);
doAnswer(invocation -> map.containsKey(invocation.getArguments()[0])).when(intent).hasExtra(anyString());
return intent;
}
}

View file

@ -0,0 +1,158 @@
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

@ -0,0 +1,70 @@
package info.nightscout.androidaps.testing.utils;
import androidx.annotation.Nullable;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
import info.nightscout.androidaps.data.BasalWatchData;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
public class BasalWatchDataExt extends BasalWatchData {
private BasalWatchDataExt() {
super();
}
public BasalWatchDataExt(BasalWatchData ref) {
super();
Set<String> parentFields = new HashSet<>();
for (Field f : BasalWatchData.class.getDeclaredFields()) {
parentFields.add(f.getName());
}
Set<String> knownFields = new HashSet<>(Arrays.asList("startTime,endTime,amount".split(",")));
// since we do not want modify BasalWatchData - we use this wrapper class
// but we make sure it has same fields
assertThat(parentFields, is(knownFields));
this.startTime = ref.startTime;
this.endTime = ref.endTime;
this.amount = ref.amount;
}
public static BasalWatchDataExt build(long startTime, long endTime, double amount) {
BasalWatchDataExt bwd = new BasalWatchDataExt();
bwd.startTime = startTime;
bwd.endTime = endTime;
bwd.amount = amount;
return bwd;
}
@Override
public boolean equals(@Nullable Object obj) {
if ((obj instanceof BasalWatchData)||(obj instanceof BasalWatchDataExt)) {
return (this.startTime == ((BasalWatchData) obj).startTime)
&& (this.endTime == ((BasalWatchData) obj).endTime)
&& (this.amount == ((BasalWatchData) obj).amount);
} else {
return false;
}
}
@Override
public String toString() {
return startTime+", "+endTime+", "+amount;
}
@Override
public int hashCode() {
return Objects.hash(startTime, endTime, amount);
}
}

View file

@ -0,0 +1,78 @@
package info.nightscout.androidaps.testing.utils;
import androidx.annotation.Nullable;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
import info.nightscout.androidaps.data.BgWatchData;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
public class BgWatchDataExt extends BgWatchData {
private BgWatchDataExt() {
super();
}
public BgWatchDataExt(double aSgv, double aHigh, double aLow, long aTimestamp, int aColor) {
super(aSgv, aHigh, aLow, aTimestamp, aColor);
}
public BgWatchDataExt(BgWatchData ref) {
super();
Set<String> parentFields = new HashSet<>();
for (Field f : BgWatchData.class.getDeclaredFields()) {
parentFields.add(f.getName());
}
Set<String> knownFields = new HashSet<>(Arrays.asList("sgv,high,low,timestamp,color".split(",")));
// since we do not want modify BgWatchDataExt - we use this wrapper class
// but we make sure it has same fields
assertThat(parentFields, is(knownFields));
this.sgv = ref.sgv;
this.high = ref.high;
this.low = ref.low;
this.timestamp = ref.timestamp;
this.color = ref.color;
}
public static BgWatchDataExt build(double sgv, long timestamp, int color) {
BgWatchDataExt twd = new BgWatchDataExt();
twd.sgv = sgv;
twd.timestamp = timestamp;
twd.color = color;
return twd;
}
@Override
public boolean equals(@Nullable Object obj) {
if ((obj instanceof BgWatchData)||(obj instanceof BgWatchDataExt)) {
return (this.sgv == ((BgWatchData) obj).sgv)
&& (this.high == ((BgWatchData) obj).high)
&& (this.low == ((BgWatchData) obj).low)
&& (this.timestamp == ((BgWatchData) obj).timestamp)
&& (this.color == ((BgWatchData) obj).color);
} else {
return false;
}
}
@Override
public String toString() {
return sgv+", "+high+", "+low+", "+timestamp+", "+color;
}
@Override
public int hashCode() {
return Objects.hash(sgv, high, low, timestamp, color);
}
}

View file

@ -0,0 +1,76 @@
package info.nightscout.androidaps.testing.utils;
import androidx.annotation.Nullable;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
import info.nightscout.androidaps.data.BolusWatchData;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
public class BolusWatchDataExt extends BolusWatchData {
private BolusWatchDataExt() {
super();
}
public BolusWatchDataExt(BolusWatchData ref) {
super();
Set<String> parentFields = new HashSet<>();
for (Field f : BolusWatchData.class.getDeclaredFields()) {
parentFields.add(f.getName());
}
Set<String> knownFields = new HashSet<>(Arrays.asList("date,bolus,carbs,isSMB,isValid".split(",")));
// since we do not want modify BolusWatchData - we use this wrapper class
// but we make sure it has same fields
assertThat(parentFields, is(knownFields));
this.date = ref.date;
this.bolus = ref.bolus;
this.carbs = ref.carbs;
this.isSMB = ref.isSMB;
this.isValid = ref.isValid;
}
public static BolusWatchDataExt build(long date, double bolus, double carbs, boolean isSMB, boolean isValid) {
BolusWatchDataExt bwd = new BolusWatchDataExt();
bwd.date = date;
bwd.bolus = bolus;
bwd.carbs = carbs;
bwd.isSMB = isSMB;
bwd.isValid = isValid;
return bwd;
}
@Override
public boolean equals(@Nullable Object obj) {
if ((obj instanceof BolusWatchData)||(obj instanceof BolusWatchDataExt)) {
return (this.date == ((BolusWatchData) obj).date)
&& (this.bolus == ((BolusWatchData) obj).bolus)
&& (this.carbs == ((BolusWatchData) obj).carbs)
&& (this.isSMB == ((BolusWatchData) obj).isSMB)
&& (this.isValid == ((BolusWatchData) obj).isValid);
} else {
return false;
}
}
@Override
public String toString() {
return date+", "+bolus+", "+carbs+", "+isSMB+", "+isValid;
}
@Override
public int hashCode() {
return Objects.hash(date, bolus, carbs, isSMB, isValid);
}
}

View file

@ -0,0 +1,78 @@
package info.nightscout.androidaps.testing.utils;
import androidx.annotation.Nullable;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
import info.nightscout.androidaps.data.TempWatchData;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
public class TempWatchDataExt extends TempWatchData {
private TempWatchDataExt() {
super();
}
public TempWatchDataExt(TempWatchData ref) {
super();
Set<String> parentFields = new HashSet<>();
for (Field f : TempWatchData.class.getDeclaredFields()) {
parentFields.add(f.getName());
}
Set<String> knownFields = new HashSet<>(Arrays.asList("startTime,startBasal,endTime,endBasal,amount".split(",")));
// since we do not want modify TempWatchData - we use this wrapper class
// but we make sure it has same fields
assertThat(parentFields, is(knownFields));
this.startTime = ref.startTime;
this.startBasal = ref.startBasal;
this.endTime = ref.endTime;
this.endBasal = ref.endBasal;
this.amount = ref.amount;
}
public static TempWatchDataExt build(long startTime, double startBasal, long endTime,
double endBasal, double amount) {
TempWatchDataExt twd = new TempWatchDataExt();
twd.startTime = startTime;
twd.startBasal = startBasal;
twd.endTime = endTime;
twd.endBasal = endBasal;
twd.amount = amount;
return twd;
}
@Override
public boolean equals(@Nullable Object obj) {
if ((obj instanceof TempWatchData)||(obj instanceof TempWatchDataExt)) {
return (this.startTime == ((TempWatchData) obj).startTime)
&& (this.startBasal == ((TempWatchData) obj).startBasal)
&& (this.endTime == ((TempWatchData) obj).endTime)
&& (this.endBasal == ((TempWatchData) obj).endBasal)
&& (this.amount == ((TempWatchData) obj).amount);
} else {
return false;
}
}
@Override
public String toString() {
return startTime+", "+startBasal+", "+endTime+", "+endBasal+", "+amount;
}
@Override
public int hashCode() {
return Objects.hash(startTime, startBasal, endTime, endBasal, amount);
}
}