Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Utils and SyncUtils tests #743

Merged
merged 8 commits into from
Feb 10, 2021
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 8 additions & 6 deletions opensrp-app/src/main/java/org/smartregister/util/SyncUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@

import androidx.annotation.NonNull;
import androidx.annotation.StringRes;
import androidx.annotation.VisibleForTesting;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
Expand Down Expand Up @@ -43,7 +44,7 @@
*/
public class SyncUtils {

private org.smartregister.Context opensrpContent = CoreLibrary.getInstance().context();
private org.smartregister.Context opensrpContext = CoreLibrary.getInstance().context();

private Context context;

Expand All @@ -61,21 +62,22 @@ public void logoutUser() throws AuthenticatorException, OperationCanceledExcepti

public void logoutUser(@StringRes int logoutMessage) throws AuthenticatorException, OperationCanceledException, IOException {
//force remote login
opensrpContent.userService().forceRemoteLogin(opensrpContent.allSharedPreferences().fetchRegisteredANM());
opensrpContext.userService().forceRemoteLogin(opensrpContext.allSharedPreferences().fetchRegisteredANM());

Intent logoutUserIntent = getLogoutUserIntent(logoutMessage);

AccountManagerFuture<Bundle> reAuthenticateFuture = AccountHelper.reAuthenticateUserAfterSessionExpired(opensrpContent.allSharedPreferences().fetchRegisteredANM(), CoreLibrary.getInstance().getAccountAuthenticatorXml().getAccountType(), AccountHelper.TOKEN_TYPE.PROVIDER);
AccountManagerFuture<Bundle> reAuthenticateFuture = AccountHelper.reAuthenticateUserAfterSessionExpired(opensrpContext.allSharedPreferences().fetchRegisteredANM(), CoreLibrary.getInstance().getAccountAuthenticatorXml().getAccountType(), AccountHelper.TOKEN_TYPE.PROVIDER);
Intent accountAuthenticatorIntent = reAuthenticateFuture.getResult().getParcelable(AccountManager.KEY_INTENT);
accountAuthenticatorIntent.putExtras(logoutUserIntent);
context.startActivity(logoutUserIntent);

//logoff opensrp session
opensrpContent.userService().logoutSession();
opensrpContext.userService().logoutSession();
}

@VisibleForTesting
@NonNull
private Intent getLogoutUserIntent(@StringRes int logoutMessage) {
protected Intent getLogoutUserIntent(@StringRes int logoutMessage) {

Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
Expand All @@ -98,7 +100,7 @@ public boolean isAppVersionAllowed() {
try {

// see if setting was synced
AllSettings settingsRepository = opensrpContent.allSettings();
AllSettings settingsRepository = opensrpContext.allSettings();
Setting rawMinAllowedAppVersionSetting;
try {
rawMinAllowedAppVersionSetting = settingsRepository.getSetting(MIN_ALLOWED_APP_VERSION_SETTING);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@
* Class containing some static utility methods.
*/
public class Utils {

private static final SimpleDateFormat UI_DF = new SimpleDateFormat("dd-MM-yyyy", Utils.getDefaultLocale());
private static final SimpleDateFormat UI_DTF = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss", Utils.getDefaultLocale());

Expand Down
5 changes: 5 additions & 0 deletions opensrp-app/src/test/assets/app.properties
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
DRISHTI_BASE_URL=
PORT=-1
SHOULD_VERIFY_CERTIFICATE=false
SYNC_DOWNLOAD_BATCH_SIZE=10
system.toaster.centered=false
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
package org.smartregister.util;

import android.accounts.AuthenticatorException;
import android.accounts.OperationCanceledException;
import android.content.Intent;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.util.ReflectionHelpers;
import org.smartregister.BaseRobolectricUnitTest;
import org.smartregister.Context;
import org.smartregister.CoreLibrary;
import org.smartregister.R;
import org.smartregister.service.UserService;

import java.io.IOException;


/**
* Created by Ephraim Kigamba - [email protected] on 09-02-2021.
*/
public class SyncUtilsRobolectricTest extends BaseRobolectricUnitTest {

private SyncUtils syncUtils;
private android.content.Context context;
private UserService userService;

@Before
public void setUp() {
Context opensrpContext = Mockito.spy(CoreLibrary.getInstance().context());
userService = Mockito.spy(opensrpContext.userService());
Mockito.doReturn(userService).when(opensrpContext).userService();

context = Mockito.spy(RuntimeEnvironment.application);

syncUtils = new SyncUtils(context);
ReflectionHelpers.setField(syncUtils, "opensrpContext", opensrpContext);
}

@Ignore
@Test
public void logoutUser() throws AuthenticatorException, OperationCanceledException, IOException {
ArgumentCaptor<Intent> intentArgumentCaptor = ArgumentCaptor.forClass(Intent.class);
Mockito.doNothing().when(context).startActivity(intentArgumentCaptor.capture());

syncUtils.logoutUser(R.string.logout_text);

Mockito.verify(userService).forceRemoteLogin(Mockito.anyString());
Mockito.verify(userService).logoutSession();

Intent intent = intentArgumentCaptor.getValue();
Assert.assertEquals(Intent.ACTION_MAIN, intent.getAction());
Assert.assertTrue(intent.getCategories().contains(Intent.CATEGORY_LAUNCHER));
Assert.assertEquals("org.smartregister", intent.getPackage());

Mockito.verify(context).startActivity(Mockito.any(Intent.class));

}

@Test
public void getLogoutUserIntentShouldProvideAnonymouseIntentWhenLauncherActivityIsUnavailable() {
ArgumentCaptor<Intent> intentArgumentCaptor = ArgumentCaptor.forClass(Intent.class);
Mockito.doNothing().when(context).startActivity(intentArgumentCaptor.capture());

Intent intent = syncUtils.getLogoutUserIntent(R.string.logout_text);

Assert.assertEquals(Intent.ACTION_MAIN, intent.getAction());
Assert.assertTrue(intent.getCategories().contains(Intent.CATEGORY_LAUNCHER));
Assert.assertEquals("org.smartregister.test", intent.getPackage());

}
}
72 changes: 67 additions & 5 deletions opensrp-app/src/test/java/org/smartregister/util/UtilsTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -65,16 +65,15 @@
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNull;

import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.only;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.smartregister.TestUtils.getContext;
import static org.smartregister.util.Utils.getDefaultLocale;

import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.smartregister.util.Utils.getUserDefaultTeamId;

/**
* Created by kaderchowdhury on 12/11/17.
Expand Down Expand Up @@ -118,7 +117,7 @@ public void assertConvertDateFormatReturnsDate() throws Exception {
@Test
public void assertConvertDateTimeFormatReturnsDate() throws Exception {
assertEquals("24-07-1985 00:00:00", Utils.convertDateTimeFormat("1985-07-24T00:00:00.000Z", true));
// org.junit.Assert.assertEquals("", Utils.convertDateTimeFormat("19850724", true));
// assertEquals("", Utils.convertDateTimeFormat("19850724", true));
}

@Test(expected = RuntimeException.class)
Expand Down Expand Up @@ -635,5 +634,68 @@ public void convert() {
assertEquals(client.getCaseId(), actualClient.getCaseId());
assertEquals(details.size(), actualClient.getColumnmaps().size());
}

@Test
public void getUserDefaultTeamIdShouldReturnNullWhenUserInfoDetailsAreNull() {
assertNull(getUserDefaultTeamId(null));

LoginResponseData loginData = new LoginResponseData();
assertNull(getUserDefaultTeamId(loginData));

loginData.team = new TeamMember();
assertNull(getUserDefaultTeamId(loginData));
}

@Ignore
@Test
public void getDurationShouldReturnValidDurationString() {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");

Calendar calendar = Calendar.getInstance();
calendar.add(1, Calendar.DAY_OF_MONTH);

assertEquals("1d", Utils.getDuration(dateFormat.format(calendar.getTime())));

calendar.add(5, Calendar.WEEK_OF_YEAR);
assertEquals("5w 1d", Utils.getDuration(calendar.getTime().toString()));

calendar.add(-1, Calendar.DAY_OF_MONTH);
assertEquals("5w", Utils.getDuration(calendar.getTime().toString()));
}


@Test
public void getDurationShouldReturnEmptyString() {
Calendar calendar = Calendar.getInstance();
calendar.add(1, Calendar.DAY_OF_MONTH);

assertEquals("", Utils.getDuration(""));
}

@Test
public void dobStringToDateTimeShouldHandleNull() {
assertNull(Utils.dobStringToDateTime(null));
}

@Test
public void dobStringToDateTimeShouldHandleInvalidDateTimeStrings() {
assertNull(Utils.dobStringToDateTime("opensrp"));
}

@Test
public void getPropertiesShouldLoadPropertiesInPropertiesFile() {
AppProperties appProperties = Utils.getProperties(RuntimeEnvironment.application);

assertEquals(5, appProperties.size());
assertEquals("", appProperties.getProperty("DRISHTI_BASE_URL"));
assertEquals("false", appProperties.getProperty("SHOULD_VERIFY_CERTIFICATE"));
assertEquals("false", appProperties.getProperty("system.toaster.centered"));
assertEquals("10", appProperties.getProperty("SYNC_DOWNLOAD_BATCH_SIZE"));
}

@Test
public void safeArrayToString() {
assertEquals("OpenSRP", Utils.safeArrayToString(new char[]{'O', 'p', 'e', 'n', 'S', 'R', 'P'}));
}
}