Skip to content

Commit 695e2ee

Browse files
committed
Fix failing unit tests ✅
Code clean up
1 parent f887266 commit 695e2ee

14 files changed

+253
-118
lines changed

opensrp-app/build.gradle

+1-14
Original file line numberDiff line numberDiff line change
@@ -227,23 +227,10 @@ dependencies {
227227
implementation 'com.evernote:android-job:1.2.6'
228228
implementation group: 'commons-validator', name: 'commons-validator', version: '1.6'
229229
implementation 'de.hdodenhof:circleimageview:2.2.0'
230-
231-
implementation('org.smartregister:android-p2p-sync:0.3.6-SNAPSHOT') {
232-
exclude group: 'com.android.support', module: 'support-v4'
233-
exclude group: 'com.android.support', module: 'appcompat-v7'
234-
exclude group: 'android.arch.core', module: 'runtime'
235-
}
236-
237-
implementation 'org.smartregister:opensrp-client-utils:0.0.2-SNAPSHOT'
238-
239-
implementation 'org.smartregister:opensrp-plan-evaluator:0.0.19-SNAPSHOT'
240-
241230
implementation 'xerces:xercesImpl:2.12.0'
242-
}
243-
244-
dependencies {
245231

246232
implementation fileTree(include: ['*.jar'], dir: 'libs')
233+
247234
androidTestImplementation 'junit:junit:4.12'
248235

249236
testImplementation group: 'com.google.android', name: 'android-test', version: '4.1.1.4'

opensrp-app/src/main/java/org/smartregister/login/task/RemoteLoginTask.java

+6
Original file line numberDiff line numberDiff line change
@@ -134,6 +134,12 @@ protected LoginResponse doInBackground(Void... params) {
134134
}
135135

136136
}
137+
} else {
138+
if (response.getAccountError() != null && response.getAccountError().getError() != null) {
139+
return LoginResponse.valueOf(response.getAccountError().getError());
140+
} else if (loginResponse == null) {
141+
return null;
142+
}
137143
}
138144

