src_fm_fc_ms_ff stringlengths 43 86.8k | target stringlengths 20 276k |
|---|---|
AllFormVersionSyncService { public DownloadStatus downloadAllPendingFormFromServer() { DownloadStatus status = DownloadStatus.nothingDownloaded; List<FormDefinitionVersion> pendingFormList = formsVersionRepository. getAllFormWithSyncStatus(SyncStatus.PENDING); if (pendingFormList.isEmpty()) { return status; } else { fo... | @Test public void shouldNotDownloadIfThereIsNoPendingForms() throws Exception { Mockito.when(formsVersionRepository.getAllFormWithSyncStatus(SyncStatus.PENDING)).thenReturn( Collections.<FormDefinitionVersion>emptyList()); DownloadStatus status = service.downloadAllPendingFormFromServer(); Assert.assertEquals(status, D... |
AllFormVersionSyncService { public FetchStatus pullFormDefinitionFromServer() { FetchStatus status = FetchStatus.nothingFetched; String baseUrl = configuration.dristhiBaseURL(); String uri = baseUrl + AllConstants.ALL_FORM_VERSION_URL; Response<String> response = httpAgent.fetch(uri); if (response.isFailure()) { logErr... | @Test public void shouldUpdateVersionIfThereIsNewerVersion() throws Exception { String jsonObject = "{\"formVersions\" : [{\"formName\": \"EC_ENGKAN\", \"formDirName\": " + "\"ec_dir\", \"formDataDefinitionVersion\": \"3\"}] }"; Mockito.when(httpAgent.fetch("http: new Response<String>( success, jsonObject)); List<FormD... |
EligibleCoupleService { public void register(FormSubmission submission) { if (isNotBlank(submission.getFieldValue(AllConstants.CommonFormFields.SUBMISSION_DATE))) { allTimelineEvents.add(TimelineEvent.forECRegistered(submission.entityId(), submission.getFieldValue(AllConstants.CommonFormFields.SUBMISSION_DATE))); } } E... | @Test public void shouldCreateTimelineEventWhenECIsRegistered() throws Exception { FormSubmission submission = Mockito.mock(FormSubmission.class); Mockito.when(submission.entityId()).thenReturn("entity id 1"); Mockito.when(submission.getFieldValue("submissionDate")).thenReturn("2012-01-01"); service.register(submission... |
EligibleCoupleService { public void closeEligibleCouple(FormSubmission submission) { allEligibleCouples.close(submission.entityId()); allBeneficiaries.closeAllMothersForEC(submission.entityId()); } EligibleCoupleService(AllEligibleCouples allEligibleCouples, AllTimelineEvents
allTimelineEvents, AllBeneficia... | @Test public void shouldCloseEC() throws Exception { FormSubmission submission = Mockito.mock(FormSubmission.class); Mockito.when(submission.entityId()).thenReturn("entity id 1"); service.closeEligibleCouple(submission); Mockito.verify(allEligibleCouples).close("entity id 1"); Mockito.verify(allBeneficiaries).closeAllM... |
EligibleCoupleService { public void fpChange(FormSubmission submission) { String fpMethodChangeDate = submission.getFieldValue( AllConstants.ECRegistrationFields.FAMILY_PLANNING_METHOD_CHANGE_DATE); if (isBlank(fpMethodChangeDate)) { fpMethodChangeDate = submission .getFieldValue(AllConstants.CommonFormFields.SUBMISSIO... | @Test public void shouldCreateTimelineEventAndUpdateEntityWhenFPChangeIsReported() throws Exception { FormSubmission submission = Mockito.mock(FormSubmission.class); Mockito.when(submission.entityId()).thenReturn("entity id 1"); Mockito.when(submission.getFieldValue("currentMethod")).thenReturn("condom"); Mockito.when(... |
DocumentConfigurationService { protected Manifest convertManifestDTOToManifest(ManifestDTO manifestDTO) throws JSONException { Manifest manifest = new Manifest(); manifest.setVersion(manifestDTO.getIdentifier()); manifest.setAppVersion(manifestDTO.getAppVersion()); manifest.setCreatedAt(manifestDTO.getCreatedAt()); JSO... | @Test public void convertManifestDTOToManifest() throws JSONException { String manifestDTOJson = "{\"json\":\"{\\\"forms_version\\\":\\\"0.0.1\\\",\\\"identifiers\\\":[\\\"anc/member_registration.json\\\",\\\"anc/pregnancy_outcome.json\\\"]}\",\"appId\":\"org.smartregister.chw\",\"appVersion\":\"0.0.1\",\"id\":1}"; Man... |
DocumentConfigurationService { protected ClientForm convertClientFormResponseToClientForm(ClientFormResponse clientFormResponse) { ClientForm clientForm = new ClientForm(); clientForm.setId(clientFormResponse.getClientForm().getId()); clientForm.setCreatedAt(clientFormResponse.getClientFormMetadata().getCreatedAt()); c... | @Test public void convertClientFormResponseToClientForm() throws JSONException { String clientFormResponseJson = "{\"clientForm\":{\"id\":3,\"json\":\"\\\"{\\\\n \\\\\\\"form\\\\\\\": \\\\\\\"ANC Referral\\\\\\\",\\\\n \\\\\\\"count\\\\\\\": \\\\\\\"1\\\\\\\",\\\\n \\\\\\\"encounter_type\\\\\\\": \\\\\\\"ANC Referral\\... |
DocumentConfigurationService { protected void fetchClientForm(String identifier, String formVersion, ClientForm latestClientForm) throws NoHttpResponseException { if (httpAgent == null) { throw new IllegalArgumentException(CLIENT_FORM_SYNC_URL + " http agent is null"); } String baseUrl = getBaseUrl(); Response resp = h... | @Test public void fetchClientForm() { String manifestJson = "{\"identifiers\":[\"referrals/anc_referral_form\"],\"formVersion\":\"0.0.8\",\"appVersion\":\"0.2.0\",\"createdAt\":\"2020-04-23T16:28:19.879+03:00\"}"; Gson gson = new GsonBuilder().setDateFormat("MMM dd, yyyy, hh:mm:ss aaa").create(); Manifest activeManifes... |
DocumentConfigurationService { @VisibleForTesting protected void saveManifestVersion(@NonNull String manifestVersion) { boolean manifestVersionSaved = CoreLibrary.getInstance() .context() .allSharedPreferences() .saveManifestVersion(manifestVersion); if (!manifestVersionSaved) { Timber.e(new Exception("Saving manifest ... | @Test public void saveManifestVersionShouldSaveVersionInSharedPreferences() { Assert.assertNull(CoreLibrary.getInstance().context().allSharedPreferences().fetchManifestVersion()); String manifestVersion = "0.0.89"; documentConfigurationService.saveManifestVersion(manifestVersion); Assert.assertEquals(manifestVersion, C... |
FormSubmissionRouter { public void route(String instanceId) throws Exception { FormSubmission submission = formDataRepository.fetchFromSubmission(instanceId); FormSubmissionHandler handler = handlerMap.get(submission.formName()); if (handler == null) { logWarn("Could not find a handler due to unknown form submission: "... | @Test public void shouldNotifyFormSubmittedListenersWhenFormIsHandled() throws Exception { FormSubmission formSubmission = create().withFormName("ec_registration").withInstanceId("instance id 1").withVersion("122").build(); when(formDataRepository.fetchFromSubmission("instance id 1")).thenReturn(formSubmission); FORM_S... |
AppProperties extends Properties { public Boolean getPropertyBoolean(String key) { return Boolean.valueOf(getProperty(key)); } Boolean getPropertyBoolean(String key); Boolean hasProperty(String key); Boolean isTrue(String key); } | @Test public void testGetPropertyBooleanReturnsCorrectValue() { AppProperties properties = new AppProperties(); Boolean value = properties.getPropertyBoolean(PROP_KEY); Assert.assertNotNull(value); Assert.assertFalse(value); properties.setProperty(PROP_KEY, TEST_VAL_TRUE); value = properties.getPropertyBoolean(PROP_KEY... |
AppProperties extends Properties { public Boolean hasProperty(String key) { return getProperty(key) != null; } Boolean getPropertyBoolean(String key); Boolean hasProperty(String key); Boolean isTrue(String key); } | @Test public void testHasPropertyReturnsCorrectValue() { AppProperties properties = new AppProperties(); Boolean value = properties.hasProperty(PROP_KEY); Assert.assertNotNull(value); Assert.assertFalse(value); properties.setProperty(PROP_KEY, TEST_VAL); value = properties.hasProperty(PROP_KEY); Assert.assertNotNull(va... |
FloatUtil { public static Float tryParse(String value, Float defaultValue) { try { return Float.parseFloat(value); } catch (NumberFormatException e) { return defaultValue; } } static Float tryParse(String value, Float defaultValue); static String tryParse(String value, String defaultValue); } | @Test public void assertTryParseWithInvalidValue() { Assert.assertEquals(FloatUtil.tryParse("invalid", 1.0f), 1.0f); Assert.assertEquals(FloatUtil.tryParse("invalid", "1"), "1"); }
@Test public void assertTryParseWithValidValue() { Assert.assertEquals(FloatUtil.tryParse("1", 1.0f), 1.0f); Assert.assertEquals(FloatUtil.... |
StringUtil { public static String humanize(String value) { return capitalize(replace(getValue(value), "_", " ")); } static String humanize(String value); static String replaceAndHumanize(String value, String oldCharacter, String
newCharacter); static String replaceAndHumanizeWithInitCapText(String value, S... | @Test public void assertShouldCapitalize() throws Exception { org.junit.Assert.assertEquals("Abc", org.smartregister.util.StringUtil.humanize("abc")); org.junit.Assert.assertEquals("Abc", org.smartregister.util.StringUtil.humanize("Abc")); }
@Test public void shouldReplaceUnderscoreWithSpace() throws Exception { org.ju... |
HTTPAgent { public Response<String> fetch(String requestURLPath) { try { HttpURLConnection urlConnection = initializeHttp(requestURLPath, true); if (HttpStatus.SC_UNAUTHORIZED == urlConnection.getResponseCode()) { invalidateExpiredCachedAccessToken(); urlConnection = initializeHttp(requestURLPath, true); } return proce... | @Test public void testFetchFailsGivenWrongUrl() { Response<String> resp = httpAgent.fetch("wrong.url"); Assert.assertEquals(ResponseStatus.failure, resp.status()); }
@Test public void testFetchPassesGivenCorrectUrl() { PowerMockito.mockStatic(Base64.class); Response<String> resp = httpAgent.fetch("https: Assert.assertE... |
HTTPAgent { public Response<String> post(String postURLPath, String jsonPayload) { HttpURLConnection urlConnection; try { urlConnection = generatePostRequest(postURLPath, jsonPayload); if (HttpStatus.SC_UNAUTHORIZED == urlConnection.getResponseCode()) { invalidateExpiredCachedAccessToken(); urlConnection = generatePost... | @Test public void testPostFailsGivenWrongUrl() { HashMap<String, String> map = new HashMap<>(); map.put("title", "OpenSRP Testing Tuesdays"); JSONObject jObject = new JSONObject(map); Response<String> resp = httpAgent.post("wrong.url", jObject.toString()); Assert.assertEquals(ResponseStatus.failure, resp.status()); }
@... |
HTTPAgent { public LoginResponse urlCanBeAccessWithGivenCredentials(String requestURL, String userName, char[] password) { LoginResponse loginResponse = null; HttpURLConnection urlConnection = null; String url = null; try { url = requestURL.replaceAll("\\s+", ""); urlConnection = initializeHttp(url, false); byte[] cred... | @Test public void testUrlCanBeAccessWithGivenCredentials() { PowerMockito.mockStatic(Base64.class); LoginResponse resp = httpAgent.urlCanBeAccessWithGivenCredentials("http: Assert.assertEquals(LoginResponse.SUCCESS.message(), resp.message()); }
@Test public void testUrlCanBeAccessWithGivenCredentialsGivenWrongUrl() { P... |
HTTPAgent { public Response<String> fetchWithCredentials(String requestURL, String accessToken) { try { HttpURLConnection urlConnection = initializeHttp(requestURL, false); urlConnection.setRequestProperty(AllConstants.HTTP_REQUEST_HEADERS.AUTHORIZATION, new StringBuilder(AllConstants.HTTP_REQUEST_AUTH_TOKEN_TYPE.BEARE... | @Test public void testfetchWithCredentialsFailsGivenWrongUrl() { Response<String> resp = httpAgent.fetchWithCredentials("wrong.url", SAMPLE_TEST_TOKEN); Assert.assertEquals(ResponseStatus.failure, resp.status()); }
@Test public void testfetchWithCredentialsPassesGivenCorrectUrl() { PowerMockito.mockStatic(Base64.class)... |
HTTPAgent { public String httpImagePost(String urlString, ProfileImage image) { OutputStream outputStream; PrintWriter writer; String responseString = ""; HttpURLConnection httpUrlConnection = null; try { httpUrlConnection = initializeHttp(urlString, true); httpUrlConnection.setRequestMethod("POST"); httpUrlConnection.... | @Test public void testHttpImagePostGivenWrongUrl() { String resp = httpAgent.httpImagePost("wrong.url", profileImage); Assert.assertEquals("", resp); }
@Test public void testHttpImagePostTimeout() { PowerMockito.mockStatic(Base64.class); PowerMockito.mockStatic(File.class); PowerMockito.mockStatic(FileInputStream.class... |
HTTPAgent { public Response<String> postWithJsonResponse(String postURLPath, String jsonPayload) { logResponse(postURLPath, jsonPayload); return post(postURLPath, jsonPayload); } HTTPAgent(Context context, AllSharedPreferences
allSharedPreferences, DristhiConfiguration configuration); Response<String> fetch... | @Test public void testPostWithJsonResponse() { PowerMockito.mockStatic(Base64.class); HashMap<String, String> map = new HashMap<>(); map.put("title", "OpenSRP Testing Tuesdays"); JSONObject jObject = new JSONObject(map); Response<String> resp = httpAgent.postWithJsonResponse("http: Assert.assertEquals(ResponseStatus.su... |
HTTPAgent { public DownloadStatus downloadFromUrl(String url, String filename) { Response<DownloadStatus> status = downloadFromURL(url, filename); Timber.d("downloading file name : %s and url %s", filename, url); return status.payload(); } HTTPAgent(Context context, AllSharedPreferences
allSharedPreferences... | @Test public void testDownloadFromUrl() throws Exception { HTTPAgent httpAgentSpy = Mockito.spy(httpAgent); Mockito.doReturn(dirFile).when(httpAgentSpy).getSDCardDownloadPath(); Mockito.doReturn(file).when(httpAgentSpy).getFile(TEST_FILE_NAME, dirFile); Mockito.doReturn(false).when(dirFile).exists(); Mockito.doReturn(t... |
DrishtiService { public Response<List<Action>> fetchNewActions(String anmIdentifier, String previouslyFetchedIndex) { String anmID = URLEncoder.encode(anmIdentifier); Response<String> response = agent .fetch(drishtiBaseURL + "/actions?anmIdentifier=" + anmID + "&timeStamp=" + previouslyFetchedIndex); Type collectionTyp... | @Test public void shouldFetchAlertActions() throws Exception { Mockito.when(httpAgent.fetch(EXPECTED_URL)).thenReturn(new Response<String>(ResponseStatus.success, IOUtils.toString(getClass().getResource("/alerts.json")))); Response<List<Action>> actions = drishtiService.fetchNewActions("anm1", "0"); Mockito.verify(http... |
FormSubmissionService { public void processSubmissions(List<FormSubmission> formSubmissions) { for (FormSubmission submission : formSubmissions) { if (!formDataRepository.submissionExists(submission.instanceId())) { try { ziggyService.saveForm(getParams(submission), submission.instance()); updateFTSsearch(submission); ... | @Test public void shouldDelegateProcessingToZiggyServiceAndMarkAsSynced() throws Exception { List<FormSubmission> submissions = Arrays.asList(FormSubmissionBuilder.create().withInstanceId("instance id 1").withVersion("122").build(), FormSubmissionBuilder.create().withInstanceId("instance id 2").withVersion("123").build... |
FormSubmissionService { public void updateFTSsearch(FormSubmission formSubmission) { if (allCommonsRepositoryMap == null || allCommonsRepositoryMap.isEmpty()) { return; } FormData form = formSubmission.getForm(); String bindType = form.getBind_type(); for (FormField field : form.fields()) { if (field.name() != null && ... | @Test public void testUpdateFTSSearchForIdField() { service = spy(service); Whitebox.setInternalState(service, "allCommonsRepositoryMap", allCommonsRepositoryMap); when(allCommonsRepositoryMap.get("bindtype1")).thenReturn(allCommonsRepository); FormSubmission formSubmission = mock(FormSubmission.class); FormData form =... |
StringUtil { public static String replaceAndHumanize(String value, String oldCharacter, String newCharacter) { return humanize(replace(getValue(value), oldCharacter, newCharacter)); } static String humanize(String value); static String replaceAndHumanize(String value, String oldCharacter, String
newCharact... | @Test public void assertReplaceAndHumanizeCallsHumanize() throws Exception { org.junit.Assert.assertEquals("Abc def", StringUtil.replaceAndHumanize("abc def", " ", "_")); } |
AlertService { public void create(Action action) { if (action.isActionActive() == null || action.isActionActive()) { Alert alert = new Alert(action.caseID(), action.get("scheduleName"), action.get("visitCode"), AlertStatus.from(action.get("alertStatus")), action.get("startDate"), action.get("expiryDate")); repository.c... | @Test public void shouldAddAnAlertIntoAlertRepositoryForMotherCreateAlertAction() throws Exception { Action actionForMother = ActionBuilder.actionForCreateAlert("Case X", AlertStatus.normal.value(), BeneficiaryType.mother.value(), "Schedule 1", "ANC 1", "2012-01-01", "2012-01-22", "0"); service.create(actionForMother);... |
AlertService { public void deleteAll(Action action) { repository.deleteAllAlertsForEntity(action.caseID()); } AlertService(AlertRepository repository); AlertService(AlertRepository repository, CommonFtsObject commonFtsObject, Map<String,
AllCommonsRepository> allCommonsRepositoryMap); void create(Action ac... | @Test public void shouldDeleteAllFromRepositoryForDeleteAllActions() throws Exception { Action firstAction = ActionBuilder.actionForDeleteAllAlert("Case X"); Action secondAction = ActionBuilder.actionForDeleteAllAlert("Case Y"); service.deleteAll(firstAction); service.deleteAll(secondAction); Mockito.verify(alertReposi... |
AlertService { public List<Alert> findByEntityId(String entityId) { return repository.findByEntityId(entityId); } AlertService(AlertRepository repository); AlertService(AlertRepository repository, CommonFtsObject commonFtsObject, Map<String,
AllCommonsRepository> allCommonsRepositoryMap); void create(Actio... | @Test public void testFindEntityById() { service.findByEntityId("entity-id"); Mockito.verify(alertRepository).findByEntityId("entity-id"); } |
StringUtil { public static String replaceAndHumanizeWithInitCapText(String value, String oldCharacter, String newCharacter) { return humanize(WordUtils.capitalize(replace(getValue(value), oldCharacter, newCharacter))); } static String humanize(String value); static String replaceAndHumanize(String value, String oldCha... | @Test public void assertReplaceAndHumanizeWithInitCapTextCallsHumanize() throws Exception { org.junit.Assert.assertEquals("Abc def", StringUtil.replaceAndHumanizeWithInitCapText("abc def", " ", "_")); } |
AlertService { public List<Alert> findByEntityIdAndAlertNames(String entityId, String... names) { return repository.findByEntityIdAndAlertNames(entityId, names); } AlertService(AlertRepository repository); AlertService(AlertRepository repository, CommonFtsObject commonFtsObject, Map<String,
AllCommonsRepos... | @Test public void testFindByEntityIdAndAlertNames() { service.findByEntityIdAndAlertNames("Entity 1", "AncAlert"); Mockito.verify(alertRepository).findByEntityIdAndAlertNames("Entity 1", "AncAlert"); } |
AlertService { public List<Alert> findByEntityIdAndOffline(String entityId, String... names) { return repository.findOfflineByEntityIdAndName(entityId, names); } AlertService(AlertRepository repository); AlertService(AlertRepository repository, CommonFtsObject commonFtsObject, Map<String,
AllCommonsReposit... | @Test public void testByEntityIdAndOffline() { service.findByEntityIdAndOffline("Entity 1", "PncAlert"); Mockito.verify(alertRepository).findOfflineByEntityIdAndName("Entity 1", "PncAlert"); } |
AlertService { public Alert findByEntityIdAndScheduleName(String entityId, String scheduleName) { return repository.findByEntityIdAndScheduleName(entityId, scheduleName); } AlertService(AlertRepository repository); AlertService(AlertRepository repository, CommonFtsObject commonFtsObject, Map<String,
AllCom... | @Test public void testFindByEntityIdAndScheduleName() { service.findByEntityIdAndScheduleName("Entity 1", "Schedule 1"); Mockito.verify(alertRepository).findByEntityIdAndScheduleName("Entity 1", "Schedule 1"); } |
AlertService { public void changeAlertStatusToInProcess(String entityId, String alertName) { repository.changeAlertStatusToInProcess(entityId, alertName); updateFtsSearchAfterStatusChange(entityId, alertName); } AlertService(AlertRepository repository); AlertService(AlertRepository repository, CommonFtsObject commonFt... | @Test public void testChangeAlertStatusToInProcess() { service = spy(service); service.changeAlertStatusToInProcess("Entity 1", "AncAlert"); Mockito.verify(alertRepository).changeAlertStatusToInProcess("Entity 1", "AncAlert"); Mockito.verify(service).updateFtsSearchAfterStatusChange("Entity 1", "AncAlert"); } |
AlertService { public void changeAlertStatusToComplete(String entityId, String alertName) { repository.changeAlertStatusToComplete(entityId, alertName); updateFtsSearchAfterStatusChange(entityId, alertName); } AlertService(AlertRepository repository); AlertService(AlertRepository repository, CommonFtsObject commonFtsO... | @Test public void testChangeAlertStatusToComplete() { service = spy(service); service.changeAlertStatusToComplete("Entity 1", "AncAlert"); Mockito.verify(alertRepository).changeAlertStatusToComplete("Entity 1", "AncAlert"); Mockito.verify(service).updateFtsSearchAfterStatusChange("Entity 1", "AncAlert"); } |
AlertService { public void deleteAlert(String entityId, String visitCode) { repository.deleteVaccineAlertForEntity(entityId, visitCode); } AlertService(AlertRepository repository); AlertService(AlertRepository repository, CommonFtsObject commonFtsObject, Map<String,
AllCommonsRepository> allCommonsReposito... | @Test public void testDeleteAlert() { service.deleteAlert("Entity 1", "Visit 1"); Mockito.verify(alertRepository).deleteVaccineAlertForEntity("Entity 1", "Visit 1"); } |
AlertService { public void deleteOfflineAlerts(String entityId) { repository.deleteOfflineAlertsForEntity(entityId); } AlertService(AlertRepository repository); AlertService(AlertRepository repository, CommonFtsObject commonFtsObject, Map<String,
AllCommonsRepository> allCommonsRepositoryMap); void create(... | @Test public void testDeleteOfflineAlerts() { service.deleteOfflineAlerts("Entity 1"); Mockito.verify(alertRepository).deleteOfflineAlertsForEntity("Entity 1"); }
@Test public void testDeleteOfflineAlertsWithNames() { service.deleteOfflineAlerts("Entity 1", "AncAlert"); Mockito.verify(alertRepository).deleteOfflineAler... |
AlertService { public void updateFtsSearchAfterStatusChange(String entityId, String alertName) { try { if (commonFtsObject != null && allCommonsRepositoryMap != null) { List<Alert> alerts = findByEntityIdAndAlertNames(entityId, alertName); if (alerts != null && !alerts.isEmpty()) { for (Alert alert : alerts) { updateFt... | @Test public void testUpdateFtsSearchAfterStatusChange() { service = spy(service); Alert alert = new Alert("Case X", "Schedule 1", "ANC 1", AlertStatus.normal, "2012-01-01", "2012-01-22"); when(service.findByEntityIdAndAlertNames("Entity 1", "AncAlert")).thenReturn(Collections.singletonList(alert)); service.updateFtsSe... |
AlertService { public boolean updateFtsSearchInACR(String bindType, String entityId, String field, String value) { AllCommonsRepository allCommonsRepository = getAllCommonRepository(bindType); if (allCommonsRepository != null) { return allCommonsRepository.updateSearch(entityId, field, value, commonFtsObject.getAlertFi... | @Test public void testUpdateFtsSearchInACR() { AllCommonsRepository allCommonsRepository = mock(AllCommonsRepository.class); when(allCommonsRepositoryMap.get("bind 1")).thenReturn(allCommonsRepository); String[] alertFilterVisitCodes = new String[] {"AncFilter"}; when(commonFtsObject.getAlertFilterVisitCodes()).thenRet... |
StringUtil { public static String humanizeAndUppercase(String value, String... skipTokens) { String res = humanizeAndDoUPPERCASE(value); for (String s : skipTokens) { res = res.replaceAll("(?i)" + s, s); } return res; } static String humanize(String value); static String replaceAndHumanize(String value, String oldChar... | @Test public void assertHumanizeAndUppercase() throws Exception { org.junit.Assert.assertEquals("ABC DEF", StringUtil.humanizeAndUppercase("abc def", " ")); } |
AlertService { public void updateFtsSearch(Alert alert, boolean statusChange) { try { if (commonFtsObject != null && allCommonsRepositoryMap != null) { String entityId = alert.caseId(); String scheduleName = alert.scheduleName(); String visitCode = alert.visitCode(); AlertStatus status = alert.status(); String bindType... | @Test public void testUpdateFtsSearch() { service = spy(service); Alert alert = new Alert("Case X", "Schedule 1", "ANC 1", AlertStatus.normal, "2012-01-01", "2012-01-22"); when(commonFtsObject.getAlertBindType("Schedule 1")).thenReturn("AncBindType"); when(commonFtsObject.alertUpdateVisitCode("Schedule 1")).thenReturn(... |
FormSubmissionSyncService { public void pushToServer() { List<FormSubmission> pendingFormSubmissions = formDataRepository .getPendingFormSubmissions(); if (pendingFormSubmissions.isEmpty()) { return; } String jsonPayload = mapToFormSubmissionDTO(pendingFormSubmissions); Response<String> response = httpAgent .post(forma... | @Test public void shouldPushPendingFormSubmissionsToServerAndMarkThemAsSynced() throws Exception { Mockito.when(httpAgent.post("http: .thenReturn(new Response<String>(ResponseStatus.success, null)); service.pushToServer(); Mockito.inOrder(allSettings, httpAgent, repository); Mockito.verify(allSharedPreferences).fetchRe... |
FormSubmissionSyncService { public FetchStatus pullFromServer() { FetchStatus dataStatus = nothingFetched; String anmId = allSharedPreferences.fetchRegisteredANM(); int downloadBatchSize = configuration.syncDownloadBatchSize(); String baseURL = configuration.dristhiBaseURL(); while (true) { String uri = format("{0}/{1}... | @Test public void shouldPullFormSubmissionsFromServerInBatchesAndDelegateToProcessing() throws Exception { this.expectedFormSubmissionsDto = Arrays.asList(new FormSubmissionDTO( "anm id 1", "id 1", "entity id 1", "form name", formInstanceJSON, "123", "1")); List<FormSubmission> expectedFormSubmissions = Arrays.asList(n... |
UserService { public Response<String> getLocationInformation() { String requestURL = configuration.dristhiBaseURL() + OPENSRP_LOCATION_URL_PATH; return httpAgent.fetch(requestURL); } UserService(AllSettings allSettingsArg, AllSharedPreferences
allSharedPreferencesArg, HTTPAgent httpAgentArg, Session session... | @Test public void shouldGetANMLocation() { when(configuration.dristhiBaseURL()).thenReturn("http: userService.getLocationInformation(); verify(httpAgent).fetch("http: } |
UserService { public void saveUserInfo(User user) { try { if (user != null && user.getPreferredName() != null) { String preferredName = user.getPreferredName(); String userName = user.getUsername(); allSharedPreferences.updateANMPreferredName(userName, preferredName); } } catch (Exception e) { Timber.e(e); } String use... | @Test public void shouldSaveUserInformationRemoteLoginIsSuccessful() { org.smartregister.domain.jsonmapping.User user = new org.smartregister.domain.jsonmapping.User(); user.setPreferredName("Test"); userService.saveUserInfo(user); String userInfoString = AssetHandler.javaToJsonString(user); verify(saveUserInfoTask).sa... |
UserService { public void saveAnmLocation(LocationTree anmLocation) { String amnLocationString = AssetHandler.javaToJsonString(anmLocation); saveANMLocationTask.save(amnLocationString); } UserService(AllSettings allSettingsArg, AllSharedPreferences
allSharedPreferencesArg, HTTPAgent httpAgentArg, Session se... | @Test public void shouldSaveANMLocation() { org.smartregister.domain.jsonmapping.util.LocationTree locationTree = new org.smartregister.domain.jsonmapping.util.LocationTree(); org.smartregister.domain.jsonmapping.Location location = new org.smartregister.domain.jsonmapping.Location(); location.setName("test location");... |
RecreateECUtil { public Pair<List<Event>, List<Client>> createEventAndClients(SQLiteDatabase database, String tablename, String query, String[] params, String eventType, String entityType, FormTag formTag) { Table table = clientProcessor.getColumnMappings(tablename); if (table == null) { return null; } List<Event> even... | @Test public void testCreateEventAndClients() throws IOException { when(database.rawQuery(query, params)).thenReturn(getECCursor()); when(clientProcessor.getColumnMappings(tableName)).thenReturn(getEcConfig()); Pair<List<Event>, List<Client>> eventsAndClients = recreateECUtil.createEventAndClients(database, tableName, ... |
UserService { public boolean isValidLocalLogin(String userName, byte[] password) { return allSharedPreferences.fetchRegisteredANM().equals(userName) && DrishtiApplication.getInstance().getRepository() .canUseThisPassword(password) && !allSharedPreferences.fetchForceRemoteLogin(userName); } UserService(AllSettings allSe... | @Test public void shouldConsiderALocalLoginValid() { when(allSharedPreferences.fetchRegisteredANM()).thenReturn("ANM X"); when(repository.canUseThisPassword(password)).thenReturn(true); assertTrue(userService.isValidLocalLogin("ANM X", password)); verify(allSharedPreferences).fetchRegisteredANM(); verify(repository).ca... |
UserService { public void logout() { logoutSession(); allSettings.registerANM(""); allSettings.savePreviousFetchIndex("0"); configuration.getDrishtiApplication().getRepository().deleteRepository(); } UserService(AllSettings allSettingsArg, AllSharedPreferences
allSharedPreferencesArg, HTTPAgent httpAgentArg... | @Test public void shouldDeleteDataAndSettingsWhenLogoutHappens() throws Exception { SyncConfiguration syncConfiguration = mock(SyncConfiguration.class); Mockito.doReturn(false).when(syncConfiguration).clearDataOnNewTeamLogin(); ReflectionHelpers.setField(CoreLibrary.getInstance(), "syncConfiguration", syncConfiguration... |
UserService { public String switchLanguagePreference() { String preferredLocale = allSharedPreferences.fetchLanguagePreference(); if (ENGLISH_LOCALE.equals(preferredLocale)) { allSharedPreferences.saveLanguagePreference(KANNADA_LOCALE); return KANNADA_LANGUAGE; } else { allSharedPreferences.saveLanguagePreference(ENGLI... | @Test public void shouldSwitchLanguageToKannada() throws Exception { when(allSharedPreferences.fetchLanguagePreference()).thenReturn(ENGLISH_LOCALE); userService.switchLanguagePreference(); verify(allSharedPreferences).saveLanguagePreference(KANNADA_LOCALE); }
@Test public void shouldSwitchLanguageToEnglish() throws Ex... |
UserService { public User getUserData(LoginResponseData userInfo) { try { if (userInfo != null) { return userInfo.user; } } catch (Exception e) { Timber.e(e); } return null; } UserService(AllSettings allSettingsArg, AllSharedPreferences
allSharedPreferencesArg, HTTPAgent httpAgentArg, Session sessionArg,
... | @Test public void shouldGetUserDataFromJSON() throws Exception { org.smartregister.domain.jsonmapping.User user = userService.getUserData(loginResponseData); assertNotNull(user); assertEquals("demotest", user.getUsername()); assertEquals("Demo test User", user.getPreferredName()); } |
UserService { public LocationTree getUserLocation(LoginResponseData userInfo) { try { if (userInfo != null) { return userInfo.locations; } } catch (Exception e) { Timber.e(e); } return null; } UserService(AllSettings allSettingsArg, AllSharedPreferences
allSharedPreferencesArg, HTTPAgent httpAgentArg, Sessi... | @Test public void shouldGetUserLocationFromJSON() throws Exception { org.smartregister.domain.jsonmapping.util.LocationTree locationTree = userService.getUserLocation(loginResponseData); LinkedHashMap<String, org.smartregister.domain.jsonmapping.util.TreeNode<String, org.smartregister.domain.jsonmapping.Location>> mapL... |
UserService { public static TimeZone getServerTimeZone(LoginResponseData userInfo) { if (userInfo != null) { try { Time time = userInfo.time; if (time != null) { TimeZone timeZone = TimeZone.getTimeZone(time.getTimeZone()); return timeZone; } } catch (Exception e) { Timber.e(e); } } return null; } UserService(AllSettin... | @Test public void testGetServerTimeZoneForExtractsTimeZoneFromResponse() { loginResponseData = mock(LoginResponseData.class); loginResponseData.time = new Time(new Date(), TimeZone.getTimeZone("Africa/Nairobi")); TimeZone timezone = UserService.getServerTimeZone(loginResponseData); assertNotNull(timezone); long millise... |
UserService { public TimeStatus validateDeviceTime(LoginResponseData userInfo, long serverTimeThreshold) { TimeZone serverTimeZone = getServerTimeZone(userInfo); TimeZone deviceTimeZone = getDeviceTimeZone(); Date serverTime = getServerTime(userInfo); Date deviceTime = getDeviceTime(); if (serverTimeZone != null && dev... | @Test public void testValidateDeviceTimeForNullServerTimeZoneReturnsError() { loginResponseData = mock(LoginResponseData.class); assertEquals(TimeStatus.ERROR, userService.validateDeviceTime(loginResponseData, 3600)); }
@Test public void testValidateDeviceTimeForDifferentTimeZoneServerTimeZoneReturnsMismatch() { loginR... |
UserService { public TimeStatus validateStoredServerTimeZone() { TimeStatus result = TimeStatus.ERROR; try { String serverTimeZoneId = allSharedPreferences.fetchServerTimeZone(); if (serverTimeZoneId != null) { TimeZone serverTimeZone = TimeZone.getTimeZone(serverTimeZoneId); TimeZone deviceTimeZone = TimeZone.getDefau... | @Test public void testValidateStoredServerTimeZoneForNullServerTimeZoneReturnsError() { when(allSharedPreferences.fetchServerTimeZone()).thenReturn(null); assertEquals(TimeStatus.ERROR, userService.validateStoredServerTimeZone()); verify(allSharedPreferences).saveForceRemoteLogin(true, userName); }
@Test public void te... |
UserService { public boolean isUserInValidGroup(final String userName, final char[] password) { if (keyStore != null && userName != null && password != null && !allSharedPreferences.fetchForceRemoteLogin(userName)) { byte[] storedHash = null; byte[] passwordHash = null; try { storedHash = getLocalAuthenticationCredenti... | @Test public void testIsUserInValidGroupForNullUserAndPassword() { assertFalse(userService.isUserInValidGroup(null, null)); }
@Test public void testIsUserInValidGroupShouldReturnFalseOnError() throws Exception { Whitebox.setInternalState(userService, "keyStore", keyStore); Whitebox.setInternalState(keyStore, "initializ... |
UserService { public boolean isUserInPioneerGroup(String userName) { String pioneerUser = allSharedPreferences.fetchPioneerUser(); if (userName.equals(pioneerUser)) { return true; } else { byte[] currentUserSecretKey = getDecryptedPassphraseValue(userName); byte[] pioneerUserSecretKey = getDecryptedPassphraseValue(pion... | @Test public void testIsUserInPioneerGroupShouldReturnTrueForPioneerUser() throws Exception { userService = spy(userService); Whitebox.setInternalState(userService, "keyStore", keyStore); Whitebox.setInternalState(keyStore, "initialized", true); Whitebox.setInternalState(keyStore, "keyStoreSpi", keyStoreSpi); String us... |
RecreateECUtil { public void saveEventAndClients(Pair<List<Event>, List<Client>> eventClients, SQLiteDatabase sqLiteDatabase) { if (eventClients == null) { return; } if (eventClients.first != null) { JSONArray events; try { events = new JSONArray(gson.toJson(eventClients.first)); Timber.d("saving %d events, %s ", event... | @Test public void testSaveEventAndClientsWithNullEC() { recreateECUtil.saveEventAndClients(null, database); verifyZeroInteractions(database); }
@Test public void testSaveEventAndClients() throws IOException { when(database.rawQuery(query, params)).thenReturn(getECCursor()); when(clientProcessor.getColumnMappings(tableN... |
ChildService { public void register(FormSubmission submission) { SubForm subForm = submission.getSubFormByName( AllConstants.DeliveryOutcomeFields.CHILD_REGISTRATION_SUB_FORM_NAME); if (handleStillBirth(submission, subForm)) { return; } String referenceDate = submission .getFieldValue(AllConstants.DeliveryOutcomeFields... | @Test public void shouldUpdateEveryOnlyNewlyBornChildrenWhileRegistering() throws Exception { Child firstChild = new Child("Child X", "Mother X", "female", EasyMap.create("weight", "3").put("immunizationsGiven", "bcg opv_0").map()); Child secondChild = new Child("Child Y", "Mother X", "female", EasyMap.create("weight",... |
ChildService { public void pncRegistrationOA(FormSubmission submission) { SubForm subForm = submission.getSubFormByName( AllConstants.PNCRegistrationOAFields.CHILD_REGISTRATION_OA_SUB_FORM_NAME); if (handleStillBirth(submission, subForm)) { return; } String referenceDate = submission .getFieldValue(AllConstants.Deliver... | @Test public void shouldUpdateNewlyRegisteredChildrenDuringPNCRegistrationOA() throws Exception { Child firstChild = new Child("Child X", "Mother X", "female", EasyMap.create("weight", "3").put("immunizationsGiven", "bcg opv_0").map()); Child secondChild = new Child("Child Y", "Mother X", "female", EasyMap.create("weig... |
ChildService { public void updateImmunizations(FormSubmission submission) { String immunizationDate = submission .getFieldValue(AllConstants.ChildImmunizationsFields.IMMUNIZATION_DATE); List<String> immunizationsGivenList = splitFieldValueBySpace(submission, AllConstants.ChildImmunizationsFields.IMMUNIZATIONS_GIVEN); L... | @Test public void shouldAddTimelineEventsWhenChildImmunizationsAreUpdated() throws Exception { FormSubmission submission = Mockito.mock(FormSubmission.class); Mockito.when(submission.entityId()).thenReturn("child id 1"); Mockito.when(submission.getFieldValue("previousImmunizations")).thenReturn("bcg"); Mockito.when(sub... |
ChildService { public void registerForEC(FormSubmission submission) { if (shouldCloseMother(submission.getFieldValue(SHOULD_CLOSE_MOTHER))) { closeMother(submission.getFieldValue(AllConstants.ChildRegistrationFields.MOTHER_ID)); } Map<String, String> immunizationDateFieldMap = createImmunizationDateFieldMap(); allTimel... | @Test public void shouldAddTimelineEventWhenChildIsRegisteredForEC() throws Exception { FormSubmission submission = Mockito.mock(FormSubmission.class); Mother mother = new Mother("mother id 1", "ec id 1", "thayi card number", "2013-01-01"); Mockito.when(submission.entityId()).thenReturn("ec id 1"); Mockito.when(submiss... |
ChildService { public void pncVisitHappened(FormSubmission submission) { String pncVisitDate = submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DATE); String pncVisitDay = submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DAY); SubForm subForm = submission .getSubFormByName(AllConstants.PNCVi... | @Test public void shouldAddPNCVisitTimelineEventWhenPNCVisitHappens() throws Exception { FormSubmission submission = Mockito.mock(FormSubmission.class); SubForm subForm = Mockito.mock(SubForm.class); Mockito.when(submission.entityId()).thenReturn("mother id 1"); Mockito.when(submission.getFieldValue("pncVisitDay")).the... |
ChildService { public void close(FormSubmission submission) { allBeneficiaries.closeChild(submission.entityId()); } ChildService(AllBeneficiaries allBeneficiariesArg, MotherRepository
motherRepositoryArg, ChildRepository childRepositoryArg, AllTimelineEvents
allTimelineEvents... | @Test public void shouldCloseChildRecordForDeleteChildAction() throws Exception { FormSubmission submission = Mockito.mock(FormSubmission.class); Mockito.when(submission.entityId()).thenReturn("child id 1"); service.close(submission); Mockito.verify(allBeneficiaries).closeChild("child id 1"); } |
ChildService { public void updateIllnessStatus(FormSubmission submission) { String sickVisitDate = submission.getFieldValue(SICK_VISIT_DATE); String date = sickVisitDate != null ? sickVisitDate : submission.getFieldValue(REPORT_CHILD_DISEASE_DATE); serviceProvidedService.add(ServiceProvided.forChildIllnessVisit(submiss... | @Test public void shouldUpdateIllnessForUpdateIllnessAction() throws Exception { FormSubmission submission = Mockito.mock(FormSubmission.class); Mockito.when(submission.entityId()).thenReturn("child id 1"); Mockito.when(submission.getFieldValue("submissionDate")).thenReturn("2012-01-02"); Mockito.when(submission.getFie... |
ChildService { public void updateVitaminAProvided(FormSubmission submission) { serviceProvidedService.add(ServiceProvided.forVitaminAProvided(submission.entityId(), submission.getFieldValue(AllConstants.VitaminAFields.VITAMIN_A_DATE), submission.getFieldValue(AllConstants.VitaminAFields.VITAMIN_A_DOSE), submission.getF... | @Test public void shouldUpdateVitaminADosagesForUpdateVitaminAProvidedAction() throws Exception { FormSubmission submission = Mockito.mock(FormSubmission.class); Mockito.when(submission.entityId()).thenReturn("child id 1"); Mockito.when(submission.getFieldValue("vitaminADate")).thenReturn("2012-01-01"); Mockito.when(su... |
ChildService { public void registerForOA(FormSubmission submission) { Child child = allBeneficiaries.findChild(submission.getFieldValue(CHILD_ID)); child.setThayiCardNumber(submission.getFieldValue(THAYI_CARD_NUMBER)); allBeneficiaries.updateChild(child); Map<String, String> immunizationDateFieldMap = createImmunizatio... | @Test public void shouldAddTimelineEventWhenChildIsRegisteredForOA() throws Exception { FormSubmission submission = Mockito.mock(FormSubmission.class); Mockito.when(submission.entityId()).thenReturn("ec id 1"); Mockito.when(submission.getFieldValue("motherId")).thenReturn("mother id 1"); Mockito.when(submission.getFiel... |
ActionService { public FetchStatus fetchNewActions() { String previousFetchIndex = allSettings.fetchPreviousFetchIndex(); Response<List<Action>> response = drishtiService .fetchNewActions(allSharedPreference.fetchRegisteredANM(), previousFetchIndex); if (response.isFailure()) { return fetchedFailed; } if (response.payl... | @Test public void shouldFetchAlertActionsAndNotSaveAnythingIfThereIsNothingNewToSave() throws Exception { setupActions(ResponseStatus.success, new ArrayList<Action>()); Assert.assertEquals(FetchStatus.nothingFetched, service.fetchNewActions()); Mockito.verify(drishtiService).fetchNewActions("ANM X", "1234"); Mockito.ve... |
FormUtils { public String retrieveValueForLinkedRecord(String link, JSONObject entityJson) { try { String entityRelationships = readFileFromAssetsFolder( "www/form/entity_relationship" + AllConstants.JSON_FILE_EXTENSION); JSONArray json = new JSONArray(entityRelationships); Timber.i(json.toString()); JSONObject rJson; ... | @Test public void assertretrieveValueForLinkedRecord() throws Exception { formUtils = new FormUtils(context_); Mockito.when(context_.getAssets()).thenReturn(assetManager); Mockito.when(assetManager.open(entityRelationShip)).thenAnswer(new Answer<InputStream>() { @Override public InputStream answer(InvocationOnMock invo... |
ReplicationIntentService extends IntentService { @Override protected void onHandleIntent(Intent intent) { } ReplicationIntentService(String name); ReplicationIntentService(); } | @Test public void assertReplicationIntentServiceInitializationTest() { ReplicationIntentService replicationIntentService = new ReplicationIntentService(); Assert.assertNotNull(replicationIntentService); replicationIntentService.onHandleIntent(null); }
@Test public void assertReplicationIntentServiceInitializationTest2(... |
MotherService { public void registerANC(FormSubmission submission) { addTimelineEventsForMotherRegistration(submission); } MotherService(AllBeneficiaries allBeneficiaries, AllEligibleCouples
allEligibleCouples, AllTimelineEvents allTimelineEvents, ServiceProvidedService
serv... | @Test public void shouldRegisterANC() throws Exception { FormSubmission submission = mock(FormSubmission.class); when(submission.entityId()).thenReturn("entity id 1"); when(submission.getFieldValue("motherId")).thenReturn("mother id 1"); when(submission.getFieldValue("thayiCardNumber")).thenReturn("thayi 1"); when(subm... |
MotherService { public void registerOutOfAreaANC(FormSubmission submission) { addTimelineEventsForMotherRegistration(submission); } MotherService(AllBeneficiaries allBeneficiaries, AllEligibleCouples
allEligibleCouples, AllTimelineEvents allTimelineEvents, ServiceProvidedService
... | @Test public void shouldRegisterOutOfAreaANC() throws Exception { FormSubmission submission = mock(FormSubmission.class); when(submission.entityId()).thenReturn("entity id 1"); when(submission.getFieldValue("motherId")).thenReturn("mother id 1"); when(submission.getFieldValue("thayiCardNumber")).thenReturn("thayi 1"); ... |
MotherService { public void ancVisit(FormSubmission submission) { allTimelines.add(forANCCareProvided(submission.entityId(), submission.getFieldValue(ANC_VISIT_NUMBER), submission.getFieldValue(ANC_VISIT_DATE), create(BP_SYSTOLIC, submission.getFieldValue(BP_SYSTOLIC)) .put(BP_DIASTOLIC, submission.getFieldValue(BP_DIA... | @Test public void shouldCreateTimelineEventsWhenANCVisitHappens() throws Exception { FormSubmission submission = mock(FormSubmission.class); when(submission.entityId()).thenReturn("entity id 1"); when(submission.getFieldValue("ancVisitDate")).thenReturn("2013-01-01"); when(submission.getFieldValue("ancVisitNumber")).th... |
MotherService { public void close(FormSubmission submission) { close(submission.entityId(), submission.getFieldValue(CLOSE_REASON_FIELD_NAME)); } MotherService(AllBeneficiaries allBeneficiaries, AllEligibleCouples
allEligibleCouples, AllTimelineEvents allTimelineEvents, ServiceProvidedService
... | @Test public void shouldNotDoAnythingWhenANCIsClosedAndMotherDoesNotExist() throws Exception { FormSubmission submission = mock(FormSubmission.class); when(submission.entityId()).thenReturn("entity id 1"); when(allBeneficiaries.findMotherWithOpenStatus("entity id 1")).thenReturn(null); service.close(submission); verify... |
FormUtils { public String generateXMLInputForFormWithEntityId(String entityId, String formName, String overrides) { try { JSONObject fieldOverrides = new JSONObject(); if (overrides != null) { fieldOverrides = new JSONObject(overrides); String overridesStr = fieldOverrides.getString("fieldOverrides"); fieldOverrides = ... | @Test public void assertgenerateXMLInputForFormWithEntityId() throws Exception { formUtils = new FormUtils(context_); Mockito.when(context_.getAssets()).thenReturn(assetManager); Mockito.when(assetManager.open(formDefinition)).thenAnswer(new Answer<InputStream>() { @Override public InputStream answer(InvocationOnMock i... |
MotherService { public void ttProvided(FormSubmission submission) { allTimelines.add(forTTShotProvided(submission.entityId(), submission.getFieldValue(TT_DOSE), submission.getFieldValue(TT_DATE))); serviceProvidedService .add(forTTDose(submission.entityId(), submission.getFieldValue(TT_DOSE), submission.getFieldValue(T... | @Test public void shouldHandleTTProvided() throws Exception { FormSubmission submission = mock(FormSubmission.class); when(submission.entityId()).thenReturn("entity id 1"); when(submission.getFieldValue("ttDose")).thenReturn("ttbooster"); when(submission.getFieldValue("ttDate")).thenReturn("2013-01-01"); service.ttProv... |
MotherService { public void ifaTabletsGiven(FormSubmission submission) { String numberOfIFATabletsGiven = submission.getFieldValue(NUMBER_OF_IFA_TABLETS_GIVEN); if (tryParse(numberOfIFATabletsGiven, 0) > 0) { allTimelines.add(forIFATabletsGiven(submission.entityId(), numberOfIFATabletsGiven, submission.getFieldValue(IF... | @Test public void shouldAddTimelineEventWhenIFATabletsAreGiven() throws Exception { FormSubmission submission = mock(FormSubmission.class); when(submission.entityId()).thenReturn("entity id 1"); when(submission.getFieldValue("numberOfIFATabletsGiven")).thenReturn("100"); when(submission.getFieldValue("ifaTabletsDate"))... |
MotherService { public void hbTest(FormSubmission submission) { serviceProvidedService .add(forHBTest(submission.entityId(), submission.getFieldValue(HB_LEVEL), submission.getFieldValue(HB_TEST_DATE))); } MotherService(AllBeneficiaries allBeneficiaries, AllEligibleCouples
allEligibleCouples, AllTimelineEven... | @Test public void shouldHandleHBTest() throws Exception { FormSubmission submission = mock(FormSubmission.class); when(submission.entityId()).thenReturn("entity id 1"); when(submission.getFieldValue("hbLevel")).thenReturn("11"); when(submission.getFieldValue("hbTestDate")).thenReturn("2013-01-01"); service.hbTest(submi... |
MotherService { public void deliveryOutcome(FormSubmission submission) { Mother mother = allBeneficiaries.findMotherWithOpenStatus(submission.entityId()); if (mother == null) { logWarn("Failed to handle delivery outcome for mother. Entity ID: " + submission .entityId()); return; } if (BOOLEAN_FALSE.equals(submission.ge... | @Test public void shouldHandleDeliveryOutcome() throws Exception { FormSubmission submission = mock(FormSubmission.class); when(submission.entityId()).thenReturn("entity id 1"); when(submission.getFieldValue("didWomanSurvive")).thenReturn("yes"); when(allBeneficiaries.findMotherWithOpenStatus("entity id 1")).thenReturn... |
MotherService { public void pncVisitHappened(FormSubmission submission) { allTimelines.add(forMotherPNCVisit(submission.entityId(), submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DAY), submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DATE), submission.getFieldValue(AllConstants.PNCVisitFie... | @Test public void shouldAddPNCVisitTimelineEventWhenPNCVisitHappens() throws Exception { FormSubmission submission = mock(FormSubmission.class); when(submission.entityId()).thenReturn("entity id 1"); when(submission.getFieldValue("pncVisitDay")).thenReturn("2"); when(submission.getFieldValue("pncVisitDate")).thenReturn... |
FormUtils { public FormSubmission generateFormSubmisionFromXMLString(String entity_id, String formData, String formName, JSONObject overrides) throws Exception { JSONObject formSubmission = XML.toJSONObject(formData); System.out.println(formSubmission); String formDefinitionJson = readFileFromAssetsFolder( "www/form/" ... | @Test public void assertgenerateFormSubmisionFromXMLString() throws Exception { formUtils = new FormUtils(context_); String formData = getStringFromStream(new FileInputStream(getFileFromPath(this, formSubmissionXML))); Mockito.when(context_.getAssets()).thenReturn(assetManager); Mockito.when(assetManager.open(formDefin... |
MotherService { public void deliveryPlan(FormSubmission submission) { allTimelines.add(forDeliveryPlan(submission.entityId(), submission.getFieldValue(DELIVERY_FACILITY_NAME), submission.getFieldValue(TRANSPORTATION_PLAN), submission.getFieldValue(BIRTH_COMPANION), submission.getFieldValue(ASHA_PHONE_NUMBER), submissio... | @Test public void shouldAddTimelineEventWhenDeliveryPlanHappens() throws Exception { FormSubmission submission = mock(FormSubmission.class); when(submission.entityId()).thenReturn("entity id 1"); when(submission.getFieldValue("deliveryFacilityName")).thenReturn("Delivery Facility Name"); when(submission.getFieldValue("... |
SecurityHelper { public static char[] readValue(Editable editable) { char[] chars = new char[editable.length()]; editable.getChars(0, editable.length(), chars, 0); return chars; } static char[] readValue(Editable editable); static void clearArray(byte[] array); static void clearArray(char[] array); static byte[] toByt... | @Test public void testReadValueClearsEditableAfterReadingValue() { Mockito.doReturn(2).when(editable).length(); SecurityHelper.readValue(editable); ArgumentCaptor<Integer> lengthCaptor = ArgumentCaptor.forClass(Integer.class); ArgumentCaptor<char[]> charsCaptor = ArgumentCaptor.forClass(char[].class); ArgumentCaptor<In... |
SecurityHelper { public static void clearArray(byte[] array) { if (array != null) { Arrays.fill(array, (byte) 0); } } static char[] readValue(Editable editable); static void clearArray(byte[] array); static void clearArray(char[] array); static byte[] toBytes(StringBuffer stringBuffer); static byte[] toBytes(char[] ch... | @Test public void clearArray() { byte[] sensitiveDataArray = SecurityHelper.toBytes(TEST_PASSWORD); SecurityHelper.clearArray(sensitiveDataArray); Assert.assertNotNull(sensitiveDataArray); for (byte c : sensitiveDataArray) { Assert.assertEquals((byte) 0, c); } }
@Test public void testClearArrayOverwritesCharArrayValues... |
SecurityHelper { public static byte[] toBytes(StringBuffer stringBuffer) throws CharacterCodingException { CharsetEncoder encoder = CHARSET.newEncoder(); CharBuffer buffer = CharBuffer.wrap(stringBuffer); ByteBuffer bytesBuffer = encoder.encode(buffer); byte[] bytes = bytesBuffer.array(); clearArray(bytesBuffer.array()... | @Test public void testToBytes() throws CharacterCodingException { StringBuffer stringBuffer = new StringBuffer(); stringBuffer.append(TEST_PASSWORD); byte[] testPasswordBytes = SecurityHelper.toBytes(stringBuffer); Assert.assertNotNull(testPasswordBytes); Assert.assertEquals(TEST_PASSWORD.length + 1, testPasswordBytes.... |
SecurityHelper { public static byte[] nullSafeBase64Decode(String base64EncodedValue) { if (!StringUtils.isBlank(base64EncodedValue)) { return Base64.decode(base64EncodedValue, Base64.DEFAULT); } else { return null; } } static char[] readValue(Editable editable); static void clearArray(byte[] array); static void clear... | @Test public void nullSafeBase64DecodeDoesNotThrowExceptionIfParameterIsNull() { PowerMockito.mockStatic(Base64.class); PowerMockito.when(Base64.decode(ArgumentMatchers.anyString(), ArgumentMatchers.eq(Base64.DEFAULT))).thenReturn(new byte[]{0, 1}); byte[] decoded = SecurityHelper.nullSafeBase64Decode(null); Assert.ass... |
FormUtils { public JSONObject getFormJson(String formIdentity) { if (mContext != null) { try { String locale = mContext.getResources().getConfiguration().locale.getLanguage(); locale = locale.equalsIgnoreCase(Locale.ENGLISH.getLanguage()) ? "" : "-" + locale; InputStream inputStream; try { inputStream = mContext.getApp... | @Test public void getFormJsonShouldReturnCorrectFormWithSameLength() { Mockito.doReturn(RuntimeEnvironment.application.getResources()).when(context_).getResources(); Mockito.doReturn(RuntimeEnvironment.application.getApplicationContext()).when(context_).getApplicationContext(); Assert.assertEquals(10011, formUtils.getF... |
SecurityHelper { public static char[] generateRandomPassphrase() { return RandomStringUtils.randomAlphanumeric(PASSPHRASE_SIZE).toCharArray(); } static char[] readValue(Editable editable); static void clearArray(byte[] array); static void clearArray(char[] array); static byte[] toBytes(StringBuffer stringBuffer); stat... | @Test public void testGenerateRandomPassphraseGeneratesAlphanumericArray() { char[] value = SecurityHelper.generateRandomPassphrase(); Assert.assertNotNull(value); Assert.assertTrue(StringUtils.isAlphanumeric(new StringBuilder().append(value).toString())); Assert.assertEquals(32, value.length); } |
CoreLibrary implements OnAccountsUpdateListener { public void initP2pLibrary(@Nullable String username) { if (p2POptions != null && p2POptions.isEnableP2PLibrary()) { String p2pUsername = username; AllSharedPreferences allSharedPreferences = new AllSharedPreferences(getDefaultSharedPreferences(context.applicationContex... | @Test public void initP2pLibrary() { String expectedUsername = "nurse1"; String expectedTeamIdPassword = "908980dslkjfljsdlf"; Mockito.doReturn(RuntimeEnvironment.application) .when(context) .applicationContext(); AllSharedPreferences allSharedPreferences = new AllSharedPreferences( PreferenceManager.getDefaultSharedPr... |
CampaignRepository extends BaseRepository { public void addOrUpdate(Campaign campaign) { if (StringUtils.isBlank(campaign.getIdentifier())) throw new IllegalArgumentException("Identifier must be specified"); ContentValues contentValues = new ContentValues(); contentValues.put(ID, campaign.getIdentifier()); contentValue... | @Test public void testAddOrUpdateShouldAdd() { Campaign campaign = gson.fromJson(campaignJson, Campaign.class); campaignRepository.addOrUpdate(campaign); verify(sqLiteDatabase).replace(stringArgumentCaptor.capture(), stringArgumentCaptor.capture(), contentValuesArgumentCaptor.capture()); assertEquals(2, stringArgumentC... |
CampaignRepository extends BaseRepository { public List<Campaign> getAllCampaigns() { Cursor cursor = null; List<Campaign> campaigns = new ArrayList<>(); try { cursor = getReadableDatabase().rawQuery("SELECT * FROM " + CAMPAIGN_TABLE, null); while (cursor.moveToNext()) { campaigns.add(readCursor(cursor)); } cursor.clos... | @Test public void tesGetCampaignsAllCampaigns() { when(sqLiteDatabase.rawQuery("SELECT * FROM " + CAMPAIGN_TABLE, null)).thenReturn(getCursor()); List<Campaign> allCampaigns = campaignRepository.getAllCampaigns(); verify(sqLiteDatabase).rawQuery("SELECT * FROM " + CAMPAIGN_TABLE, null); assertEquals(1, allCampaigns.siz... |
CampaignRepository extends BaseRepository { public Campaign getCampaignByIdentifier(String identifier) { Cursor cursor = null; try { cursor = getReadableDatabase().rawQuery("SELECT * FROM " + CAMPAIGN_TABLE + " WHERE " + ID + " =?", new String[]{identifier}); if (cursor.moveToFirst()) { return readCursor(cursor); } } c... | @Test public void testGetCampaignByIdentifier() { when(sqLiteDatabase.rawQuery("SELECT * FROM campaign WHERE _id =?", new String[]{"IRS_2018_S1"})).thenReturn(getCursor()); Campaign campaign = campaignRepository.getCampaignByIdentifier("IRS_2018_S1"); verify(sqLiteDatabase).rawQuery(stringArgumentCaptor.capture(), args... |
TaskNotesRepository extends BaseRepository { public void addOrUpdate(Note note, String taskId) { if (StringUtils.isBlank(taskId)) { throw new IllegalArgumentException("taskId must be specified"); } ContentValues contentValues = new ContentValues(); contentValues.put(TASK_ID, taskId); contentValues.put(AUTHOR, note.getA... | @Test public void testAddOrUpdateShouldAdd() { Note note = new Note(); note.setText("Should be completed by End of November"); Long now = System.currentTimeMillis(); note.setTime(new DateTime(now)); note.setAuthorString("jdoe"); taskNotesRepository.addOrUpdate(note, "task22132"); verify(sqLiteDatabase).replace(stringAr... |
TaskNotesRepository extends BaseRepository { public List<Note> getNotesByTask(String taskId) { List<Note> notes = new ArrayList<>(); Cursor cursor = null; try { cursor = getReadableDatabase().rawQuery("SELECT * FROM " + TASK_NOTES_TABLE + " WHERE " + TASK_ID + " =?", new String[]{taskId}); while (cursor.moveToNext()) {... | @Test public void tesGetTasksAllTasks() { when(sqLiteDatabase.rawQuery("SELECT * FROM task_note WHERE task_id =?", new String[]{"task22132"})).thenReturn(getCursor()); List<Note> notes = taskNotesRepository.getNotesByTask("task22132"); verify(sqLiteDatabase).rawQuery("SELECT * FROM task_note WHERE task_id =?", new Stri... |
TaskRepository extends BaseRepository { public void addOrUpdate(Task task) { addOrUpdate(task, false); } TaskRepository(TaskNotesRepository taskNotesRepository); static void createTable(SQLiteDatabase database); void addOrUpdate(Task task); void addOrUpdate(Task task, boolean updateOnly); Map<String, Set<Task>> getTask... | @Test public void testAddOrUpdateShouldAdd() { Task task = gson.fromJson(taskJson, Task.class); taskRepository.addOrUpdate(task); verify(sqLiteDatabase).replace(stringArgumentCaptor.capture(), stringArgumentCaptor.capture(), contentValuesArgumentCaptor.capture()); Iterator<String> iterator = stringArgumentCaptor.getAll... |
FormUtils { public static int getIndexForFormName(String formName, String[] formNames) { for (int i = 0; i < formNames.length; i++) { if (formName.equalsIgnoreCase(formNames[i])) { return i; } } return -1; } FormUtils(Context context); static FormUtils getInstance(Context ctx); static boolean hasChildElements(Node elem... | @Test public void getIndexForFormNameShouldReturnCorrectIndex() { String[] formNames = new String[] {"Birth Reg", "Immunisation Reg", "Death Form"}; Assert.assertEquals(1, formUtils.getIndexForFormName("Immunisation Reg", formNames)); } |
TaskRepository extends BaseRepository { public Map<String, Set<Task>> getTasksByPlanAndGroup(String planId, String groupId) { Cursor cursor = null; Map<String, Set<Task>> tasks = new HashMap<>(); try { String[] params = new String[]{planId, groupId}; cursor = getReadableDatabase().rawQuery(String.format("SELECT * FROM ... | @Test public void testGetTasksByPlanAndGroup() { when(sqLiteDatabase.rawQuery("SELECT * FROM task WHERE plan_id=? AND group_id =? AND status NOT IN (?,?)", new String[]{"IRS_2018_S1", "2018_IRS-3734", CANCELLED.name(), ARCHIVED.name()})).thenReturn(getCursor()); Map<String, Set<Task>> allTasks = taskRepository.getTasks... |
TaskRepository extends BaseRepository { public Set<Task> getTasksByEntityAndCode(String planId, String groupId, String forEntity, String code) { return getTasks(String.format("SELECT * FROM %s WHERE %s=? AND %s =? AND %s =? AND %s =? AND %s NOT IN (%s)", TASK_TABLE, PLAN_ID, GROUP_ID, FOR, CODE, STATUS, TextUtils.join(... | @Test public void testGetTasksByEntityAndCode() { when(sqLiteDatabase.rawQuery("SELECT * FROM task WHERE plan_id=? AND group_id =? AND for =? AND code =? AND status NOT IN (?,?)", new String[]{"IRS_2018_S1", "2018_IRS-3734", "location.properties.uid:41587456-b7c8-4c4e-b433-23a786f742fc", "IRS", CANCELLED.name(), ARCHIV... |
TaskRepository extends BaseRepository { public Task getTaskByIdentifier(String identifier) { try (Cursor cursor = getReadableDatabase().rawQuery("SELECT * FROM " + TASK_TABLE + " WHERE " + ID + " =?", new String[]{identifier})) { if (cursor.moveToFirst()) { return readCursor(cursor); } } catch (Exception e) { Timber.e(... | @Test public void testGetTaskByIdentifier() { when(sqLiteDatabase.rawQuery("SELECT * FROM task WHERE _id =?", new String[]{"tsk11231jh22"})).thenReturn(getCursor()); Task task = taskRepository.getTaskByIdentifier("tsk11231jh22"); verify(sqLiteDatabase).rawQuery(stringArgumentCaptor.capture(), argsCaptor.capture()); ass... |
TaskRepository extends BaseRepository { public List<TaskUpdate> getUnSyncedTaskStatus() { Cursor cursor = null; List<TaskUpdate> taskUpdates = new ArrayList<>(); try { cursor = getReadableDatabase().rawQuery(String.format("SELECT " + ID + "," + STATUS + "," + BUSINESS_STATUS + "," + SERVER_VERSION + " FROM %s WHERE %s ... | @Test public void testGetUnSyncedTaskStatus() { taskRepository.getUnSyncedTaskStatus(); verify(sqLiteDatabase).rawQuery(stringArgumentCaptor.capture(), argsCaptor.capture()); assertNotNull(taskRepository.getUnSyncedTaskStatus()); } |
TaskRepository extends BaseRepository { public boolean updateTaskStructureIdFromClient(List<Client> clients, String attribute) { if (clients == null || clients.isEmpty()) { return false; } SQLiteStatement updateStatement = null; try { getWritableDatabase().beginTransaction(); String updateTaskSructureIdQuery = String.f... | @Test public void testUpdateTaskStructureIdFromClient() throws Exception { List<Client> clients = new ArrayList<>(); Client client = gson.fromJson(clientJson, Client.class); clients.add(client); taskRepository.updateTaskStructureIdFromClient(clients, ""); assertNotNull(taskRepository.getUnSyncedTaskStatus()); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.