139145
} else {

opensrp-app/src/test/java/org/smartregister/clientandeventmodel/FormAttributeParserTest.java

+2-2
Original file line numberDiff line numberDiff line change
@@ -216,8 +216,8 @@ public void assertGetFieldnameSubForm() throws Exception {
216216
Mockito.when(context.getAssets()).thenReturn(assetManager);
217217
FileInputStream formDefinitionIS = (new FileInputStream(getFileFromPath(this, formDefinition)));
218218
String stringOfFormDefinition = getStringFromStream(formDefinitionIS);
219-
JsonParser jsonparser = new JsonParser();
220-
Object obj = jsonparser.parse(stringOfFormDefinition);
219+
220+
Object obj = JsonParser.parseString(stringOfFormDefinition);
221221
Mockito.doReturn(obj).when(spyparser).getFormDefinitionData(FORMNAME);
222222
Mockito.when(assetManager.open(model)).thenReturn(new FileInputStream(getFileFromPath(this, model)));
223223
Mockito.when(assetManager.open(formJSON)).thenReturn(new FileInputStream(getFileFromPath(this, formMultiJSON)));

opensrp-app/src/test/java/org/smartregister/login/interactor/BaseLoginInteractorTest.java

+180-78
Large diffs are not rendered by default.

opensrp-app/src/test/java/org/smartregister/login/model/BaseLoginModelTest.java

+9-2
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
11
package org.smartregister.login.model;
22

3+
import org.junit.After;
34
import org.junit.Before;
45
import org.junit.Test;
56
import org.mockito.Mock;
7+
import org.robolectric.util.ReflectionHelpers;
68
import org.smartregister.BaseRobolectricUnitTest;
79
import org.smartregister.Context;
810
import org.smartregister.CoreLibrary;
@@ -30,6 +32,11 @@ public void setUp() {
3032
loginModel = new BaseLoginModel();
3133
}
3234

35+
@After
36+
public void tearDown() {
37+
ReflectionHelpers.setStaticField(CoreLibrary.class, "instance", null);
38+
}
39+
3340
@Test
3441
public void testGetOpenSRPContextShouldReturnContext() {
3542
assertNotNull(loginModel.getOpenSRPContext());
@@ -39,8 +46,8 @@ public void testGetOpenSRPContextShouldReturnContext() {
3946

4047
@Test
4148
public void testIsPasswordValidReturnsCorrectResult() {
42-
assertFalse(loginModel.isPasswordValid(""));
43-
assertTrue(loginModel.isPasswordValid("qwerty120"));
49+
assertFalse(loginModel.isPasswordValid("".toCharArray()));
50+
assertTrue(loginModel.isPasswordValid("qwerty120".toCharArray()));
4451

4552

4653
}

opensrp-app/src/test/java/org/smartregister/login/presenter/BaseLoginPresenterTest.java

+12-4
Original file line numberDiff line numberDiff line change
@@ -6,14 +6,17 @@
66
import android.widget.RelativeLayout;
77
import android.widget.ScrollView;
88

9+
import org.junit.After;
910
import org.junit.Before;
1011
import org.junit.Test;
1112
import org.mockito.Answers;
1213
import org.mockito.Mock;
1314
import org.mockito.Spy;
1415
import org.powermock.reflect.Whitebox;
1516
import org.robolectric.Robolectric;
17+
import org.robolectric.util.ReflectionHelpers;
1618
import org.smartregister.BaseRobolectricUnitTest;
19+
import org.smartregister.CoreLibrary;
1720
import org.smartregister.R;
1821
import org.smartregister.login.model.BaseLoginModel;
1922
import org.smartregister.view.activity.BaseLoginActivityTest.BaseLoginActivityImpl;
@@ -60,6 +63,11 @@ public void setUp() {
6063
when(loginView.getActivityContext()).thenReturn(activity);
6164
}
6265

66+
@After
67+
public void tearDown() {
68+
ReflectionHelpers.setStaticField(CoreLibrary.class, "instance", null);
69+
}
70+
6371
@Test
6472
public void testOnDestroyShouldCleanUp() {
6573
presenter.onDestroy(false);
@@ -77,7 +85,7 @@ public void testGetLoginViewShouldReturnView() {
7785
@Test
7886
public void testAttemptLoginShouldErrorIfAppIsOutdated() {
7987
when(loginView.isAppVersionAllowed()).thenReturn(false);
80-
presenter.attemptLogin("john", "doe");
88+
presenter.attemptLogin("john", "doe".toCharArray());
8189
verify(loginView).showErrorDialog(activity.getString(R.string.outdated_app));
8290
verify(loginView).isAppVersionAllowed();
8391
verify(loginView).getActivityContext();
@@ -88,7 +96,7 @@ public void testAttemptLoginShouldErrorIfAppIsOutdated() {
8896
@Test
8997
public void testAttemptLoginShouldNotInvokeLoginAndDisplaysErrors() {
9098
when(loginView.isAppVersionAllowed()).thenReturn(true);
91-
presenter.attemptLogin("", "");
99+
presenter.attemptLogin("", "".toCharArray());
92100
verify(loginView).setPasswordError(R.string.error_invalid_password);
93101
verify(loginView).setUsernameError(R.string.error_field_required);
94102
verify(loginView).enableLoginButton(true);
@@ -98,11 +106,11 @@ public void testAttemptLoginShouldNotInvokeLoginAndDisplaysErrors() {
98106
@Test
99107
public void testAttemptLoginShouldInvokeLogin() {
100108
when(loginView.isAppVersionAllowed()).thenReturn(true);
101-
presenter.attemptLogin("john", "doe");
109+
presenter.attemptLogin("john", "doe".toCharArray());
102110
verify(loginView, never()).setPasswordError(R.string.error_invalid_password);
103111
verify(loginView, never()).setUsernameError(R.string.error_field_required);
104112
verify(loginView, never()).enableLoginButton(true);
105-
verify(loginInteractor).login(any(), eq("john"), eq("doe"));
113+
verify(loginInteractor).login(any(), eq("john"), eq("doe".toCharArray()));
106114
}
107115

108116
@Test

opensrp-app/src/test/java/org/smartregister/repository/RepositoryRobolectricTest.java

+2-1
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
import org.smartregister.AllConstants;
1313
import org.smartregister.BaseRobolectricUnitTest;
1414
import org.smartregister.commonregistry.CommonFtsObject;
15+
import org.smartregister.security.SecurityHelper;
1516
import org.smartregister.util.Session;
1617

1718
import java.io.File;
@@ -135,7 +136,7 @@ public void onCreateShouldCreateFtsTablesWithSortFieldIncluded() {
135136
@Test
136137
public void canUseThisPasswordShouldCallIsDatabaseWritableAndReturnTrue() {
137138
Repository repository = Mockito.mock(Repository.class, Mockito.CALLS_REAL_METHODS);
138-
String password = "mypwd";
139+
byte[] password = SecurityHelper.toBytes("mypwd".toCharArray());
139140

140141
Mockito.doReturn(true).when(repository).isDatabaseWritable(password);
141142
Assert.assertTrue(repository.canUseThisPassword(password));

opensrp-app/src/test/java/org/smartregister/repository/RepositoryTest.java

+15-13
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,7 @@
1414
import org.powermock.modules.junit4.rule.PowerMockRule;
1515
import org.robolectric.util.ReflectionHelpers;
1616
import org.smartregister.BaseUnitTest;
17-
import org.smartregister.repository.mock.RepositoryMock;
18-
import org.smartregister.util.Session;
17+
import org.smartregister.security.SecurityHelper;
1918
import org.smartregister.view.activity.DrishtiApplication;
2019

2120
import java.io.File;
@@ -29,38 +28,40 @@ public class RepositoryTest extends BaseUnitTest {
2928
@Rule
3029
public PowerMockRule rule = new PowerMockRule();
3130

32-
private RepositoryMock repositoryMock;
33-
3431
@Mock
3532
private DrishtiApplication drishtiApplication;
3633

3734
private Repository repository;
35+
3836
@Mock
3937
private android.content.Context context;
38+
4039
@Mock
41-
private Session session;
42-
@Mock
43-
private DrishtiRepository drishtiRepository;
40+
private SQLiteDatabase database;
4441

4542
private String dbName;
46-
private String password;
43+
private char[] password;
4744

4845
@Before
4946
public void setUp() {
5047
dbName = "drishti.db";
51-
password = "Android7832!";
48+
password = "Android7832!".toCharArray();
5249

5350
MockitoAnnotations.initMocks(this);
5451
PowerMockito.mockStatic(DrishtiApplication.class);
5552
PowerMockito.when(DrishtiApplication.getInstance()).thenReturn(drishtiApplication);
5653
PowerMockito.when(drishtiApplication.getApplicationContext()).thenReturn(context);
57-
Mockito.doReturn(password).when(drishtiApplication).getPassword();
54+
55+
ReflectionHelpers.setField(drishtiApplication, "password", SecurityHelper.toBytes(password));
5856
PowerMockito.when(context.getDir("opensrp", android.content.Context.MODE_PRIVATE)).thenReturn(new File("/"));
5957

6058

61-
repository = Mockito.mock(Repository.class, Mockito.CALLS_REAL_METHODS);
59+
repository = Mockito.spy(Mockito.mock(Repository.class, Mockito.CALLS_REAL_METHODS));
6260
ReflectionHelpers.setField(repository, "context", context);
6361
ReflectionHelpers.setField(repository, "dbName", dbName);
62+
63+
Mockito.doReturn(true).when(database).isOpen();
64+
ReflectionHelpers.setField(repository, "mDatabase", database);
6465
}
6566

6667
@Test
@@ -69,7 +70,7 @@ public void getReadableDatabaseShouldCallGetReadableDbAndPassword() {
6970

7071
repository.getReadableDatabase();
7172

72-
Mockito.verify(repository).getReadableDatabase(password);
73+
Mockito.verify(repository).getReadableDatabase(SecurityHelper.toBytes(password));
7374
}
7475

7576
@Test(expected = RuntimeException.class)
@@ -83,9 +84,10 @@ public void getReadableDatabaseShouldThrowRuntimeException() {
8384
public void getWritableDatabaseShouldCallGetWritableDbAndPassword() {
8485
Mockito.doReturn(null).when(repository).getWritableDatabase(password);
8586

87+
8688
repository.getWritableDatabase();
8789

88-
Mockito.verify(repository).getWritableDatabase(password);
90+
Mockito.verify(repository).getWritableDatabase(SecurityHelper.toBytes(password));
8991
}
9092

9193
@Test(expected = RuntimeException.class)

opensrp-app/src/test/java/org/smartregister/service/UserServiceTest.java

+2-1
Original file line numberDiff line numberDiff line change
@@ -199,6 +199,7 @@ public void shouldDeleteDataAndSettingsWhenLogoutHappens() throws Exception {
199199
SyncConfiguration syncConfiguration = mock(SyncConfiguration.class);
200200
Mockito.doReturn(false).when(syncConfiguration).clearDataOnNewTeamLogin();
201201
ReflectionHelpers.setField(CoreLibrary.getInstance(), "syncConfiguration", syncConfiguration);
202+
Whitebox.setInternalState(drishtiApplication, "password", password);
202203

203204
userService.logout();
204205

@@ -357,7 +358,7 @@ public void testIsUserInValidGroupShouldReturnFalseOnError() throws Exception {
357358
when(keyStore.getEntry(user, null)).thenReturn(privateKeyEntry);
358359
String password = UUID.randomUUID().toString();
359360
assertFalse(userService.isUserInValidGroup(user, password.toCharArray()));
360-
// verify(allSharedPreferences, never()).fetchEncryptedGroupId(user);
361+
verify(allSharedPreferences, never()).fetchEncryptedGroupId(user);
361362
verifyZeroInteractions(repository);
362363
}
363364

opensrp-app/src/test/java/org/smartregister/sync/intent/SyncIntentServiceTest.java

+1-1
Original file line numberDiff line numberDiff line change
@@ -104,7 +104,7 @@ public void testHandleSyncCallsLogoutUserIfHasValidAuthorizationIsFalse() throws
104104
}
105105

106106
@Test
107-
public void testHandleSyncCallsLogOutUserIfAppVersionIsNotAllowedAnd() {
107+
public void testHandleSyncCallsLogOutUserIfAppVersionIsNotAllowedAnd() throws AuthenticatorException, OperationCanceledException, IOException {
108108
syncIntentService = spy(syncIntentService);
109109
Whitebox.setInternalState(syncIntentService, "syncUtils", syncUtils);
110110
when(syncUtils.verifyAuthorization()).thenReturn(true);

opensrp-app/src/test/java/org/smartregister/view/activity/BaseLoginActivityTest.java

+6
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
import android.widget.Button;
1818
import android.widget.EditText;
1919

20+
import org.junit.After;
2021
import org.junit.Assert;
2122
import org.junit.Before;
2223
import org.junit.BeforeClass;
@@ -65,6 +66,11 @@ public void setUp() {
6566
baseLoginActivity = Mockito.spy(controller.get());
6667
}
6768

69+
@After
70+
public void tearDown() {
71+
resetCoreLibrary();
72+
}
73+
6874
@Test
6975
public void onCreateShouldCallSetupOperations() {
7076
// Setup again for

opensrp-app/src/test/java/org/smartregister/view/activity/BaseRegisterActivityTest.java

+8-1
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313

1414
import com.google.android.gms.vision.barcode.Barcode;
1515

16+
import org.junit.After;
1617
import org.junit.Before;
1718
import org.junit.Test;
1819
import org.mockito.Mock;
@@ -22,6 +23,7 @@
2223
import org.robolectric.annotation.Config;
2324
import org.robolectric.shadows.ShadowActivity;
2425
import org.robolectric.shadows.ShadowToast;
26+
import org.robolectric.util.ReflectionHelpers;
2527
import org.smartregister.AllConstants;
2628
import org.smartregister.AllConstants.BARCODE;
2729
import org.smartregister.BaseRobolectricUnitTest;
@@ -85,10 +87,15 @@ public class BaseRegisterActivityTest extends BaseRobolectricUnitTest {
8587
@Before
8688
public void setUp() {
8789
Whitebox.setInternalState(CoreLibrary.getInstance().context(), "ziggyService", ziggyService);
88-
controller = Robolectric.buildActivity(BaseRegisterActivityMock.class).create().start().resume();
90+
controller = Robolectric.buildActivity(BaseRegisterActivityMock.class).create().start();
8991
activity = controller.get();
9092
}
9193

94+
@After
95+
public void tearDown() {
96+
ReflectionHelpers.setStaticField(CoreLibrary.class, "instance", null);
97+
}
98+
9299
@Test
93100
public void testOnCreate() {
94101

opensrp-app/src/test/java/org/smartregister/view/activity/mock/BaseRegisterActivityMock.java

+6
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
import android.view.View;
77

88
import org.json.JSONObject;
9+
import org.smartregister.Context;
910
import org.smartregister.R;
1011
import org.smartregister.view.activity.BaseRegisterActivity;
1112
import org.smartregister.view.contract.BaseRegisterContract;
@@ -29,6 +30,11 @@ protected void onCreate(Bundle savedInstanceState) {
2930
super.onCreate(savedInstanceState);
3031
}
3132

33+
@Override
34+
protected Context context(){
35+
return mock(Context.class);
36+
}
37+
3238
@Override
3339
protected void initializePresenter() {
3440
presenter = mock(BaseRegisterContract.Presenter.class);

opensrp-app/src/test/java/org/smartregister/view/receiver/ConnectivityChangeReceiverTest.java

+3-1
Original file line numberDiff line numberDiff line change
@@ -39,11 +39,13 @@ public void setUp() throws Exception {
3939
}
4040

4141
@After
42-
public void tearDown() throws Exception {
42+
public void tearDown(){
4343
// Log out the user
4444
Session session = ReflectionHelpers.getField(CoreLibrary.getInstance().context().userService(), "session");
4545
session.setPassword(null);
4646
session.start(0);
47+
ReflectionHelpers.setStaticField(CoreLibrary.class, "instance", null);
48+
4749
}
4850

4951
@Test

0 commit comments

Comments
 (0)