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 { for (FormDefinitionVersion l : pendingFormList) { String downloadLink = configuration.dristhiBaseURL() + AllConstants.FORM_DOWNLOAD_URL + l .getFormDirName(); status = httpAgent.downloadFromUrl(downloadLink, l.getFormDirName() + ".zip"); if (status == DownloadStatus.downloaded) { formsVersionRepository.updateSyncStatus(l.getFormDirName(), SyncStatus.SYNCED); } } } return status; } AllFormVersionSyncService(HTTPAgent httpAgentArg, DristhiConfiguration
configurationArg, FormsVersionRepository formsVersionRepositoryArg); FetchStatus pullFormDefinitionFromServer(); DownloadStatus downloadAllPendingFormFromServer(); void unzipAllDownloadedFormFile(); void verifyFormsInFolder(); } | @Test public void shouldNotDownloadIfThereIsNoPendingForms() throws Exception { Mockito.when(formsVersionRepository.getAllFormWithSyncStatus(SyncStatus.PENDING)).thenReturn( Collections.<FormDefinitionVersion>emptyList()); DownloadStatus status = service.downloadAllPendingFormFromServer(); Assert.assertEquals(status, DownloadStatus.nothingDownloaded); Mockito.verify(formsVersionRepository).getAllFormWithSyncStatus(SyncStatus.PENDING); Mockito.verifyNoMoreInteractions(formsVersionRepository); Mockito.verifyZeroInteractions(httpAgent); }
@Test public void shouldDownloadIfThereIsAPendingForms() throws Exception { Mockito.when(formsVersionRepository.getAllFormWithSyncStatus(SyncStatus.PENDING)).thenReturn( this.expectedFormDefinitionVersion); Mockito.when(httpAgent.downloadFromUrl("http: "ec_dir.zip")).thenReturn(DownloadStatus.downloaded); DownloadStatus status = service.downloadAllPendingFormFromServer(); Assert.assertEquals(status, DownloadStatus.downloaded); Mockito.verify(formsVersionRepository).getAllFormWithSyncStatus(SyncStatus.PENDING); Mockito.verify(httpAgent).downloadFromUrl( "http: "ec_dir.zip"); } |
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()) { logError("Form definition pull error"); status = FetchStatus.fetchedFailed; return status; } String formVersions; try { JSONObject jsonObject = new JSONObject(response.payload()); formVersions = jsonObject.get("formVersions").toString(); } catch (JSONException e) { return status; } List<FormDefinitionVersion> forms = new Gson() .fromJson(formVersions, new TypeToken<List<FormDefinitionVersion>>() { }.getType()); if (forms.size() > 0) { for (FormDefinitionVersion form : forms) { try { if (!formsVersionRepository.formExists(form.getFormDirName())) { form.setSyncStatus(SyncStatus.PENDING); formsVersionRepository.addFormVersionFromObject(form); } else { FormDefinitionVersion formDefinitionVersion = formsVersionRepository .getFormByFormDirName(form.getFormDirName()); if (!formDefinitionVersion.getFormName().equals(form.getFormName())) { formsVersionRepository .updateFormName(form.getFormDirName(), form.getFormName()); } int repoVersion = Integer.parseInt(formDefinitionVersion.getVersion()); int pulledVersion = Integer.parseInt(form.getVersion()); if (pulledVersion > repoVersion) { formsVersionRepository .updateServerVersion(form.getFormDirName(), form.getVersion()); formsVersionRepository .updateSyncStatus(form.getFormDirName(), SyncStatus.PENDING); status = FetchStatus.fetched; } } } catch (Exception e) { Timber.e(e); } } } return status; } AllFormVersionSyncService(HTTPAgent httpAgentArg, DristhiConfiguration
configurationArg, FormsVersionRepository formsVersionRepositoryArg); FetchStatus pullFormDefinitionFromServer(); DownloadStatus downloadAllPendingFormFromServer(); void unzipAllDownloadedFormFile(); void verifyFormsInFolder(); } | @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<FormDefinitionVersion> repoForm = Arrays.asList(new FormDefinitionVersion("form_ec", "ec_dir", "1")); Mockito.when(formsVersionRepository.formExists("ec_dir")).thenReturn(true); Mockito.when(formsVersionRepository.getAllFormWithSyncStatus(SyncStatus.PENDING)).thenReturn( repoForm); Mockito.when(formsVersionRepository.getFormByFormDirName("ec_dir")).thenReturn( new FormDefinitionVersion( "EC_ENGAN", "ec_dir", "1")); Mockito.when(formsVersionRepository.getVersion("ec_dir")).thenReturn("1"); FetchStatus fetchStatus = service.pullFormDefinitionFromServer(); Assert.assertEquals(fetched, fetchStatus); Mockito.verify(httpAgent).fetch("http: Mockito.verify(formsVersionRepository).updateFormName("ec_dir", "EC_ENGKAN"); Mockito.verify(formsVersionRepository).formExists("ec_dir"); Mockito.verify(formsVersionRepository).updateServerVersion("ec_dir", "3"); Mockito.verify(formsVersionRepository).updateSyncStatus("ec_dir", SyncStatus.PENDING); }
@Test public void shouldNotUpdateIfLocalFormIsTheLatestVersion() throws Exception { String jsonObject = "{\"formVersions\" : [{\"formName\": \"EC_ENGKAN\", \"formDirName\":" + " \"ec_dir\", \"formDataDefinitionVersion\": \"2\"}] }"; Mockito.when(httpAgent.fetch("http: new Response<String>( success, jsonObject)); List<FormDefinitionVersion> repoForm = Arrays.asList(new FormDefinitionVersion("form_ec", "ec_dir", "3")); Mockito.when(formsVersionRepository.formExists("ec_dir")).thenReturn(true); Mockito.when(formsVersionRepository.getAllFormWithSyncStatus(SyncStatus.PENDING)).thenReturn( repoForm); Mockito.when(formsVersionRepository.getFormByFormDirName("ec_dir")).thenReturn( new FormDefinitionVersion( "EC_ENGAN", "ec_dir", "3")); Mockito.when(formsVersionRepository.getVersion("ec_dir")).thenReturn("3"); FetchStatus fetchStatus = service.pullFormDefinitionFromServer(); Assert.assertEquals(nothingFetched, fetchStatus); } |
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))); } } EligibleCoupleService(AllEligibleCouples allEligibleCouples, AllTimelineEvents
allTimelineEvents, AllBeneficiaries allBeneficiaries); void register(FormSubmission submission); void fpComplications(FormSubmission submission); void fpChange(FormSubmission submission); void renewFPProduct(FormSubmission submission); void closeEligibleCouple(FormSubmission submission); } | @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); Mockito.verify(allTimelineEvents).add(TimelineEvent.forECRegistered("entity id 1", "2012-01-01")); }
@Test public void shouldNotCreateTimelineEventWhenECIsRegisteredWithoutSubmissionDate() throws Exception { FormSubmission submission = Mockito.mock(FormSubmission.class); Mockito.when(submission.entityId()).thenReturn("entity id 1"); Mockito.when(submission.getFieldValue("submissionDate")).thenReturn(null); service.register(submission); Mockito.verifyZeroInteractions(allTimelineEvents); } |
EligibleCoupleService { public void closeEligibleCouple(FormSubmission submission) { allEligibleCouples.close(submission.entityId()); allBeneficiaries.closeAllMothersForEC(submission.entityId()); } EligibleCoupleService(AllEligibleCouples allEligibleCouples, AllTimelineEvents
allTimelineEvents, AllBeneficiaries allBeneficiaries); void register(FormSubmission submission); void fpComplications(FormSubmission submission); void fpChange(FormSubmission submission); void renewFPProduct(FormSubmission submission); void closeEligibleCouple(FormSubmission submission); } | @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).closeAllMothersForEC("entity id 1"); } |
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.SUBMISSION_DATE); } allTimelineEvents.add(forChangeOfFPMethod(submission.entityId(), submission.getFieldValue(AllConstants.ECRegistrationFields.CURRENT_FP_METHOD), submission.getFieldValue(NEW_FP_METHOD_FIELD_NAME), fpMethodChangeDate)); allEligibleCouples.mergeDetails(submission.entityId(), mapOf(AllConstants.ECRegistrationFields.CURRENT_FP_METHOD, submission.getFieldValue(NEW_FP_METHOD_FIELD_NAME))); } EligibleCoupleService(AllEligibleCouples allEligibleCouples, AllTimelineEvents
allTimelineEvents, AllBeneficiaries allBeneficiaries); void register(FormSubmission submission); void fpComplications(FormSubmission submission); void fpChange(FormSubmission submission); void renewFPProduct(FormSubmission submission); void closeEligibleCouple(FormSubmission submission); } | @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(submission.getFieldValue("newMethod")).thenReturn("ocp"); Mockito.when(submission.getFieldValue("familyPlanningMethodChangeDate")).thenReturn("2012-01-01"); service.fpChange(submission); Mockito.verify(allTimelineEvents).add(TimelineEvent.forChangeOfFPMethod("entity id 1", "condom", "ocp", "2012-01-01")); Mockito.verify(allEligibleCouples).mergeDetails("entity id 1", EasyMap.mapOf("currentMethod", "ocp")); }
@Test public void shouldUseFormSubmissionDateAsChangeDateWhenFPMethodIsChangedAndChangeDateIsBlank() 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(submission.getFieldValue("newMethod")).thenReturn("none"); Mockito.when(submission.getFieldValue("submissionDate")).thenReturn("2012-02-01"); service.fpChange(submission); Mockito.verify(allTimelineEvents).add(TimelineEvent.forChangeOfFPMethod("entity id 1", "condom", "none", "2012-02-01")); Mockito.verify(allEligibleCouples).mergeDetails("entity id 1", EasyMap.mapOf("currentMethod", "none")); } |
DocumentConfigurationService { protected Manifest convertManifestDTOToManifest(ManifestDTO manifestDTO) throws JSONException { Manifest manifest = new Manifest(); manifest.setVersion(manifestDTO.getIdentifier()); manifest.setAppVersion(manifestDTO.getAppVersion()); manifest.setCreatedAt(manifestDTO.getCreatedAt()); JSONObject json = new JSONObject(manifestDTO.getJson()); if (json.has(MANIFEST_FORMS_VERSION)) { manifest.setFormVersion(json.getString(MANIFEST_FORMS_VERSION)); } if (json.has(IDENTIFIERS)) { List<String> identifiers = new Gson().fromJson(json.getJSONArray(IDENTIFIERS).toString(), new TypeToken<List<String>>() { }.getType()); manifest.setIdentifiers(identifiers); } return manifest; } DocumentConfigurationService(HTTPAgent httpAgentArg, ManifestRepository manifestRepositoryArg, ClientFormRepository clientFormRepositoryArg, DristhiConfiguration
configurationArg); void fetchManifest(); static final String MANIFEST_FORMS_VERSION; static final String FORM_VERSION; static final String CURRENT_FORM_VERSION; static final String IDENTIFIERS; } | @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}"; ManifestDTO manifestDTO = new Gson().fromJson(manifestDTOJson, ManifestDTO.class); Manifest manifest; manifest = documentConfigurationService.convertManifestDTOToManifest(manifestDTO); Assert.assertEquals(manifest.getAppVersion(), manifestDTO.getAppVersion()); Assert.assertEquals(manifest.getCreatedAt(), manifestDTO.getCreatedAt()); JSONObject json = new JSONObject(manifestDTO.getJson()); Assert.assertEquals(manifest.getFormVersion(), json.getString(MANIFEST_FORMS_VERSION)); Assert.assertEquals(manifest.getIdentifiers(), new Gson().fromJson(json.getString(IDENTIFIERS), new TypeToken<List<String>>() { }.getType())); } |
DocumentConfigurationService { protected ClientForm convertClientFormResponseToClientForm(ClientFormResponse clientFormResponse) { ClientForm clientForm = new ClientForm(); clientForm.setId(clientFormResponse.getClientForm().getId()); clientForm.setCreatedAt(clientFormResponse.getClientFormMetadata().getCreatedAt()); clientForm.setIdentifier(clientFormResponse.getClientFormMetadata().getIdentifier()); String jsonString = StringEscapeUtils.unescapeJson(clientFormResponse.getClientForm().getJson()); jsonString = jsonString.substring(1, jsonString.length() - 1); clientForm.setJson(jsonString); clientForm.setVersion(clientFormResponse.getClientFormMetadata().getVersion()); clientForm.setLabel(clientFormResponse.getClientFormMetadata().getLabel()); clientForm.setJurisdiction(clientFormResponse.getClientFormMetadata().getJurisdiction()); clientForm.setModule(clientFormResponse.getClientFormMetadata().getModule()); return clientForm; } DocumentConfigurationService(HTTPAgent httpAgentArg, ManifestRepository manifestRepositoryArg, ClientFormRepository clientFormRepositoryArg, DristhiConfiguration
configurationArg); void fetchManifest(); static final String MANIFEST_FORMS_VERSION; static final String FORM_VERSION; static final String CURRENT_FORM_VERSION; static final String IDENTIFIERS; } | @Test public void convertClientFormResponseToClientForm() throws JSONException { String clientFormResponseJson = "{\"clientForm\":{\"id\":3,\"json\":\"\\\"{\\\\n \\\\\\\"form\\\\\\\": \\\\\\\"ANC Referral\\\\\\\",\\\\n \\\\\\\"count\\\\\\\": \\\\\\\"1\\\\\\\",\\\\n \\\\\\\"encounter_type\\\\\\\": \\\\\\\"ANC Referral\\\\\\\",\\\\n \\\\\\\"entity_id\\\\\\\": \\\\\\\"\\\\\\\",\\\\n \\\\\\\"relational_id\\\\\\\": \\\\\\\"\\\\\\\",\\\\n \\\\\\\"rules_file\\\\\\\": \\\\\\\"rule/general_neat_referral_form_rules.yml\\\\\\\",\\\\n \\\\\\\"metadata\\\\\\\": {\\\\n \\\\\\\"start\\\\\\\": {\\\\n \\\\\\\"openmrs_entity_parent\\\\\\\": \\\\\\\"\\\\\\\",\\\\n \\\\\\\"openmrs_entity\\\\\\\": \\\\\\\"concept\\\\\\\",\\\\n \\\\\\\"openmrs_data_type\\\\\\\": \\\\\\\"start\\\\\\\",\\\\n \\\\\\\"openmrs_entity_id\\\\\\\": \\\\\\\"163137AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\\\\\"\\\\n },\\\\n \\\\\\\"end\\\\\\\": {\\\\n \\\\\\\"openmrs_entity_parent\\\\\\\": \\\\\\\"\\\\\\\",\\\\n \\\\\\\"openmrs_entity\\\\\\\": \\\\\\\"concept\\\\\\\",\\\\n \\\\\\\"openmrs_data_type\\\\\\\": \\\\\\\"end\\\\\\\",\\\\n \\\\\\\"openmrs_entity_id\\\\\\\": \\\\\\\"163138AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\\\\\"\\\\n },\\\\n \\\\\\\"today\\\\\\\": {\\\\n \\\\\\\"openmrs_entity_parent\\\\\\\": \\\\\\\"\\\\\\\",\\\\n \\\\\\\"openmrs_entity\\\\\\\": \\\\\\\"encounter\\\\\\\",\\\\n \\\\\\\"openmrs_entity_id\\\\\\\": \\\\\\\"encounter_date\\\\\\\"\\\\n },\\\\n \\\\\\\"deviceid\\\\\\\": {\\\\n \\\\\\\"openmrs_entity_parent\\\\\\\": \\\\\\\"\\\\\\\",\\\\n \\\\\\\"openmrs_entity\\\\\\\": \\\\\\\"concept\\\\\\\",\\\\n \\\\\\\"openmrs_data_type\\\\\\\": \\\\\\\"deviceid\\\\\\\",\\\\n \\\\\\\"openmrs_entity_id\\\\\\\": \\\\\\\"163149AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\\\\\"\\\\n },\\\\n \\\\\\\"subscriberid\\\\\\\": {\\\\n \\\\\\\"openmrs_entity_parent\\\\\\\": \\\\\\\"\\\\\\\",\\\\n \\\\\\\"openmrs_entity\\\\\\\": \\\\\\\"concept\\\\\\\",\\\\n \\\\\\\"openmrs_data_type\\\\\\\": \\\\\\\"subscriberid\\\\\\\",\\\\n \\\\\\\"openmrs_entity_id\\\\\\\": \\\\\\\"163150AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\\\\\"\\\\n },\\\\n \\\\\\\"simserial\\\\\\\": {\\\\n \\\\\\\"openmrs_entity_parent\\\\\\\": \\\\\\\"\\\\\\\",\\\\n \\\\\\\"openmrs_entity\\\\\\\": \\\\\\\"concept\\\\\\\",\\\\n \\\\\\\"openmrs_data_type\\\\\\\": \\\\\\\"simserial\\\\\\\",\\\\n \\\\\\\"openmrs_entity_id\\\\\\\": \\\\\\\"163151AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\\\\\"\\\\n },\\\\n \\\\\\\"phonenumber\\\\\\\": {\\\\n \\\\\\\"openmrs_entity_parent\\\\\\\": \\\\\\\"\\\\\\\",\\\\n \\\\\\\"openmrs_entity\\\\\\\": \\\\\\\"concept\\\\\\\",\\\\n \\\\\\\"openmrs_data_type\\\\\\\": \\\\\\\"phonenumber\\\\\\\",\\\\n \\\\\\\"openmrs_entity_id\\\\\\\": \\\\\\\"163152AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\\\\\"\\\\n },\\\\n \\\\\\\"encounter_location\\\\\\\": \\\\\\\"\\\\\\\",\\\\n \\\\\\\"look_up\\\\\\\": {\\\\n \\\\\\\"entity_id\\\\\\\": \\\\\\\"\\\\\\\",\\\\n \\\\\\\"value\\\\\\\": \\\\\\\"\\\\\\\"\\\\n }\\\\n },\\\\n \\\\\\\"steps\\\\\\\": [\\\\n {\\\\n \\\\\\\"title\\\\\\\": \\\\\\\"ANC referral form\\\\\\\",\\\\n \\\\\\\"fields\\\\\\\": [\\\\n {\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"chw_referral_service\\\\\\\",\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"invisible\\\\\\\",\\\\n \\\\\\\"properties\\\\\\\": {\\\\n \\\\\\\"text\\\\\\\": \\\\\\\"Choose referral service\\\\\\\"\\\\n },\\\\n \\\\\\\"meta_data\\\\\\\": {\\\\n \\\\\\\"openmrs_entity\\\\\\\": \\\\\\\"concept\\\\\\\",\\\\n \\\\\\\"openmrs_entity_id\\\\\\\": \\\\\\\"09978\\\\\\\",\\\\n \\\\\\\"openmrs_entity_parent\\\\\\\": \\\\\\\"\\\\\\\"\\\\n },\\\\n \\\\\\\"options\\\\\\\": [],\\\\n \\\\\\\"required_status\\\\\\\": \\\\\\\"yes:Please specify referral service\\\\\\\"\\\\n },\\\\n {\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"problem\\\\\\\",\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"multi_choice_checkbox\\\\\\\",\\\\n \\\\\\\"properties\\\\\\\": {\\\\n \\\\\\\"text\\\\\\\": \\\\\\\"Pick condition/problem associated with the client.\\\\\\\"\\\\n },\\\\n \\\\\\\"meta_data\\\\\\\": {\\\\n \\\\\\\"openmrs_entity_parent\\\\\\\": \\\\\\\"\\\\\\\",\\\\n \\\\\\\"openmrs_entity\\\\\\\": \\\\\\\"concept\\\\\\\",\\\\n \\\\\\\"openmrs_entity_id\\\\\\\": \\\\\\\"163182AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\\\\\"\\\\n },\\\\n \\\\\\\"options\\\\\\\": [\\\\n {\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Vaginal_bleeding\\\\\\\",\\\\n \\\\\\\"text\\\\\\\": \\\\\\\"Vaginal bleeding\\\\\\\",\\\\n \\\\\\\"meta_data\\\\\\\": {\\\\n \\\\\\\"openmrs_entity\\\\\\\": \\\\\\\"\\\\\\\",\\\\n \\\\\\\"openmrs_entity_id\\\\\\\": \\\\\\\"147232AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\\\\\",\\\\n \\\\\\\"openmrs_entity_parent\\\\\\\": \\\\\\\"\\\\\\\"\\\\n }\\\\n },\\\\n {\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Discoloured_or_watery_liquid_vaginal_discharge_with_a_bad_smell\\\\\\\",\\\\n \\\\\\\"text\\\\\\\": \\\\\\\"Discoloured or watery, liquid vaginal discharge with a bad smell\\\\\\\",\\\\n \\\\\\\"meta_data\\\\\\\": {\\\\n \\\\\\\"openmrs_entity\\\\\\\": \\\\\\\"\\\\\\\",\\\\n \\\\\\\"openmrs_entity_id\\\\\\\": \\\\\\\"123396AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\\\\\",\\\\n \\\\\\\"openmrs_entity_parent\\\\\\\": \\\\\\\"\\\\\\\"\\\\n }\\\\n },\\\\n {\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"High_blood_pressure\\\\\\\",\\\\n \\\\\\\"text\\\\\\\": \\\\\\\"High blood pressure\\\\\\\",\\\\n \\\\\\\"meta_data\\\\\\\": {\\\\n \\\\\\\"openmrs_entity\\\\\\\": \\\\\\\"\\\\\\\",\\\\n \\\\\\\"openmrs_entity_id\\\\\\\": \\\\\\\"113088AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\\\\\",\\\\n \\\\\\\"openmrs_entity_parent\\\\\\\": \\\\\\\"\\\\\\\"\\\\n }\\\\n },\\\\n {\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Severe_abdominal_pain\\\\\\\",\\\\n \\\\\\\"text\\\\\\\": \\\\\\\"Severe abdominal pain\\\\\\\",\\\\n \\\\\\\"meta_data\\\\\\\": {\\\\n \\\\\\\"openmrs_entity\\\\\\\": \\\\\\\"\\\\\\\",\\\\n \\\\\\\"openmrs_entity_id\\\\\\\": \\\\\\\"165271AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\\\\\",\\\\n \\\\\\\"openmrs_entity_parent\\\\\\\": \\\\\\\"\\\\\\\"\\\\n }\\\\n },\\\\n {\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Severe_anaemia\\\\\\\",\\\\n \\\\\\\"text\\\\\\\": \\\\\\\"Severe anaemia\\\\\\\",\\\\n \\\\\\\"meta_data\\\\\\\": {\\\\n \\\\\\\"openmrs_entity\\\\\\\": \\\\\\\"\\\\\\\",\\\\n \\\\\\\"openmrs_entity_id\\\\\\\": \\\\\\\"162044AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\\\\\",\\\\n \\\\\\\"openmrs_entity_parent\\\\\\\": \\\\\\\"\\\\\\\"\\\\n }\\\\n },\\\\n {\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Convulsions\\\\\\\",\\\\n \\\\\\\"text\\\\\\\": \\\\\\\"Convulsions\\\\\\\",\\\\n \\\\\\\"meta_data\\\\\\\": {\\\\n \\\\\\\"openmrs_entity\\\\\\\": \\\\\\\"\\\\\\\",\\\\n \\\\\\\"openmrs_entity_id\\\\\\\": \\\\\\\"113054AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\\\\\",\\\\n \\\\\\\"openmrs_entity_parent\\\\\\\": \\\\\\\"\\\\\\\"\\\\n }\\\\n },\\\\n {\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"No_movement_unusual_movement_for_a_child_in_the_womb\\\\\\\",\\\\n \\\\\\\"text\\\\\\\": \\\\\\\"No movement / unusual movement for a child in the womb\\\\\\\",\\\\n \\\\\\\"meta_data\\\\\\\": {\\\\n \\\\\\\"openmrs_entity\\\\\\\": \\\\\\\"\\\\\\\",\\\\n \\\\\\\"openmrs_entity_id\\\\\\\": \\\\\\\"113377AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\\\\\",\\\\n \\\\\\\"openmrs_entity_parent\\\\\\\": \\\\\\\"\\\\\\\"\\\\n }\\\\n },\\\\n {\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Pregnancy_pains_before_9_months\\\\\\\",\\\\n \\\\\\\"text\\\\\\\": \\\\\\\"Pregnancy pains before 9 months\\\\\\\",\\\\n \\\\\\\"meta_data\\\\\\\": {\\\\n \\\\\\\"openmrs_entity\\\\\\\": \\\\\\\"\\\\\\\",\\\\n \\\\\\\"openmrs_entity_id\\\\\\\": \\\\\\\"153316AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\\\\\",\\\\n \\\\\\\"openmrs_entity_parent\\\\\\\": \\\\\\\"\\\\\\\"\\\\n }\\\\n },\\\\n {\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Early_age_pregnancy_below_18_years\\\\\\\",\\\\n \\\\\\\"text\\\\\\\": \\\\\\\"Early age pregnancy (below 18 years)\\\\\\\",\\\\n \\\\\\\"meta_data\\\\\\\": {\\\\n \\\\\\\"openmrs_entity\\\\\\\": \\\\\\\"\\\\\\\",\\\\n \\\\\\\"openmrs_entity_id\\\\\\\": \\\\\\\"163119AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\\\\\",\\\\n \\\\\\\"openmrs_entity_parent\\\\\\\": \\\\\\\"\\\\\\\"\\\\n }\\\\n },\\\\n {\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"A_severe_headache_dizziness\\\\\\\",\\\\n \\\\\\\"text\\\\\\\": \\\\\\\"A severe headache / dizziness\\\\\\\",\\\\n \\\\\\\"meta_data\\\\\\\": {\\\\n \\\\\\\"openmrs_entity\\\\\\\": \\\\\\\"\\\\\\\",\\\\n \\\\\\\"openmrs_entity_id\\\\\\\": \\\\\\\"139081AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\\\\\",\\\\n \\\\\\\"openmrs_entity_parent\\\\\\\": \\\\\\\"\\\\\\\"\\\\n }\\\\n },\\\\n {\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Swelling_of_the_face_andor_hands\\\\\\\",\\\\n \\\\\\\"text\\\\\\\": \\\\\\\"Swelling of the face and/or hands\\\\\\\",\\\\n \\\\\\\"meta_data\\\\\\\": {\\\\n \\\\\\\"openmrs_entity\\\\\\\": \\\\\\\"\\\\\\\",\\\\n \\\\\\\"openmrs_entity_id\\\\\\\": \\\\\\\"460AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\\\\\",\\\\n \\\\\\\"openmrs_entity_parent\\\\\\\": \\\\\\\"\\\\\\\"\\\\n }\\\\n },\\\\n {\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Fever\\\\\\\",\\\\n \\\\\\\"text\\\\\\\": \\\\\\\"Fever\\\\\\\",\\\\n \\\\\\\"meta_data\\\\\\\": {\\\\n \\\\\\\"openmrs_entity\\\\\\\": \\\\\\\"\\\\\\\",\\\\n \\\\\\\"openmrs_entity_id\\\\\\\": \\\\\\\"140238AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\\\\\",\\\\n \\\\\\\"openmrs_entity_parent\\\\\\\": \\\\\\\"\\\\\\\"\\\\n }\\\\n },\\\\n {\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Shivering_trembling\\\\\\\",\\\\n \\\\\\\"text\\\\\\\": \\\\\\\"Shivering/trembling\\\\\\\",\\\\n \\\\\\\"meta_data\\\\\\\": {\\\\n \\\\\\\"openmrs_entity\\\\\\\": \\\\\\\"\\\\\\\",\\\\n \\\\\\\"openmrs_entity_id\\\\\\\": \\\\\\\"158359AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\\\\\",\\\\n \\\\\\\"openmrs_entity_parent\\\\\\\": \\\\\\\"\\\\\\\"\\\\n }\\\\n },\\\\n {\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Nausea_and_Vomiting\\\\\\\",\\\\n \\\\\\\"text\\\\\\\": \\\\\\\"Nausea and vomiting\\\\\\\",\\\\n \\\\\\\"meta_data\\\\\\\": {\\\\n \\\\\\\"openmrs_entity\\\\\\\": \\\\\\\"\\\\\\\",\\\\n \\\\\\\"openmrs_entity_id\\\\\\\": \\\\\\\"133473AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\\\\\",\\\\n \\\\\\\"openmrs_entity_parent\\\\\\\": \\\\\\\"\\\\\\\"\\\\n }\\\\n },\\\\n {\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Water_sack_broke_before_contractions\\\\\\\",\\\\n \\\\\\\"text\\\\\\\": \\\\\\\"Water sack broke before contractions\\\\\\\",\\\\n \\\\\\\"meta_data\\\\\\\": {\\\\n \\\\\\\"openmrs_entity\\\\\\\": \\\\\\\"\\\\\\\",\\\\n \\\\\\\"openmrs_entity_id\\\\\\\": \\\\\\\"129211AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\\\\\",\\\\n \\\\\\\"openmrs_entity_parent\\\\\\\": \\\\\\\"\\\\\\\"\\\\n }\\\\n },\\\\n {\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Cord_prolapse\\\\\\\",\\\\n \\\\\\\"text\\\\\\\": \\\\\\\"Cord prolapse\\\\\\\",\\\\n \\\\\\\"meta_data\\\\\\\": {\\\\n \\\\\\\"openmrs_entity\\\\\\\": \\\\\\\"\\\\\\\",\\\\n \\\\\\\"openmrs_entity_id\\\\\\\": \\\\\\\"128419AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\\\\\",\\\\n \\\\\\\"openmrs_entity_parent\\\\\\\": \\\\\\\"\\\\\\\"\\\\n }\\\\n },\\\\n {\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"HIV_care_and_support_services\\\\\\\",\\\\n \\\\\\\"text\\\\\\\": \\\\\\\"HIV care and support services\\\\\\\",\\\\n \\\\\\\"meta_data\\\\\\\": {\\\\n \\\\\\\"openmrs_entity\\\\\\\": \\\\\\\"\\\\\\\",\\\\n \\\\\\\"openmrs_entity_id\\\\\\\": \\\\\\\"159811AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\\\\\",\\\\n \\\\\\\"openmrs_entity_parent\\\\\\\": \\\\\\\"\\\\\\\"\\\\n }\\\\n },\\\\n {\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Family_planning_services\\\\\\\",\\\\n \\\\\\\"text\\\\\\\": \\\\\\\"Family planning services\\\\\\\",\\\\n \\\\\\\"meta_data\\\\\\\": {\\\\n \\\\\\\"openmrs_entity\\\\\\\": \\\\\\\"\\\\\\\",\\\\n \\\\\\\"openmrs_entity_id\\\\\\\": \\\\\\\"5271AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\\\\\",\\\\n \\\\\\\"openmrs_entity_parent\\\\\\\": \\\\\\\"\\\\\\\"\\\\n }\\\\n },\\\\n {\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"PMTCT_for_mothers\\\\\\\",\\\\n \\\\\\\"text\\\\\\\": \\\\\\\"PMTCT for mothers\\\\\\\",\\\\n \\\\\\\"meta_data\\\\\\\": {\\\\n \\\\\\\"openmrs_entity\\\\\\\": \\\\\\\"\\\\\\\",\\\\n \\\\\\\"openmrs_entity_id\\\\\\\": \\\\\\\"160538AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\\\\\",\\\\n \\\\\\\"openmrs_entity_parent\\\\\\\": \\\\\\\"\\\\\\\"\\\\n }\\\\n },\\\\n {\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Fistula\\\\\\\",\\\\n \\\\\\\"text\\\\\\\": \\\\\\\"Fistula\\\\\\\",\\\\n \\\\\\\"meta_data\\\\\\\": {\\\\n \\\\\\\"openmrs_entity\\\\\\\": \\\\\\\"\\\\\\\",\\\\n \\\\\\\"openmrs_entity_id\\\\\\\": \\\\\\\"160854AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\\\\\",\\\\n \\\\\\\"openmrs_entity_parent\\\\\\\": \\\\\\\"\\\\\\\"\\\\n }\\\\n },\\\\n {\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Difficultly_breathing\\\\\\\",\\\\n \\\\\\\"text\\\\\\\": \\\\\\\"Difficultly breathing\\\\\\\",\\\\n \\\\\\\"meta_data\\\\\\\": {\\\\n \\\\\\\"openmrs_entity\\\\\\\": \\\\\\\"\\\\\\\",\\\\n \\\\\\\"openmrs_entity_id\\\\\\\": \\\\\\\"142373AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\\\\\",\\\\n \\\\\\\"openmrs_entity_parent\\\\\\\": \\\\\\\"\\\\\\\"\\\\n }\\\\n },\\\\n {\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Breast_engorgement\\\\\\\",\\\\n \\\\\\\"text\\\\\\\": \\\\\\\"Breast engorgement\\\\\\\",\\\\n \\\\\\\"meta_data\\\\\\\": {\\\\n \\\\\\\"openmrs_entity\\\\\\\": \\\\\\\"\\\\\\\",\\\\n \\\\\\\"openmrs_entity_id\\\\\\\": \\\\\\\"118620AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\\\\\",\\\\n \\\\\\\"openmrs_entity_parent\\\\\\\": \\\\\\\"\\\\\\\"\\\\n }\\\\n },\\\\n {\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Blurred_vision\\\\\\\",\\\\n \\\\\\\"text\\\\\\\": \\\\\\\"Blurred vision\\\\\\\",\\\\n \\\\\\\"meta_data\\\\\\\": {\\\\n \\\\\\\"openmrs_entity\\\\\\\": \\\\\\\"\\\\\\\",\\\\n \\\\\\\"openmrs_entity_id\\\\\\\": \\\\\\\"147104AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\\\\\",\\\\n \\\\\\\"openmrs_entity_parent\\\\\\\": \\\\\\\"\\\\\\\"\\\\n }\\\\n },\\\\n {\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Perineum_tear\\\\\\\",\\\\n \\\\\\\"text\\\\\\\": \\\\\\\"Perineum tear\\\\\\\",\\\\n \\\\\\\"meta_data\\\\\\\": {\\\\n \\\\\\\"openmrs_entity\\\\\\\": \\\\\\\"\\\\\\\",\\\\n \\\\\\\"openmrs_entity_id\\\\\\\": \\\\\\\"136938AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\\\\\",\\\\n \\\\\\\"openmrs_entity_parent\\\\\\\": \\\\\\\"\\\\\\\"\\\\n }\\\\n },\\\\n {\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Pregnancy_confirmation\\\\\\\",\\\\n \\\\\\\"text\\\\\\\": \\\\\\\"Pregnancy confirmation\\\\\\\",\\\\n \\\\\\\"meta_data\\\\\\\": {\\\\n \\\\\\\"openmrs_entity\\\\\\\": \\\\\\\"\\\\\\\",\\\\n \\\\\\\"openmrs_entity_id\\\\\\\": \\\\\\\"152305AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\\\\\",\\\\n \\\\\\\"openmrs_entity_parent\\\\\\\": \\\\\\\"\\\\\\\"\\\\n }\\\\n },\\\\n {\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Other_symptoms\\\\\\\",\\\\n \\\\\\\"text\\\\\\\": \\\\\\\"Other symptoms\\\\\\\",\\\\n \\\\\\\"meta_data\\\\\\\": {\\\\n \\\\\\\"openmrs_entity\\\\\\\": \\\\\\\"\\\\\\\",\\\\n \\\\\\\"openmrs_entity_id\\\\\\\": \\\\\\\"5622AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\\\\\",\\\\n \\\\\\\"openmrs_entity_parent\\\\\\\": \\\\\\\"\\\\\\\"\\\\n }\\\\n }\\\\n ],\\\\n \\\\\\\"required_status\\\\\\\": \\\\\\\"yes:Please specify reason for ANC referral\\\\\\\"\\\\n },\\\\n {\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"problem_other\\\\\\\",\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"text_input_edit_text\\\\\\\",\\\\n \\\\\\\"meta_data\\\\\\\": {\\\\n \\\\\\\"openmrs_entity\\\\\\\": \\\\\\\"concept\\\\\\\",\\\\n \\\\\\\"openmrs_entity_id\\\\\\\": \\\\\\\"160632AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\\\\\",\\\\n \\\\\\\"openmrs_entity_parent\\\\\\\": \\\\\\\"163182AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\\\\\"\\\\n },\\\\n \\\\\\\"properties\\\\\\\": {\\\\n \\\\\\\"hint\\\\\\\": \\\\\\\"Other symptoms\\\\\\\",\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"name\\\\\\\"\\\\n },\\\\n \\\\\\\"required_status\\\\\\\": \\\\\\\"true:Please specify other symptoms\\\\\\\",\\\\n \\\\\\\"subjects\\\\\\\": \\\\\\\"problem:map\\\\\\\"\\\\n },\\\\n {\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"service_before_referral\\\\\\\",\\\\n \\\\\\\"meta_data\\\\\\\": {\\\\n \\\\\\\"openmrs_entity_parent\\\\\\\": \\\\\\\"\\\\\\\",\\\\n \\\\\\\"openmrs_entity\\\\\\\": \\\\\\\"concept\\\\\\\",\\\\n \\\\\\\"openmrs_entity_id\\\\\\\": \\\\\\\"164378AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\\\\\"\\\\n },\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"multi_choice_checkbox\\\\\\\",\\\\n \\\\\\\"is_problem\\\\\\\": false,\\\\n \\\\\\\"properties\\\\\\\": {\\\\n \\\\\\\"text\\\\\\\": \\\\\\\"Pre-referral management given.\\\\\\\"\\\\n },\\\\n \\\\\\\"options\\\\\\\": [\\\\n {\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"ORS\\\\\\\",\\\\n \\\\\\\"text\\\\\\\": \\\\\\\"ORS\\\\\\\",\\\\n \\\\\\\"meta_data\\\\\\\": {\\\\n \\\\\\\"openmrs_entity\\\\\\\": \\\\\\\"\\\\\\\",\\\\n \\\\\\\"openmrs_entity_id\\\\\\\": \\\\\\\"351AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\\\\\",\\\\n \\\\\\\"openmrs_entity_parent\\\\\\\": \\\\\\\"\\\\\\\"\\\\n }\\\\n },\\\\n {\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Panadol\\\\\\\",\\\\n \\\\\\\"text\\\\\\\": \\\\\\\"Panadol\\\\\\\",\\\\n \\\\\\\"meta_data\\\\\\\": {\\\\n \\\\\\\"openmrs_entity\\\\\\\": \\\\\\\"\\\\\\\",\\\\n \\\\\\\"openmrs_entity_id\\\\\\\": \\\\\\\"70116AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\\\\\",\\\\n \\\\\\\"openmrs_entity_parent\\\\\\\": \\\\\\\"\\\\\\\"\\\\n }\\\\n },\\\\n {\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Other_treatment\\\\\\\",\\\\n \\\\\\\"text\\\\\\\": \\\\\\\"Other treatment\\\\\\\",\\\\n \\\\\\\"meta_data\\\\\\\": {\\\\n \\\\\\\"openmrs_entity\\\\\\\": \\\\\\\"\\\\\\\",\\\\n \\\\\\\"openmrs_entity_id\\\\\\\": \\\\\\\"5622AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\\\\\",\\\\n \\\\\\\"openmrs_entity_parent\\\\\\\": \\\\\\\"\\\\\\\"\\\\n }\\\\n },\\\\n {\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"None\\\\\\\",\\\\n \\\\\\\"text\\\\\\\": \\\\\\\"None\\\\\\\",\\\\n \\\\\\\"is_exclusive\\\\\\\": true,\\\\n \\\\\\\"meta_data\\\\\\\": {\\\\n \\\\\\\"openmrs_entity\\\\\\\": \\\\\\\"\\\\\\\",\\\\n \\\\\\\"openmrs_entity_id\\\\\\\": \\\\\\\"164369AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\\\\\",\\\\n \\\\\\\"openmrs_entity_parent\\\\\\\": \\\\\\\"\\\\\\\"\\\\n }\\\\n }\\\\n ],\\\\n \\\\\\\"required_status\\\\\\\": \\\\\\\"Pre-referral management field is required\\\\\\\"\\\\n },\\\\n {\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"service_before_referral_other\\\\\\\",\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"text_input_edit_text\\\\\\\",\\\\n \\\\\\\"meta_data\\\\\\\": {\\\\n \\\\\\\"openmrs_entity\\\\\\\": \\\\\\\"concept\\\\\\\",\\\\n \\\\\\\"openmrs_entity_id\\\\\\\": \\\\\\\"160632AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\\\\\",\\\\n \\\\\\\"openmrs_entity_parent\\\\\\\": \\\\\\\"164378AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\\\\\"\\\\n },\\\\n \\\\\\\"properties\\\\\\\": {\\\\n \\\\\\\"hint\\\\\\\": \\\\\\\"Other Treatment\\\\\\\",\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"name\\\\\\\"\\\\n },\\\\n \\\\\\\"required_status\\\\\\\": \\\\\\\"true:Please specify other treatment given\\\\\\\",\\\\n \\\\\\\"subjects\\\\\\\": \\\\\\\"service_before_referral:map\\\\\\\"\\\\n },\\\\n {\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"chw_referral_hf\\\\\\\",\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"spinner\\\\\\\",\\\\n \\\\\\\"meta_data\\\\\\\": {\\\\n \\\\\\\"openmrs_entity\\\\\\\": \\\\\\\"concept\\\\\\\",\\\\n \\\\\\\"openmrs_entity_id\\\\\\\": \\\\\\\"chw_referral_hf\\\\\\\",\\\\n \\\\\\\"openmrs_entity_parent\\\\\\\": \\\\\\\"\\\\\\\"\\\\n },\\\\n \\\\\\\"properties\\\\\\\": {\\\\n \\\\\\\"text\\\\\\\": \\\\\\\"Choose referral facility\\\\\\\",\\\\n \\\\\\\"searchable\\\\\\\": \\\\\\\"Choose referral facility\\\\\\\"\\\\n },\\\\n \\\\\\\"options\\\\\\\": [],\\\\n \\\\\\\"required_status\\\\\\\": \\\\\\\"yes:Please specify referral facility\\\\\\\"\\\\n },\\\\n {\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"referral_appointment_date\\\\\\\",\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"datetime_picker\\\\\\\",\\\\n \\\\\\\"properties\\\\\\\": {\\\\n \\\\\\\"hint\\\\\\\": \\\\\\\"Please select the appointment date\\\\\\\",\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"date_picker\\\\\\\",\\\\n \\\\\\\"display_format\\\\\\\": \\\\\\\"dd/MM/yyyy\\\\\\\"\\\\n },\\\\n \\\\\\\"meta_data\\\\\\\": {\\\\n \\\\\\\"openmrs_entity\\\\\\\": \\\\\\\"concept\\\\\\\",\\\\n \\\\\\\"openmrs_entity_id\\\\\\\": \\\\\\\"referral_appointment_date\\\\\\\",\\\\n \\\\\\\"openmrs_entity_parent\\\\\\\": \\\\\\\"\\\\\\\"\\\\n },\\\\n \\\\\\\"required_status\\\\\\\": \\\\\\\"true:Please specify the appointment date\\\\\\\"\\\\n },\\\\n {\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"referral_date\\\\\\\",\\\\n \\\\\\\"meta_data\\\\\\\": {\\\\n \\\\\\\"openmrs_entity_parent\\\\\\\": \\\\\\\"\\\\\\\",\\\\n \\\\\\\"openmrs_entity\\\\\\\": \\\\\\\"concept\\\\\\\",\\\\n \\\\\\\"openmrs_entity_id\\\\\\\": \\\\\\\"163181AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\\\\\"\\\\n },\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"hidden\\\\\\\"\\\\n },\\\\n {\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"referral_time\\\\\\\",\\\\n \\\\\\\"meta_data\\\\\\\": {\\\\n \\\\\\\"openmrs_entity_parent\\\\\\\": \\\\\\\"\\\\\\\",\\\\n \\\\\\\"openmrs_entity\\\\\\\": \\\\\\\"concept\\\\\\\",\\\\n \\\\\\\"openmrs_entity_id\\\\\\\": \\\\\\\"referral_time\\\\\\\"\\\\n },\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"hidden\\\\\\\"\\\\n },\\\\n {\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"referral_type\\\\\\\",\\\\n \\\\\\\"openmrs_entity_parent\\\\\\\": \\\\\\\"\\\\\\\",\\\\n \\\\\\\"openmrs_entity\\\\\\\": \\\\\\\"concept\\\\\\\",\\\\n \\\\\\\"openmrs_entity_id\\\\\\\": \\\\\\\"referral_type\\\\\\\",\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"hidden\\\\\\\"\\\\n },\\\\n {\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"referral_status\\\\\\\",\\\\n \\\\\\\"openmrs_entity_parent\\\\\\\": \\\\\\\"\\\\\\\",\\\\n \\\\\\\"openmrs_entity\\\\\\\": \\\\\\\"concept\\\\\\\",\\\\n \\\\\\\"openmrs_entity_id\\\\\\\": \\\\\\\"referral_status\\\\\\\",\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"hidden\\\\\\\"\\\\n }\\\\n ]\\\\n }\\\\n ]\\\\n}\\\"\",\"createdAt\":\"Apr 22, 2020, 7:00:40 PM\"},\"clientFormMetadata\":{\"id\":3,\"identifier\":\"referrals/anc_referral_form\",\"version\":\"0.0.2\",\"label\":\"ANC Referral form\",\"module\":\"ANC\",\"createdAt\":\"Apr 22, 2020, 7:00:40 PM\"}}"; Gson gson = new GsonBuilder().setDateFormat("MMM dd, yyyy, hh:mm:ss aaa").create(); ClientFormResponse clientFormResponse = gson.fromJson(clientFormResponseJson, ClientFormResponse.class); ClientForm clientForm = documentConfigurationService.convertClientFormResponseToClientForm(clientFormResponse); Assert.assertEquals(clientForm.getIdentifier(), clientFormResponse.getClientFormMetadata().getIdentifier()); Assert.assertEquals(clientForm.getCreatedAt(), clientFormResponse.getClientFormMetadata().getCreatedAt()); JSONObject formJson = null; formJson = new JSONObject(clientForm.getJson()); Assert.assertNotNull(formJson); Assert.assertEquals(clientForm.getVersion(), clientFormResponse.getClientFormMetadata().getVersion()); } |
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 = httpAgent.fetch( MessageFormat.format("{0}{1}{2}", baseUrl, CLIENT_FORM_SYNC_URL, "?" + FORM_IDENTIFIER + "=" + identifier + "&" + FORM_VERSION + "=" + formVersion + (latestClientForm == null ? "" : "&" + CURRENT_FORM_VERSION + "=" + latestClientForm.getVersion()))); if (resp.isFailure()) { throw new NoHttpResponseException(CLIENT_FORM_SYNC_URL + " not returned data"); } Gson gson = new GsonBuilder().setDateFormat("MMM dd, yyyy, hh:mm:ss aaa").create(); ClientFormResponse clientFormResponse = gson.fromJson(resp.payload().toString(), ClientFormResponse.class); if (clientFormResponse == null) { throw new NoHttpResponseException(CLIENT_FORM_SYNC_URL + " not returned data"); } if (latestClientForm == null || !clientFormResponse.getClientFormMetadata().getVersion().equals(latestClientForm.getVersion())) { if (latestClientForm != null) { latestClientForm.setActive(false); latestClientForm.setNew(false); clientFormRepository.addOrUpdate(latestClientForm); } ClientForm clientForm = convertClientFormResponseToClientForm(clientFormResponse); saveReceivedClientForm(clientForm); } } DocumentConfigurationService(HTTPAgent httpAgentArg, ManifestRepository manifestRepositoryArg, ClientFormRepository clientFormRepositoryArg, DristhiConfiguration
configurationArg); void fetchManifest(); static final String MANIFEST_FORMS_VERSION; static final String FORM_VERSION; static final String CURRENT_FORM_VERSION; static final String IDENTIFIERS; } | @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 activeManifest = gson.fromJson(manifestJson, Manifest.class); String jsonObject = "{\"clientForm\":{\"id\":3,\"json\":\"\\\"{\\\\n \\\\\\\"form\\\\\\\": \\\\\\\"ANC Referral\\\\\\\",\\\\n \\\\\\\"count\\\\\\\": \\\\\\\"1\\\\\\\",\\\\n \\\\\\\"encounter_type\\\\\\\": \\\\\\\"ANC Referral\\\\\\\",\\\\n \\\\\\\"entity_id\\\\\\\": \\\\\\\"\\\\\\\",\\\\n \\\\\\\"relational_id\\\\\\\": \\\\\\\"\\\\\\\",\\\\n \\\\\\\"rules_file\\\\\\\": \\\\\\\"rule/general_neat_referral_form_rules.yml\\\\\\\",\\\\n \\\\\\\"metadata\\\\\\\": {\\\\n \\\\\\\"start\\\\\\\": {\\\\n \\\\\\\"openmrs_entity_parent\\\\\\\": \\\\\\\"\\\\\\\",\\\\n \\\\\\\"openmrs_entity\\\\\\\": \\\\\\\"concept\\\\\\\",\\\\n \\\\\\\"openmrs_data_type\\\\\\\": \\\\\\\"start\\\\\\\",\\\\n \\\\\\\"openmrs_entity_id\\\\\\\": \\\\\\\"163137AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\\\\\"\\\\n },\\\\n \\\\\\\"end\\\\\\\": {\\\\n \\\\\\\"openmrs_entity_parent\\\\\\\": \\\\\\\"\\\\\\\",\\\\n \\\\\\\"openmrs_entity\\\\\\\": \\\\\\\"concept\\\\\\\",\\\\n \\\\\\\"openmrs_data_type\\\\\\\": \\\\\\\"end\\\\\\\",\\\\n \\\\\\\"openmrs_entity_id\\\\\\\": \\\\\\\"163138AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\\\\\"\\\\n },\\\\n \\\\\\\"today\\\\\\\": {\\\\n \\\\\\\"openmrs_entity_parent\\\\\\\": \\\\\\\"\\\\\\\",\\\\n \\\\\\\"openmrs_entity\\\\\\\": \\\\\\\"encounter\\\\\\\",\\\\n \\\\\\\"openmrs_entity_id\\\\\\\": \\\\\\\"encounter_date\\\\\\\"\\\\n },\\\\n \\\\\\\"deviceid\\\\\\\": {\\\\n \\\\\\\"openmrs_entity_parent\\\\\\\": \\\\\\\"\\\\\\\",\\\\n \\\\\\\"openmrs_entity\\\\\\\": \\\\\\\"concept\\\\\\\",\\\\n \\\\\\\"openmrs_data_type\\\\\\\": \\\\\\\"deviceid\\\\\\\",\\\\n \\\\\\\"openmrs_entity_id\\\\\\\": \\\\\\\"163149AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\\\\\"\\\\n },\\\\n \\\\\\\"subscriberid\\\\\\\": {\\\\n \\\\\\\"openmrs_entity_parent\\\\\\\": \\\\\\\"\\\\\\\",\\\\n \\\\\\\"openmrs_entity\\\\\\\": \\\\\\\"concept\\\\\\\",\\\\n \\\\\\\"openmrs_data_type\\\\\\\": \\\\\\\"subscriberid\\\\\\\",\\\\n \\\\\\\"openmrs_entity_id\\\\\\\": \\\\\\\"163150AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\\\\\"\\\\n },\\\\n \\\\\\\"simserial\\\\\\\": {\\\\n \\\\\\\"openmrs_entity_parent\\\\\\\": \\\\\\\"\\\\\\\",\\\\n \\\\\\\"openmrs_entity\\\\\\\": \\\\\\\"concept\\\\\\\",\\\\n \\\\\\\"openmrs_data_type\\\\\\\": \\\\\\\"simserial\\\\\\\",\\\\n \\\\\\\"openmrs_entity_id\\\\\\\": \\\\\\\"163151AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\\\\\"\\\\n },\\\\n \\\\\\\"phonenumber\\\\\\\": {\\\\n \\\\\\\"openmrs_entity_parent\\\\\\\": \\\\\\\"\\\\\\\",\\\\n \\\\\\\"openmrs_entity\\\\\\\": \\\\\\\"concept\\\\\\\",\\\\n \\\\\\\"openmrs_data_type\\\\\\\": \\\\\\\"phonenumber\\\\\\\",\\\\n \\\\\\\"openmrs_entity_id\\\\\\\": \\\\\\\"163152AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\\\\\"\\\\n },\\\\n \\\\\\\"encounter_location\\\\\\\": \\\\\\\"\\\\\\\",\\\\n \\\\\\\"look_up\\\\\\\": {\\\\n \\\\\\\"entity_id\\\\\\\": \\\\\\\"\\\\\\\",\\\\n \\\\\\\"value\\\\\\\": \\\\\\\"\\\\\\\"\\\\n }\\\\n },\\\\n \\\\\\\"steps\\\\\\\": [\\\\n {\\\\n \\\\\\\"title\\\\\\\": \\\\\\\"ANC referral form\\\\\\\",\\\\n \\\\\\\"fields\\\\\\\": [\\\\n {\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"chw_referral_service\\\\\\\",\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"invisible\\\\\\\",\\\\n \\\\\\\"properties\\\\\\\": {\\\\n \\\\\\\"text\\\\\\\": \\\\\\\"Choose referral service\\\\\\\"\\\\n },\\\\n \\\\\\\"meta_data\\\\\\\": {\\\\n \\\\\\\"openmrs_entity\\\\\\\": \\\\\\\"concept\\\\\\\",\\\\n \\\\\\\"openmrs_entity_id\\\\\\\": \\\\\\\"09978\\\\\\\",\\\\n \\\\\\\"openmrs_entity_parent\\\\\\\": \\\\\\\"\\\\\\\"\\\\n },\\\\n \\\\\\\"options\\\\\\\": [],\\\\n \\\\\\\"required_status\\\\\\\": \\\\\\\"yes:Please specify referral service\\\\\\\"\\\\n },\\\\n {\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"problem\\\\\\\",\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"multi_choice_checkbox\\\\\\\",\\\\n \\\\\\\"properties\\\\\\\": {\\\\n \\\\\\\"text\\\\\\\": \\\\\\\"Pick condition/problem associated with the client.\\\\\\\"\\\\n },\\\\n \\\\\\\"meta_data\\\\\\\": {\\\\n \\\\\\\"openmrs_entity_parent\\\\\\\": \\\\\\\"\\\\\\\",\\\\n \\\\\\\"openmrs_entity\\\\\\\": \\\\\\\"concept\\\\\\\",\\\\n \\\\\\\"openmrs_entity_id\\\\\\\": \\\\\\\"163182AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\\\\\"\\\\n },\\\\n \\\\\\\"options\\\\\\\": [\\\\n {\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Vaginal_bleeding\\\\\\\",\\\\n \\\\\\\"text\\\\\\\": \\\\\\\"Vaginal bleeding\\\\\\\",\\\\n \\\\\\\"meta_data\\\\\\\": {\\\\n \\\\\\\"openmrs_entity\\\\\\\": \\\\\\\"\\\\\\\",\\\\n \\\\\\\"openmrs_entity_id\\\\\\\": \\\\\\\"147232AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\\\\\",\\\\n \\\\\\\"openmrs_entity_parent\\\\\\\": \\\\\\\"\\\\\\\"\\\\n }\\\\n },\\\\n {\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Discoloured_or_watery_liquid_vaginal_discharge_with_a_bad_smell\\\\\\\",\\\\n \\\\\\\"text\\\\\\\": \\\\\\\"Discoloured or watery, liquid vaginal discharge with a bad smell\\\\\\\",\\\\n \\\\\\\"meta_data\\\\\\\": {\\\\n \\\\\\\"openmrs_entity\\\\\\\": \\\\\\\"\\\\\\\",\\\\n \\\\\\\"openmrs_entity_id\\\\\\\": \\\\\\\"123396AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\\\\\",\\\\n \\\\\\\"openmrs_entity_parent\\\\\\\": \\\\\\\"\\\\\\\"\\\\n }\\\\n },\\\\n {\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"High_blood_pressure\\\\\\\",\\\\n \\\\\\\"text\\\\\\\": \\\\\\\"High blood pressure\\\\\\\",\\\\n \\\\\\\"meta_data\\\\\\\": {\\\\n \\\\\\\"openmrs_entity\\\\\\\": \\\\\\\"\\\\\\\",\\\\n \\\\\\\"openmrs_entity_id\\\\\\\": \\\\\\\"113088AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\\\\\",\\\\n \\\\\\\"openmrs_entity_parent\\\\\\\": \\\\\\\"\\\\\\\"\\\\n }\\\\n },\\\\n {\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Severe_abdominal_pain\\\\\\\",\\\\n \\\\\\\"text\\\\\\\": \\\\\\\"Severe abdominal pain\\\\\\\",\\\\n \\\\\\\"meta_data\\\\\\\": {\\\\n \\\\\\\"openmrs_entity\\\\\\\": \\\\\\\"\\\\\\\",\\\\n \\\\\\\"openmrs_entity_id\\\\\\\": \\\\\\\"165271AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\\\\\",\\\\n \\\\\\\"openmrs_entity_parent\\\\\\\": \\\\\\\"\\\\\\\"\\\\n }\\\\n },\\\\n {\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Severe_anaemia\\\\\\\",\\\\n \\\\\\\"text\\\\\\\": \\\\\\\"Severe anaemia\\\\\\\",\\\\n \\\\\\\"meta_data\\\\\\\": {\\\\n \\\\\\\"openmrs_entity\\\\\\\": \\\\\\\"\\\\\\\",\\\\n \\\\\\\"openmrs_entity_id\\\\\\\": \\\\\\\"162044AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\\\\\",\\\\n \\\\\\\"openmrs_entity_parent\\\\\\\": \\\\\\\"\\\\\\\"\\\\n }\\\\n },\\\\n {\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Convulsions\\\\\\\",\\\\n \\\\\\\"text\\\\\\\": \\\\\\\"Convulsions\\\\\\\",\\\\n \\\\\\\"meta_data\\\\\\\": {\\\\n \\\\\\\"openmrs_entity\\\\\\\": \\\\\\\"\\\\\\\",\\\\n \\\\\\\"openmrs_entity_id\\\\\\\": \\\\\\\"113054AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\\\\\",\\\\n \\\\\\\"openmrs_entity_parent\\\\\\\": \\\\\\\"\\\\\\\"\\\\n }\\\\n },\\\\n {\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"No_movement_unusual_movement_for_a_child_in_the_womb\\\\\\\",\\\\n \\\\\\\"text\\\\\\\": \\\\\\\"No movement / unusual movement for a child in the womb\\\\\\\",\\\\n \\\\\\\"meta_data\\\\\\\": {\\\\n \\\\\\\"openmrs_entity\\\\\\\": \\\\\\\"\\\\\\\",\\\\n \\\\\\\"openmrs_entity_id\\\\\\\": \\\\\\\"113377AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\\\\\",\\\\n \\\\\\\"openmrs_entity_parent\\\\\\\": \\\\\\\"\\\\\\\"\\\\n }\\\\n },\\\\n {\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Pregnancy_pains_before_9_months\\\\\\\",\\\\n \\\\\\\"text\\\\\\\": \\\\\\\"Pregnancy pains before 9 months\\\\\\\",\\\\n \\\\\\\"meta_data\\\\\\\": {\\\\n \\\\\\\"openmrs_entity\\\\\\\": \\\\\\\"\\\\\\\",\\\\n \\\\\\\"openmrs_entity_id\\\\\\\": \\\\\\\"153316AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\\\\\",\\\\n \\\\\\\"openmrs_entity_parent\\\\\\\": \\\\\\\"\\\\\\\"\\\\n }\\\\n },\\\\n {\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Early_age_pregnancy_below_18_years\\\\\\\",\\\\n \\\\\\\"text\\\\\\\": \\\\\\\"Early age pregnancy (below 18 years)\\\\\\\",\\\\n \\\\\\\"meta_data\\\\\\\": {\\\\n \\\\\\\"openmrs_entity\\\\\\\": \\\\\\\"\\\\\\\",\\\\n \\\\\\\"openmrs_entity_id\\\\\\\": \\\\\\\"163119AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\\\\\",\\\\n \\\\\\\"openmrs_entity_parent\\\\\\\": \\\\\\\"\\\\\\\"\\\\n }\\\\n },\\\\n {\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"A_severe_headache_dizziness\\\\\\\",\\\\n \\\\\\\"text\\\\\\\": \\\\\\\"A severe headache / dizziness\\\\\\\",\\\\n \\\\\\\"meta_data\\\\\\\": {\\\\n \\\\\\\"openmrs_entity\\\\\\\": \\\\\\\"\\\\\\\",\\\\n \\\\\\\"openmrs_entity_id\\\\\\\": \\\\\\\"139081AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\\\\\",\\\\n \\\\\\\"openmrs_entity_parent\\\\\\\": \\\\\\\"\\\\\\\"\\\\n }\\\\n },\\\\n {\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Swelling_of_the_face_andor_hands\\\\\\\",\\\\n \\\\\\\"text\\\\\\\": \\\\\\\"Swelling of the face and/or hands\\\\\\\",\\\\n \\\\\\\"meta_data\\\\\\\": {\\\\n \\\\\\\"openmrs_entity\\\\\\\": \\\\\\\"\\\\\\\",\\\\n \\\\\\\"openmrs_entity_id\\\\\\\": \\\\\\\"460AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\\\\\",\\\\n \\\\\\\"openmrs_entity_parent\\\\\\\": \\\\\\\"\\\\\\\"\\\\n }\\\\n },\\\\n {\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Fever\\\\\\\",\\\\n \\\\\\\"text\\\\\\\": \\\\\\\"Fever\\\\\\\",\\\\n \\\\\\\"meta_data\\\\\\\": {\\\\n \\\\\\\"openmrs_entity\\\\\\\": \\\\\\\"\\\\\\\",\\\\n \\\\\\\"openmrs_entity_id\\\\\\\": \\\\\\\"140238AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\\\\\",\\\\n \\\\\\\"openmrs_entity_parent\\\\\\\": \\\\\\\"\\\\\\\"\\\\n }\\\\n },\\\\n {\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Shivering_trembling\\\\\\\",\\\\n \\\\\\\"text\\\\\\\": \\\\\\\"Shivering/trembling\\\\\\\",\\\\n \\\\\\\"meta_data\\\\\\\": {\\\\n \\\\\\\"openmrs_entity\\\\\\\": \\\\\\\"\\\\\\\",\\\\n \\\\\\\"openmrs_entity_id\\\\\\\": \\\\\\\"158359AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\\\\\",\\\\n \\\\\\\"openmrs_entity_parent\\\\\\\": \\\\\\\"\\\\\\\"\\\\n }\\\\n },\\\\n {\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Nausea_and_Vomiting\\\\\\\",\\\\n \\\\\\\"text\\\\\\\": \\\\\\\"Nausea and vomiting\\\\\\\",\\\\n \\\\\\\"meta_data\\\\\\\": {\\\\n \\\\\\\"openmrs_entity\\\\\\\": \\\\\\\"\\\\\\\",\\\\n \\\\\\\"openmrs_entity_id\\\\\\\": \\\\\\\"133473AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\\\\\",\\\\n \\\\\\\"openmrs_entity_parent\\\\\\\": \\\\\\\"\\\\\\\"\\\\n }\\\\n },\\\\n {\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Water_sack_broke_before_contractions\\\\\\\",\\\\n \\\\\\\"text\\\\\\\": \\\\\\\"Water sack broke before contractions\\\\\\\",\\\\n \\\\\\\"meta_data\\\\\\\": {\\\\n \\\\\\\"openmrs_entity\\\\\\\": \\\\\\\"\\\\\\\",\\\\n \\\\\\\"openmrs_entity_id\\\\\\\": \\\\\\\"129211AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\\\\\",\\\\n \\\\\\\"openmrs_entity_parent\\\\\\\": \\\\\\\"\\\\\\\"\\\\n }\\\\n },\\\\n {\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Cord_prolapse\\\\\\\",\\\\n \\\\\\\"text\\\\\\\": \\\\\\\"Cord prolapse\\\\\\\",\\\\n \\\\\\\"meta_data\\\\\\\": {\\\\n \\\\\\\"openmrs_entity\\\\\\\": \\\\\\\"\\\\\\\",\\\\n \\\\\\\"openmrs_entity_id\\\\\\\": \\\\\\\"128419AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\\\\\",\\\\n \\\\\\\"openmrs_entity_parent\\\\\\\": \\\\\\\"\\\\\\\"\\\\n }\\\\n },\\\\n {\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"HIV_care_and_support_services\\\\\\\",\\\\n \\\\\\\"text\\\\\\\": \\\\\\\"HIV care and support services\\\\\\\",\\\\n \\\\\\\"meta_data\\\\\\\": {\\\\n \\\\\\\"openmrs_entity\\\\\\\": \\\\\\\"\\\\\\\",\\\\n \\\\\\\"openmrs_entity_id\\\\\\\": \\\\\\\"159811AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\\\\\",\\\\n \\\\\\\"openmrs_entity_parent\\\\\\\": \\\\\\\"\\\\\\\"\\\\n }\\\\n },\\\\n {\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Family_planning_services\\\\\\\",\\\\n \\\\\\\"text\\\\\\\": \\\\\\\"Family planning services\\\\\\\",\\\\n \\\\\\\"meta_data\\\\\\\": {\\\\n \\\\\\\"openmrs_entity\\\\\\\": \\\\\\\"\\\\\\\",\\\\n \\\\\\\"openmrs_entity_id\\\\\\\": \\\\\\\"5271AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\\\\\",\\\\n \\\\\\\"openmrs_entity_parent\\\\\\\": \\\\\\\"\\\\\\\"\\\\n }\\\\n },\\\\n {\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"PMTCT_for_mothers\\\\\\\",\\\\n \\\\\\\"text\\\\\\\": \\\\\\\"PMTCT for mothers\\\\\\\",\\\\n \\\\\\\"meta_data\\\\\\\": {\\\\n \\\\\\\"openmrs_entity\\\\\\\": \\\\\\\"\\\\\\\",\\\\n \\\\\\\"openmrs_entity_id\\\\\\\": \\\\\\\"160538AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\\\\\",\\\\n \\\\\\\"openmrs_entity_parent\\\\\\\": \\\\\\\"\\\\\\\"\\\\n }\\\\n },\\\\n {\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Fistula\\\\\\\",\\\\n \\\\\\\"text\\\\\\\": \\\\\\\"Fistula\\\\\\\",\\\\n \\\\\\\"meta_data\\\\\\\": {\\\\n \\\\\\\"openmrs_entity\\\\\\\": \\\\\\\"\\\\\\\",\\\\n \\\\\\\"openmrs_entity_id\\\\\\\": \\\\\\\"160854AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\\\\\",\\\\n \\\\\\\"openmrs_entity_parent\\\\\\\": \\\\\\\"\\\\\\\"\\\\n }\\\\n },\\\\n {\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Difficultly_breathing\\\\\\\",\\\\n \\\\\\\"text\\\\\\\": \\\\\\\"Difficultly breathing\\\\\\\",\\\\n \\\\\\\"meta_data\\\\\\\": {\\\\n \\\\\\\"openmrs_entity\\\\\\\": \\\\\\\"\\\\\\\",\\\\n \\\\\\\"openmrs_entity_id\\\\\\\": \\\\\\\"142373AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\\\\\",\\\\n \\\\\\\"openmrs_entity_parent\\\\\\\": \\\\\\\"\\\\\\\"\\\\n }\\\\n },\\\\n {\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Breast_engorgement\\\\\\\",\\\\n \\\\\\\"text\\\\\\\": \\\\\\\"Breast engorgement\\\\\\\",\\\\n \\\\\\\"meta_data\\\\\\\": {\\\\n \\\\\\\"openmrs_entity\\\\\\\": \\\\\\\"\\\\\\\",\\\\n \\\\\\\"openmrs_entity_id\\\\\\\": \\\\\\\"118620AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\\\\\",\\\\n \\\\\\\"openmrs_entity_parent\\\\\\\": \\\\\\\"\\\\\\\"\\\\n }\\\\n },\\\\n {\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Blurred_vision\\\\\\\",\\\\n \\\\\\\"text\\\\\\\": \\\\\\\"Blurred vision\\\\\\\",\\\\n \\\\\\\"meta_data\\\\\\\": {\\\\n \\\\\\\"openmrs_entity\\\\\\\": \\\\\\\"\\\\\\\",\\\\n \\\\\\\"openmrs_entity_id\\\\\\\": \\\\\\\"147104AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\\\\\",\\\\n \\\\\\\"openmrs_entity_parent\\\\\\\": \\\\\\\"\\\\\\\"\\\\n }\\\\n },\\\\n {\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Perineum_tear\\\\\\\",\\\\n \\\\\\\"text\\\\\\\": \\\\\\\"Perineum tear\\\\\\\",\\\\n \\\\\\\"meta_data\\\\\\\": {\\\\n \\\\\\\"openmrs_entity\\\\\\\": \\\\\\\"\\\\\\\",\\\\n \\\\\\\"openmrs_entity_id\\\\\\\": \\\\\\\"136938AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\\\\\",\\\\n \\\\\\\"openmrs_entity_parent\\\\\\\": \\\\\\\"\\\\\\\"\\\\n }\\\\n },\\\\n {\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Pregnancy_confirmation\\\\\\\",\\\\n \\\\\\\"text\\\\\\\": \\\\\\\"Pregnancy confirmation\\\\\\\",\\\\n \\\\\\\"meta_data\\\\\\\": {\\\\n \\\\\\\"openmrs_entity\\\\\\\": \\\\\\\"\\\\\\\",\\\\n \\\\\\\"openmrs_entity_id\\\\\\\": \\\\\\\"152305AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\\\\\",\\\\n \\\\\\\"openmrs_entity_parent\\\\\\\": \\\\\\\"\\\\\\\"\\\\n }\\\\n },\\\\n {\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Other_symptoms\\\\\\\",\\\\n \\\\\\\"text\\\\\\\": \\\\\\\"Other symptoms\\\\\\\",\\\\n \\\\\\\"meta_data\\\\\\\": {\\\\n \\\\\\\"openmrs_entity\\\\\\\": \\\\\\\"\\\\\\\",\\\\n \\\\\\\"openmrs_entity_id\\\\\\\": \\\\\\\"5622AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\\\\\",\\\\n \\\\\\\"openmrs_entity_parent\\\\\\\": \\\\\\\"\\\\\\\"\\\\n }\\\\n }\\\\n ],\\\\n \\\\\\\"required_status\\\\\\\": \\\\\\\"yes:Please specify reason for ANC referral\\\\\\\"\\\\n },\\\\n {\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"problem_other\\\\\\\",\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"text_input_edit_text\\\\\\\",\\\\n \\\\\\\"meta_data\\\\\\\": {\\\\n \\\\\\\"openmrs_entity\\\\\\\": \\\\\\\"concept\\\\\\\",\\\\n \\\\\\\"openmrs_entity_id\\\\\\\": \\\\\\\"160632AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\\\\\",\\\\n \\\\\\\"openmrs_entity_parent\\\\\\\": \\\\\\\"163182AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\\\\\"\\\\n },\\\\n \\\\\\\"properties\\\\\\\": {\\\\n \\\\\\\"hint\\\\\\\": \\\\\\\"Other symptoms\\\\\\\",\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"name\\\\\\\"\\\\n },\\\\n \\\\\\\"required_status\\\\\\\": \\\\\\\"true:Please specify other symptoms\\\\\\\",\\\\n \\\\\\\"subjects\\\\\\\": \\\\\\\"problem:map\\\\\\\"\\\\n },\\\\n {\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"service_before_referral\\\\\\\",\\\\n \\\\\\\"meta_data\\\\\\\": {\\\\n \\\\\\\"openmrs_entity_parent\\\\\\\": \\\\\\\"\\\\\\\",\\\\n \\\\\\\"openmrs_entity\\\\\\\": \\\\\\\"concept\\\\\\\",\\\\n \\\\\\\"openmrs_entity_id\\\\\\\": \\\\\\\"164378AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\\\\\"\\\\n },\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"multi_choice_checkbox\\\\\\\",\\\\n \\\\\\\"is_problem\\\\\\\": false,\\\\n \\\\\\\"properties\\\\\\\": {\\\\n \\\\\\\"text\\\\\\\": \\\\\\\"Pre-referral management given.\\\\\\\"\\\\n },\\\\n \\\\\\\"options\\\\\\\": [\\\\n {\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"ORS\\\\\\\",\\\\n \\\\\\\"text\\\\\\\": \\\\\\\"ORS\\\\\\\",\\\\n \\\\\\\"meta_data\\\\\\\": {\\\\n \\\\\\\"openmrs_entity\\\\\\\": \\\\\\\"\\\\\\\",\\\\n \\\\\\\"openmrs_entity_id\\\\\\\": \\\\\\\"351AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\\\\\",\\\\n \\\\\\\"openmrs_entity_parent\\\\\\\": \\\\\\\"\\\\\\\"\\\\n }\\\\n },\\\\n {\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Panadol\\\\\\\",\\\\n \\\\\\\"text\\\\\\\": \\\\\\\"Panadol\\\\\\\",\\\\n \\\\\\\"meta_data\\\\\\\": {\\\\n \\\\\\\"openmrs_entity\\\\\\\": \\\\\\\"\\\\\\\",\\\\n \\\\\\\"openmrs_entity_id\\\\\\\": \\\\\\\"70116AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\\\\\",\\\\n \\\\\\\"openmrs_entity_parent\\\\\\\": \\\\\\\"\\\\\\\"\\\\n }\\\\n },\\\\n {\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Other_treatment\\\\\\\",\\\\n \\\\\\\"text\\\\\\\": \\\\\\\"Other treatment\\\\\\\",\\\\n \\\\\\\"meta_data\\\\\\\": {\\\\n \\\\\\\"openmrs_entity\\\\\\\": \\\\\\\"\\\\\\\",\\\\n \\\\\\\"openmrs_entity_id\\\\\\\": \\\\\\\"5622AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\\\\\",\\\\n \\\\\\\"openmrs_entity_parent\\\\\\\": \\\\\\\"\\\\\\\"\\\\n }\\\\n },\\\\n {\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"None\\\\\\\",\\\\n \\\\\\\"text\\\\\\\": \\\\\\\"None\\\\\\\",\\\\n \\\\\\\"is_exclusive\\\\\\\": true,\\\\n \\\\\\\"meta_data\\\\\\\": {\\\\n \\\\\\\"openmrs_entity\\\\\\\": \\\\\\\"\\\\\\\",\\\\n \\\\\\\"openmrs_entity_id\\\\\\\": \\\\\\\"164369AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\\\\\",\\\\n \\\\\\\"openmrs_entity_parent\\\\\\\": \\\\\\\"\\\\\\\"\\\\n }\\\\n }\\\\n ],\\\\n \\\\\\\"required_status\\\\\\\": \\\\\\\"Pre-referral management field is required\\\\\\\"\\\\n },\\\\n {\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"service_before_referral_other\\\\\\\",\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"text_input_edit_text\\\\\\\",\\\\n \\\\\\\"meta_data\\\\\\\": {\\\\n \\\\\\\"openmrs_entity\\\\\\\": \\\\\\\"concept\\\\\\\",\\\\n \\\\\\\"openmrs_entity_id\\\\\\\": \\\\\\\"160632AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\\\\\",\\\\n \\\\\\\"openmrs_entity_parent\\\\\\\": \\\\\\\"164378AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\\\\\"\\\\n },\\\\n \\\\\\\"properties\\\\\\\": {\\\\n \\\\\\\"hint\\\\\\\": \\\\\\\"Other Treatment\\\\\\\",\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"name\\\\\\\"\\\\n },\\\\n \\\\\\\"required_status\\\\\\\": \\\\\\\"true:Please specify other treatment given\\\\\\\",\\\\n \\\\\\\"subjects\\\\\\\": \\\\\\\"service_before_referral:map\\\\\\\"\\\\n },\\\\n {\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"chw_referral_hf\\\\\\\",\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"spinner\\\\\\\",\\\\n \\\\\\\"meta_data\\\\\\\": {\\\\n \\\\\\\"openmrs_entity\\\\\\\": \\\\\\\"concept\\\\\\\",\\\\n \\\\\\\"openmrs_entity_id\\\\\\\": \\\\\\\"chw_referral_hf\\\\\\\",\\\\n \\\\\\\"openmrs_entity_parent\\\\\\\": \\\\\\\"\\\\\\\"\\\\n },\\\\n \\\\\\\"properties\\\\\\\": {\\\\n \\\\\\\"text\\\\\\\": \\\\\\\"Choose referral facility\\\\\\\",\\\\n \\\\\\\"searchable\\\\\\\": \\\\\\\"Choose referral facility\\\\\\\"\\\\n },\\\\n \\\\\\\"options\\\\\\\": [],\\\\n \\\\\\\"required_status\\\\\\\": \\\\\\\"yes:Please specify referral facility\\\\\\\"\\\\n },\\\\n {\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"referral_appointment_date\\\\\\\",\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"datetime_picker\\\\\\\",\\\\n \\\\\\\"properties\\\\\\\": {\\\\n \\\\\\\"hint\\\\\\\": \\\\\\\"Please select the appointment date\\\\\\\",\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"date_picker\\\\\\\",\\\\n \\\\\\\"display_format\\\\\\\": \\\\\\\"dd/MM/yyyy\\\\\\\"\\\\n },\\\\n \\\\\\\"meta_data\\\\\\\": {\\\\n \\\\\\\"openmrs_entity\\\\\\\": \\\\\\\"concept\\\\\\\",\\\\n \\\\\\\"openmrs_entity_id\\\\\\\": \\\\\\\"referral_appointment_date\\\\\\\",\\\\n \\\\\\\"openmrs_entity_parent\\\\\\\": \\\\\\\"\\\\\\\"\\\\n },\\\\n \\\\\\\"required_status\\\\\\\": \\\\\\\"true:Please specify the appointment date\\\\\\\"\\\\n },\\\\n {\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"referral_date\\\\\\\",\\\\n \\\\\\\"meta_data\\\\\\\": {\\\\n \\\\\\\"openmrs_entity_parent\\\\\\\": \\\\\\\"\\\\\\\",\\\\n \\\\\\\"openmrs_entity\\\\\\\": \\\\\\\"concept\\\\\\\",\\\\n \\\\\\\"openmrs_entity_id\\\\\\\": \\\\\\\"163181AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\\\\\"\\\\n },\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"hidden\\\\\\\"\\\\n },\\\\n {\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"referral_time\\\\\\\",\\\\n \\\\\\\"meta_data\\\\\\\": {\\\\n \\\\\\\"openmrs_entity_parent\\\\\\\": \\\\\\\"\\\\\\\",\\\\n \\\\\\\"openmrs_entity\\\\\\\": \\\\\\\"concept\\\\\\\",\\\\n \\\\\\\"openmrs_entity_id\\\\\\\": \\\\\\\"referral_time\\\\\\\"\\\\n },\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"hidden\\\\\\\"\\\\n },\\\\n {\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"referral_type\\\\\\\",\\\\n \\\\\\\"openmrs_entity_parent\\\\\\\": \\\\\\\"\\\\\\\",\\\\n \\\\\\\"openmrs_entity\\\\\\\": \\\\\\\"concept\\\\\\\",\\\\n \\\\\\\"openmrs_entity_id\\\\\\\": \\\\\\\"referral_type\\\\\\\",\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"hidden\\\\\\\"\\\\n },\\\\n {\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"referral_status\\\\\\\",\\\\n \\\\\\\"openmrs_entity_parent\\\\\\\": \\\\\\\"\\\\\\\",\\\\n \\\\\\\"openmrs_entity\\\\\\\": \\\\\\\"concept\\\\\\\",\\\\n \\\\\\\"openmrs_entity_id\\\\\\\": \\\\\\\"referral_status\\\\\\\",\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"hidden\\\\\\\"\\\\n }\\\\n ]\\\\n }\\\\n ]\\\\n}\\\"\",\"createdAt\":\"Apr 22, 2020, 7:00:40 PM\"},\"clientFormMetadata\":{\"id\":3,\"identifier\":\"referrals/anc_referral_form\",\"version\":\"0.0.2\",\"label\":\"ANC Referral form\",\"module\":\"ANC\",\"createdAt\":\"Apr 22, 2020, 7:00:40 PM\"}}"; Mockito.when(httpAgent.fetch("http: new Response<String>( success, jsonObject)); Mockito.doNothing().when(clientFormRepository).addOrUpdate(Mockito.any(ClientForm.class)); documentConfigurationService.syncClientForms(activeManifest); Mockito.verify(clientFormRepository).addOrUpdate(Mockito.any(ClientForm.class)); } |
DocumentConfigurationService { @VisibleForTesting protected void saveManifestVersion(@NonNull String manifestVersion) { boolean manifestVersionSaved = CoreLibrary.getInstance() .context() .allSharedPreferences() .saveManifestVersion(manifestVersion); if (!manifestVersionSaved) { Timber.e(new Exception("Saving manifest version failed")); } } DocumentConfigurationService(HTTPAgent httpAgentArg, ManifestRepository manifestRepositoryArg, ClientFormRepository clientFormRepositoryArg, DristhiConfiguration
configurationArg); void fetchManifest(); static final String MANIFEST_FORMS_VERSION; static final String FORM_VERSION; static final String CURRENT_FORM_VERSION; static final String IDENTIFIERS; } | @Test public void saveManifestVersionShouldSaveVersionInSharedPreferences() { Assert.assertNull(CoreLibrary.getInstance().context().allSharedPreferences().fetchManifestVersion()); String manifestVersion = "0.0.89"; documentConfigurationService.saveManifestVersion(manifestVersion); Assert.assertEquals(manifestVersion, CoreLibrary.getInstance().context().allSharedPreferences().fetchManifestVersion()); } |
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: " + submission); } else { try { handler.handle(submission); } catch (Exception e) { Log.logError(format("Handling {0} form submission with instance Id: {1} for " + "entity: {2} failed with exception : {3}", submission.formName(), submission.instanceId(), submission.entityId(), ExceptionUtils.getStackTrace(e))); throw e; } } FORM_SUBMITTED.notifyListeners(instanceId); } FormSubmissionRouter(FormDataRepository formDataRepository, ECRegistrationHandler
ecRegistrationHandler, FPComplicationsHandler fpComplicationsHandler, FPChangeHandler
fpChangeHandler, RenewFPProductHandler renewFPProductHandler, ECCloseHandler
ecCloseHandler, ANCRegistrationHandler ancRegistrationHandler,
ANCRegistrationOAHandler ancRegistrationOAHandler,
ANCVisitHandler ancVisitHandler, ANCCloseHandler ancCloseHandler,
TTHandler ttHandler, IFAHandler ifaHandler, HBTestHandler
hbTestHandler, DeliveryOutcomeHandler
deliveryOutcomeHandler, PNCRegistrationOAHandler
pncRegistrationOAHandler, PNCCloseHandler
pncCloseHandler, PNCVisitHandler pncVisitHandler,
ChildImmunizationsHandler childImmunizationsHandler,
ChildRegistrationECHandler childRegistrationECHandler,
ChildRegistrationOAHandler childRegistrationOAHandler,
ChildCloseHandler childCloseHandler, ChildIllnessHandler
childIllnessHandler, VitaminAHandler vitaminAHandler,
DeliveryPlanHandler deliveryPlanHandler, ECEditHandler
ecEditHandler, ANCInvestigationsHandler
ancInvestigationsHandler); void route(String instanceId); Map<String, FormSubmissionHandler> getHandlerMap(); void handleSubmission(FormSubmission submission, String formName); } | @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_SUBMITTED.addListener(formSubmittedListener); router.route("instance id 1"); InOrder inOrder = inOrder(formDataRepository, ecRegistrationHandler, formSubmittedListener); inOrder.verify(formDataRepository).fetchFromSubmission("instance id 1"); inOrder.verify(ecRegistrationHandler).handle(formSubmission); inOrder.verify(formSubmittedListener).onEvent("instance id 1"); }
@Test public void shouldNotifyFormSubmittedListenersWhenThereIsNoHandlerForForm() throws Exception { FormSubmission formSubmission = create().withFormName("form-without-handler").withInstanceId("instance id 1").withVersion("122").build(); when(formDataRepository.fetchFromSubmission("instance id 1")).thenReturn(formSubmission); FORM_SUBMITTED.addListener(formSubmittedListener); router.route("instance id 1"); InOrder inOrder = inOrder(formDataRepository, formSubmittedListener); inOrder.verify(formDataRepository).fetchFromSubmission("instance id 1"); inOrder.verify(formSubmittedListener).onEvent("instance id 1"); }
@Test public void shouldDelegateECRegistrationFormSubmissionHandlingToECRegistrationHandler() throws Exception { FormSubmission formSubmission = create().withFormName("ec_registration").withInstanceId("instance id 1").withVersion("122").build(); when(formDataRepository.fetchFromSubmission("instance id 1")).thenReturn(formSubmission); FORM_SUBMITTED.addListener(formSubmittedListener); router.route("instance id 1"); verify(formDataRepository).fetchFromSubmission("instance id 1"); verify(ecRegistrationHandler).handle(formSubmission); }
@Test public void shouldDelegateFPComplicationsFormSubmissionHandlingToFPComplicationsHandler() throws Exception { FormSubmission formSubmission = create().withFormName("fp_complications").withInstanceId("instance id 2").withVersion("123").build(); when(formDataRepository.fetchFromSubmission("instance id 1")).thenReturn(formSubmission); router.route("instance id 1"); verify(formDataRepository).fetchFromSubmission("instance id 1"); verify(fpComplicationsHandler).handle(formSubmission); }
@Test public void shouldDelegateRenewFPProductFormSubmissionHandlingToRenewFPProductHandler() throws Exception { FormSubmission formSubmission = create().withFormName("renew_fp_product").withInstanceId("instance id 1").withVersion("122").build(); when(formDataRepository.fetchFromSubmission("instance id 1")).thenReturn(formSubmission); router.route("instance id 1"); verify(formDataRepository).fetchFromSubmission("instance id 1"); verify(renewFPProductHandler).handle(formSubmission); }
@Test public void shouldDelegateECCloseFormSubmissionHandlingToECCloseHandler() throws Exception { FormSubmission formSubmission = create().withFormName("ec_close").withInstanceId("instance id 1").withVersion("122").build(); when(formDataRepository.fetchFromSubmission("instance id 1")).thenReturn(formSubmission); router.route("instance id 1"); verify(formDataRepository).fetchFromSubmission("instance id 1"); verify(ecCloseHandler).handle(formSubmission); }
@Test public void shouldDelegateANCRegistrationFormSubmissionHandlingToANCRegistrationHandler() throws Exception { FormSubmission formSubmission = create().withFormName("anc_registration").withInstanceId("instance id 1").withVersion("122").build(); when(formDataRepository.fetchFromSubmission("instance id 1")).thenReturn(formSubmission); router.route("instance id 1"); verify(formDataRepository).fetchFromSubmission("instance id 1"); verify(ancRegistrationHandler).handle(formSubmission); }
@Test public void shouldDelegateANCRegistrationOAFormSubmissionHandlingToANCRegistrationOAHandler() throws Exception { FormSubmission formSubmission = create().withFormName("anc_registration_oa").withInstanceId("instance id 1").withVersion("122").build(); when(formDataRepository.fetchFromSubmission("instance id 1")).thenReturn(formSubmission); router.route("instance id 1"); verify(formDataRepository).fetchFromSubmission("instance id 1"); verify(ancRegistrationOAHandler).handle(formSubmission); }
@Test public void shouldDelegateANCVisitFormSubmissionHandlingToANCVisitHandler() throws Exception { FormSubmission formSubmission = create().withFormName("anc_visit").withInstanceId("instance id 1").withVersion("122").build(); when(formDataRepository.fetchFromSubmission("instance id 1")).thenReturn(formSubmission); router.route("instance id 1"); verify(formDataRepository).fetchFromSubmission("instance id 1"); verify(ancVisitHandler).handle(formSubmission); }
@Test public void shouldDelegateANCCloseFormSubmissionHandlingToANCCloseHandler() throws Exception { FormSubmission formSubmission = create().withFormName("anc_close").withInstanceId("instance id 1").withVersion("122").build(); when(formDataRepository.fetchFromSubmission("instance id 1")).thenReturn(formSubmission); router.route("instance id 1"); verify(formDataRepository).fetchFromSubmission("instance id 1"); verify(ancCloseHandler).handle(formSubmission); }
@Test public void shouldDelegateTTFormSubmissionHandlingToTTHandler() throws Exception { FormSubmission formSubmission = create().withFormName("tt").withInstanceId("instance id 1").withVersion("122").build(); when(formDataRepository.fetchFromSubmission("instance id 1")).thenReturn(formSubmission); router.route("instance id 1"); verify(formDataRepository).fetchFromSubmission("instance id 1"); verify(ttHandler).handle(formSubmission); }
@Test public void shouldDelegateTTBoosterFormSubmissionHandlingToTTHandler() throws Exception { FormSubmission formSubmission = create().withFormName("tt_booster").withInstanceId("instance id 1").withVersion("122").build(); when(formDataRepository.fetchFromSubmission("instance id 1")).thenReturn(formSubmission); router.route("instance id 1"); verify(formDataRepository).fetchFromSubmission("instance id 1"); verify(ttHandler).handle(formSubmission); }
@Test public void shouldDelegateTT1FormSubmissionHandlingToTTHandler() throws Exception { FormSubmission formSubmission = create().withFormName("tt_1").withInstanceId("instance id 1").withVersion("122").build(); when(formDataRepository.fetchFromSubmission("instance id 1")).thenReturn(formSubmission); router.route("instance id 1"); verify(formDataRepository).fetchFromSubmission("instance id 1"); verify(ttHandler).handle(formSubmission); }
@Test public void shouldDelegateTT2FormSubmissionHandlingToTTHandler() throws Exception { FormSubmission formSubmission = create().withFormName("tt_2").withInstanceId("instance id 1").withVersion("122").build(); when(formDataRepository.fetchFromSubmission("instance id 1")).thenReturn(formSubmission); router.route("instance id 1"); verify(formDataRepository).fetchFromSubmission("instance id 1"); verify(ttHandler).handle(formSubmission); }
@Test public void shouldDelegateIFAFormSubmissionHandlingToIFAHandler() throws Exception { FormSubmission formSubmission = create().withFormName("ifa").withInstanceId("instance id 1").withVersion("122").build(); when(formDataRepository.fetchFromSubmission("instance id 1")).thenReturn(formSubmission); router.route("instance id 1"); verify(formDataRepository).fetchFromSubmission("instance id 1"); verify(ifaHandler).handle(formSubmission); }
@Test public void shouldDelegateHBTestFormSubmissionHandlingToHBTestHandler() throws Exception { FormSubmission formSubmission = create().withFormName("hb_test").withInstanceId("instance id 1").withVersion("122").build(); when(formDataRepository.fetchFromSubmission("instance id 1")).thenReturn(formSubmission); router.route("instance id 1"); verify(formDataRepository).fetchFromSubmission("instance id 1"); verify(hbTestHandler).handle(formSubmission); }
@Test public void shouldDelegateDeliveryOutcomeFormSubmissionHandlingToDeliveryOutcomeHandler() throws Exception { FormSubmission formSubmission = create().withFormName("delivery_outcome").withInstanceId("instance id 1").withVersion("122").build(); when(formDataRepository.fetchFromSubmission("instance id 1")).thenReturn(formSubmission); router.route("instance id 1"); verify(formDataRepository).fetchFromSubmission("instance id 1"); verify(deliveryOutcomeHandler).handle(formSubmission); }
@Test public void shouldDelegatePNCRegistrationFormSubmissionHandlingToPNCRegistrationHandler() throws Exception { FormSubmission formSubmission = create().withFormName("pnc_registration_oa").withInstanceId("instance id 1").withVersion("122").build(); when(formDataRepository.fetchFromSubmission("instance id 1")).thenReturn(formSubmission); router.route("instance id 1"); verify(formDataRepository).fetchFromSubmission("instance id 1"); verify(pncRegistrationOAHandler).handle(formSubmission); }
@Test public void shouldDelegatePNCVisitFormSubmissionHandlingToPNCVisitHandler() throws Exception { FormSubmission formSubmission = create().withFormName("pnc_visit").withInstanceId("instance id 1").withVersion("122").build(); when(formDataRepository.fetchFromSubmission("instance id 1")).thenReturn(formSubmission); router.route("instance id 1"); verify(formDataRepository).fetchFromSubmission("instance id 1"); verify(pncVisitHandler).handle(formSubmission); }
@Test public void shouldDelegatePNCCloseFormSubmissionHandlingToPNCCloseHandler() throws Exception { FormSubmission formSubmission = create().withFormName("pnc_close").withInstanceId("instance id 1").withVersion("122").build(); when(formDataRepository.fetchFromSubmission("instance id 1")).thenReturn(formSubmission); router.route("instance id 1"); verify(formDataRepository).fetchFromSubmission("instance id 1"); verify(pncCloseHandler).handle(formSubmission); }
@Test public void shouldDelegateChildImmunizationsFormSubmissionHandlingToChildImmunizationsHandler() throws Exception { FormSubmission formSubmission = create().withFormName("child_immunizations").withInstanceId("instance id 1").withVersion("122").build(); when(formDataRepository.fetchFromSubmission("instance id 1")).thenReturn(formSubmission); router.route("instance id 1"); verify(formDataRepository).fetchFromSubmission("instance id 1"); verify(childImmunizationsHandler).handle(formSubmission); }
@Test public void shouldDelegateChildRegistrationECFormSubmissionHandlingToChildRegistrationECHandler() throws Exception { FormSubmission formSubmission = create().withFormName("child_registration_ec").withInstanceId("instance id 1").withVersion("122").build(); when(formDataRepository.fetchFromSubmission("instance id 1")).thenReturn(formSubmission); router.route("instance id 1"); verify(formDataRepository).fetchFromSubmission("instance id 1"); verify(childRegistrationECHandler).handle(formSubmission); }
@Test public void shouldDelegateChildCloseFormSubmissionHandlingToChildCloseHandler() throws Exception { FormSubmission formSubmission = create().withFormName("child_close").withInstanceId("instance id 1").withVersion("122").build(); when(formDataRepository.fetchFromSubmission("instance id 1")).thenReturn(formSubmission); router.route("instance id 1"); verify(formDataRepository).fetchFromSubmission("instance id 1"); verify(childCloseHandler).handle(formSubmission); }
@Test public void shouldDelegateChildIllnessFormSubmissionHandlingToChildIllnessHandler() throws Exception { FormSubmission formSubmission = create().withFormName("child_illness").withInstanceId("instance id 1").withVersion("122").build(); when(formDataRepository.fetchFromSubmission("instance id 1")).thenReturn(formSubmission); router.route("instance id 1"); verify(formDataRepository).fetchFromSubmission("instance id 1"); verify(childIllnessHandler).handle(formSubmission); }
@Test public void shouldDelegateVitaminAFormSubmissionHandlingToVitaminAHandler() throws Exception { FormSubmission formSubmission = create().withFormName("vitamin_a").withInstanceId("instance id 1").withVersion("122").build(); when(formDataRepository.fetchFromSubmission("instance id 1")).thenReturn(formSubmission); router.route("instance id 1"); verify(formDataRepository).fetchFromSubmission("instance id 1"); verify(vitaminAHandler).handle(formSubmission); }
@Test public void shouldDelegateChildRegistrationOAFormSubmissionHandlingToChildRegistrationOAHandler() throws Exception { FormSubmission formSubmission = create().withFormName("child_registration_oa").withInstanceId("instance id 1").withVersion("122").build(); when(formDataRepository.fetchFromSubmission("instance id 1")).thenReturn(formSubmission); router.route("instance id 1"); verify(formDataRepository).fetchFromSubmission("instance id 1"); verify(childRegistrationOAHandler).handle(formSubmission); }
@Test public void shouldDelegateDeliveryPlanFormSubmissionHandlingToDeliveryPlanHandler() throws Exception { FormSubmission formSubmission = create().withFormName("delivery_plan").withInstanceId("instance id 1").withVersion("122").build(); when(formDataRepository.fetchFromSubmission("instance id 1")).thenReturn(formSubmission); router.route("instance id 1"); verify(formDataRepository).fetchFromSubmission("instance id 1"); verify(deliveryPlanHandler).handle(formSubmission); }
@Test public void shouldDelegateECEditFormSubmissionHandlingToECEditHandler() throws Exception { FormSubmission formSubmission = create().withFormName("ec_edit").withInstanceId("instance id 1").withVersion("122").build(); when(formDataRepository.fetchFromSubmission("instance id 1")).thenReturn(formSubmission); router.route("instance id 1"); verify(formDataRepository).fetchFromSubmission("instance id 1"); verify(ecEditHandler).handle(formSubmission); }
@Test public void shouldDelegateANCInvestigationsFormSubmissionHandlingToANCInvestigationsHandler() throws Exception { FormSubmission formSubmission = create().withFormName("anc_investigations").withInstanceId("instance id 1").withVersion("122").build(); when(formDataRepository.fetchFromSubmission("instance id 1")).thenReturn(formSubmission); router.route("instance id 1"); verify(formDataRepository).fetchFromSubmission("instance id 1"); verify(ancInvestigationsHandler).handle(formSubmission); } |
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); Assert.assertNotNull(value); Assert.assertTrue(value); } |
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(value); Assert.assertTrue(value); } |
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.tryParse("1", "1"), "1.0"); } |
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, String oldCharacter,
String newCharacter); static String humanizeAndDoUPPERCASE(String value); static String humanizeAndUppercase(String value, String... skipTokens); static String getValue(String value); } | @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.junit.Assert.assertEquals("Abc def", org.smartregister.util.StringUtil.humanize("abc_def")); org.junit.Assert.assertEquals("Abc def", org.smartregister.util.StringUtil.humanize("Abc_def")); }
@Test public void assertShouldHandleEmptyAndNull() throws Exception { org.junit.Assert.assertEquals("", org.smartregister.util.StringUtil.humanize("")); } |
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 processResponse(urlConnection); } catch (IOException ex) { Timber.e(ex, "EXCEPTION %s", ex.toString()); return new Response<>(ResponseStatus.failure, null); } } HTTPAgent(Context context, AllSharedPreferences
allSharedPreferences, DristhiConfiguration configuration); Response<String> fetch(String requestURLPath); void invalidateExpiredCachedAccessToken(); Response<String> post(String postURLPath, String jsonPayload); Response<String> postWithJsonResponse(String postURLPath, String jsonPayload); LoginResponse urlCanBeAccessWithGivenCredentials(String requestURL, String userName, char[] password); DownloadStatus downloadFromUrl(String url, String filename); Response<String> fetchWithCredentials(String requestURL, String accessToken); String httpImagePost(String urlString, ProfileImage image); int getReadTimeout(); int getConnectTimeout(); void setConnectTimeout(int connectTimeout); void setReadTimeout(int readTimeout); AccountResponse oauth2authenticateCore(StringBuffer requestParamBuffer, String grantType, String tokenEndpointURL); AccountResponse oauth2authenticate(String username, char[] password, String grantType, String tokenEndpointURL); AccountResponse oauth2authenticateRefreshToken(String refreshToken); LoginResponse fetchUserDetails(String requestURL, String oauthAccessToken); Response<DownloadStatus> downloadFromURL(String downloadURL_, String fileName); boolean verifyAuthorization(); boolean verifyAuthorizationLegacy(); AccountConfiguration fetchOAuthConfiguration(); static final int FILE_UPLOAD_CHUNK_SIZE_BYTES; } | @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.assertEquals(ResponseStatus.success, resp.status()); } |
HTTPAgent { public Response<String> post(String postURLPath, String jsonPayload) { HttpURLConnection urlConnection; try { urlConnection = generatePostRequest(postURLPath, jsonPayload); if (HttpStatus.SC_UNAUTHORIZED == urlConnection.getResponseCode()) { invalidateExpiredCachedAccessToken(); urlConnection = generatePostRequest(postURLPath, jsonPayload); } return processResponse(urlConnection); } catch (IOException ex) { Timber.e(ex, "EXCEPTION: %s", ex.toString()); return new Response<>(ResponseStatus.failure, null); } } HTTPAgent(Context context, AllSharedPreferences
allSharedPreferences, DristhiConfiguration configuration); Response<String> fetch(String requestURLPath); void invalidateExpiredCachedAccessToken(); Response<String> post(String postURLPath, String jsonPayload); Response<String> postWithJsonResponse(String postURLPath, String jsonPayload); LoginResponse urlCanBeAccessWithGivenCredentials(String requestURL, String userName, char[] password); DownloadStatus downloadFromUrl(String url, String filename); Response<String> fetchWithCredentials(String requestURL, String accessToken); String httpImagePost(String urlString, ProfileImage image); int getReadTimeout(); int getConnectTimeout(); void setConnectTimeout(int connectTimeout); void setReadTimeout(int readTimeout); AccountResponse oauth2authenticateCore(StringBuffer requestParamBuffer, String grantType, String tokenEndpointURL); AccountResponse oauth2authenticate(String username, char[] password, String grantType, String tokenEndpointURL); AccountResponse oauth2authenticateRefreshToken(String refreshToken); LoginResponse fetchUserDetails(String requestURL, String oauthAccessToken); Response<DownloadStatus> downloadFromURL(String downloadURL_, String fileName); boolean verifyAuthorization(); boolean verifyAuthorizationLegacy(); AccountConfiguration fetchOAuthConfiguration(); static final int FILE_UPLOAD_CHUNK_SIZE_BYTES; } | @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()); }
@Test public void testPostPassesGivenCorrectUrl() { 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.post("http: Assert.assertEquals(ResponseStatus.success, 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[] credentials = SecurityHelper.toBytes(new StringBuffer(userName).append(':').append(password)); final String basicAuth = AllConstants.HTTP_REQUEST_AUTH_TOKEN_TYPE.BASIC + " " + Base64.encodeToString(credentials, Base64.NO_WRAP); urlConnection.setRequestProperty(AllConstants.HTTP_REQUEST_HEADERS.AUTHORIZATION, basicAuth); int statusCode = urlConnection.getResponseCode(); InputStream inputStream; String responseString = ""; if (statusCode >= HttpStatus.SC_BAD_REQUEST) inputStream = urlConnection.getErrorStream(); else inputStream = urlConnection.getInputStream(); if (inputStream != null) responseString = IOUtils.toString(inputStream); if (statusCode == HttpStatus.SC_OK) { Timber.d("response String: %s using request url %s", responseString, url); LoginResponseData responseData = getResponseBody(responseString); loginResponse = retrieveResponse(responseData); } else if (statusCode == HttpStatus.SC_UNAUTHORIZED) { Timber.e("Invalid credentials for: %s using %s", userName, url); loginResponse = UNAUTHORIZED; } else if (StringUtils.isNotBlank(responseString)) { responseString = StringUtils.substringBetween(responseString, "<p><b>message</b>", "</u></p>"); if (StringUtils.isNotBlank(responseString)) { responseString = responseString.replace("<u>", "").trim(); loginResponse = CUSTOM_SERVER_RESPONSE.withMessage(responseString); } } else { Timber.e("Bad response from Dristhi. Status code: %s username: %s using %s ", statusCode, userName, url); loginResponse = UNKNOWN_RESPONSE; } } catch (MalformedURLException e) { Timber.e(e, "Failed to check credentials bad url %s", url); loginResponse = MALFORMED_URL; } catch (SocketTimeoutException e) { Timber.e(e, "SocketTimeoutException when authenticating %s", userName); loginResponse = TIMEOUT; Timber.e(e, "Failed to check credentials of: %s using %s . Error: %s", userName, url, e.toString()); } catch (IOException e) { Timber.e(e, "Failed to check credentials of: %s using %s . Error: %s", userName, url, e.toString()); loginResponse = NO_INTERNET_CONNECTIVITY; } finally { closeConnection(urlConnection); } return loginResponse; } HTTPAgent(Context context, AllSharedPreferences
allSharedPreferences, DristhiConfiguration configuration); Response<String> fetch(String requestURLPath); void invalidateExpiredCachedAccessToken(); Response<String> post(String postURLPath, String jsonPayload); Response<String> postWithJsonResponse(String postURLPath, String jsonPayload); LoginResponse urlCanBeAccessWithGivenCredentials(String requestURL, String userName, char[] password); DownloadStatus downloadFromUrl(String url, String filename); Response<String> fetchWithCredentials(String requestURL, String accessToken); String httpImagePost(String urlString, ProfileImage image); int getReadTimeout(); int getConnectTimeout(); void setConnectTimeout(int connectTimeout); void setReadTimeout(int readTimeout); AccountResponse oauth2authenticateCore(StringBuffer requestParamBuffer, String grantType, String tokenEndpointURL); AccountResponse oauth2authenticate(String username, char[] password, String grantType, String tokenEndpointURL); AccountResponse oauth2authenticateRefreshToken(String refreshToken); LoginResponse fetchUserDetails(String requestURL, String oauthAccessToken); Response<DownloadStatus> downloadFromURL(String downloadURL_, String fileName); boolean verifyAuthorization(); boolean verifyAuthorizationLegacy(); AccountConfiguration fetchOAuthConfiguration(); static final int FILE_UPLOAD_CHUNK_SIZE_BYTES; } | @Test public void testUrlCanBeAccessWithGivenCredentials() { PowerMockito.mockStatic(Base64.class); LoginResponse resp = httpAgent.urlCanBeAccessWithGivenCredentials("http: Assert.assertEquals(LoginResponse.SUCCESS.message(), resp.message()); }
@Test public void testUrlCanBeAccessWithGivenCredentialsGivenWrongUrl() { PowerMockito.mockStatic(Base64.class); LoginResponse resp = httpAgent.urlCanBeAccessWithGivenCredentials("wrong.url", "", "".toCharArray()); Assert.assertEquals(LoginResponse.MALFORMED_URL.message(), resp.message()); }
@Test public void testUrlCanBeAccessWithGivenCredentialsGivenEmptyResp() { PowerMockito.mockStatic(Base64.class); LoginResponse resp = httpAgent.urlCanBeAccessWithGivenCredentials("http: Assert.assertEquals(LoginResponse.SUCCESS_WITH_EMPTY_RESPONSE.message(), resp.message()); } |
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.BEARER + " ").append(accessToken).toString()); if (HttpStatus.SC_UNAUTHORIZED == urlConnection.getResponseCode()) { AccountAuthenticatorXml authenticatorXml = CoreLibrary.getInstance().getAccountAuthenticatorXml(); AccountHelper.invalidateAuthToken(authenticatorXml.getAccountType(), accessToken); urlConnection = initializeHttp(requestURL, true); } return processResponse(urlConnection); } catch (IOException ex) { Timber.e(ex, "EXCEPTION %s", ex.toString()); return new Response<>(ResponseStatus.failure, null); } } HTTPAgent(Context context, AllSharedPreferences
allSharedPreferences, DristhiConfiguration configuration); Response<String> fetch(String requestURLPath); void invalidateExpiredCachedAccessToken(); Response<String> post(String postURLPath, String jsonPayload); Response<String> postWithJsonResponse(String postURLPath, String jsonPayload); LoginResponse urlCanBeAccessWithGivenCredentials(String requestURL, String userName, char[] password); DownloadStatus downloadFromUrl(String url, String filename); Response<String> fetchWithCredentials(String requestURL, String accessToken); String httpImagePost(String urlString, ProfileImage image); int getReadTimeout(); int getConnectTimeout(); void setConnectTimeout(int connectTimeout); void setReadTimeout(int readTimeout); AccountResponse oauth2authenticateCore(StringBuffer requestParamBuffer, String grantType, String tokenEndpointURL); AccountResponse oauth2authenticate(String username, char[] password, String grantType, String tokenEndpointURL); AccountResponse oauth2authenticateRefreshToken(String refreshToken); LoginResponse fetchUserDetails(String requestURL, String oauthAccessToken); Response<DownloadStatus> downloadFromURL(String downloadURL_, String fileName); boolean verifyAuthorization(); boolean verifyAuthorizationLegacy(); AccountConfiguration fetchOAuthConfiguration(); static final int FILE_UPLOAD_CHUNK_SIZE_BYTES; } | @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); Response<String> resp = httpAgent.fetchWithCredentials("https: Assert.assertEquals(ResponseStatus.success, resp.status()); } |
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.setUseCaches(false); httpUrlConnection.setDoInput(true); httpUrlConnection.setDoOutput(true); httpUrlConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); httpUrlConnection.setChunkedStreamingMode(FILE_UPLOAD_CHUNK_SIZE_BYTES); outputStream = httpUrlConnection.getOutputStream(); writer = getPrintWriter(outputStream); attachImage(writer, image, outputStream); addParameter(writer, "anm-id", image.getAnmId()); addParameter(writer, "entity-id", image.getEntityID()); addParameter(writer, "content-type", image.getContenttype() != null ? image.getContenttype() : "jpeg"); addParameter(writer, "file-category", image.getFilecategory() != null ? image.getFilecategory() : "profilepic"); writer.append(crlf).flush(); writer.append(twoHyphens + boundary + twoHyphens).append(crlf); writer.close(); int status = httpUrlConnection.getResponseCode(); String line; if (status == HttpURLConnection.HTTP_OK) { BufferedReader reader = new BufferedReader(new InputStreamReader( httpUrlConnection.getInputStream())); while ((line = reader.readLine()) != null) { responseString = line; Timber.d("SERVER RESPONSE %s", line); } reader.close(); } else { Timber.e("SERVER RESPONSE %s Server returned non-OK status: %s :-", status, httpUrlConnection.getResponseMessage()); BufferedReader reader = new BufferedReader(new InputStreamReader(httpUrlConnection.getErrorStream())); while ((line = reader.readLine()) != null) { Timber.e("SERVER RESPONSE %s", line); } reader.close(); } } catch (ProtocolException e) { Timber.e(e, "Protocol exception %s", e.toString()); } catch (SocketTimeoutException e) { Timber.e(e, "SocketTimeout %s %s", TIMEOUT, e.toString()); } catch (MalformedURLException e) { Timber.e(e, "MalformedUrl %s %s", MALFORMED_URL, e.toString()); } catch (IOException e) { Timber.e(e, "IOException %s %s", NO_INTERNET_CONNECTIVITY, e.toString()); } finally { closeConnection(httpUrlConnection); } return responseString; } HTTPAgent(Context context, AllSharedPreferences
allSharedPreferences, DristhiConfiguration configuration); Response<String> fetch(String requestURLPath); void invalidateExpiredCachedAccessToken(); Response<String> post(String postURLPath, String jsonPayload); Response<String> postWithJsonResponse(String postURLPath, String jsonPayload); LoginResponse urlCanBeAccessWithGivenCredentials(String requestURL, String userName, char[] password); DownloadStatus downloadFromUrl(String url, String filename); Response<String> fetchWithCredentials(String requestURL, String accessToken); String httpImagePost(String urlString, ProfileImage image); int getReadTimeout(); int getConnectTimeout(); void setConnectTimeout(int connectTimeout); void setReadTimeout(int readTimeout); AccountResponse oauth2authenticateCore(StringBuffer requestParamBuffer, String grantType, String tokenEndpointURL); AccountResponse oauth2authenticate(String username, char[] password, String grantType, String tokenEndpointURL); AccountResponse oauth2authenticateRefreshToken(String refreshToken); LoginResponse fetchUserDetails(String requestURL, String oauthAccessToken); Response<DownloadStatus> downloadFromURL(String downloadURL_, String fileName); boolean verifyAuthorization(); boolean verifyAuthorizationLegacy(); AccountConfiguration fetchOAuthConfiguration(); static final int FILE_UPLOAD_CHUNK_SIZE_BYTES; } | @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); ProfileImage profileImage2 = new ProfileImage(); profileImage2.setFilepath("test"); String resp = httpAgent.httpImagePost("http: Assert.assertEquals("", resp); } |
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(String requestURLPath); void invalidateExpiredCachedAccessToken(); Response<String> post(String postURLPath, String jsonPayload); Response<String> postWithJsonResponse(String postURLPath, String jsonPayload); LoginResponse urlCanBeAccessWithGivenCredentials(String requestURL, String userName, char[] password); DownloadStatus downloadFromUrl(String url, String filename); Response<String> fetchWithCredentials(String requestURL, String accessToken); String httpImagePost(String urlString, ProfileImage image); int getReadTimeout(); int getConnectTimeout(); void setConnectTimeout(int connectTimeout); void setReadTimeout(int readTimeout); AccountResponse oauth2authenticateCore(StringBuffer requestParamBuffer, String grantType, String tokenEndpointURL); AccountResponse oauth2authenticate(String username, char[] password, String grantType, String tokenEndpointURL); AccountResponse oauth2authenticateRefreshToken(String refreshToken); LoginResponse fetchUserDetails(String requestURL, String oauthAccessToken); Response<DownloadStatus> downloadFromURL(String downloadURL_, String fileName); boolean verifyAuthorization(); boolean verifyAuthorizationLegacy(); AccountConfiguration fetchOAuthConfiguration(); static final int FILE_UPLOAD_CHUNK_SIZE_BYTES; } | @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.success, resp.status()); } |
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, DristhiConfiguration configuration); Response<String> fetch(String requestURLPath); void invalidateExpiredCachedAccessToken(); Response<String> post(String postURLPath, String jsonPayload); Response<String> postWithJsonResponse(String postURLPath, String jsonPayload); LoginResponse urlCanBeAccessWithGivenCredentials(String requestURL, String userName, char[] password); DownloadStatus downloadFromUrl(String url, String filename); Response<String> fetchWithCredentials(String requestURL, String accessToken); String httpImagePost(String urlString, ProfileImage image); int getReadTimeout(); int getConnectTimeout(); void setConnectTimeout(int connectTimeout); void setReadTimeout(int readTimeout); AccountResponse oauth2authenticateCore(StringBuffer requestParamBuffer, String grantType, String tokenEndpointURL); AccountResponse oauth2authenticate(String username, char[] password, String grantType, String tokenEndpointURL); AccountResponse oauth2authenticateRefreshToken(String refreshToken); LoginResponse fetchUserDetails(String requestURL, String oauthAccessToken); Response<DownloadStatus> downloadFromURL(String downloadURL_, String fileName); boolean verifyAuthorization(); boolean verifyAuthorizationLegacy(); AccountConfiguration fetchOAuthConfiguration(); static final int FILE_UPLOAD_CHUNK_SIZE_BYTES; } | @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(true).when(dirFile).mkdirs(); Mockito.doReturn(httpsURLConnection).when(httpAgentSpy).getHttpURLConnection(TEST_IMAGE_DOWNLOAD_ENDPOINT); Mockito.doReturn(HttpURLConnection.HTTP_OK).when(httpsURLConnection).getResponseCode(); Mockito.doReturn(inputStream).when(httpsURLConnection).getInputStream(); Mockito.doReturn(bufferedInputStream).when(httpAgentSpy).getBufferedInputStream(inputStream); Mockito.doReturn(1985).when(bufferedInputStream).available(); Mockito.doReturn(-1).when(bufferedInputStream).read(); Mockito.doReturn(fileOutputStream).when(httpAgentSpy).getFileOutputStream(file); DownloadStatus downloadStatus = httpAgentSpy.downloadFromUrl(TEST_IMAGE_DOWNLOAD_ENDPOINT, TEST_FILE_NAME); Assert.assertNotNull(downloadStatus); Assert.assertEquals("Download successful", downloadStatus.displayValue()); Mockito.verify(fileOutputStream).write(ArgumentMatchers.any(byte[].class)); Mockito.verify(fileOutputStream).flush(); Mockito.verify(fileOutputStream).close(); } |
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 collectionType = new TypeToken<List<Action>>() { }.getType(); List<Action> actions; try { actions = new Gson().fromJson(response.payload(), collectionType); } catch (JsonSyntaxException e) { return new Response<List<Action>>(failure, new ArrayList<Action>()); } catch (Exception e) { return new Response<List<Action>>(failure, new ArrayList<Action>()); } return new Response<List<Action>>(response.status(), actions == null ? new ArrayList<Action>() : actions); } DrishtiService(HTTPAgent agent, String drishtiBaseURL); Response<List<Action>> fetchNewActions(String anmIdentifier, String
previouslyFetchedIndex); } | @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(httpAgent).fetch(EXPECTED_URL); Assert.assertEquals(Arrays.asList(ActionBuilder.actionForCreateAlert("Case X", AlertStatus.normal.value(), BeneficiaryType.mother.value(), "Ante Natal Care - Normal", "ANC 1", "2012-01-01", "2012-01-11", "1333695798583"), ActionBuilder.actionForCloseAlert("Case Y", "ANC 1", "2012-01-01", "1333695798644")), actions.payload()); Assert.assertEquals(ResponseStatus.success, actions.status()); }
@Test public void shouldFetchNoAlertActionsWhenJsonIsForEmptyList() throws Exception { Mockito.when(httpAgent.fetch(EXPECTED_URL)).thenReturn(new Response<String>(ResponseStatus.success, "[]")); Response<List<Action>> actions = drishtiService.fetchNewActions("anm1", "0"); Assert.assertTrue(actions.payload().isEmpty()); }
@Test public void shouldFetchNoAlertActionsWhenHTTPCallFails() throws Exception { Mockito.when(httpAgent.fetch(EXPECTED_URL)).thenReturn(new Response<String>(ResponseStatus.failure, null)); Response<List<Action>> actions = drishtiService.fetchNewActions("anm1", "0"); Assert.assertTrue(actions.payload().isEmpty()); Assert.assertEquals(ResponseStatus.failure, actions.status()); }
@Test public void shouldURLEncodeTheANMIdentifierPartWhenItHasASpace() { String expectedURLWithSpaces = "http: Mockito.when(httpAgent.fetch(expectedURLWithSpaces)).thenReturn(new Response<String>(ResponseStatus.success, "[]")); drishtiService.fetchNewActions("ANM WITH SPACE", "0"); Mockito.verify(httpAgent).fetch(expectedURLWithSpaces); }
@Test public void shouldReturnFailureResponseWhenJsonIsMalformed() { String expectedURLWithSpaces = "http: Mockito.when(httpAgent.fetch(expectedURLWithSpaces)).thenReturn(new Response<String>(ResponseStatus.success, "[{\"anmIdentifier\": \"ANMX\", ")); Response<List<Action>> actions = drishtiService.fetchNewActions("ANMX", "0"); Assert.assertTrue(actions.payload().isEmpty()); Assert.assertEquals(ResponseStatus.failure, actions.status()); } |
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); } catch (Exception e) { logError(format("Form submission processing failed, with instanceId: {0}. " + "Exception: {1}, StackTrace: {2}", submission.instanceId(), e.getMessage(), ExceptionUtils.getStackTrace(e))); } } formDataRepository .updateServerVersion(submission.instanceId(), submission.serverVersion()); allSettings.savePreviousFormSyncIndex(submission.serverVersion()); } } FormSubmissionService(ZiggyService ziggyService, FormDataRepository
formDataRepository, AllSettings allSettings); FormSubmissionService(ZiggyService ziggyService, FormDataRepository
formDataRepository, AllSettings allSettings, Map<String, AllCommonsRepository>
allCommonsRepositoryMap); void processSubmissions(List<FormSubmission> formSubmissions); void updateFTSsearch(FormSubmission formSubmission); } | @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()); service.processSubmissions(submissions); String paramsForFirstSubmission = new Gson().toJson( EasyMap.create("instanceId", "instance id 1") .put("entityId", "entity id 1") .put("formName", "form name 1") .put("version", "122") .put("sync_status", SyncStatus.SYNCED.value()) .map()); String paramsForSecondSubmission = new Gson().toJson( EasyMap.create("instanceId", "instance id 2") .put("entityId", "entity id 1") .put("formName", "form name 1") .put("sync_status", SyncStatus.SYNCED.value()) .put("version", "123") .map()); InOrder inOrder = Mockito.inOrder(ziggyService, allSettings, formDataRepository); inOrder.verify(ziggyService).saveForm(paramsForFirstSubmission, "{}"); inOrder.verify(formDataRepository).updateServerVersion("instance id 1", "0"); inOrder.verify(allSettings).savePreviousFormSyncIndex("0"); inOrder.verify(ziggyService).saveForm(paramsForSecondSubmission, "{}"); inOrder.verify(formDataRepository).updateServerVersion("instance id 2", "0"); inOrder.verify(allSettings).savePreviousFormSyncIndex("0"); }
@Test public void shouldNotDelegateProcessingToZiggyServiceForProcessedSubmissions() throws Exception { FormSubmission firstFormSubmission = FormSubmissionBuilder.create().withInstanceId("instance id 1").withVersion("122").build(); FormSubmission secondFormSubmission = FormSubmissionBuilder.create().withInstanceId("instance id 2").withVersion("123").withServerVersion("1").build(); List<FormSubmission> submissions = Arrays.asList(firstFormSubmission, secondFormSubmission); when(formDataRepository.submissionExists("instance id 1")).thenReturn(true); when(formDataRepository.submissionExists("instance id 2")).thenReturn(false); service.processSubmissions(submissions); String paramsForFirstSubmission = new Gson().toJson( EasyMap.create("instanceId", "instance id 1") .put("entityId", "entity id 1") .put("formName", "form name 1") .put("version", "122") .put("sync_status", SyncStatus.SYNCED.value()) .map()); String paramsForSecondSubmission = new Gson().toJson( EasyMap.create("instanceId", "instance id 2") .put("entityId", "entity id 1") .put("formName", "form name 1") .put("version", "123") .put("sync_status", SyncStatus.SYNCED.value()) .map()); InOrder inOrder = Mockito.inOrder(ziggyService, allSettings, formDataRepository); inOrder.verify(ziggyService, Mockito.times(0)).saveForm(paramsForFirstSubmission, "{}"); inOrder.verify(formDataRepository).updateServerVersion("instance id 1", "0"); inOrder.verify(allSettings).savePreviousFormSyncIndex("0"); inOrder.verify(ziggyService).saveForm(paramsForSecondSubmission, "{}"); inOrder.verify(formDataRepository).updateServerVersion("instance id 2", "1"); inOrder.verify(allSettings).savePreviousFormSyncIndex("1"); } |
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 && field.name().equals("id")) { String entityId = field.value(); updateFTSsearch(bindType, entityId); } } List<FormField> fields = form.fields(); if (fields != null && !fields.isEmpty()) { for (FormField field : fields) { String source = field.source(); if (source != null && source.contains(".id")) { String[] sourceArray = source.split("\\."); String innerBindType = sourceArray[sourceArray.length - 2]; if (!bindType.equals(innerBindType)) { String innerEntityId = field.value(); updateFTSsearch(innerBindType, innerEntityId); } } } } List<SubForm> subForms = form.getSub_forms(); if (subForms != null && !subForms.isEmpty()) { for (SubForm subForm : subForms) { String subBindType = subForm.getBindType(); List<Map<String, String>> instances = subForm.instances(); if (instances != null && !instances.isEmpty()) { for (Map<String, String> instance : instances) { String subEntityId = instance.get("id"); updateFTSsearch(subBindType, subEntityId); } } } } } FormSubmissionService(ZiggyService ziggyService, FormDataRepository
formDataRepository, AllSettings allSettings); FormSubmissionService(ZiggyService ziggyService, FormDataRepository
formDataRepository, AllSettings allSettings, Map<String, AllCommonsRepository>
allCommonsRepositoryMap); void processSubmissions(List<FormSubmission> formSubmissions); void updateFTSsearch(FormSubmission formSubmission); } | @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 = mock(FormData.class); when(formSubmission.getForm()).thenReturn(form); when(form.getBind_type()).thenReturn("bindtype1"); FormField field = new FormField("id", "formid1", "bindtype1.id"); List<FormField> fields = Collections.singletonList(field); when(form.fields()).thenReturn(fields); service.updateFTSsearch(formSubmission); verify(allCommonsRepository).updateSearch("formid1"); }
@Test public void testUpdateFTSSearchForInnerBindType() { service = spy(service); Whitebox.setInternalState(service, "allCommonsRepositoryMap", allCommonsRepositoryMap); when(allCommonsRepositoryMap.get("innerBindType")).thenReturn(allCommonsRepository); FormSubmission formSubmission = mock(FormSubmission.class); FormData form = mock(FormData.class); when(formSubmission.getForm()).thenReturn(form); when(form.getBind_type()).thenReturn("bindtype1"); FormField field = new FormField("baseEntityid", "formid1", "innerBindType.id"); List<FormField> fields = Collections.singletonList(field); when(form.fields()).thenReturn(fields); service.updateFTSsearch(formSubmission); verify(allCommonsRepository).updateSearch("formid1"); }
@Test public void testUpdateFTSSearchForSubForms() { String subFormBindType = "subBindType1"; String subFormEntityId = "subEntityId1"; Whitebox.setInternalState(service, "allCommonsRepositoryMap", allCommonsRepositoryMap); when(allCommonsRepositoryMap.get(subFormBindType)).thenReturn(allCommonsRepository); FormSubmission formSubmission = mock(FormSubmission.class); FormData form = mock(FormData.class); when(formSubmission.getForm()).thenReturn(form); when(form.getBind_type()).thenReturn("bindtype1"); SubForm subForm = mock(SubForm.class); when(subForm.getBindType()).thenReturn(subFormBindType); Map<String, String> instance = new HashMap<>(); instance.put("id", subFormEntityId); when(subForm.instances()).thenReturn(Collections.singletonList(instance)); List<SubForm> subforms = Collections.singletonList(subForm); when(form.getSub_forms()).thenReturn(subforms); service.updateFTSsearch(formSubmission); verify(allCommonsRepository).updateSearch(subFormEntityId); } |
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
newCharacter); static String replaceAndHumanizeWithInitCapText(String value, String oldCharacter,
String newCharacter); static String humanizeAndDoUPPERCASE(String value); static String humanizeAndUppercase(String value, String... skipTokens); static String getValue(String value); } | @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.createAlert(alert); updateFtsSearch(alert, false); } } AlertService(AlertRepository repository); AlertService(AlertRepository repository, CommonFtsObject commonFtsObject, Map<String,
AllCommonsRepository> allCommonsRepositoryMap); void create(Action action); void create(Alert alert); void close(Action action); void deleteAll(Action action); List<Alert> findByEntityId(String entityId); List<Alert> findByEntityIdAndAlertNames(String entityId, String... names); List<Alert> findByEntityIdAndOffline(String entityId, String... names); Alert findByEntityIdAndScheduleName(String entityId, String scheduleName); void changeAlertStatusToInProcess(String entityId, String alertName); void changeAlertStatusToComplete(String entityId, String alertName); void deleteAlert(String entityId, String visitCode); void deleteOfflineAlerts(String entityId); void deleteOfflineAlerts(String entityId, String... names); void updateFtsSearchAfterStatusChange(String entityId, String alertName); void updateFtsSearch(Alert alert, boolean statusChange); boolean updateFtsSearchInACR(String bindType, String entityId, String field, String
value); } | @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); Mockito.verify(alertRepository).createAlert(new Alert("Case X", "Schedule 1", "ANC 1", AlertStatus.normal, "2012-01-01", "2012-01-22")); Mockito.verifyNoMoreInteractions(alertRepository); }
@Test public void shouldAddAnAlertIntoAlertRepositoryForECCreateAlertAction() throws Exception { Action actionForEC = ActionBuilder.actionForCreateAlert("Case X", AlertStatus.normal.value(), BeneficiaryType.ec.value(), "Schedule 1", "Milestone 1", "2012-01-01", "2012-01-22", "0"); service.create(actionForEC); Mockito.verify(alertRepository).createAlert(new Alert("Case X", "Schedule 1", "Milestone 1", AlertStatus.normal, "2012-01-01", "2012-01-22")); Mockito.verifyNoMoreInteractions(alertRepository); }
@Test public void shouldAddAnAlertIntoAlertRepositoryForECCreateAlertActionWhenThereIsNoMother() throws Exception { Action actionForEC = ActionBuilder.actionForCreateAlert("Case X", AlertStatus.normal.value(), BeneficiaryType.ec.value(), "Schedule 1", "Milestone 1", "2012-01-01", "2012-01-22", "0"); service.create(actionForEC); Mockito.verify(alertRepository).createAlert(new Alert("Case X", "Schedule 1", "Milestone 1", AlertStatus.normal, "2012-01-01", "2012-01-22")); Mockito.verifyNoMoreInteractions(alertRepository); }
@Test public void shouldNotCreateIfActionIsInactive() throws Exception { Action actionForMother = new Action("Case X", "alert", "createAlert", new HashMap<String, String>(), "0", false, new HashMap<String, String>()); service.create(actionForMother); Mockito.verifyZeroInteractions(alertRepository); }
@Test public void shouldAddAnAlertIntoAlertRepositoryForChildCreateAlertAction() throws Exception { Action actionForMother = ActionBuilder.actionForCreateAlert("Case X", AlertStatus.urgent.value(), BeneficiaryType.child.value(), "Schedule 1", "Milestone 1", "2012-01-01", "2012-01-22", "0"); service.create(actionForMother); Mockito.verify(alertRepository).createAlert(new Alert("Case X", "Schedule 1", "Milestone 1", AlertStatus.urgent, "2012-01-01", "2012-01-22")); Mockito.verifyNoMoreInteractions(alertRepository); }
@Test public void testConstructorWithAlertParam() { Alert alert = new Alert("Case X", "Schedule 1", "ANC 1", AlertStatus.normal, "2012-01-01", "2012-01-22"); service.create(alert); Mockito.verify(alertRepository).createAlert(alert); } |
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 action); void create(Alert alert); void close(Action action); void deleteAll(Action action); List<Alert> findByEntityId(String entityId); List<Alert> findByEntityIdAndAlertNames(String entityId, String... names); List<Alert> findByEntityIdAndOffline(String entityId, String... names); Alert findByEntityIdAndScheduleName(String entityId, String scheduleName); void changeAlertStatusToInProcess(String entityId, String alertName); void changeAlertStatusToComplete(String entityId, String alertName); void deleteAlert(String entityId, String visitCode); void deleteOfflineAlerts(String entityId); void deleteOfflineAlerts(String entityId, String... names); void updateFtsSearchAfterStatusChange(String entityId, String alertName); void updateFtsSearch(Alert alert, boolean statusChange); boolean updateFtsSearchInACR(String bindType, String entityId, String field, String
value); } | @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(alertRepository).deleteAllAlertsForEntity("Case X"); Mockito.verify(alertRepository).deleteAllAlertsForEntity("Case Y"); Mockito.verifyNoMoreInteractions(alertRepository); } |
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(Action action); void create(Alert alert); void close(Action action); void deleteAll(Action action); List<Alert> findByEntityId(String entityId); List<Alert> findByEntityIdAndAlertNames(String entityId, String... names); List<Alert> findByEntityIdAndOffline(String entityId, String... names); Alert findByEntityIdAndScheduleName(String entityId, String scheduleName); void changeAlertStatusToInProcess(String entityId, String alertName); void changeAlertStatusToComplete(String entityId, String alertName); void deleteAlert(String entityId, String visitCode); void deleteOfflineAlerts(String entityId); void deleteOfflineAlerts(String entityId, String... names); void updateFtsSearchAfterStatusChange(String entityId, String alertName); void updateFtsSearch(Alert alert, boolean statusChange); boolean updateFtsSearchInACR(String bindType, String entityId, String field, String
value); } | @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 oldCharacter, String
newCharacter); static String replaceAndHumanizeWithInitCapText(String value, String oldCharacter,
String newCharacter); static String humanizeAndDoUPPERCASE(String value); static String humanizeAndUppercase(String value, String... skipTokens); static String getValue(String value); } | @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,
AllCommonsRepository> allCommonsRepositoryMap); void create(Action action); void create(Alert alert); void close(Action action); void deleteAll(Action action); List<Alert> findByEntityId(String entityId); List<Alert> findByEntityIdAndAlertNames(String entityId, String... names); List<Alert> findByEntityIdAndOffline(String entityId, String... names); Alert findByEntityIdAndScheduleName(String entityId, String scheduleName); void changeAlertStatusToInProcess(String entityId, String alertName); void changeAlertStatusToComplete(String entityId, String alertName); void deleteAlert(String entityId, String visitCode); void deleteOfflineAlerts(String entityId); void deleteOfflineAlerts(String entityId, String... names); void updateFtsSearchAfterStatusChange(String entityId, String alertName); void updateFtsSearch(Alert alert, boolean statusChange); boolean updateFtsSearchInACR(String bindType, String entityId, String field, String
value); } | @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,
AllCommonsRepository> allCommonsRepositoryMap); void create(Action action); void create(Alert alert); void close(Action action); void deleteAll(Action action); List<Alert> findByEntityId(String entityId); List<Alert> findByEntityIdAndAlertNames(String entityId, String... names); List<Alert> findByEntityIdAndOffline(String entityId, String... names); Alert findByEntityIdAndScheduleName(String entityId, String scheduleName); void changeAlertStatusToInProcess(String entityId, String alertName); void changeAlertStatusToComplete(String entityId, String alertName); void deleteAlert(String entityId, String visitCode); void deleteOfflineAlerts(String entityId); void deleteOfflineAlerts(String entityId, String... names); void updateFtsSearchAfterStatusChange(String entityId, String alertName); void updateFtsSearch(Alert alert, boolean statusChange); boolean updateFtsSearchInACR(String bindType, String entityId, String field, String
value); } | @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,
AllCommonsRepository> allCommonsRepositoryMap); void create(Action action); void create(Alert alert); void close(Action action); void deleteAll(Action action); List<Alert> findByEntityId(String entityId); List<Alert> findByEntityIdAndAlertNames(String entityId, String... names); List<Alert> findByEntityIdAndOffline(String entityId, String... names); Alert findByEntityIdAndScheduleName(String entityId, String scheduleName); void changeAlertStatusToInProcess(String entityId, String alertName); void changeAlertStatusToComplete(String entityId, String alertName); void deleteAlert(String entityId, String visitCode); void deleteOfflineAlerts(String entityId); void deleteOfflineAlerts(String entityId, String... names); void updateFtsSearchAfterStatusChange(String entityId, String alertName); void updateFtsSearch(Alert alert, boolean statusChange); boolean updateFtsSearchInACR(String bindType, String entityId, String field, String
value); } | @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 commonFtsObject, Map<String,
AllCommonsRepository> allCommonsRepositoryMap); void create(Action action); void create(Alert alert); void close(Action action); void deleteAll(Action action); List<Alert> findByEntityId(String entityId); List<Alert> findByEntityIdAndAlertNames(String entityId, String... names); List<Alert> findByEntityIdAndOffline(String entityId, String... names); Alert findByEntityIdAndScheduleName(String entityId, String scheduleName); void changeAlertStatusToInProcess(String entityId, String alertName); void changeAlertStatusToComplete(String entityId, String alertName); void deleteAlert(String entityId, String visitCode); void deleteOfflineAlerts(String entityId); void deleteOfflineAlerts(String entityId, String... names); void updateFtsSearchAfterStatusChange(String entityId, String alertName); void updateFtsSearch(Alert alert, boolean statusChange); boolean updateFtsSearchInACR(String bindType, String entityId, String field, String
value); } | @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 commonFtsObject, Map<String,
AllCommonsRepository> allCommonsRepositoryMap); void create(Action action); void create(Alert alert); void close(Action action); void deleteAll(Action action); List<Alert> findByEntityId(String entityId); List<Alert> findByEntityIdAndAlertNames(String entityId, String... names); List<Alert> findByEntityIdAndOffline(String entityId, String... names); Alert findByEntityIdAndScheduleName(String entityId, String scheduleName); void changeAlertStatusToInProcess(String entityId, String alertName); void changeAlertStatusToComplete(String entityId, String alertName); void deleteAlert(String entityId, String visitCode); void deleteOfflineAlerts(String entityId); void deleteOfflineAlerts(String entityId, String... names); void updateFtsSearchAfterStatusChange(String entityId, String alertName); void updateFtsSearch(Alert alert, boolean statusChange); boolean updateFtsSearchInACR(String bindType, String entityId, String field, String
value); } | @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> allCommonsRepositoryMap); void create(Action action); void create(Alert alert); void close(Action action); void deleteAll(Action action); List<Alert> findByEntityId(String entityId); List<Alert> findByEntityIdAndAlertNames(String entityId, String... names); List<Alert> findByEntityIdAndOffline(String entityId, String... names); Alert findByEntityIdAndScheduleName(String entityId, String scheduleName); void changeAlertStatusToInProcess(String entityId, String alertName); void changeAlertStatusToComplete(String entityId, String alertName); void deleteAlert(String entityId, String visitCode); void deleteOfflineAlerts(String entityId); void deleteOfflineAlerts(String entityId, String... names); void updateFtsSearchAfterStatusChange(String entityId, String alertName); void updateFtsSearch(Alert alert, boolean statusChange); boolean updateFtsSearchInACR(String bindType, String entityId, String field, String
value); } | @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(Action action); void create(Alert alert); void close(Action action); void deleteAll(Action action); List<Alert> findByEntityId(String entityId); List<Alert> findByEntityIdAndAlertNames(String entityId, String... names); List<Alert> findByEntityIdAndOffline(String entityId, String... names); Alert findByEntityIdAndScheduleName(String entityId, String scheduleName); void changeAlertStatusToInProcess(String entityId, String alertName); void changeAlertStatusToComplete(String entityId, String alertName); void deleteAlert(String entityId, String visitCode); void deleteOfflineAlerts(String entityId); void deleteOfflineAlerts(String entityId, String... names); void updateFtsSearchAfterStatusChange(String entityId, String alertName); void updateFtsSearch(Alert alert, boolean statusChange); boolean updateFtsSearchInACR(String bindType, String entityId, String field, String
value); } | @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).deleteOfflineAlertsForEntity("Entity 1", "AncAlert"); } |
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) { updateFtsSearch(alert, true); } } } } catch (Exception e) { Log.logError(android.util.Log.getStackTraceString(e)); } } AlertService(AlertRepository repository); AlertService(AlertRepository repository, CommonFtsObject commonFtsObject, Map<String,
AllCommonsRepository> allCommonsRepositoryMap); void create(Action action); void create(Alert alert); void close(Action action); void deleteAll(Action action); List<Alert> findByEntityId(String entityId); List<Alert> findByEntityIdAndAlertNames(String entityId, String... names); List<Alert> findByEntityIdAndOffline(String entityId, String... names); Alert findByEntityIdAndScheduleName(String entityId, String scheduleName); void changeAlertStatusToInProcess(String entityId, String alertName); void changeAlertStatusToComplete(String entityId, String alertName); void deleteAlert(String entityId, String visitCode); void deleteOfflineAlerts(String entityId); void deleteOfflineAlerts(String entityId, String... names); void updateFtsSearchAfterStatusChange(String entityId, String alertName); void updateFtsSearch(Alert alert, boolean statusChange); boolean updateFtsSearchInACR(String bindType, String entityId, String field, String
value); } | @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.updateFtsSearchAfterStatusChange("Entity 1", "AncAlert"); verify(service).updateFtsSearch(alert, true); } |
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.getAlertFilterVisitCodes()); } return false; } AlertService(AlertRepository repository); AlertService(AlertRepository repository, CommonFtsObject commonFtsObject, Map<String,
AllCommonsRepository> allCommonsRepositoryMap); void create(Action action); void create(Alert alert); void close(Action action); void deleteAll(Action action); List<Alert> findByEntityId(String entityId); List<Alert> findByEntityIdAndAlertNames(String entityId, String... names); List<Alert> findByEntityIdAndOffline(String entityId, String... names); Alert findByEntityIdAndScheduleName(String entityId, String scheduleName); void changeAlertStatusToInProcess(String entityId, String alertName); void changeAlertStatusToComplete(String entityId, String alertName); void deleteAlert(String entityId, String visitCode); void deleteOfflineAlerts(String entityId); void deleteOfflineAlerts(String entityId, String... names); void updateFtsSearchAfterStatusChange(String entityId, String alertName); void updateFtsSearch(Alert alert, boolean statusChange); boolean updateFtsSearchInACR(String bindType, String entityId, String field, String
value); } | @Test public void testUpdateFtsSearchInACR() { AllCommonsRepository allCommonsRepository = mock(AllCommonsRepository.class); when(allCommonsRepositoryMap.get("bind 1")).thenReturn(allCommonsRepository); String[] alertFilterVisitCodes = new String[] {"AncFilter"}; when(commonFtsObject.getAlertFilterVisitCodes()).thenReturn(alertFilterVisitCodes); service.updateFtsSearchInACR("bind 1", "Entity 1", "baseEntityId", "id 1"); verify(allCommonsRepository).updateSearch("Entity 1", "baseEntityId", "id 1", alertFilterVisitCodes); } |
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 oldCharacter, String
newCharacter); static String replaceAndHumanizeWithInitCapText(String value, String oldCharacter,
String newCharacter); static String humanizeAndDoUPPERCASE(String value); static String humanizeAndUppercase(String value, String... skipTokens); static String getValue(String value); } | @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 = commonFtsObject.getAlertBindType(scheduleName); if (StringUtils.isNotBlank(bindType) && status != null && StringUtils .isNotBlank(scheduleName) && StringUtils.isNotBlank(entityId)) { String field = scheduleName.replace(" ", "_"); updateFtsSearchInACR(bindType, entityId, field, status.value()); if (!statusChange && StringUtils.isNotBlank(visitCode) && commonFtsObject .alertUpdateVisitCode(scheduleName)) { updateFtsSearchInACR(bindType, entityId, CommonFtsObject.phraseColumn, visitCode); } } } } catch (Exception e) { Log.logError(android.util.Log.getStackTraceString(e)); } } AlertService(AlertRepository repository); AlertService(AlertRepository repository, CommonFtsObject commonFtsObject, Map<String,
AllCommonsRepository> allCommonsRepositoryMap); void create(Action action); void create(Alert alert); void close(Action action); void deleteAll(Action action); List<Alert> findByEntityId(String entityId); List<Alert> findByEntityIdAndAlertNames(String entityId, String... names); List<Alert> findByEntityIdAndOffline(String entityId, String... names); Alert findByEntityIdAndScheduleName(String entityId, String scheduleName); void changeAlertStatusToInProcess(String entityId, String alertName); void changeAlertStatusToComplete(String entityId, String alertName); void deleteAlert(String entityId, String visitCode); void deleteOfflineAlerts(String entityId); void deleteOfflineAlerts(String entityId, String... names); void updateFtsSearchAfterStatusChange(String entityId, String alertName); void updateFtsSearch(Alert alert, boolean statusChange); boolean updateFtsSearchInACR(String bindType, String entityId, String field, String
value); } | @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(true); service.updateFtsSearch(alert, false); verify(service).updateFtsSearchInACR("AncBindType", "Case X", "Schedule_1", AlertStatus.normal.value()); verify(service).updateFtsSearchInACR("AncBindType", "Case X", CommonFtsObject.phraseColumn, "ANC 1"); } |
FormSubmissionSyncService { public void pushToServer() { List<FormSubmission> pendingFormSubmissions = formDataRepository .getPendingFormSubmissions(); if (pendingFormSubmissions.isEmpty()) { return; } String jsonPayload = mapToFormSubmissionDTO(pendingFormSubmissions); Response<String> response = httpAgent .post(format("{0}/{1}", configuration.dristhiBaseURL(), FORM_SUBMISSIONS_PATH), jsonPayload); if (response.isFailure()) { logError(format("Form submissions sync failed. Submissions: {0}", pendingFormSubmissions)); return; } formDataRepository.markFormSubmissionsAsSynced(pendingFormSubmissions); logInfo(format("Form submissions sync successfully. Submissions: {0}", pendingFormSubmissions)); } FormSubmissionSyncService(FormSubmissionService formSubmissionService, HTTPAgent
httpAgent, FormDataRepository formDataRepository, AllSettings allSettings,
AllSharedPreferences allSharedPreferences,
DristhiConfiguration configuration); FetchStatus sync(); void pushToServer(); FetchStatus pullFromServer(); static final String FORM_SUBMISSIONS_PATH; } | @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).fetchRegisteredANM(); Mockito.verify(httpAgent).post("http: Mockito.verify(repository).markFormSubmissionsAsSynced(submissions); }
@Test public void shouldNotMarkPendingSubmissionsAsSyncedIfPostFails() throws Exception { Mockito.when(httpAgent.post("http: .thenReturn(new Response<String>(ResponseStatus.failure, null)); service.pushToServer(); Mockito.verify(repository).getPendingFormSubmissions(); Mockito.verifyNoMoreInteractions(repository); }
@Test public void shouldNotPushIfThereAreNoPendingSubmissions() throws Exception { Mockito.when(repository.getPendingFormSubmissions()).thenReturn(Collections.<FormSubmission>emptyList()); service.pushToServer(); Mockito.verify(repository).getPendingFormSubmissions(); Mockito.verifyNoMoreInteractions(repository); Mockito.verifyZeroInteractions(allSettings); Mockito.verifyZeroInteractions(httpAgent); } |
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}?anm-id={2}×tamp={3}&batch-size={4}", baseURL, FORM_SUBMISSIONS_PATH, anmId, allSettings.fetchPreviousFormSyncIndex(), downloadBatchSize); Response<String> response = httpAgent.fetch(uri); if (response.isFailure()) { logError(format("Form submissions pull failed.")); return fetchedFailed; } List<FormSubmissionDTO> formSubmissions = new Gson() .fromJson(response.payload(), new TypeToken<List<FormSubmissionDTO>>() { }.getType()); if (formSubmissions.isEmpty()) { return dataStatus; } else { formSubmissionService.processSubmissions(toDomain(formSubmissions)); dataStatus = fetched; } } } FormSubmissionSyncService(FormSubmissionService formSubmissionService, HTTPAgent
httpAgent, FormDataRepository formDataRepository, AllSettings allSettings,
AllSharedPreferences allSharedPreferences,
DristhiConfiguration configuration); FetchStatus sync(); void pushToServer(); FetchStatus pullFromServer(); static final String FORM_SUBMISSIONS_PATH; } | @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(new FormSubmission("id 1", "entity id 1", "form name", formInstanceJSON, "123", SyncStatus.SYNCED, "1")); Mockito.when(configuration.syncDownloadBatchSize()).thenReturn(1); Mockito.when(allSettings.fetchPreviousFormSyncIndex()).thenReturn("122"); Mockito.when(httpAgent.fetch("http: .thenReturn(new Response<String>(ResponseStatus.success, new Gson().toJson(this.expectedFormSubmissionsDto)), new Response<String>(ResponseStatus.success, new Gson().toJson(Collections.emptyList()))); FetchStatus fetchStatus = service.pullFromServer(); Assert.assertEquals(FetchStatus.fetched, fetchStatus); Mockito.verify(httpAgent, Mockito.times(2)) .fetch("http: Mockito.verify(formSubmissionService).processSubmissions(expectedFormSubmissions); }
@Test public void shouldReturnNothingFetchedStatusWhenNoFormSubmissionsAreGotFromServer() throws Exception { Mockito.when(configuration.syncDownloadBatchSize()).thenReturn(1); Mockito.when(allSettings.fetchPreviousFormSyncIndex()).thenReturn("122"); Mockito.when(httpAgent.fetch("http: .thenReturn(new Response<String>(ResponseStatus.success, new Gson().toJson(Collections.emptyList()))); FetchStatus fetchStatus = service.pullFromServer(); Assert.assertEquals(FetchStatus.nothingFetched, fetchStatus); Mockito.verify(httpAgent).fetch("http: Mockito.verifyZeroInteractions(formSubmissionService); }
@Test public void shouldNotDelegateToProcessingIfPullFails() throws Exception { Mockito.when(configuration.syncDownloadBatchSize()).thenReturn(1); Mockito.when(allSettings.fetchPreviousFormSyncIndex()).thenReturn("122"); Mockito.when(httpAgent.fetch("http: .thenReturn(new Response<String>(ResponseStatus.failure, null)); FetchStatus fetchStatus = service.pullFromServer(); Assert.assertEquals(FetchStatus.fetchedFailed, fetchStatus); Mockito.verifyZeroInteractions(formSubmissionService); } |
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 sessionArg,
DristhiConfiguration configurationArg, SaveANMLocationTask
saveANMLocationTaskArg, SaveUserInfoTask saveUserInfoTaskArg, SaveANMTeamTask saveANMTeamTaskArg); static TimeZone getServerTimeZone(LoginResponseData userInfo); void initKeyStore(); TimeStatus validateStoredServerTimeZone(); TimeStatus validateDeviceTime(LoginResponseData userInfo, long serverTimeThreshold); boolean isValidLocalLogin(String userName, byte[] password); boolean isUserInValidGroup(final String userName, final char[] password); byte[] getDecryptedAccountValue(String userName, String key); byte[] getDecryptedPassphraseValue(String userName); boolean isUserInPioneerGroup(String userName); LoginResponse fetchUserDetails(String accessToken); AllSharedPreferences getAllSharedPreferences(); Response<String> getLocationInformation(); boolean localLoginWith(String userName); void processLoginResponseDataForUser(String userName, LoginResponseData userInfo); void forceRemoteLogin(String userName); User getUserData(LoginResponseData userInfo); LocationTree getUserLocation(LoginResponseData userInfo); TeamMember getUserTeam(LoginResponseData userInfo); void saveDefaultLocationId(String userName, String locationId); String getUserDefaultTeam(LoginResponseData userInfo); void saveDefaultTeam(String userName, String team); String getUserDefaultTeamId(LoginResponseData userInfo); void saveDefaultTeamId(String userName, String teamId); String getUserDefaultLocationId(LoginResponseData userInfo); String getUserLocationId(LoginResponseData userInfo); void saveUserLocationId(String userName, String locationId); void saveAnmLocation(LocationTree anmLocation); void saveAnmTeam(TeamMember anmTeam); void saveJurisdictions(List<String> jurisdictions); void saveJurisdictionIds(Set<String> jurisdictionIds); Set<String> fetchJurisdictionIds(); void saveOrganizations(TeamMember teamMember); void saveOrganizations(List<Long> organizations); Set<Long> fetchOrganizations(); void saveUserInfo(User user); Bundle saveUserCredentials(String userName, char[] password, LoginResponseData userInfo); boolean hasARegisteredUser(); void logout(); void logoutSession(); boolean hasSessionExpired(); String switchLanguagePreference(); KeyStore getKeyStore(); @Deprecated byte[] getGroupId(String userName); @Deprecated byte[] getGroupId(String userName, KeyStore.PrivateKeyEntry privateKeyEntry); } | @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 userInfoString = AssetHandler.javaToJsonString(user); saveUserInfoTask.save(userInfoString); } UserService(AllSettings allSettingsArg, AllSharedPreferences
allSharedPreferencesArg, HTTPAgent httpAgentArg, Session sessionArg,
DristhiConfiguration configurationArg, SaveANMLocationTask
saveANMLocationTaskArg, SaveUserInfoTask saveUserInfoTaskArg, SaveANMTeamTask saveANMTeamTaskArg); static TimeZone getServerTimeZone(LoginResponseData userInfo); void initKeyStore(); TimeStatus validateStoredServerTimeZone(); TimeStatus validateDeviceTime(LoginResponseData userInfo, long serverTimeThreshold); boolean isValidLocalLogin(String userName, byte[] password); boolean isUserInValidGroup(final String userName, final char[] password); byte[] getDecryptedAccountValue(String userName, String key); byte[] getDecryptedPassphraseValue(String userName); boolean isUserInPioneerGroup(String userName); LoginResponse fetchUserDetails(String accessToken); AllSharedPreferences getAllSharedPreferences(); Response<String> getLocationInformation(); boolean localLoginWith(String userName); void processLoginResponseDataForUser(String userName, LoginResponseData userInfo); void forceRemoteLogin(String userName); User getUserData(LoginResponseData userInfo); LocationTree getUserLocation(LoginResponseData userInfo); TeamMember getUserTeam(LoginResponseData userInfo); void saveDefaultLocationId(String userName, String locationId); String getUserDefaultTeam(LoginResponseData userInfo); void saveDefaultTeam(String userName, String team); String getUserDefaultTeamId(LoginResponseData userInfo); void saveDefaultTeamId(String userName, String teamId); String getUserDefaultLocationId(LoginResponseData userInfo); String getUserLocationId(LoginResponseData userInfo); void saveUserLocationId(String userName, String locationId); void saveAnmLocation(LocationTree anmLocation); void saveAnmTeam(TeamMember anmTeam); void saveJurisdictions(List<String> jurisdictions); void saveJurisdictionIds(Set<String> jurisdictionIds); Set<String> fetchJurisdictionIds(); void saveOrganizations(TeamMember teamMember); void saveOrganizations(List<Long> organizations); Set<Long> fetchOrganizations(); void saveUserInfo(User user); Bundle saveUserCredentials(String userName, char[] password, LoginResponseData userInfo); boolean hasARegisteredUser(); void logout(); void logoutSession(); boolean hasSessionExpired(); String switchLanguagePreference(); KeyStore getKeyStore(); @Deprecated byte[] getGroupId(String userName); @Deprecated byte[] getGroupId(String userName, KeyStore.PrivateKeyEntry privateKeyEntry); } | @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).save(userInfoString); } |
UserService { public void saveAnmLocation(LocationTree anmLocation) { String amnLocationString = AssetHandler.javaToJsonString(anmLocation); saveANMLocationTask.save(amnLocationString); } UserService(AllSettings allSettingsArg, AllSharedPreferences
allSharedPreferencesArg, HTTPAgent httpAgentArg, Session sessionArg,
DristhiConfiguration configurationArg, SaveANMLocationTask
saveANMLocationTaskArg, SaveUserInfoTask saveUserInfoTaskArg, SaveANMTeamTask saveANMTeamTaskArg); static TimeZone getServerTimeZone(LoginResponseData userInfo); void initKeyStore(); TimeStatus validateStoredServerTimeZone(); TimeStatus validateDeviceTime(LoginResponseData userInfo, long serverTimeThreshold); boolean isValidLocalLogin(String userName, byte[] password); boolean isUserInValidGroup(final String userName, final char[] password); byte[] getDecryptedAccountValue(String userName, String key); byte[] getDecryptedPassphraseValue(String userName); boolean isUserInPioneerGroup(String userName); LoginResponse fetchUserDetails(String accessToken); AllSharedPreferences getAllSharedPreferences(); Response<String> getLocationInformation(); boolean localLoginWith(String userName); void processLoginResponseDataForUser(String userName, LoginResponseData userInfo); void forceRemoteLogin(String userName); User getUserData(LoginResponseData userInfo); LocationTree getUserLocation(LoginResponseData userInfo); TeamMember getUserTeam(LoginResponseData userInfo); void saveDefaultLocationId(String userName, String locationId); String getUserDefaultTeam(LoginResponseData userInfo); void saveDefaultTeam(String userName, String team); String getUserDefaultTeamId(LoginResponseData userInfo); void saveDefaultTeamId(String userName, String teamId); String getUserDefaultLocationId(LoginResponseData userInfo); String getUserLocationId(LoginResponseData userInfo); void saveUserLocationId(String userName, String locationId); void saveAnmLocation(LocationTree anmLocation); void saveAnmTeam(TeamMember anmTeam); void saveJurisdictions(List<String> jurisdictions); void saveJurisdictionIds(Set<String> jurisdictionIds); Set<String> fetchJurisdictionIds(); void saveOrganizations(TeamMember teamMember); void saveOrganizations(List<Long> organizations); Set<Long> fetchOrganizations(); void saveUserInfo(User user); Bundle saveUserCredentials(String userName, char[] password, LoginResponseData userInfo); boolean hasARegisteredUser(); void logout(); void logoutSession(); boolean hasSessionExpired(); String switchLanguagePreference(); KeyStore getKeyStore(); @Deprecated byte[] getGroupId(String userName); @Deprecated byte[] getGroupId(String userName, KeyStore.PrivateKeyEntry privateKeyEntry); } | @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"); location.setLocationId("Test location ID"); locationTree.addLocation(location); userService.saveAnmLocation(locationTree); String locationString = AssetHandler.javaToJsonString(locationTree); verify(saveANMLocationTask).save(locationString); } |
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> events = new ArrayList<>(); List<Client> clients = new ArrayList<>(); List<Map<String, String>> savedEventClients = new ArrayList<>(); Cursor cursor = null; try { cursor = database.rawQuery(query, params); int columncount = cursor.getColumnCount(); while (cursor.moveToNext()) { Map<String, String> details = new HashMap<>(); for (int i = 0; i < columncount; i++) { details.put(cursor.getColumnName(i), cursor.getString(i)); } savedEventClients.add(details); } } catch (Exception e) { Timber.e(e); } finally { if (cursor != null) { cursor.close(); } } for (Map<String, String> details : savedEventClients) { String entityId = details.get("base_entity_id"); Event event = new Event(); event.withBaseEntityId(entityId) .withEventType(eventType) .withEntityType(entityType) .withFormSubmissionId(UUID.randomUUID().toString()) .withSyncStatus(BaseRepository.TYPE_Unsynced) .withDateCreated(new Date()); Client client = new Client(entityId).withSyncStatus(BaseRepository.TYPE_Unsynced); boolean eventChanged = false; boolean clientChanged = false; for (Column column : table.columns) { String value = details.get(column.column_name); if (StringUtils.isBlank(value)) { continue; } if (EventClientRepository.Table.event.name().equalsIgnoreCase(column.type)) { populateEvent(column, value, event); eventChanged = true; } else { populateClient(column, value, client); clientChanged = true; } } if (eventChanged) { tagEvent(event, formTag); events.add(event); } if (clientChanged) { clients.add(client); } } return new Pair<>(events, clients); } Pair<List<Event>, List<Client>> createEventAndClients(SQLiteDatabase database, String tablename, String query, String[] params, String eventType, String entityType, FormTag formTag); void saveEventAndClients(Pair<List<Event>, List<Client>> eventClients, SQLiteDatabase sqLiteDatabase); } | @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, query, params, "FamilyRegistration", "Family", formTag); assertNotNull(eventsAndClients); assertEquals(3, eventsAndClients.first.size()); assertEquals(3, eventsAndClients.second.size()); Event event1 = eventsAndClients.first.get(0); Client client1 = eventsAndClients.second.get(0); assertEquals("person12", client1.getBaseEntityId()); assertEquals("12", client1.getIdentifiers().get("opensrp_id")); assertEquals("family10", client1.getRelationships().get("family").get(0)); assertEquals("Jane", client1.getFirstName()); assertEquals("Doe", client1.getLastName()); assertEquals("23", client1.getAttribute("residence")); assertEquals(0, new DateTime("1993-10-21T07:00:00.000+07:00").toDate().compareTo(client1.getBirthdate())); assertEquals("person12", event1.getBaseEntityId()); assertEquals("Screening", event1.getEventType()); assertEquals("FamilyMember", event1.getEntityType()); assertEquals(2, event1.getObs().size()); assertEquals("163084AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", event1.getObs().get(0).getFieldCode()); assertEquals("1230", event1.getObs().get(0).getValue()); assertEquals("sleeps_outdoors", event1.getObs().get(1).getFieldCode()); assertEquals("no", event1.getObs().get(1).getValue()); assertEquals("12383", event1.getDetails().get("task_identifier")); assertEquals(formTag.locationId, event1.getLocationId()); }
@Test public void testCreateEventAndClientsForMissingTable() { when(clientProcessor.getColumnMappings(tableName)).thenReturn(null); Pair<List<Event>, List<Client>> eventsAndClients = recreateECUtil.createEventAndClients(database, tableName, query, params, "FamilyRegistration", "Family", formTag); assertNull(eventsAndClients); verifyZeroInteractions(database); verify(clientProcessor).getColumnMappings(tableName); } |
UserService { public boolean isValidLocalLogin(String userName, byte[] password) { return allSharedPreferences.fetchRegisteredANM().equals(userName) && DrishtiApplication.getInstance().getRepository() .canUseThisPassword(password) && !allSharedPreferences.fetchForceRemoteLogin(userName); } UserService(AllSettings allSettingsArg, AllSharedPreferences
allSharedPreferencesArg, HTTPAgent httpAgentArg, Session sessionArg,
DristhiConfiguration configurationArg, SaveANMLocationTask
saveANMLocationTaskArg, SaveUserInfoTask saveUserInfoTaskArg, SaveANMTeamTask saveANMTeamTaskArg); static TimeZone getServerTimeZone(LoginResponseData userInfo); void initKeyStore(); TimeStatus validateStoredServerTimeZone(); TimeStatus validateDeviceTime(LoginResponseData userInfo, long serverTimeThreshold); boolean isValidLocalLogin(String userName, byte[] password); boolean isUserInValidGroup(final String userName, final char[] password); byte[] getDecryptedAccountValue(String userName, String key); byte[] getDecryptedPassphraseValue(String userName); boolean isUserInPioneerGroup(String userName); LoginResponse fetchUserDetails(String accessToken); AllSharedPreferences getAllSharedPreferences(); Response<String> getLocationInformation(); boolean localLoginWith(String userName); void processLoginResponseDataForUser(String userName, LoginResponseData userInfo); void forceRemoteLogin(String userName); User getUserData(LoginResponseData userInfo); LocationTree getUserLocation(LoginResponseData userInfo); TeamMember getUserTeam(LoginResponseData userInfo); void saveDefaultLocationId(String userName, String locationId); String getUserDefaultTeam(LoginResponseData userInfo); void saveDefaultTeam(String userName, String team); String getUserDefaultTeamId(LoginResponseData userInfo); void saveDefaultTeamId(String userName, String teamId); String getUserDefaultLocationId(LoginResponseData userInfo); String getUserLocationId(LoginResponseData userInfo); void saveUserLocationId(String userName, String locationId); void saveAnmLocation(LocationTree anmLocation); void saveAnmTeam(TeamMember anmTeam); void saveJurisdictions(List<String> jurisdictions); void saveJurisdictionIds(Set<String> jurisdictionIds); Set<String> fetchJurisdictionIds(); void saveOrganizations(TeamMember teamMember); void saveOrganizations(List<Long> organizations); Set<Long> fetchOrganizations(); void saveUserInfo(User user); Bundle saveUserCredentials(String userName, char[] password, LoginResponseData userInfo); boolean hasARegisteredUser(); void logout(); void logoutSession(); boolean hasSessionExpired(); String switchLanguagePreference(); KeyStore getKeyStore(); @Deprecated byte[] getGroupId(String userName); @Deprecated byte[] getGroupId(String userName, KeyStore.PrivateKeyEntry privateKeyEntry); } | @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).canUseThisPassword(password); }
@Test public void shouldConsiderALocalLoginInvalidWhenRegisteredUserDoesNotMatch() { when(allSharedPreferences.fetchRegisteredANM()).thenReturn("ANM X"); assertFalse(userService.isValidLocalLogin("SOME OTHER ANM", "password".getBytes())); verify(allSharedPreferences).fetchRegisteredANM(); verifyZeroInteractions(repository); }
@Test public void shouldConsiderALocalLoginInvalidWhenRegisteredUserMatchesButNotThePassword() { when(allSharedPreferences.fetchRegisteredANM()).thenReturn("ANM X"); when(repository.canUseThisPassword(password)).thenReturn(false); assertFalse(userService.isValidLocalLogin("ANM X", password)); verify(allSharedPreferences).fetchRegisteredANM(); verify(repository).canUseThisPassword(password); } |
UserService { public void logout() { logoutSession(); allSettings.registerANM(""); allSettings.savePreviousFetchIndex("0"); configuration.getDrishtiApplication().getRepository().deleteRepository(); } UserService(AllSettings allSettingsArg, AllSharedPreferences
allSharedPreferencesArg, HTTPAgent httpAgentArg, Session sessionArg,
DristhiConfiguration configurationArg, SaveANMLocationTask
saveANMLocationTaskArg, SaveUserInfoTask saveUserInfoTaskArg, SaveANMTeamTask saveANMTeamTaskArg); static TimeZone getServerTimeZone(LoginResponseData userInfo); void initKeyStore(); TimeStatus validateStoredServerTimeZone(); TimeStatus validateDeviceTime(LoginResponseData userInfo, long serverTimeThreshold); boolean isValidLocalLogin(String userName, byte[] password); boolean isUserInValidGroup(final String userName, final char[] password); byte[] getDecryptedAccountValue(String userName, String key); byte[] getDecryptedPassphraseValue(String userName); boolean isUserInPioneerGroup(String userName); LoginResponse fetchUserDetails(String accessToken); AllSharedPreferences getAllSharedPreferences(); Response<String> getLocationInformation(); boolean localLoginWith(String userName); void processLoginResponseDataForUser(String userName, LoginResponseData userInfo); void forceRemoteLogin(String userName); User getUserData(LoginResponseData userInfo); LocationTree getUserLocation(LoginResponseData userInfo); TeamMember getUserTeam(LoginResponseData userInfo); void saveDefaultLocationId(String userName, String locationId); String getUserDefaultTeam(LoginResponseData userInfo); void saveDefaultTeam(String userName, String team); String getUserDefaultTeamId(LoginResponseData userInfo); void saveDefaultTeamId(String userName, String teamId); String getUserDefaultLocationId(LoginResponseData userInfo); String getUserLocationId(LoginResponseData userInfo); void saveUserLocationId(String userName, String locationId); void saveAnmLocation(LocationTree anmLocation); void saveAnmTeam(TeamMember anmTeam); void saveJurisdictions(List<String> jurisdictions); void saveJurisdictionIds(Set<String> jurisdictionIds); Set<String> fetchJurisdictionIds(); void saveOrganizations(TeamMember teamMember); void saveOrganizations(List<Long> organizations); Set<Long> fetchOrganizations(); void saveUserInfo(User user); Bundle saveUserCredentials(String userName, char[] password, LoginResponseData userInfo); boolean hasARegisteredUser(); void logout(); void logoutSession(); boolean hasSessionExpired(); String switchLanguagePreference(); KeyStore getKeyStore(); @Deprecated byte[] getGroupId(String userName); @Deprecated byte[] getGroupId(String userName, KeyStore.PrivateKeyEntry privateKeyEntry); } | @Test public void shouldDeleteDataAndSettingsWhenLogoutHappens() throws Exception { SyncConfiguration syncConfiguration = mock(SyncConfiguration.class); Mockito.doReturn(false).when(syncConfiguration).clearDataOnNewTeamLogin(); ReflectionHelpers.setField(CoreLibrary.getInstance(), "syncConfiguration", syncConfiguration); Whitebox.setInternalState(drishtiApplication, "password", password); userService.logout(); verify(repository).deleteRepository(); verify(repository).deleteRepository(); verify(repository).deleteRepository(); verify(allSettings).savePreviousFetchIndex("0"); verify(allSettings).registerANM(""); } |
UserService { public String switchLanguagePreference() { String preferredLocale = allSharedPreferences.fetchLanguagePreference(); if (ENGLISH_LOCALE.equals(preferredLocale)) { allSharedPreferences.saveLanguagePreference(KANNADA_LOCALE); return KANNADA_LANGUAGE; } else { allSharedPreferences.saveLanguagePreference(ENGLISH_LOCALE); return ENGLISH_LANGUAGE; } } UserService(AllSettings allSettingsArg, AllSharedPreferences
allSharedPreferencesArg, HTTPAgent httpAgentArg, Session sessionArg,
DristhiConfiguration configurationArg, SaveANMLocationTask
saveANMLocationTaskArg, SaveUserInfoTask saveUserInfoTaskArg, SaveANMTeamTask saveANMTeamTaskArg); static TimeZone getServerTimeZone(LoginResponseData userInfo); void initKeyStore(); TimeStatus validateStoredServerTimeZone(); TimeStatus validateDeviceTime(LoginResponseData userInfo, long serverTimeThreshold); boolean isValidLocalLogin(String userName, byte[] password); boolean isUserInValidGroup(final String userName, final char[] password); byte[] getDecryptedAccountValue(String userName, String key); byte[] getDecryptedPassphraseValue(String userName); boolean isUserInPioneerGroup(String userName); LoginResponse fetchUserDetails(String accessToken); AllSharedPreferences getAllSharedPreferences(); Response<String> getLocationInformation(); boolean localLoginWith(String userName); void processLoginResponseDataForUser(String userName, LoginResponseData userInfo); void forceRemoteLogin(String userName); User getUserData(LoginResponseData userInfo); LocationTree getUserLocation(LoginResponseData userInfo); TeamMember getUserTeam(LoginResponseData userInfo); void saveDefaultLocationId(String userName, String locationId); String getUserDefaultTeam(LoginResponseData userInfo); void saveDefaultTeam(String userName, String team); String getUserDefaultTeamId(LoginResponseData userInfo); void saveDefaultTeamId(String userName, String teamId); String getUserDefaultLocationId(LoginResponseData userInfo); String getUserLocationId(LoginResponseData userInfo); void saveUserLocationId(String userName, String locationId); void saveAnmLocation(LocationTree anmLocation); void saveAnmTeam(TeamMember anmTeam); void saveJurisdictions(List<String> jurisdictions); void saveJurisdictionIds(Set<String> jurisdictionIds); Set<String> fetchJurisdictionIds(); void saveOrganizations(TeamMember teamMember); void saveOrganizations(List<Long> organizations); Set<Long> fetchOrganizations(); void saveUserInfo(User user); Bundle saveUserCredentials(String userName, char[] password, LoginResponseData userInfo); boolean hasARegisteredUser(); void logout(); void logoutSession(); boolean hasSessionExpired(); String switchLanguagePreference(); KeyStore getKeyStore(); @Deprecated byte[] getGroupId(String userName); @Deprecated byte[] getGroupId(String userName, KeyStore.PrivateKeyEntry privateKeyEntry); } | @Test public void shouldSwitchLanguageToKannada() throws Exception { when(allSharedPreferences.fetchLanguagePreference()).thenReturn(ENGLISH_LOCALE); userService.switchLanguagePreference(); verify(allSharedPreferences).saveLanguagePreference(KANNADA_LOCALE); }
@Test public void shouldSwitchLanguageToEnglish() throws Exception { when(allSharedPreferences.fetchLanguagePreference()).thenReturn(KANNADA_LOCALE); userService.switchLanguagePreference(); verify(allSharedPreferences).saveLanguagePreference(ENGLISH_LOCALE); } |
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,
DristhiConfiguration configurationArg, SaveANMLocationTask
saveANMLocationTaskArg, SaveUserInfoTask saveUserInfoTaskArg, SaveANMTeamTask saveANMTeamTaskArg); static TimeZone getServerTimeZone(LoginResponseData userInfo); void initKeyStore(); TimeStatus validateStoredServerTimeZone(); TimeStatus validateDeviceTime(LoginResponseData userInfo, long serverTimeThreshold); boolean isValidLocalLogin(String userName, byte[] password); boolean isUserInValidGroup(final String userName, final char[] password); byte[] getDecryptedAccountValue(String userName, String key); byte[] getDecryptedPassphraseValue(String userName); boolean isUserInPioneerGroup(String userName); LoginResponse fetchUserDetails(String accessToken); AllSharedPreferences getAllSharedPreferences(); Response<String> getLocationInformation(); boolean localLoginWith(String userName); void processLoginResponseDataForUser(String userName, LoginResponseData userInfo); void forceRemoteLogin(String userName); User getUserData(LoginResponseData userInfo); LocationTree getUserLocation(LoginResponseData userInfo); TeamMember getUserTeam(LoginResponseData userInfo); void saveDefaultLocationId(String userName, String locationId); String getUserDefaultTeam(LoginResponseData userInfo); void saveDefaultTeam(String userName, String team); String getUserDefaultTeamId(LoginResponseData userInfo); void saveDefaultTeamId(String userName, String teamId); String getUserDefaultLocationId(LoginResponseData userInfo); String getUserLocationId(LoginResponseData userInfo); void saveUserLocationId(String userName, String locationId); void saveAnmLocation(LocationTree anmLocation); void saveAnmTeam(TeamMember anmTeam); void saveJurisdictions(List<String> jurisdictions); void saveJurisdictionIds(Set<String> jurisdictionIds); Set<String> fetchJurisdictionIds(); void saveOrganizations(TeamMember teamMember); void saveOrganizations(List<Long> organizations); Set<Long> fetchOrganizations(); void saveUserInfo(User user); Bundle saveUserCredentials(String userName, char[] password, LoginResponseData userInfo); boolean hasARegisteredUser(); void logout(); void logoutSession(); boolean hasSessionExpired(); String switchLanguagePreference(); KeyStore getKeyStore(); @Deprecated byte[] getGroupId(String userName); @Deprecated byte[] getGroupId(String userName, KeyStore.PrivateKeyEntry privateKeyEntry); } | @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, Session sessionArg,
DristhiConfiguration configurationArg, SaveANMLocationTask
saveANMLocationTaskArg, SaveUserInfoTask saveUserInfoTaskArg, SaveANMTeamTask saveANMTeamTaskArg); static TimeZone getServerTimeZone(LoginResponseData userInfo); void initKeyStore(); TimeStatus validateStoredServerTimeZone(); TimeStatus validateDeviceTime(LoginResponseData userInfo, long serverTimeThreshold); boolean isValidLocalLogin(String userName, byte[] password); boolean isUserInValidGroup(final String userName, final char[] password); byte[] getDecryptedAccountValue(String userName, String key); byte[] getDecryptedPassphraseValue(String userName); boolean isUserInPioneerGroup(String userName); LoginResponse fetchUserDetails(String accessToken); AllSharedPreferences getAllSharedPreferences(); Response<String> getLocationInformation(); boolean localLoginWith(String userName); void processLoginResponseDataForUser(String userName, LoginResponseData userInfo); void forceRemoteLogin(String userName); User getUserData(LoginResponseData userInfo); LocationTree getUserLocation(LoginResponseData userInfo); TeamMember getUserTeam(LoginResponseData userInfo); void saveDefaultLocationId(String userName, String locationId); String getUserDefaultTeam(LoginResponseData userInfo); void saveDefaultTeam(String userName, String team); String getUserDefaultTeamId(LoginResponseData userInfo); void saveDefaultTeamId(String userName, String teamId); String getUserDefaultLocationId(LoginResponseData userInfo); String getUserLocationId(LoginResponseData userInfo); void saveUserLocationId(String userName, String locationId); void saveAnmLocation(LocationTree anmLocation); void saveAnmTeam(TeamMember anmTeam); void saveJurisdictions(List<String> jurisdictions); void saveJurisdictionIds(Set<String> jurisdictionIds); Set<String> fetchJurisdictionIds(); void saveOrganizations(TeamMember teamMember); void saveOrganizations(List<Long> organizations); Set<Long> fetchOrganizations(); void saveUserInfo(User user); Bundle saveUserCredentials(String userName, char[] password, LoginResponseData userInfo); boolean hasARegisteredUser(); void logout(); void logoutSession(); boolean hasSessionExpired(); String switchLanguagePreference(); KeyStore getKeyStore(); @Deprecated byte[] getGroupId(String userName); @Deprecated byte[] getGroupId(String userName, KeyStore.PrivateKeyEntry privateKeyEntry); } | @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>> mapLocation = locationTree.getLocationsHierarchy(); assertEquals("Pakistan", mapLocation.values().iterator().next().getLabel()); } |
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(AllSettings allSettingsArg, AllSharedPreferences
allSharedPreferencesArg, HTTPAgent httpAgentArg, Session sessionArg,
DristhiConfiguration configurationArg, SaveANMLocationTask
saveANMLocationTaskArg, SaveUserInfoTask saveUserInfoTaskArg, SaveANMTeamTask saveANMTeamTaskArg); static TimeZone getServerTimeZone(LoginResponseData userInfo); void initKeyStore(); TimeStatus validateStoredServerTimeZone(); TimeStatus validateDeviceTime(LoginResponseData userInfo, long serverTimeThreshold); boolean isValidLocalLogin(String userName, byte[] password); boolean isUserInValidGroup(final String userName, final char[] password); byte[] getDecryptedAccountValue(String userName, String key); byte[] getDecryptedPassphraseValue(String userName); boolean isUserInPioneerGroup(String userName); LoginResponse fetchUserDetails(String accessToken); AllSharedPreferences getAllSharedPreferences(); Response<String> getLocationInformation(); boolean localLoginWith(String userName); void processLoginResponseDataForUser(String userName, LoginResponseData userInfo); void forceRemoteLogin(String userName); User getUserData(LoginResponseData userInfo); LocationTree getUserLocation(LoginResponseData userInfo); TeamMember getUserTeam(LoginResponseData userInfo); void saveDefaultLocationId(String userName, String locationId); String getUserDefaultTeam(LoginResponseData userInfo); void saveDefaultTeam(String userName, String team); String getUserDefaultTeamId(LoginResponseData userInfo); void saveDefaultTeamId(String userName, String teamId); String getUserDefaultLocationId(LoginResponseData userInfo); String getUserLocationId(LoginResponseData userInfo); void saveUserLocationId(String userName, String locationId); void saveAnmLocation(LocationTree anmLocation); void saveAnmTeam(TeamMember anmTeam); void saveJurisdictions(List<String> jurisdictions); void saveJurisdictionIds(Set<String> jurisdictionIds); Set<String> fetchJurisdictionIds(); void saveOrganizations(TeamMember teamMember); void saveOrganizations(List<Long> organizations); Set<Long> fetchOrganizations(); void saveUserInfo(User user); Bundle saveUserCredentials(String userName, char[] password, LoginResponseData userInfo); boolean hasARegisteredUser(); void logout(); void logoutSession(); boolean hasSessionExpired(); String switchLanguagePreference(); KeyStore getKeyStore(); @Deprecated byte[] getGroupId(String userName); @Deprecated byte[] getGroupId(String userName, KeyStore.PrivateKeyEntry privateKeyEntry); } | @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 millisecondsPerHour = 3600 * 1000; assertEquals(3 * millisecondsPerHour, timezone.getRawOffset()); assertEquals("Africa/Nairobi", timezone.getID()); } |
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 && deviceTimeZone != null && serverTime != null && deviceTime != null) { if (serverTimeZone.getRawOffset() == deviceTimeZone.getRawOffset()) { long timeDiff = Math.abs(serverTime.getTime() - deviceTime.getTime()); if (timeDiff <= serverTimeThreshold) { return TimeStatus.OK; } else { return TimeStatus.TIME_MISMATCH; } } else { return TimeStatus.TIMEZONE_MISMATCH; } } return TimeStatus.ERROR; } UserService(AllSettings allSettingsArg, AllSharedPreferences
allSharedPreferencesArg, HTTPAgent httpAgentArg, Session sessionArg,
DristhiConfiguration configurationArg, SaveANMLocationTask
saveANMLocationTaskArg, SaveUserInfoTask saveUserInfoTaskArg, SaveANMTeamTask saveANMTeamTaskArg); static TimeZone getServerTimeZone(LoginResponseData userInfo); void initKeyStore(); TimeStatus validateStoredServerTimeZone(); TimeStatus validateDeviceTime(LoginResponseData userInfo, long serverTimeThreshold); boolean isValidLocalLogin(String userName, byte[] password); boolean isUserInValidGroup(final String userName, final char[] password); byte[] getDecryptedAccountValue(String userName, String key); byte[] getDecryptedPassphraseValue(String userName); boolean isUserInPioneerGroup(String userName); LoginResponse fetchUserDetails(String accessToken); AllSharedPreferences getAllSharedPreferences(); Response<String> getLocationInformation(); boolean localLoginWith(String userName); void processLoginResponseDataForUser(String userName, LoginResponseData userInfo); void forceRemoteLogin(String userName); User getUserData(LoginResponseData userInfo); LocationTree getUserLocation(LoginResponseData userInfo); TeamMember getUserTeam(LoginResponseData userInfo); void saveDefaultLocationId(String userName, String locationId); String getUserDefaultTeam(LoginResponseData userInfo); void saveDefaultTeam(String userName, String team); String getUserDefaultTeamId(LoginResponseData userInfo); void saveDefaultTeamId(String userName, String teamId); String getUserDefaultLocationId(LoginResponseData userInfo); String getUserLocationId(LoginResponseData userInfo); void saveUserLocationId(String userName, String locationId); void saveAnmLocation(LocationTree anmLocation); void saveAnmTeam(TeamMember anmTeam); void saveJurisdictions(List<String> jurisdictions); void saveJurisdictionIds(Set<String> jurisdictionIds); Set<String> fetchJurisdictionIds(); void saveOrganizations(TeamMember teamMember); void saveOrganizations(List<Long> organizations); Set<Long> fetchOrganizations(); void saveUserInfo(User user); Bundle saveUserCredentials(String userName, char[] password, LoginResponseData userInfo); boolean hasARegisteredUser(); void logout(); void logoutSession(); boolean hasSessionExpired(); String switchLanguagePreference(); KeyStore getKeyStore(); @Deprecated byte[] getGroupId(String userName); @Deprecated byte[] getGroupId(String userName, KeyStore.PrivateKeyEntry privateKeyEntry); } | @Test public void testValidateDeviceTimeForNullServerTimeZoneReturnsError() { loginResponseData = mock(LoginResponseData.class); assertEquals(TimeStatus.ERROR, userService.validateDeviceTime(loginResponseData, 3600)); }
@Test public void testValidateDeviceTimeForDifferentTimeZoneServerTimeZoneReturnsMismatch() { loginResponseData = mock(LoginResponseData.class); loginResponseData.time = new Time(new Date(), TimeZone.getTimeZone("Africa/Nairobi")); TimeZone.setDefault(TimeZone.getTimeZone("GMT")); assertEquals(TimeStatus.TIMEZONE_MISMATCH, userService.validateDeviceTime(loginResponseData, 3600 * 1000)); }
@Test public void testValidateDeviceTimeForDifferentTimeReturnsMismatch() { loginResponseData = mock(LoginResponseData.class); Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.MINUTE, -30); loginResponseData.time = new Time(calendar.getTime(), TimeZone.getTimeZone("Africa/Nairobi")); TimeZone.setDefault(TimeZone.getTimeZone("Africa/Nairobi")); assertEquals(TimeStatus.TIME_MISMATCH, userService.validateDeviceTime(loginResponseData, 15 * 1000)); }
@Test public void testValidateDeviceTimeSameTimeTimeAndTimeZone() { loginResponseData = mock(LoginResponseData.class); Calendar calendar = Calendar.getInstance(); loginResponseData.time = new Time(calendar.getTime(), TimeZone.getTimeZone("Africa/Nairobi")); TimeZone.setDefault(TimeZone.getTimeZone("Africa/Nairobi")); assertEquals(TimeStatus.OK, userService.validateDeviceTime(loginResponseData, 15 * 1000)); } |
UserService { public TimeStatus validateStoredServerTimeZone() { TimeStatus result = TimeStatus.ERROR; try { String serverTimeZoneId = allSharedPreferences.fetchServerTimeZone(); if (serverTimeZoneId != null) { TimeZone serverTimeZone = TimeZone.getTimeZone(serverTimeZoneId); TimeZone deviceTimeZone = TimeZone.getDefault(); if (serverTimeZone != null && deviceTimeZone != null && serverTimeZone.getRawOffset() == deviceTimeZone.getRawOffset()) { result = TimeStatus.OK; } else { result = TimeStatus.TIMEZONE_MISMATCH; } } } catch (Exception e) { Timber.e(e); } if (!result.equals(TimeStatus.OK)) { forceRemoteLogin(allSharedPreferences.fetchRegisteredANM()); } return result; } UserService(AllSettings allSettingsArg, AllSharedPreferences
allSharedPreferencesArg, HTTPAgent httpAgentArg, Session sessionArg,
DristhiConfiguration configurationArg, SaveANMLocationTask
saveANMLocationTaskArg, SaveUserInfoTask saveUserInfoTaskArg, SaveANMTeamTask saveANMTeamTaskArg); static TimeZone getServerTimeZone(LoginResponseData userInfo); void initKeyStore(); TimeStatus validateStoredServerTimeZone(); TimeStatus validateDeviceTime(LoginResponseData userInfo, long serverTimeThreshold); boolean isValidLocalLogin(String userName, byte[] password); boolean isUserInValidGroup(final String userName, final char[] password); byte[] getDecryptedAccountValue(String userName, String key); byte[] getDecryptedPassphraseValue(String userName); boolean isUserInPioneerGroup(String userName); LoginResponse fetchUserDetails(String accessToken); AllSharedPreferences getAllSharedPreferences(); Response<String> getLocationInformation(); boolean localLoginWith(String userName); void processLoginResponseDataForUser(String userName, LoginResponseData userInfo); void forceRemoteLogin(String userName); User getUserData(LoginResponseData userInfo); LocationTree getUserLocation(LoginResponseData userInfo); TeamMember getUserTeam(LoginResponseData userInfo); void saveDefaultLocationId(String userName, String locationId); String getUserDefaultTeam(LoginResponseData userInfo); void saveDefaultTeam(String userName, String team); String getUserDefaultTeamId(LoginResponseData userInfo); void saveDefaultTeamId(String userName, String teamId); String getUserDefaultLocationId(LoginResponseData userInfo); String getUserLocationId(LoginResponseData userInfo); void saveUserLocationId(String userName, String locationId); void saveAnmLocation(LocationTree anmLocation); void saveAnmTeam(TeamMember anmTeam); void saveJurisdictions(List<String> jurisdictions); void saveJurisdictionIds(Set<String> jurisdictionIds); Set<String> fetchJurisdictionIds(); void saveOrganizations(TeamMember teamMember); void saveOrganizations(List<Long> organizations); Set<Long> fetchOrganizations(); void saveUserInfo(User user); Bundle saveUserCredentials(String userName, char[] password, LoginResponseData userInfo); boolean hasARegisteredUser(); void logout(); void logoutSession(); boolean hasSessionExpired(); String switchLanguagePreference(); KeyStore getKeyStore(); @Deprecated byte[] getGroupId(String userName); @Deprecated byte[] getGroupId(String userName, KeyStore.PrivateKeyEntry privateKeyEntry); } | @Test public void testValidateStoredServerTimeZoneForNullServerTimeZoneReturnsError() { when(allSharedPreferences.fetchServerTimeZone()).thenReturn(null); assertEquals(TimeStatus.ERROR, userService.validateStoredServerTimeZone()); verify(allSharedPreferences).saveForceRemoteLogin(true, userName); }
@Test public void testValidateStoredServerTimeZoneForDifferentTimeZoneServerTimeZoneReturnsMismatch() { when(allSharedPreferences.fetchServerTimeZone()).thenReturn("Africa/Nairobi"); when(allSharedPreferences.fetchRegisteredANM()).thenReturn(userName); TimeZone.setDefault(TimeZone.getTimeZone("GMT")); assertEquals(TimeStatus.TIMEZONE_MISMATCH, userService.validateStoredServerTimeZone()); verify(allSharedPreferences).saveForceRemoteLogin(true, userName); }
@Test public void testValidateStoredServerTimeZoneForSameTimeTimeAndTimeZone() { when(allSharedPreferences.fetchServerTimeZone()).thenReturn("Africa/Nairobi"); TimeZone.setDefault(TimeZone.getTimeZone("Africa/Nairobi")); assertEquals(TimeStatus.OK, userService.validateStoredServerTimeZone()); verify(allSharedPreferences, never()).saveForceRemoteLogin(true, userName); } |
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 = getLocalAuthenticationCredentials(userName); passwordHash = generatePasswordHash(userName, password); if (storedHash != null && Arrays.equals(storedHash, passwordHash)) { return isValidDBPassword(getDBAuthenticationCredentials(userName)); } } catch (Exception e) { Timber.e(e); } finally { SecurityHelper.clearArray(password); SecurityHelper.clearArray(passwordHash); SecurityHelper.clearArray(storedHash); } } return false; } UserService(AllSettings allSettingsArg, AllSharedPreferences
allSharedPreferencesArg, HTTPAgent httpAgentArg, Session sessionArg,
DristhiConfiguration configurationArg, SaveANMLocationTask
saveANMLocationTaskArg, SaveUserInfoTask saveUserInfoTaskArg, SaveANMTeamTask saveANMTeamTaskArg); static TimeZone getServerTimeZone(LoginResponseData userInfo); void initKeyStore(); TimeStatus validateStoredServerTimeZone(); TimeStatus validateDeviceTime(LoginResponseData userInfo, long serverTimeThreshold); boolean isValidLocalLogin(String userName, byte[] password); boolean isUserInValidGroup(final String userName, final char[] password); byte[] getDecryptedAccountValue(String userName, String key); byte[] getDecryptedPassphraseValue(String userName); boolean isUserInPioneerGroup(String userName); LoginResponse fetchUserDetails(String accessToken); AllSharedPreferences getAllSharedPreferences(); Response<String> getLocationInformation(); boolean localLoginWith(String userName); void processLoginResponseDataForUser(String userName, LoginResponseData userInfo); void forceRemoteLogin(String userName); User getUserData(LoginResponseData userInfo); LocationTree getUserLocation(LoginResponseData userInfo); TeamMember getUserTeam(LoginResponseData userInfo); void saveDefaultLocationId(String userName, String locationId); String getUserDefaultTeam(LoginResponseData userInfo); void saveDefaultTeam(String userName, String team); String getUserDefaultTeamId(LoginResponseData userInfo); void saveDefaultTeamId(String userName, String teamId); String getUserDefaultLocationId(LoginResponseData userInfo); String getUserLocationId(LoginResponseData userInfo); void saveUserLocationId(String userName, String locationId); void saveAnmLocation(LocationTree anmLocation); void saveAnmTeam(TeamMember anmTeam); void saveJurisdictions(List<String> jurisdictions); void saveJurisdictionIds(Set<String> jurisdictionIds); Set<String> fetchJurisdictionIds(); void saveOrganizations(TeamMember teamMember); void saveOrganizations(List<Long> organizations); Set<Long> fetchOrganizations(); void saveUserInfo(User user); Bundle saveUserCredentials(String userName, char[] password, LoginResponseData userInfo); boolean hasARegisteredUser(); void logout(); void logoutSession(); boolean hasSessionExpired(); String switchLanguagePreference(); KeyStore getKeyStore(); @Deprecated byte[] getGroupId(String userName); @Deprecated byte[] getGroupId(String userName, KeyStore.PrivateKeyEntry privateKeyEntry); } | @Test public void testIsUserInValidGroupForNullUserAndPassword() { assertFalse(userService.isUserInValidGroup(null, null)); }
@Test public void testIsUserInValidGroupShouldReturnFalseOnError() throws Exception { Whitebox.setInternalState(userService, "keyStore", keyStore); Whitebox.setInternalState(keyStore, "initialized", true); Whitebox.setInternalState(keyStore, "keyStoreSpi", keyStoreSpi); String user = "johndoe"; when(keyStore.containsAlias(user)).thenReturn(true); KeyStore.PrivateKeyEntry privateKeyEntry = PowerMockito.mock(KeyStore.PrivateKeyEntry.class); when(keyStore.getEntry(user, null)).thenReturn(privateKeyEntry); String password = UUID.randomUUID().toString(); assertFalse(userService.isUserInValidGroup(user, password.toCharArray())); verify(allSharedPreferences, never()).fetchEncryptedGroupId(user); verifyZeroInteractions(repository); } |
UserService { public boolean isUserInPioneerGroup(String userName) { String pioneerUser = allSharedPreferences.fetchPioneerUser(); if (userName.equals(pioneerUser)) { return true; } else { byte[] currentUserSecretKey = getDecryptedPassphraseValue(userName); byte[] pioneerUserSecretKey = getDecryptedPassphraseValue(pioneerUser); if (currentUserSecretKey != null && Arrays.equals(pioneerUserSecretKey, currentUserSecretKey)) { return isValidDBPassword(currentUserSecretKey); } } return false; } UserService(AllSettings allSettingsArg, AllSharedPreferences
allSharedPreferencesArg, HTTPAgent httpAgentArg, Session sessionArg,
DristhiConfiguration configurationArg, SaveANMLocationTask
saveANMLocationTaskArg, SaveUserInfoTask saveUserInfoTaskArg, SaveANMTeamTask saveANMTeamTaskArg); static TimeZone getServerTimeZone(LoginResponseData userInfo); void initKeyStore(); TimeStatus validateStoredServerTimeZone(); TimeStatus validateDeviceTime(LoginResponseData userInfo, long serverTimeThreshold); boolean isValidLocalLogin(String userName, byte[] password); boolean isUserInValidGroup(final String userName, final char[] password); byte[] getDecryptedAccountValue(String userName, String key); byte[] getDecryptedPassphraseValue(String userName); boolean isUserInPioneerGroup(String userName); LoginResponse fetchUserDetails(String accessToken); AllSharedPreferences getAllSharedPreferences(); Response<String> getLocationInformation(); boolean localLoginWith(String userName); void processLoginResponseDataForUser(String userName, LoginResponseData userInfo); void forceRemoteLogin(String userName); User getUserData(LoginResponseData userInfo); LocationTree getUserLocation(LoginResponseData userInfo); TeamMember getUserTeam(LoginResponseData userInfo); void saveDefaultLocationId(String userName, String locationId); String getUserDefaultTeam(LoginResponseData userInfo); void saveDefaultTeam(String userName, String team); String getUserDefaultTeamId(LoginResponseData userInfo); void saveDefaultTeamId(String userName, String teamId); String getUserDefaultLocationId(LoginResponseData userInfo); String getUserLocationId(LoginResponseData userInfo); void saveUserLocationId(String userName, String locationId); void saveAnmLocation(LocationTree anmLocation); void saveAnmTeam(TeamMember anmTeam); void saveJurisdictions(List<String> jurisdictions); void saveJurisdictionIds(Set<String> jurisdictionIds); Set<String> fetchJurisdictionIds(); void saveOrganizations(TeamMember teamMember); void saveOrganizations(List<Long> organizations); Set<Long> fetchOrganizations(); void saveUserInfo(User user); Bundle saveUserCredentials(String userName, char[] password, LoginResponseData userInfo); boolean hasARegisteredUser(); void logout(); void logoutSession(); boolean hasSessionExpired(); String switchLanguagePreference(); KeyStore getKeyStore(); @Deprecated byte[] getGroupId(String userName); @Deprecated byte[] getGroupId(String userName, KeyStore.PrivateKeyEntry privateKeyEntry); } | @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 user = "johndoe"; when(keyStore.containsAlias(user)).thenReturn(true); KeyStore.PrivateKeyEntry privateKeyEntry = PowerMockito.mock(KeyStore.PrivateKeyEntry.class); when(keyStore.getEntry(user, null)).thenReturn(privateKeyEntry); when(allSharedPreferences.fetchPioneerUser()).thenReturn(user); assertTrue(userService.isUserInPioneerGroup(user)); }
@Test public void testIsUserInPioneerGroupShouldReturnFalseForOthers() throws Exception { when(allSharedPreferences.fetchPioneerUser()).thenReturn("user"); assertFalse(userService.isUserInPioneerGroup("john")); } |
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 ", eventClients.first.size(), events); eventClientRepository.batchInsertEvents(events, 0, sqLiteDatabase); } catch (JSONException e) { Timber.e(e); } } if (eventClients.second != null) { JSONArray clients; try { clients = new JSONArray(gson.toJson(eventClients.second)); Timber.d("saving %d clients, %s", eventClients.second.size(), clients); eventClientRepository.batchInsertClients(clients, sqLiteDatabase); } catch (JSONException e) { Timber.e(e); } } } Pair<List<Event>, List<Client>> createEventAndClients(SQLiteDatabase database, String tablename, String query, String[] params, String eventType, String entityType, FormTag formTag); void saveEventAndClients(Pair<List<Event>, List<Client>> eventClients, SQLiteDatabase sqLiteDatabase); } | @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(tableName)).thenReturn(getEcConfig()); Whitebox.setInternalState(recreateECUtil, "eventClientRepository", eventClientRepository); Pair<List<Event>, List<Client>> eventsAndClients = recreateECUtil.createEventAndClients(database, tableName, query, params, "FamilyRegistration", "Family", formTag); eventsAndClients.first.get(0).addDetails("opearational_area1", "123"); eventsAndClients.first.get(0).addDetails("task_business_status", "Completed"); recreateECUtil.saveEventAndClients(eventsAndClients, database); verify(eventClientRepository).batchInsertClients(jsonArrayArgumentCaptor.capture(), eq(database)); verify(eventClientRepository).batchInsertEvents(jsonArrayArgumentCaptor.capture(), eq(0l), eq(database)); Gson gson = JsonFormUtils.gson; assertEquals(gson.toJson(eventsAndClients.second), jsonArrayArgumentCaptor.getAllValues().get(0).toString()); assertEquals(gson.toJson(eventsAndClients.first), jsonArrayArgumentCaptor.getAllValues().get(1).toString()); } |
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.REFERENCE_DATE); String deliveryPlace = submission .getFieldValue(AllConstants.DeliveryOutcomeFields.DELIVERY_PLACE); Mother mother = motherRepository.findById(submission.entityId()); for (Map<String, String> childInstance : subForm.instances()) { Child child = childRepository.find(childInstance.get(ENTITY_ID_FIELD_NAME)); childRepository .update(child.setIsClosed(false).setThayiCardNumber(mother.thayiCardNumber()) .setDateOfBirth(referenceDate)); allTimelines.add(forChildBirthInChildProfile(child.caseId(), referenceDate, child.getDetail(AllConstants.ChildRegistrationFields.WEIGHT), child.getDetail(AllConstants.ChildRegistrationFields.IMMUNIZATIONS_GIVEN))); allTimelines.add(forChildBirthInMotherProfile(mother.caseId(), referenceDate, child.gender(), referenceDate, deliveryPlace)); allTimelines .add(forChildBirthInECProfile(mother.ecCaseId(), referenceDate, child.gender(), referenceDate)); String immunizationsGiven = child .getDetail(AllConstants.ChildRegistrationFields.IMMUNIZATIONS_GIVEN); for (String immunization : immunizationsGiven.split(SPACE)) { serviceProvidedService.add(ServiceProvided .forChildImmunization(child.caseId(), immunization, referenceDate)); } } } ChildService(AllBeneficiaries allBeneficiariesArg, MotherRepository
motherRepositoryArg, ChildRepository childRepositoryArg, AllTimelineEvents
allTimelineEventsArg, ServiceProvidedService serviceProvidedServiceArg, AllAlerts
allAlertsArg); void register(FormSubmission submission); void registerForEC(FormSubmission submission); void pncRegistrationOA(FormSubmission submission); void updateImmunizations(FormSubmission submission); void pncVisitHappened(FormSubmission submission); void close(FormSubmission submission); void updatePhotoPath(String entityId, String imagePath); void updateIllnessStatus(FormSubmission submission); void updateVitaminAProvided(FormSubmission submission); void registerForOA(FormSubmission submission); } | @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", "4").put("immunizationsGiven", "bcg").map()); FormSubmission submission = Mockito.mock(FormSubmission.class); SubForm subForm = Mockito.mock(SubForm.class); Mockito.when(motherRepository.findById("Mother X")).thenReturn(new Mother("Mother X", "EC 1", "TC 1", "2012-01-01")); Mockito.when(childRepository.find("Child X")).thenReturn(firstChild); Mockito.when(childRepository.find("Child Y")).thenReturn(secondChild); Mockito.when(submission.entityId()).thenReturn("Mother X"); Mockito.when(submission.getFieldValue("referenceDate")).thenReturn("2012-01-01"); Mockito.when(submission.getFieldValue("deliveryPlace")).thenReturn("phc"); Mockito.when(submission.getSubFormByName("child_registration")).thenReturn(subForm); Mockito.when(subForm.instances()).thenReturn(Arrays.asList(EasyMap.mapOf("id", "Child X"), EasyMap.mapOf("id", "Child Y"))); service.register(submission); Mockito.verify(childRepository).find("Child X"); Mockito.verify(childRepository).find("Child Y"); Mockito.verify(childRepository).update(firstChild.setIsClosed(false).setDateOfBirth("2012-01-01").setThayiCardNumber("TC 1")); Mockito.verify(childRepository).update(secondChild.setIsClosed(false).setDateOfBirth("2012-01-01").setThayiCardNumber("TC 1")); Mockito.verify(allTimelineEvents).add(TimelineEvent.forChildBirthInChildProfile("Child X", "2012-01-01", "3", "bcg opv_0")); Mockito.verify(allTimelineEvents).add(TimelineEvent.forChildBirthInChildProfile("Child Y", "2012-01-01", "4", "bcg")); Mockito.verify(allTimelineEvents, Mockito.times(2)).add(TimelineEvent.forChildBirthInMotherProfile("Mother X", "2012-01-01", "female", "2012-01-01", "phc")); Mockito.verify(allTimelineEvents, Mockito.times(2)).add(TimelineEvent.forChildBirthInECProfile("EC 1", "2012-01-01", "female", "2012-01-01")); Mockito.verify(serviceProvidedService).add(ServiceProvided.forChildImmunization("Child X", "bcg", "2012-01-01")); Mockito.verify(serviceProvidedService).add(ServiceProvided.forChildImmunization("Child X", "opv_0", "2012-01-01")); Mockito.verify(serviceProvidedService).add(ServiceProvided.forChildImmunization("Child Y", "bcg", "2012-01-01")); Mockito.verifyNoMoreInteractions(childRepository); Mockito.verifyNoMoreInteractions(allTimelineEvents); }
@Test public void shouldDeleteRegisteredChildWhenDeliveryOutcomeIsStillBirth() throws Exception { FormSubmission submission = Mockito.mock(FormSubmission.class); SubForm subForm = Mockito.mock(SubForm.class); Mockito.when(submission.entityId()).thenReturn("Mother X"); Mockito.when(submission.getFieldValue("referenceDate")).thenReturn("2012-01-01"); Mockito.when(submission.getFieldValue("deliveryPlace")).thenReturn("phc"); Mockito.when(submission.getFieldValue("deliveryOutcome")).thenReturn("still_birth"); Mockito.when(submission.getSubFormByName("child_registration")).thenReturn(subForm); Mockito.when(subForm.instances()).thenReturn(Arrays.asList(EasyMap.mapOf("id", "Child X"))); service.register(submission); Mockito.verify(childRepository).delete("Child X"); Mockito.verifyNoMoreInteractions(childRepository); Mockito.verifyNoMoreInteractions(allTimelineEvents); Mockito.verifyNoMoreInteractions(serviceProvidedService); } |
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.DeliveryOutcomeFields.REFERENCE_DATE); String deliveryPlace = submission .getFieldValue(AllConstants.DeliveryOutcomeFields.DELIVERY_PLACE); Mother mother = motherRepository.findAllCasesForEC(submission.entityId()).get(0); for (Map<String, String> childInstances : subForm.instances()) { Child child = childRepository.find(childInstances.get(ENTITY_ID_FIELD_NAME)); childRepository .update(child.setIsClosed(false).setThayiCardNumber(mother.thayiCardNumber()) .setDateOfBirth(referenceDate)); allTimelines.add(forChildBirthInChildProfile(child.caseId(), referenceDate, child.getDetail(AllConstants.PNCRegistrationOAFields.WEIGHT), child.getDetail(AllConstants.PNCRegistrationOAFields.IMMUNIZATIONS_GIVEN))); allTimelines.add(forChildBirthInMotherProfile(mother.caseId(), referenceDate, child.gender(), referenceDate, deliveryPlace)); allTimelines .add(forChildBirthInECProfile(mother.ecCaseId(), referenceDate, child.gender(), referenceDate)); String immunizationsGiven = child .getDetail(AllConstants.PNCRegistrationOAFields.IMMUNIZATIONS_GIVEN); for (String immunization : immunizationsGiven.split(SPACE)) { serviceProvidedService.add(ServiceProvided .forChildImmunization(child.caseId(), immunization, referenceDate)); } } } ChildService(AllBeneficiaries allBeneficiariesArg, MotherRepository
motherRepositoryArg, ChildRepository childRepositoryArg, AllTimelineEvents
allTimelineEventsArg, ServiceProvidedService serviceProvidedServiceArg, AllAlerts
allAlertsArg); void register(FormSubmission submission); void registerForEC(FormSubmission submission); void pncRegistrationOA(FormSubmission submission); void updateImmunizations(FormSubmission submission); void pncVisitHappened(FormSubmission submission); void close(FormSubmission submission); void updatePhotoPath(String entityId, String imagePath); void updateIllnessStatus(FormSubmission submission); void updateVitaminAProvided(FormSubmission submission); void registerForOA(FormSubmission submission); } | @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("weight", "4").put("immunizationsGiven", "bcg").map()); Mother mother = new Mother("Mother X", "EC X", "TC 1", "2012-01-02"); Mockito.when(motherRepository.findAllCasesForEC("EC X")).thenReturn(Arrays.asList(mother)); Mockito.when(childRepository.find("Child X")).thenReturn(firstChild); Mockito.when(childRepository.find("Child Y")).thenReturn(secondChild); FormSubmission submission = Mockito.mock(FormSubmission.class); SubForm subForm = Mockito.mock(SubForm.class); Mockito.when(submission.entityId()).thenReturn("EC X"); Mockito.when(submission.getFieldValue("referenceDate")).thenReturn("2012-01-01"); Mockito.when(submission.getFieldValue("deliveryPlace")).thenReturn("subcenter"); Mockito.when(submission.getSubFormByName("child_registration_oa")).thenReturn(subForm); Mockito.when(subForm.instances()).thenReturn(Arrays.asList(EasyMap.mapOf("id", "Child X"), EasyMap.mapOf("id", "Child Y"))); service.pncRegistrationOA(submission); Mockito.verify(childRepository).find("Child X"); Mockito.verify(childRepository).find("Child Y"); Mockito.verify(childRepository).update(firstChild.setIsClosed(false).setDateOfBirth("2012-01-01").setThayiCardNumber("TC 1")); Mockito.verify(childRepository).update(secondChild.setIsClosed(false).setDateOfBirth("2012-01-01").setThayiCardNumber("TC 1")); Mockito.verify(allTimelineEvents).add(TimelineEvent.forChildBirthInChildProfile("Child X", "2012-01-01", "3", "bcg opv_0")); Mockito.verify(allTimelineEvents).add(TimelineEvent.forChildBirthInChildProfile("Child Y", "2012-01-01", "4", "bcg")); Mockito.verify(allTimelineEvents, Mockito.times(2)).add(TimelineEvent.forChildBirthInMotherProfile("Mother X", "2012-01-01", "female", "2012-01-01", "subcenter")); Mockito.verify(allTimelineEvents, Mockito.times(2)).add(TimelineEvent.forChildBirthInECProfile("EC X", "2012-01-01", "female", "2012-01-01")); Mockito.verify(serviceProvidedService).add(ServiceProvided.forChildImmunization("Child X", "bcg", "2012-01-01")); Mockito.verify(serviceProvidedService).add(ServiceProvided.forChildImmunization("Child X", "opv_0", "2012-01-01")); Mockito.verify(serviceProvidedService).add(ServiceProvided.forChildImmunization("Child Y", "bcg", "2012-01-01")); Mockito.verifyNoMoreInteractions(childRepository); }
@Test public void shouldDeleteRegisteredChildWhenPNCRegistrationOAIsHandledAndDeliveryOutcomeIsStillBirth() throws Exception { FormSubmission submission = Mockito.mock(FormSubmission.class); SubForm subForm = Mockito.mock(SubForm.class); Mockito.when(submission.entityId()).thenReturn("Mother X"); Mockito.when(submission.getFieldValue("referenceDate")).thenReturn("2012-01-01"); Mockito.when(submission.getFieldValue("deliveryPlace")).thenReturn("phc"); Mockito.when(submission.getFieldValue("deliveryOutcome")).thenReturn("still_birth"); Mockito.when(submission.getSubFormByName("child_registration_oa")).thenReturn(subForm); Mockito.when(subForm.instances()).thenReturn(Arrays.asList(EasyMap.mapOf("id", "Child X"))); service.pncRegistrationOA(submission); Mockito.verify(childRepository).delete("Child X"); Mockito.verifyNoMoreInteractions(childRepository); Mockito.verifyNoMoreInteractions(allTimelineEvents); Mockito.verifyNoMoreInteractions(serviceProvidedService); }
@Test public void shouldCheckForEmptyInstanceInTheCaseOfStillBirth() throws Exception { FormSubmission submission = Mockito.mock(FormSubmission.class); SubForm subForm = Mockito.mock(SubForm.class); Mockito.when(submission.entityId()).thenReturn("Mother X"); Mockito.when(submission.getFieldValue("referenceDate")).thenReturn("2012-01-01"); Mockito.when(submission.getFieldValue("deliveryPlace")).thenReturn("phc"); Mockito.when(submission.getFieldValue("deliveryOutcome")).thenReturn("still_birth"); Mockito.when(submission.getSubFormByName("child_registration_oa")).thenReturn(subForm); Mockito.when(subForm.instances()).thenReturn(new ArrayList<Map<String, String>>()); service.pncRegistrationOA(submission); Mockito.verifyNoMoreInteractions(childRepository); Mockito.verifyNoMoreInteractions(allTimelineEvents); Mockito.verifyNoMoreInteractions(serviceProvidedService); } |
ChildService { public void updateImmunizations(FormSubmission submission) { String immunizationDate = submission .getFieldValue(AllConstants.ChildImmunizationsFields.IMMUNIZATION_DATE); List<String> immunizationsGivenList = splitFieldValueBySpace(submission, AllConstants.ChildImmunizationsFields.IMMUNIZATIONS_GIVEN); List<String> previousImmunizationsList = splitFieldValueBySpace(submission, AllConstants.ChildImmunizationsFields.PREVIOUS_IMMUNIZATIONS_GIVEN); immunizationsGivenList.removeAll(previousImmunizationsList); for (String immunization : immunizationsGivenList) { allTimelines.add(forChildImmunization(submission.entityId(), immunization, immunizationDate)); serviceProvidedService.add(ServiceProvided .forChildImmunization(submission.entityId(), immunization, immunizationDate)); allAlerts.changeAlertStatusToInProcess(submission.entityId(), immunization); } } ChildService(AllBeneficiaries allBeneficiariesArg, MotherRepository
motherRepositoryArg, ChildRepository childRepositoryArg, AllTimelineEvents
allTimelineEventsArg, ServiceProvidedService serviceProvidedServiceArg, AllAlerts
allAlertsArg); void register(FormSubmission submission); void registerForEC(FormSubmission submission); void pncRegistrationOA(FormSubmission submission); void updateImmunizations(FormSubmission submission); void pncVisitHappened(FormSubmission submission); void close(FormSubmission submission); void updatePhotoPath(String entityId, String imagePath); void updateIllnessStatus(FormSubmission submission); void updateVitaminAProvided(FormSubmission submission); void registerForOA(FormSubmission submission); } | @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(submission.getFieldValue("immunizationsGiven")).thenReturn("bcg opv_0 pentavalent_0"); Mockito.when(submission.getFieldValue("immunizationDate")).thenReturn("2013-01-01"); service.updateImmunizations(submission); Mockito.verify(allTimelineEvents).add(TimelineEvent.forChildImmunization("child id 1", "opv_0", "2013-01-01")); Mockito.verify(allTimelineEvents).add(TimelineEvent.forChildImmunization("child id 1", "pentavalent_0", "2013-01-01")); Mockito.verifyNoMoreInteractions(allTimelineEvents); }
@Test public void shouldAddServiceProvidedWhenChildImmunizationsAreUpdated() 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(submission.getFieldValue("immunizationsGiven")).thenReturn("bcg opv_0 pentavalent_0"); Mockito.when(submission.getFieldValue("immunizationDate")).thenReturn("2013-01-01"); service.updateImmunizations(submission); Mockito.verify(serviceProvidedService).add(new ServiceProvided("child id 1", "opv_0", "2013-01-01", null)); Mockito.verify(serviceProvidedService).add(new ServiceProvided("child id 1", "pentavalent_0", "2013-01-01", null)); Mockito.verifyNoMoreInteractions(serviceProvidedService); }
@Test public void shouldMarkRemindersAsInProcessWhenImmunizationsAreProvided() 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(submission.getFieldValue("immunizationsGiven")).thenReturn("bcg opv_0 pentavalent_0"); Mockito.when(submission.getFieldValue("immunizationDate")).thenReturn("2013-01-01"); service.updateImmunizations(submission); Mockito.verify(allAlerts).changeAlertStatusToInProcess("child id 1", "opv_0"); Mockito.verify(allAlerts).changeAlertStatusToInProcess("child id 1", "pentavalent_0"); Mockito.verifyNoMoreInteractions(allAlerts); } |
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(); allTimelines.add(forChildBirthInChildProfile( submission.getFieldValue(AllConstants.ChildRegistrationFields.CHILD_ID), submission.getFieldValue(AllConstants.ChildRegistrationFields.DATE_OF_BIRTH), submission.getFieldValue(AllConstants.ChildRegistrationFields.WEIGHT), submission .getFieldValue(AllConstants.ChildRegistrationFields.IMMUNIZATIONS_GIVEN))); allTimelines.add(forChildBirthInMotherProfile( submission.getFieldValue(AllConstants.ChildRegistrationFields.MOTHER_ID), submission.getFieldValue(AllConstants.ChildRegistrationFields.DATE_OF_BIRTH), submission.getFieldValue(AllConstants.ChildRegistrationFields.GENDER), null, null)); allTimelines.add(forChildBirthInECProfile(submission.entityId(), submission.getFieldValue(AllConstants.ChildRegistrationFields.DATE_OF_BIRTH), submission.getFieldValue(AllConstants.ChildRegistrationFields.GENDER), null)); String immunizationsGiven = submission .getFieldValue(AllConstants.ChildRegistrationFields.IMMUNIZATIONS_GIVEN); for (String immunization : immunizationsGiven.split(SPACE)) { serviceProvidedService.add(ServiceProvided.forChildImmunization( submission.getFieldValue(AllConstants.ChildRegistrationFields.CHILD_ID), immunization, submission.getFieldValue(immunizationDateFieldMap.get(immunization)))); } } ChildService(AllBeneficiaries allBeneficiariesArg, MotherRepository
motherRepositoryArg, ChildRepository childRepositoryArg, AllTimelineEvents
allTimelineEventsArg, ServiceProvidedService serviceProvidedServiceArg, AllAlerts
allAlertsArg); void register(FormSubmission submission); void registerForEC(FormSubmission submission); void pncRegistrationOA(FormSubmission submission); void updateImmunizations(FormSubmission submission); void pncVisitHappened(FormSubmission submission); void close(FormSubmission submission); void updatePhotoPath(String entityId, String imagePath); void updateIllnessStatus(FormSubmission submission); void updateVitaminAProvided(FormSubmission submission); void registerForOA(FormSubmission submission); } | @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(submission.getFieldValue("motherId")).thenReturn("mother id 1"); Mockito.when(submission.getFieldValue("childId")).thenReturn("child id 1"); Mockito.when(submission.getFieldValue("dateOfBirth")).thenReturn("2013-01-02"); Mockito.when(submission.getFieldValue("gender")).thenReturn("female"); Mockito.when(submission.getFieldValue("weight")).thenReturn("3"); Mockito.when(submission.getFieldValue("immunizationsGiven")).thenReturn("bcg opv_0"); Mockito.when(submission.getFieldValue("bcgDate")).thenReturn("2012-01-06"); Mockito.when(submission.getFieldValue("opv0Date")).thenReturn("2012-01-07"); Mockito.when(submission.getFieldValue("shouldCloseMother")).thenReturn(""); Mockito.when(allBeneficiaries.findMother("mother id 1")).thenReturn(mother); service.registerForEC(submission); Mockito.verify(allBeneficiaries).updateMother(mother.setIsClosed(true)); Mockito.verify(allTimelineEvents).add(TimelineEvent.forChildBirthInChildProfile("child id 1", "2013-01-02", "3", "bcg opv_0")); Mockito.verify(allTimelineEvents).add(TimelineEvent.forChildBirthInMotherProfile("mother id 1", "2013-01-02", "female", null, null)); Mockito.verify(allTimelineEvents).add(TimelineEvent.forChildBirthInECProfile("ec id 1", "2013-01-02", "female", null)); Mockito.verify(serviceProvidedService).add(ServiceProvided.forChildImmunization("child id 1", "bcg", "2012-01-06")); Mockito.verify(serviceProvidedService).add(ServiceProvided.forChildImmunization("child id 1", "opv_0", "2012-01-07")); }
@Test public void shouldNotCloseMotherWhenAnOpenANCAlreadyExistWhileRegisteringAChildForEC() 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.getFieldValue("childId")).thenReturn("child id 1"); Mockito.when(submission.getFieldValue("dateOfBirth")).thenReturn("2013-01-02"); Mockito.when(submission.getFieldValue("gender")).thenReturn("female"); Mockito.when(submission.getFieldValue("weight")).thenReturn("3"); Mockito.when(submission.getFieldValue("immunizationsGiven")).thenReturn("bcg opv_0"); Mockito.when(submission.getFieldValue("bcgDate")).thenReturn("2012-01-06"); Mockito.when(submission.getFieldValue("opv0Date")).thenReturn("2012-01-07"); Mockito.when(submission.getFieldValue("shouldCloseMother")).thenReturn("false"); service.registerForEC(submission); Mockito.verify(allTimelineEvents).add(TimelineEvent.forChildBirthInChildProfile("child id 1", "2013-01-02", "3", "bcg opv_0")); Mockito.verify(allTimelineEvents).add(TimelineEvent.forChildBirthInMotherProfile("mother id 1", "2013-01-02", "female", null, null)); Mockito.verify(allTimelineEvents).add(TimelineEvent.forChildBirthInECProfile("ec id 1", "2013-01-02", "female", null)); Mockito.verify(serviceProvidedService).add(ServiceProvided.forChildImmunization("child id 1", "bcg", "2012-01-06")); Mockito.verify(serviceProvidedService).add(ServiceProvided.forChildImmunization("child id 1", "opv_0", "2012-01-07")); } |
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.PNCVisitFields.CHILD_PNC_VISIT_SUB_FORM_NAME); if (handleStillBirth(submission, subForm)) { return; } for (Map<String, String> childInstances : subForm.instances()) { allTimelines.add(forChildPNCVisit(childInstances.get(ENTITY_ID_FIELD_NAME), pncVisitDay, pncVisitDate, childInstances.get(AllConstants.PNCVisitFields.WEIGHT), childInstances.get(AllConstants.PNCVisitFields.TEMPERATURE))); serviceProvidedService.add(ServiceProvided .forChildPNCVisit(childInstances.get(ENTITY_ID_FIELD_NAME), pncVisitDay, pncVisitDate)); } } ChildService(AllBeneficiaries allBeneficiariesArg, MotherRepository
motherRepositoryArg, ChildRepository childRepositoryArg, AllTimelineEvents
allTimelineEventsArg, ServiceProvidedService serviceProvidedServiceArg, AllAlerts
allAlertsArg); void register(FormSubmission submission); void registerForEC(FormSubmission submission); void pncRegistrationOA(FormSubmission submission); void updateImmunizations(FormSubmission submission); void pncVisitHappened(FormSubmission submission); void close(FormSubmission submission); void updatePhotoPath(String entityId, String imagePath); void updateIllnessStatus(FormSubmission submission); void updateVitaminAProvided(FormSubmission submission); void registerForOA(FormSubmission submission); } | @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")).thenReturn("2"); Mockito.when(submission.getFieldValue("pncVisitDate")).thenReturn("2012-01-01"); Mockito.when(submission.getSubFormByName("child_pnc_visit")).thenReturn(subForm); Mockito.when(subForm.instances()).thenReturn( Arrays.asList( EasyMap.create("id", "child id 1") .put("weight", "3") .put("temperature", "98") .map(), EasyMap.create("id", "child id 2") .put("weight", "4") .put("temperature", "98.1") .map())); service.pncVisitHappened(submission); Mockito.verify(allTimelineEvents).add(TimelineEvent.forChildPNCVisit("child id 1", "2", "2012-01-01", "3", "98")); Mockito.verify(allTimelineEvents).add(TimelineEvent.forChildPNCVisit("child id 2", "2", "2012-01-01", "4", "98.1")); }
@Test public void shouldHandleStillBirthWhenPNCVisitHappens() 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")).thenReturn("2"); Mockito.when(submission.getFieldValue("pncVisitDate")).thenReturn("2012-01-01"); Mockito.when(submission.getFieldValue("deliveryOutcome")).thenReturn("still_birth"); Mockito.when(submission.getSubFormByName("child_pnc_visit")).thenReturn(subForm); Mockito.when(subForm.instances()).thenReturn(Arrays.asList(EasyMap.create("id", "child id 1").map())); service.pncVisitHappened(submission); Mockito.verify(childRepository).delete("child id 1"); Mockito.verifyNoMoreInteractions(allTimelineEvents); }
@Test public void shouldAddPNCVisitServiceProvidedWhenPNCVisitHappens() 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")).thenReturn("2"); Mockito.when(submission.getFieldValue("pncVisitDate")).thenReturn("2012-01-01"); Mockito.when(submission.getSubFormByName("child_pnc_visit")).thenReturn(subForm); Mockito.when(subForm.instances()).thenReturn( Arrays.asList(EasyMap.mapOf("id", "child id 1"), EasyMap.mapOf("id", "child id 2"))); service.pncVisitHappened(submission); Mockito.verify(serviceProvidedService).add(new ServiceProvided("child id 1", "PNC", "2012-01-01", EasyMap.mapOf("day", "2"))); Mockito.verify(serviceProvidedService).add(new ServiceProvided("child id 2", "PNC", "2012-01-01", EasyMap.mapOf("day", "2"))); } |
ChildService { public void close(FormSubmission submission) { allBeneficiaries.closeChild(submission.entityId()); } ChildService(AllBeneficiaries allBeneficiariesArg, MotherRepository
motherRepositoryArg, ChildRepository childRepositoryArg, AllTimelineEvents
allTimelineEventsArg, ServiceProvidedService serviceProvidedServiceArg, AllAlerts
allAlertsArg); void register(FormSubmission submission); void registerForEC(FormSubmission submission); void pncRegistrationOA(FormSubmission submission); void updateImmunizations(FormSubmission submission); void pncVisitHappened(FormSubmission submission); void close(FormSubmission submission); void updatePhotoPath(String entityId, String imagePath); void updateIllnessStatus(FormSubmission submission); void updateVitaminAProvided(FormSubmission submission); void registerForOA(FormSubmission submission); } | @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(submission.entityId(), date, createChildIllnessMap(submission))); } ChildService(AllBeneficiaries allBeneficiariesArg, MotherRepository
motherRepositoryArg, ChildRepository childRepositoryArg, AllTimelineEvents
allTimelineEventsArg, ServiceProvidedService serviceProvidedServiceArg, AllAlerts
allAlertsArg); void register(FormSubmission submission); void registerForEC(FormSubmission submission); void pncRegistrationOA(FormSubmission submission); void updateImmunizations(FormSubmission submission); void pncVisitHappened(FormSubmission submission); void close(FormSubmission submission); void updatePhotoPath(String entityId, String imagePath); void updateIllnessStatus(FormSubmission submission); void updateVitaminAProvided(FormSubmission submission); void registerForOA(FormSubmission submission); } | @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.getFieldValue("sickVisitDate")).thenReturn("2012-01-01"); Mockito.when(submission.getFieldValue("childSigns")).thenReturn("child signs"); Mockito.when(submission.getFieldValue("childSignsOther")).thenReturn("child signs other"); Mockito.when(submission.getFieldValue("reportChildDisease")).thenReturn("report child disease"); Mockito.when(submission.getFieldValue("reportChildDiseaseOther")).thenReturn("report child disease other"); Mockito.when(submission.getFieldValue("reportChildDiseaseDate")).thenReturn(null); Mockito.when(submission.getFieldValue("reportChildDiseasePlace")).thenReturn("report child disease place"); Mockito.when(submission.getFieldValue("childReferral")).thenReturn("child referral"); service.updateIllnessStatus(submission); Map<String, String> map = EasyMap.create("sickVisitDate", "2012-01-01") .put("childSignsOther", "child signs other") .put("childSigns", "child signs") .put("reportChildDisease", "report child disease") .put("reportChildDiseaseOther", "report child disease other") .put("reportChildDiseaseDate", null) .put("reportChildDiseasePlace", "report child disease place") .put("childReferral", "child referral").map(); Mockito.verify(serviceProvidedService).add(ServiceProvided.forChildIllnessVisit("child id 1", "2012-01-01", map)); } |
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.getFieldValue(AllConstants.VitaminAFields.VITAMIN_A_PLACE))); } ChildService(AllBeneficiaries allBeneficiariesArg, MotherRepository
motherRepositoryArg, ChildRepository childRepositoryArg, AllTimelineEvents
allTimelineEventsArg, ServiceProvidedService serviceProvidedServiceArg, AllAlerts
allAlertsArg); void register(FormSubmission submission); void registerForEC(FormSubmission submission); void pncRegistrationOA(FormSubmission submission); void updateImmunizations(FormSubmission submission); void pncVisitHappened(FormSubmission submission); void close(FormSubmission submission); void updatePhotoPath(String entityId, String imagePath); void updateIllnessStatus(FormSubmission submission); void updateVitaminAProvided(FormSubmission submission); void registerForOA(FormSubmission submission); } | @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(submission.getFieldValue("vitaminADose")).thenReturn("1"); Mockito.when(submission.getFieldValue("vitaminAPlace")).thenReturn("PHC"); service.updateVitaminAProvided(submission); Mockito.verify(serviceProvidedService).add(ServiceProvided.forVitaminAProvided("child id 1", "2012-01-01", "1", "PHC")); } |
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 = createImmunizationDateFieldMap(); String immunizationsGiven = submission .getFieldValue(AllConstants.ChildRegistrationOAFields.IMMUNIZATIONS_GIVEN); immunizationsGiven = isBlank(immunizationsGiven) ? "" : immunizationsGiven; allTimelines.add(forChildBirthInChildProfile(submission.getFieldValue(CHILD_ID), submission.getFieldValue(AllConstants.ChildRegistrationOAFields.DATE_OF_BIRTH), submission.getFieldValue(AllConstants.ChildRegistrationOAFields.WEIGHT), immunizationsGiven)); for (String immunization : immunizationsGiven.split(SPACE)) { serviceProvidedService.add(ServiceProvided .forChildImmunization(submission.entityId(), immunization, submission.getFieldValue(immunizationDateFieldMap.get(immunization)))); } } ChildService(AllBeneficiaries allBeneficiariesArg, MotherRepository
motherRepositoryArg, ChildRepository childRepositoryArg, AllTimelineEvents
allTimelineEventsArg, ServiceProvidedService serviceProvidedServiceArg, AllAlerts
allAlertsArg); void register(FormSubmission submission); void registerForEC(FormSubmission submission); void pncRegistrationOA(FormSubmission submission); void updateImmunizations(FormSubmission submission); void pncVisitHappened(FormSubmission submission); void close(FormSubmission submission); void updatePhotoPath(String entityId, String imagePath); void updateIllnessStatus(FormSubmission submission); void updateVitaminAProvided(FormSubmission submission); void registerForOA(FormSubmission submission); } | @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.getFieldValue("id")).thenReturn("child id 1"); Mockito.when(submission.getFieldValue("dateOfBirth")).thenReturn("2013-01-02"); Mockito.when(submission.getFieldValue("gender")).thenReturn("female"); Mockito.when(submission.getFieldValue("weight")).thenReturn("3"); Mockito.when(submission.getFieldValue("immunizationsGiven")).thenReturn("bcg opv_0"); Mockito.when(submission.getFieldValue("bcgDate")).thenReturn("2012-01-06"); Mockito.when(submission.getFieldValue("opv0Date")).thenReturn("2012-01-07"); Mockito.when(submission.getFieldValue("thayiCardNumber")).thenReturn("1234567"); Mockito.when(allBeneficiaries.findChild("child id 1")).thenReturn(child); service.registerForOA(submission); Mockito.verify(child).setThayiCardNumber("1234567"); Mockito.verify(allBeneficiaries).updateChild(child); Mockito.verify(allTimelineEvents).add(TimelineEvent.forChildBirthInChildProfile("child id 1", "2013-01-02", "3", "bcg opv_0")); Mockito.verify(serviceProvidedService).add(ServiceProvided.forChildImmunization("ec id 1", "bcg", "2012-01-06")); Mockito.verify(serviceProvidedService).add(ServiceProvided.forChildImmunization("ec id 1", "opv_0", "2012-01-07")); } |
ActionService { public FetchStatus fetchNewActions() { String previousFetchIndex = allSettings.fetchPreviousFetchIndex(); Response<List<Action>> response = drishtiService .fetchNewActions(allSharedPreference.fetchRegisteredANM(), previousFetchIndex); if (response.isFailure()) { return fetchedFailed; } if (response.payload().isEmpty()) { return nothingFetched; } handleActions(response); return FetchStatus.fetched; } ActionService(DrishtiService drishtiService, AllSettings allSettings,
AllSharedPreferences allSharedPreferences, AllReports allReports); ActionService(DrishtiService drishtiService, AllSettings allSettings,
AllSharedPreferences allSharedPreferences, AllReports allReports,
ActionRouter actionRouter); FetchStatus fetchNewActions(); } | @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.verifyNoMoreInteractions(drishtiService); Mockito.verifyNoMoreInteractions(actionRouter); }
@Test public void shouldNotSaveAnythingIfTheDrishtiResponseStatusIsFailure() throws Exception { setupActions(ResponseStatus.failure, Arrays.asList(ActionBuilder.actionForCloseAlert("Case X", "ANC 1", "2012-01-01", "0"))); Assert.assertEquals(FetchStatus.fetchedFailed, service.fetchNewActions()); Mockito.verify(drishtiService).fetchNewActions("ANM X", "1234"); Mockito.verifyNoMoreInteractions(drishtiService); Mockito.verifyNoMoreInteractions(actionRouter); }
@Test public void shouldFetchAlertActionsAndSaveThemToRepository() throws Exception { Action action = ActionBuilder.actionForCreateAlert("Case X", "normal", "mother", "Ante Natal Care - Normal", "ANC 1", "2012-01-01", null, "0"); setupActions(ResponseStatus.success, Arrays.asList(action)); Assert.assertEquals(FetchStatus.fetched, service.fetchNewActions()); Mockito.verify(drishtiService).fetchNewActions("ANM X", "1234"); Mockito.verify(actionRouter).directAlertAction(action); }
@Test public void shouldUpdatePreviousIndexWithIndexOfEachActionThatIsHandled() throws Exception { Action firstAction = ActionBuilder.actionForCreateAlert("Case X", "normal", "mother", "Ante Natal Care - Normal", "ANC 1", "2012-01-01", "2012-01-22", "11111"); Action secondAction = ActionBuilder.actionForCreateAlert("Case Y", "normal", "mother", "Ante Natal Care - Normal", "ANC 2", "2012-01-01", "2012-01-11", "12345"); setupActions(ResponseStatus.success, Arrays.asList(firstAction, secondAction)); service.fetchNewActions(); InOrder inOrder = Mockito.inOrder(actionRouter, allSettings); inOrder.verify(actionRouter).directAlertAction(firstAction); inOrder.verify(allSettings).savePreviousFetchIndex("11111"); inOrder.verify(actionRouter).directAlertAction(secondAction); inOrder.verify(allSettings).savePreviousFetchIndex("12345"); } |
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; if ((rJson = retrieveRelationshipJsonForLink(link, json)) != null) { String[] path = link.split("\\."); String parentTable = path[0]; String childTable = path[1]; String joinValueKey = parentTable.equals(rJson.getString("parent")) ? rJson.getString("from") : rJson.getString("to"); joinValueKey = joinValueKey.contains(".") ? joinValueKey .substring(joinValueKey.lastIndexOf(".") + 1) : joinValueKey; String val = entityJson.getString(joinValueKey); String joinField = parentTable.equals(rJson.getString("parent")) ? rJson.getString("to") : rJson.getString("from"); String sql = "select * from " + childTable + " where " + joinField + "=?"; Timber.d(sql); String dbEntity = theAppContext.formDataRepository().queryUniqueResult(sql, new String[]{val}); JSONObject linkedEntityJson = new JSONObject(); if (dbEntity != null && !dbEntity.isEmpty()) { linkedEntityJson = new JSONObject(dbEntity); } String sourceKey = link.substring(link.lastIndexOf(".") + 1); if (linkedEntityJson.has(sourceKey)) { return linkedEntityJson.getString(sourceKey); } } } catch (Exception e) { Timber.e(e); } return null; } FormUtils(Context context); static FormUtils getInstance(Context ctx); static boolean hasChildElements(Node element); static int getIndexForFormName(String formName, String[] formNames); FormSubmission generateFormSubmisionFromXMLString(String entity_id, String formData,
String formName, JSONObject
overrides); String generateXMLInputForFormWithEntityId(String entityId, String formName, String
overrides); Object getObjectAtPath(String[] path, JSONObject jsonObject); JSONArray getPopulatedFieldsForArray(JSONObject fieldsDefinition, String entityId,
JSONObject jsonObject, JSONObject overrides); String retrieveValueForLinkedRecord(String link, JSONObject entityJson); JSONArray getFieldsArrayForSubFormDefinition(JSONObject fieldsDefinition); JSONObject getFieldValuesForSubFormDefinition(JSONObject fieldsDefinition, String
relationalId, String entityId, JSONObject jsonObject, JSONObject overrides); String getValueForPath(String[] path, JSONObject jsonObject); JSONObject getFormJson(String formIdentity); static final String TAG; static final String ecClientRelationships; } | @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 invocation) throws Throwable { return new FileInputStream(getFileFromPath(this, entityRelationShip)); } }); JSONObject mockobject = Mockito.mock(JSONObject.class); Mockito.when(mockobject.getString(Mockito.anyString())).thenReturn("val"); formUtils.retrieveValueForLinkedRecord("household.elco", mockobject); } |
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() { ReplicationIntentService replicationIntentService = new ReplicationIntentService("service_name"); Assert.assertNotNull(replicationIntentService); replicationIntentService.onHandleIntent(null); } |
MotherService { public void registerANC(FormSubmission submission) { addTimelineEventsForMotherRegistration(submission); } MotherService(AllBeneficiaries allBeneficiaries, AllEligibleCouples
allEligibleCouples, AllTimelineEvents allTimelineEvents, ServiceProvidedService
serviceProvidedService); void registerANC(FormSubmission submission); void registerOutOfAreaANC(FormSubmission submission); void ancVisit(FormSubmission submission); void close(FormSubmission submission); void close(String entityId, String reason); void ttProvided(FormSubmission submission); void ifaTabletsGiven(FormSubmission submission); void hbTest(FormSubmission submission); void deliveryOutcome(FormSubmission submission); void pncVisitHappened(FormSubmission submission); void deliveryPlan(FormSubmission submission); static final String MOTHER_ID; static String submissionDate; } | @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(submission.getFieldValue("registrationDate")).thenReturn("2012-01-02"); when(submission.getFieldValue("referenceDate")).thenReturn("2012-01-01"); service.registerANC(submission); allTimelineEvents.add(TimelineEvent.forStartOfPregnancy("mother id 1", "2012-01-02", "2012-01-01")); allTimelineEvents.add(TimelineEvent.forStartOfPregnancyForEC("entity id 1", "thayi 1", "2012-01-02", "2012-01-01")); } |
MotherService { public void registerOutOfAreaANC(FormSubmission submission) { addTimelineEventsForMotherRegistration(submission); } MotherService(AllBeneficiaries allBeneficiaries, AllEligibleCouples
allEligibleCouples, AllTimelineEvents allTimelineEvents, ServiceProvidedService
serviceProvidedService); void registerANC(FormSubmission submission); void registerOutOfAreaANC(FormSubmission submission); void ancVisit(FormSubmission submission); void close(FormSubmission submission); void close(String entityId, String reason); void ttProvided(FormSubmission submission); void ifaTabletsGiven(FormSubmission submission); void hbTest(FormSubmission submission); void deliveryOutcome(FormSubmission submission); void pncVisitHappened(FormSubmission submission); void deliveryPlan(FormSubmission submission); static final String MOTHER_ID; static String submissionDate; } | @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"); when(submission.getFieldValue("registrationDate")).thenReturn("2012-01-02"); when(submission.getFieldValue("referenceDate")).thenReturn("2012-01-01"); service.registerOutOfAreaANC(submission); allTimelineEvents.add(TimelineEvent.forStartOfPregnancy("mother id 1", "2012-01-02", "2012-01-01")); allTimelineEvents.add(TimelineEvent.forStartOfPregnancyForEC("entity id 1", "thayi 1", "2012-01-02", "2012-01-01")); } |
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_DIASTOLIC)) .put(TEMPERATURE, submission.getFieldValue(TEMPERATURE)) .put(WEIGHT, submission.getFieldValue(WEIGHT)).map())); serviceProvidedService.add(ServiceProvided.forANCCareProvided(submission.entityId(), submission.getFieldValue(ANC_VISIT_NUMBER), submission.getFieldValue(ANC_VISIT_DATE), submission.getFieldValue(BP_SYSTOLIC), submission.getFieldValue(BP_DIASTOLIC), submission.getFieldValue(WEIGHT))); } MotherService(AllBeneficiaries allBeneficiaries, AllEligibleCouples
allEligibleCouples, AllTimelineEvents allTimelineEvents, ServiceProvidedService
serviceProvidedService); void registerANC(FormSubmission submission); void registerOutOfAreaANC(FormSubmission submission); void ancVisit(FormSubmission submission); void close(FormSubmission submission); void close(String entityId, String reason); void ttProvided(FormSubmission submission); void ifaTabletsGiven(FormSubmission submission); void hbTest(FormSubmission submission); void deliveryOutcome(FormSubmission submission); void pncVisitHappened(FormSubmission submission); void deliveryPlan(FormSubmission submission); static final String MOTHER_ID; static String submissionDate; } | @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")).thenReturn("2"); when(submission.getFieldValue("weight")).thenReturn("21"); when(submission.getFieldValue("bpDiastolic")).thenReturn("80"); when(submission.getFieldValue("bpSystolic")).thenReturn("90"); when(submission.getFieldValue("temperature")).thenReturn("98.5"); service.ancVisit(submission); verify(allTimelineEvents).add(TimelineEvent.forANCCareProvided("entity id 1", "2", "2013-01-01", create("bpDiastolic", "80").put("bpSystolic", "90").put("temperature", "98.5").put("weight", "21").map())); }
@Test public void shouldAddServiceProvidedWhenANCVisitHappens() 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")).thenReturn("1"); when(submission.getFieldValue("weight")).thenReturn("21"); when(submission.getFieldValue("bpDiastolic")).thenReturn("80"); when(submission.getFieldValue("bpSystolic")).thenReturn("90"); service.ancVisit(submission); verify(serviceProvidedService).add( new ServiceProvided("entity id 1", "ANC 1", "2013-01-01", create("bpDiastolic", "80").put("bpSystolic", "90").put("weight", "21").map())); } |
MotherService { public void close(FormSubmission submission) { close(submission.entityId(), submission.getFieldValue(CLOSE_REASON_FIELD_NAME)); } MotherService(AllBeneficiaries allBeneficiaries, AllEligibleCouples
allEligibleCouples, AllTimelineEvents allTimelineEvents, ServiceProvidedService
serviceProvidedService); void registerANC(FormSubmission submission); void registerOutOfAreaANC(FormSubmission submission); void ancVisit(FormSubmission submission); void close(FormSubmission submission); void close(String entityId, String reason); void ttProvided(FormSubmission submission); void ifaTabletsGiven(FormSubmission submission); void hbTest(FormSubmission submission); void deliveryOutcome(FormSubmission submission); void pncVisitHappened(FormSubmission submission); void deliveryPlan(FormSubmission submission); static final String MOTHER_ID; static String submissionDate; } | @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(allBeneficiaries, times(0)).closeMother("entity id 1"); verifyZeroInteractions(allEligibleCouples); }
@Test public void shouldCloseECWhenMotherIsClosedAndReasonIsDeath() throws Exception { FormSubmission submission = mock(FormSubmission.class); when(submission.entityId()).thenReturn("entity id 1"); when(submission.getFieldValue("closeReason")).thenReturn("death_of_mother"); when(allBeneficiaries.findMotherWithOpenStatus("entity id 1")).thenReturn(new Mother("entity id 1", "ec entity id 1", "thayi 1", "2013-01-01")); service.close(submission); verify(allEligibleCouples).close("ec entity id 1"); }
@Test public void shouldCloseECWhenWomanIsClosedAndReasonIsDeath() throws Exception { FormSubmission submission = mock(FormSubmission.class); when(submission.entityId()).thenReturn("entity id 1"); when(submission.getFieldValue("closeReason")).thenReturn("death_of_woman"); when(allBeneficiaries.findMotherWithOpenStatus("entity id 1")).thenReturn(new Mother("entity id 1", "ec entity id 1", "thayi 1", "2013-01-01")); service.close(submission); verify(allEligibleCouples).close("ec entity id 1"); }
@Test public void shouldCloseECWhenMotherIsClosedAndReasonIsPermanentRelocation() throws Exception { FormSubmission submission = mock(FormSubmission.class); when(submission.entityId()).thenReturn("entity id 1"); when(submission.getFieldValue("closeReason")).thenReturn("relocation_permanent"); when(allBeneficiaries.findMotherWithOpenStatus("entity id 1")).thenReturn(new Mother("entity id 1", "ec entity id 1", "thayi 1", "2013-01-01")); service.close(submission); verify(allEligibleCouples).close("ec entity id 1"); }
@Test public void shouldCloseECWhenMotherIsClosedUsingPNCCloseAndReasonIsPermanentRelocation() throws Exception { FormSubmission submission = mock(FormSubmission.class); when(submission.entityId()).thenReturn("entity id 1"); when(submission.getFieldValue("closeReason")).thenReturn("permanent_relocation"); when(allBeneficiaries.findMotherWithOpenStatus("entity id 1")).thenReturn(new Mother("entity id 1", "ec entity id 1", "thayi 1", "2013-01-01")); service.close(submission); verify(allEligibleCouples).close("ec entity id 1"); }
@Test public void shouldNotCloseECWhenMotherIsClosedForOtherReasons() throws Exception { FormSubmission submission = mock(FormSubmission.class); when(submission.entityId()).thenReturn("entity id 1"); when(submission.getFieldValue("closeReason")).thenReturn("other_reason"); when(allBeneficiaries.findMotherWithOpenStatus("entity id 1")).thenReturn(new Mother("entity id 1", "ec entity id 1", "thayi 1", "2013-01-01")); service.close(submission); verifyZeroInteractions(allEligibleCouples); } |
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 = new JSONObject(overridesStr); } String formDefinitionJson = readFileFromAssetsFolder( "www/form/" + formName + "/form_definition.json"); JSONObject formDefinition = new JSONObject(formDefinitionJson); String ec_bind_path = formDefinition.getJSONObject("form").getString("ec_bind_type"); String sql = "select * from " + ec_bind_path + " where base_entity_id =?"; Map<String, String> dbEntity = theAppContext.formDataRepository(). getMapFromSQLQuery(sql, new String[]{entityId}); Map<String, String> detailsMap = theAppContext.detailsRepository(). getAllDetailsForClient(entityId); detailsMap.putAll(dbEntity); JSONObject entityJson = new JSONObject(); if (detailsMap != null && !detailsMap.isEmpty()) { entityJson = new JSONObject(detailsMap); } String formModelString = readFileFromAssetsFolder( "www/form/" + formName + "/model" + ".xml").replaceAll("\n", " ") .replaceAll("\r", " "); InputStream is = new ByteArrayInputStream(formModelString.getBytes()); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setValidating(false); DocumentBuilder db = dbf.newDocumentBuilder(); Document document = db.parse(is); XmlSerializer serializer = Xml.newSerializer(); StringWriter writer = new StringWriter(); serializer.setOutput(writer); serializer.startDocument(CharEncoding.UTF_8, true); NodeList els = ((Element) document.getElementsByTagName("model").item(0)). getElementsByTagName("instance"); Element el = (Element) els.item(0); NodeList entries = el.getChildNodes(); int num = entries.getLength(); for (int i = 0; i < num; i++) { Node n = entries.item(i); if (n instanceof Element) { Element node = (Element) n; writeXML(node, serializer, fieldOverrides, formDefinition, entityJson, null); } } serializer.endDocument(); String xml = writer.toString(); xml = xml.substring(56); System.out.println(xml); return xml; } catch (Exception e) { Timber.e(e); } return ""; } FormUtils(Context context); static FormUtils getInstance(Context ctx); static boolean hasChildElements(Node element); static int getIndexForFormName(String formName, String[] formNames); FormSubmission generateFormSubmisionFromXMLString(String entity_id, String formData,
String formName, JSONObject
overrides); String generateXMLInputForFormWithEntityId(String entityId, String formName, String
overrides); Object getObjectAtPath(String[] path, JSONObject jsonObject); JSONArray getPopulatedFieldsForArray(JSONObject fieldsDefinition, String entityId,
JSONObject jsonObject, JSONObject overrides); String retrieveValueForLinkedRecord(String link, JSONObject entityJson); JSONArray getFieldsArrayForSubFormDefinition(JSONObject fieldsDefinition); JSONObject getFieldValuesForSubFormDefinition(JSONObject fieldsDefinition, String
relationalId, String entityId, JSONObject jsonObject, JSONObject overrides); String getValueForPath(String[] path, JSONObject jsonObject); JSONObject getFormJson(String formIdentity); static final String TAG; static final String ecClientRelationships; } | @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 invocation) throws Throwable { return new FileInputStream(getFileFromPath(this, formDefinition)); } }); Mockito.when(assetManager.open(model)).thenAnswer(new Answer<InputStream>() { @Override public InputStream answer(InvocationOnMock invocation) throws Throwable { return new FileInputStream(getFileFromPath(this, model)); } }); Mockito.when(assetManager.open(formJSON)).thenAnswer(new Answer<InputStream>() { @Override public InputStream answer(InvocationOnMock invocation) throws Throwable { return new FileInputStream(getFileFromPath(this, formJSON)); } }); FormDataRepository formDataRepository = Mockito.mock(FormDataRepository.class); Mockito.when(context.formDataRepository()).thenReturn(formDataRepository); Mockito.when(formDataRepository.getMapFromSQLQuery(Mockito.anyString(),Mockito.any(String[].class))).thenReturn(new HashMap<String, String>()); DetailsRepository detailsRepository = Mockito.mock(DetailsRepository.class); Mockito.when(context.detailsRepository()).thenReturn(detailsRepository); Mockito.when(detailsRepository.getAllDetailsForClient(Mockito.anyString())).thenReturn(new HashMap<String, String>()); PowerMockito.mockStatic(Xml.class); XmlSerializerMock xmlSerializer = new XmlSerializerMock(); PowerMockito.when(Xml.newSerializer()).thenReturn(xmlSerializer); Assert.assertNotNull(formUtils.generateXMLInputForFormWithEntityId("baseEntityId", FORMNAME, null)); } |
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(TT_DATE))); } MotherService(AllBeneficiaries allBeneficiaries, AllEligibleCouples
allEligibleCouples, AllTimelineEvents allTimelineEvents, ServiceProvidedService
serviceProvidedService); void registerANC(FormSubmission submission); void registerOutOfAreaANC(FormSubmission submission); void ancVisit(FormSubmission submission); void close(FormSubmission submission); void close(String entityId, String reason); void ttProvided(FormSubmission submission); void ifaTabletsGiven(FormSubmission submission); void hbTest(FormSubmission submission); void deliveryOutcome(FormSubmission submission); void pncVisitHappened(FormSubmission submission); void deliveryPlan(FormSubmission submission); static final String MOTHER_ID; static String submissionDate; } | @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.ttProvided(submission); verify(allTimelineEvents).add(forTTShotProvided("entity id 1", "ttbooster", "2013-01-01")); verify(serviceProvidedService).add(new ServiceProvided("entity id 1", "TT Booster", "2013-01-01", mapOf("dose", "TT Booster"))); } |
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(IFA_TABLETS_DATE))); serviceProvidedService.add(ServiceProvided .forIFATabletsGiven(submission.entityId(), numberOfIFATabletsGiven, submission.getFieldValue(IFA_TABLETS_DATE))); } } MotherService(AllBeneficiaries allBeneficiaries, AllEligibleCouples
allEligibleCouples, AllTimelineEvents allTimelineEvents, ServiceProvidedService
serviceProvidedService); void registerANC(FormSubmission submission); void registerOutOfAreaANC(FormSubmission submission); void ancVisit(FormSubmission submission); void close(FormSubmission submission); void close(String entityId, String reason); void ttProvided(FormSubmission submission); void ifaTabletsGiven(FormSubmission submission); void hbTest(FormSubmission submission); void deliveryOutcome(FormSubmission submission); void pncVisitHappened(FormSubmission submission); void deliveryPlan(FormSubmission submission); static final String MOTHER_ID; static String submissionDate; } | @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")).thenReturn("2013-02-01"); service.ifaTabletsGiven(submission); verify(allTimelineEvents).add(forIFATabletsGiven("entity id 1", "100", "2013-02-01")); }
@Test public void shouldAddServiceProvidedWhenIFATabletsAreGiven() throws Exception { FormSubmission submission = mock(FormSubmission.class); when(submission.entityId()).thenReturn("entity id 1"); when(submission.getFieldValue("numberOfIFATabletsGiven")).thenReturn("100"); when(submission.getFieldValue("ifaTabletsDate")).thenReturn("2013-02-01"); service.ifaTabletsGiven(submission); verify(serviceProvidedService).add(new ServiceProvided("entity id 1", "IFA", "2013-02-01", mapOf("dose", "100"))); }
@Test public void shouldDoNothingWhenIFATabletsAreNotGiven() throws Exception { FormSubmission submission = mock(FormSubmission.class); when(submission.entityId()).thenReturn("entity id 1"); when(submission.getFieldValue("numberOfIFATabletsGiven")).thenReturn("0"); when(submission.getFieldValue("ifaTabletsDate")).thenReturn("2013-02-01"); service.ifaTabletsGiven(submission); verifyZeroInteractions(allTimelineEvents); verifyZeroInteractions(serviceProvidedService); } |
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, AllTimelineEvents allTimelineEvents, ServiceProvidedService
serviceProvidedService); void registerANC(FormSubmission submission); void registerOutOfAreaANC(FormSubmission submission); void ancVisit(FormSubmission submission); void close(FormSubmission submission); void close(String entityId, String reason); void ttProvided(FormSubmission submission); void ifaTabletsGiven(FormSubmission submission); void hbTest(FormSubmission submission); void deliveryOutcome(FormSubmission submission); void pncVisitHappened(FormSubmission submission); void deliveryPlan(FormSubmission submission); static final String MOTHER_ID; static String submissionDate; } | @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(submission); verify(serviceProvidedService).add(new ServiceProvided("entity id 1", "Hb Test", "2013-01-01", mapOf("hbLevel", "11"))); } |
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.getFieldValue(DID_WOMAN_SURVIVE)) || BOOLEAN_FALSE .equals(submission.getFieldValue(DID_MOTHER_SURVIVE))) { allBeneficiaries.closeMother(submission.entityId()); allEligibleCouples.close(mother.ecCaseId()); return; } allBeneficiaries.switchMotherToPNC(submission.entityId()); } MotherService(AllBeneficiaries allBeneficiaries, AllEligibleCouples
allEligibleCouples, AllTimelineEvents allTimelineEvents, ServiceProvidedService
serviceProvidedService); void registerANC(FormSubmission submission); void registerOutOfAreaANC(FormSubmission submission); void ancVisit(FormSubmission submission); void close(FormSubmission submission); void close(String entityId, String reason); void ttProvided(FormSubmission submission); void ifaTabletsGiven(FormSubmission submission); void hbTest(FormSubmission submission); void deliveryOutcome(FormSubmission submission); void pncVisitHappened(FormSubmission submission); void deliveryPlan(FormSubmission submission); static final String MOTHER_ID; static String submissionDate; } | @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(new Mother("entity id 1", "ec id 1", "1234567", "2014-01-01")); service.deliveryOutcome(submission); verify(allBeneficiaries).switchMotherToPNC("entity id 1"); } |
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.PNCVisitFields.BP_SYSTOLIC), submission.getFieldValue(AllConstants.PNCVisitFields.BP_DIASTOLIC), submission.getFieldValue(AllConstants.PNCVisitFields.TEMPERATURE), submission.getFieldValue(AllConstants.PNCVisitFields.HB_LEVEL))); serviceProvidedService.add(ServiceProvided.forMotherPNCVisit(submission.entityId(), submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DAY), submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DATE))); String numberOfIFATabletsGiven = submission .getFieldValue(AllConstants.PNCVisitFields.NUMBER_OF_IFA_TABLETS_GIVEN); if (tryParse(numberOfIFATabletsGiven, 0) > 0) { allTimelines.add(forIFATabletsGiven(submission.entityId(), numberOfIFATabletsGiven, submission.getFieldValue(SUBMISSION_DATE))); } } MotherService(AllBeneficiaries allBeneficiaries, AllEligibleCouples
allEligibleCouples, AllTimelineEvents allTimelineEvents, ServiceProvidedService
serviceProvidedService); void registerANC(FormSubmission submission); void registerOutOfAreaANC(FormSubmission submission); void ancVisit(FormSubmission submission); void close(FormSubmission submission); void close(String entityId, String reason); void ttProvided(FormSubmission submission); void ifaTabletsGiven(FormSubmission submission); void hbTest(FormSubmission submission); void deliveryOutcome(FormSubmission submission); void pncVisitHappened(FormSubmission submission); void deliveryPlan(FormSubmission submission); static final String MOTHER_ID; static String submissionDate; } | @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("2012-01-01"); when(submission.getFieldValue("numberOfIFATabletsGiven")).thenReturn("100"); when(submission.getFieldValue("bpSystolic")).thenReturn("120"); when(submission.getFieldValue("bpDiastolic")).thenReturn("80"); when(submission.getFieldValue("temperature")).thenReturn("98.1"); when(submission.getFieldValue("hbLevel")).thenReturn("10.0"); when(submission.getFieldValue("submissionDate")).thenReturn("2013-01-01"); service.pncVisitHappened(submission); verify(allTimelineEvents).add(TimelineEvent.forMotherPNCVisit("entity id 1", "2", "2012-01-01", "120", "80", "98.1", "10.0")); }
@Test public void shouldAddIFATabletsGivenTimelineEventWhenPNCVisitHappens() 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("2012-01-01"); when(submission.getFieldValue("numberOfIFATabletsGiven")).thenReturn("100"); when(submission.getFieldValue("bpSystolic")).thenReturn("120"); when(submission.getFieldValue("bpDiastolic")).thenReturn("80"); when(submission.getFieldValue("temperature")).thenReturn("98.1"); when(submission.getFieldValue("hbLevel")).thenReturn("10.0"); when(submission.getFieldValue("submissionDate")).thenReturn("2012-01-02"); service.pncVisitHappened(submission); verify(allTimelineEvents).add(forIFATabletsGiven("entity id 1", "100", "2012-01-02")); }
@Test public void shouldAddPNCVisitServiceProvidedWhenPNCVisitHappens() 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("2012-01-01"); when(submission.getFieldValue("numberOfIFATabletsGiven")).thenReturn("100"); when(submission.getFieldValue("bpSystolic")).thenReturn("120"); when(submission.getFieldValue("bpDiastolic")).thenReturn("80"); when(submission.getFieldValue("temperature")).thenReturn("98.1"); when(submission.getFieldValue("hbLevel")).thenReturn("10.0"); when(submission.getFieldValue("submissionDate")).thenReturn("2013-01-01"); service.pncVisitHappened(submission); verify(serviceProvidedService).add(new ServiceProvided("entity id 1", "PNC", "2012-01-01", mapOf("day", "2"))); }
@Test public void shouldNotAddIFATabletsGivenTimelineEventWhenPNCVisitHappensAndNoIFATabletsWereGiven() 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("2012-01-01"); when(submission.getFieldValue("numberOfIFATabletsGiven")).thenReturn(""); when(submission.getFieldValue("ifaTabletsDate")).thenReturn(null); when(submission.getFieldValue("bpSystolic")).thenReturn("120"); when(submission.getFieldValue("bpDiastolic")).thenReturn("80"); when(submission.getFieldValue("temperature")).thenReturn("98.1"); when(submission.getFieldValue("hbLevel")).thenReturn("10.0"); service.pncVisitHappened(submission); verify(allTimelineEvents, times(0)).add(forIFATabletsGiven("entity id 1", "2012-01-01", "100")); } |
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/" + formName + "/form_definition.json"); JSONObject formDefinition = new JSONObject(formDefinitionJson); String rootNodeKey = formSubmission.keys().next(); entity_id = formSubmission.getJSONObject(rootNodeKey).has(databaseIdKey) ? formSubmission .getJSONObject(rootNodeKey).getString(databaseIdKey) : generateRandomUUIDString(); JSONObject fieldsDefinition = formDefinition.getJSONObject("form"); JSONArray populatedFieldsArray = getPopulatedFieldsForArray(fieldsDefinition, entity_id, formSubmission, overrides); formDefinition.getJSONObject("form").put("fields", populatedFieldsArray); if (formDefinition.getJSONObject("form").has("sub_forms")) { JSONObject subFormDefinition = formDefinition.getJSONObject("form"). getJSONArray("sub_forms").getJSONObject(0); String bindPath = subFormDefinition.getString("default_bind_path"); JSONArray subFormDataArray = new JSONArray(); Object subFormDataObject = getObjectAtPath(bindPath.split("/"), formSubmission); if (subFormDataObject instanceof JSONObject) { JSONObject subFormData = (JSONObject) subFormDataObject; subFormDataArray.put(0, subFormData); } else if (subFormDataObject instanceof JSONArray) { subFormDataArray = (JSONArray) subFormDataObject; } JSONArray subForms = getSubForms(subFormDataArray, entity_id, subFormDefinition, overrides); formDefinition.getJSONObject("form").put("sub_forms", subForms); } String instanceId = generateRandomUUIDString(); String entityId = retrieveIdForSubmission(formDefinition); String formDefinitionVersionString = formDefinition .getString("form_data_definition_version"); String clientVersion = String.valueOf(new Date().getTime()); String instance = formDefinition.toString(); FormSubmission fs = new FormSubmission(instanceId, entityId, formName, instance, clientVersion, SyncStatus.PENDING, formDefinitionVersionString); generateClientAndEventModelsForFormSubmission(fs, formName); return fs; } FormUtils(Context context); static FormUtils getInstance(Context ctx); static boolean hasChildElements(Node element); static int getIndexForFormName(String formName, String[] formNames); FormSubmission generateFormSubmisionFromXMLString(String entity_id, String formData,
String formName, JSONObject
overrides); String generateXMLInputForFormWithEntityId(String entityId, String formName, String
overrides); Object getObjectAtPath(String[] path, JSONObject jsonObject); JSONArray getPopulatedFieldsForArray(JSONObject fieldsDefinition, String entityId,
JSONObject jsonObject, JSONObject overrides); String retrieveValueForLinkedRecord(String link, JSONObject entityJson); JSONArray getFieldsArrayForSubFormDefinition(JSONObject fieldsDefinition); JSONObject getFieldValuesForSubFormDefinition(JSONObject fieldsDefinition, String
relationalId, String entityId, JSONObject jsonObject, JSONObject overrides); String getValueForPath(String[] path, JSONObject jsonObject); JSONObject getFormJson(String formIdentity); static final String TAG; static final String ecClientRelationships; } | @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(formDefinition)).thenAnswer(new Answer<InputStream>() { @Override public InputStream answer(InvocationOnMock invocation) throws Throwable { return new FileInputStream(getFileFromPath(this, formDefinition)); } }); Mockito.when(assetManager.open(model)).thenAnswer(new Answer<InputStream>() { @Override public InputStream answer(InvocationOnMock invocation) throws Throwable { return new FileInputStream(getFileFromPath(this, model)); } }); Mockito.when(assetManager.open(formJSON)).thenAnswer(new Answer<InputStream>() { @Override public InputStream answer(InvocationOnMock invocation) throws Throwable { return new FileInputStream(getFileFromPath(this, formJSON)); } }); FormDataRepository formDataRepository = Mockito.mock(FormDataRepository.class); Mockito.when(context.formDataRepository()).thenReturn(formDataRepository); Mockito.when(formDataRepository.queryUniqueResult(Mockito.anyString(),Mockito.any(String[].class))).thenReturn(null); Assert.assertNotNull(formUtils.generateFormSubmisionFromXMLString("baseEntityId", formData, FORMNAME, new JSONObject())); } |
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), submission.getFieldValue(PHONE_NUMBER), submission.getFieldValue(REVIEWED_HRP_STATUS), submission.getFieldValue(SUBMISSION_DATE))); serviceProvidedService.add(ServiceProvided.forDeliveryPlan(submission.entityId(), submission.getFieldValue(DELIVERY_FACILITY_NAME), submission.getFieldValue(TRANSPORTATION_PLAN), submission.getFieldValue(BIRTH_COMPANION), submission.getFieldValue(ASHA_PHONE_NUMBER), submission.getFieldValue(PHONE_NUMBER), submission.getFieldValue(REVIEWED_HRP_STATUS), submission.getFieldValue(SUBMISSION_DATE))); } MotherService(AllBeneficiaries allBeneficiaries, AllEligibleCouples
allEligibleCouples, AllTimelineEvents allTimelineEvents, ServiceProvidedService
serviceProvidedService); void registerANC(FormSubmission submission); void registerOutOfAreaANC(FormSubmission submission); void ancVisit(FormSubmission submission); void close(FormSubmission submission); void close(String entityId, String reason); void ttProvided(FormSubmission submission); void ifaTabletsGiven(FormSubmission submission); void hbTest(FormSubmission submission); void deliveryOutcome(FormSubmission submission); void pncVisitHappened(FormSubmission submission); void deliveryPlan(FormSubmission submission); static final String MOTHER_ID; static String submissionDate; } | @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("transportationPlan")).thenReturn("Transportation Plan"); when(submission.getFieldValue("birthCompanion")).thenReturn("Birth Companion"); when(submission.getFieldValue("ashaPhoneNumber")).thenReturn("Asha Phone"); when(submission.getFieldValue("phoneNumber")).thenReturn("1234567890"); when(submission.getFieldValue("reviewedHRPStatus")).thenReturn("HRP Status"); when(submission.getFieldValue("submissionDate")).thenReturn("2012-01-01"); service.deliveryPlan(submission); verify(allTimelineEvents).add(forDeliveryPlan("entity id 1", "Delivery Facility Name", "Transportation Plan", "Birth Companion", "Asha Phone", "1234567890", "HRP Status", "2012-01-01")); }
@Test public void shouldAddServiceProvidedWhenDeliveryPlanHappens() 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("transportationPlan")).thenReturn("Transportation Plan"); when(submission.getFieldValue("birthCompanion")).thenReturn("Birth Companion"); when(submission.getFieldValue("ashaPhoneNumber")).thenReturn("Asha Phone"); when(submission.getFieldValue("phoneNumber")).thenReturn("1234567890"); when(submission.getFieldValue("reviewedHRPStatus")).thenReturn("HRP Status"); when(submission.getFieldValue("submissionDate")).thenReturn("2012-01-01"); service.deliveryPlan(submission); verify(serviceProvidedService).add(ServiceProvided.forDeliveryPlan("entity id 1", "Delivery Facility Name", "Transportation Plan", "Birth Companion", "Asha Phone", "1234567890", "HRP Status", "2012-01-01")); } |
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[] toBytes(StringBuffer stringBuffer); static byte[] toBytes(char[] chars); static char[] toChars(byte[] bytes); static PasswordHash getPasswordHash(char[] password); static byte[] hashPassword(char[] password, byte[] salt); static byte[] nullSafeBase64Decode(String base64EncodedValue); static char[] generateRandomPassphrase(); static final int ITERATION_COUNT; } | @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<Integer> firstArgCaptor = ArgumentCaptor.forClass(Integer.class); ArgumentCaptor<Integer> lastArgCaptor = ArgumentCaptor.forClass(Integer.class); Mockito.verify(editable).getChars(firstArgCaptor.capture(), lengthCaptor.capture(), charsCaptor.capture(), lastArgCaptor.capture()); Assert.assertEquals(2, lengthCaptor.getValue().intValue()); Assert.assertEquals(0, firstArgCaptor.getValue().intValue()); Assert.assertEquals(0, lastArgCaptor.getValue().intValue()); } |
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[] chars); static char[] toChars(byte[] bytes); static PasswordHash getPasswordHash(char[] password); static byte[] hashPassword(char[] password, byte[] salt); static byte[] nullSafeBase64Decode(String base64EncodedValue); static char[] generateRandomPassphrase(); static final int ITERATION_COUNT; } | @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 testClearArrayOverwritesCharArrayValuesWithAsterisk() { char[] sensitiveDataArray = TEST_PASSWORD; SecurityHelper.clearArray(sensitiveDataArray); Assert.assertNotNull(sensitiveDataArray); for (char c : sensitiveDataArray) { Assert.assertEquals('*', c); } } |
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()); clearStringBuffer(stringBuffer); return bytes; } static char[] readValue(Editable editable); static void clearArray(byte[] array); static void clearArray(char[] array); static byte[] toBytes(StringBuffer stringBuffer); static byte[] toBytes(char[] chars); static char[] toChars(byte[] bytes); static PasswordHash getPasswordHash(char[] password); static byte[] hashPassword(char[] password, byte[] salt); static byte[] nullSafeBase64Decode(String base64EncodedValue); static char[] generateRandomPassphrase(); static final int ITERATION_COUNT; } | @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.length); } |
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 clearArray(char[] array); static byte[] toBytes(StringBuffer stringBuffer); static byte[] toBytes(char[] chars); static char[] toChars(byte[] bytes); static PasswordHash getPasswordHash(char[] password); static byte[] hashPassword(char[] password, byte[] salt); static byte[] nullSafeBase64Decode(String base64EncodedValue); static char[] generateRandomPassphrase(); static final int ITERATION_COUNT; } | @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.assertNull(decoded); } |
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.getApplicationContext().getAssets() .open("json.form" + locale + "/" + formIdentity + AllConstants.JSON_FILE_EXTENSION); } catch (FileNotFoundException e) { inputStream = mContext.getApplicationContext().getAssets() .open("json.form/" + formIdentity + AllConstants.JSON_FILE_EXTENSION); } BufferedReader reader = new BufferedReader( new InputStreamReader(inputStream, CharEncoding.UTF_8)); String jsonString; StringBuilder stringBuilder = new StringBuilder(); while ((jsonString = reader.readLine()) != null) { stringBuilder.append(jsonString); } inputStream.close(); return new JSONObject(stringBuilder.toString()); } catch (IOException | JSONException e) { Timber.e(e); } } return null; } FormUtils(Context context); static FormUtils getInstance(Context ctx); static boolean hasChildElements(Node element); static int getIndexForFormName(String formName, String[] formNames); FormSubmission generateFormSubmisionFromXMLString(String entity_id, String formData,
String formName, JSONObject
overrides); String generateXMLInputForFormWithEntityId(String entityId, String formName, String
overrides); Object getObjectAtPath(String[] path, JSONObject jsonObject); JSONArray getPopulatedFieldsForArray(JSONObject fieldsDefinition, String entityId,
JSONObject jsonObject, JSONObject overrides); String retrieveValueForLinkedRecord(String link, JSONObject entityJson); JSONArray getFieldsArrayForSubFormDefinition(JSONObject fieldsDefinition); JSONObject getFieldValuesForSubFormDefinition(JSONObject fieldsDefinition, String
relationalId, String entityId, JSONObject jsonObject, JSONObject overrides); String getValueForPath(String[] path, JSONObject jsonObject); JSONObject getFormJson(String formIdentity); static final String TAG; static final String ecClientRelationships; } | @Test public void getFormJsonShouldReturnCorrectFormWithSameLength() { Mockito.doReturn(RuntimeEnvironment.application.getResources()).when(context_).getResources(); Mockito.doReturn(RuntimeEnvironment.application.getApplicationContext()).when(context_).getApplicationContext(); Assert.assertEquals(10011, formUtils.getFormJson("test_basic_form").toString().length()); } |
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); static byte[] toBytes(char[] chars); static char[] toChars(byte[] bytes); static PasswordHash getPasswordHash(char[] password); static byte[] hashPassword(char[] password, byte[] salt); static byte[] nullSafeBase64Decode(String base64EncodedValue); static char[] generateRandomPassphrase(); static final int ITERATION_COUNT; } | @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.applicationContext())); if (p2pUsername == null) { p2pUsername = allSharedPreferences.fetchRegisteredANM(); } if (!TextUtils.isEmpty(p2pUsername)) { String teamId = allSharedPreferences.fetchDefaultTeamId(p2pUsername); if (p2POptions.getAuthorizationService() == null) { p2POptions.setAuthorizationService(new P2PSyncAuthorizationService(teamId)); } if (p2POptions.getReceiverTransferDao() == null) { p2POptions.setReceiverTransferDao(new P2PReceiverTransferDao()); } if (p2POptions.getSenderTransferDao() == null) { p2POptions.setSenderTransferDao(new P2PSenderTransferDao()); } if (p2POptions.getSyncFinishedCallback() == null) { p2POptions.setSyncFinishedCallback(new P2PSyncFinishCallback()); } P2PLibrary.Options options = new P2PLibrary.Options(context.applicationContext() , teamId, p2pUsername, p2POptions.getAuthorizationService(), p2POptions.getReceiverTransferDao() , p2POptions.getSenderTransferDao()); options.setBatchSize(p2POptions.getBatchSize()); options.setSyncFinishedCallback(p2POptions.getSyncFinishedCallback()); options.setRecalledIdentifier(p2POptions.getRecalledIdentifier()); P2PLibrary.init(options); } } } protected CoreLibrary(Context contextArg, SyncConfiguration syncConfiguration, @Nullable P2POptions p2POptions); static void init(Context context); static void init(Context context, SyncConfiguration syncConfiguration); static void init(Context context, SyncConfiguration syncConfiguration, long buildTimestamp); static void init(Context context, SyncConfiguration syncConfiguration, long buildTimestamp, @NonNull P2POptions options); static CoreLibrary getInstance(); void initP2pLibrary(@Nullable String username); Context context(); static void reset(Context context); static void reset(Context context, SyncConfiguration syncConfiguration); SyncConfiguration getSyncConfiguration(); AccountManager getAccountManager(); AccountAuthenticatorXml getAccountAuthenticatorXml(); static long getBuildTimeStamp(); String getEcClientFieldsFile(); void setEcClientFieldsFile(String ecClientFieldsFile); @Nullable P2POptions getP2POptions(); boolean isPeerToPeerProcessing(); void setPeerToPeerProcessing(boolean peerToPeerProcessing); @Override void onAccountsUpdated(Account[] accounts); } | @Test public void initP2pLibrary() { String expectedUsername = "nurse1"; String expectedTeamIdPassword = "908980dslkjfljsdlf"; Mockito.doReturn(RuntimeEnvironment.application) .when(context) .applicationContext(); AllSharedPreferences allSharedPreferences = new AllSharedPreferences( PreferenceManager.getDefaultSharedPreferences(RuntimeEnvironment.application.getApplicationContext()) ); allSharedPreferences.updateANMUserName(expectedUsername); allSharedPreferences.saveDefaultTeamId(expectedUsername, expectedTeamIdPassword); P2PLibrary.Options p2POptions = new P2PLibrary.Options(context.applicationContext(), expectedTeamIdPassword, expectedUsername, p2PAuthorizationService, receiverTransferDao, senderTransferDao); P2PLibrary.init(p2POptions); P2PLibrary p2PLibrary = P2PLibrary.getInstance(); assertEquals(expectedUsername, p2PLibrary.getUsername()); } |
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()); contentValues.put(TITLE, campaign.getTitle()); contentValues.put(DESCRIPTION, campaign.getDescription()); if (campaign.getStatus() != null) { contentValues.put(STATUS, campaign.getStatus().name()); } if (campaign.getExecutionPeriod() != null) { contentValues.put(START, DateUtil.getMillis(campaign.getExecutionPeriod().getStart())); contentValues.put(END, DateUtil.getMillis(campaign.getExecutionPeriod().getEnd())); } contentValues.put(AUTHORED_ON, DateUtil.getMillis(campaign.getAuthoredOn())); contentValues.put(LAST_MODIFIED, DateUtil.getMillis(campaign.getLastModified())); contentValues.put(OWNER, campaign.getOwner()); contentValues.put(SERVER_VERSION, campaign.getServerVersion()); getWritableDatabase().replace(CAMPAIGN_TABLE, null, contentValues); } static void createTable(SQLiteDatabase database); void addOrUpdate(Campaign campaign); List<Campaign> getAllCampaigns(); Campaign getCampaignByIdentifier(String identifier); } | @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, stringArgumentCaptor.getAllValues().size()); Iterator<String> iterator = stringArgumentCaptor.getAllValues().iterator(); assertEquals(CAMPAIGN_TABLE, iterator.next()); assertNull(iterator.next()); ContentValues contentValues = contentValuesArgumentCaptor.getValue(); assertEquals(10, contentValues.size()); assertEquals("IRS_2018_S1", contentValues.getAsString("_id")); assertEquals("2019 IRS Season 1", contentValues.getAsString("title")); assertEquals(IN_PROGRESS.name(), contentValues.getAsString("status")); }
@Test(expected = IllegalArgumentException.class) public void testAddOrUpdateShouldThrowException() { Campaign campaign = new Campaign(); campaignRepository.addOrUpdate(campaign); } |
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.close(); } catch (Exception e) { Timber.e(e); } finally { if (cursor != null) cursor.close(); } return campaigns; } static void createTable(SQLiteDatabase database); void addOrUpdate(Campaign campaign); List<Campaign> getAllCampaigns(); Campaign getCampaignByIdentifier(String identifier); } | @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.size()); assertEquals(campaignJson, gson.toJson(allCampaigns.get(0))); } |
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); } } catch (Exception e) { Timber.e(e); } finally { if (cursor != null) cursor.close(); } return null; } static void createTable(SQLiteDatabase database); void addOrUpdate(Campaign campaign); List<Campaign> getAllCampaigns(); Campaign getCampaignByIdentifier(String identifier); } | @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(), argsCaptor.capture()); assertEquals(1, argsCaptor.getValue().length); assertEquals("IRS_2018_S1", argsCaptor.getValue()[0]); assertEquals("SELECT * FROM campaign WHERE _id =?", stringArgumentCaptor.getValue()); assertEquals(campaignJson, gson.toJson(campaign)); } |
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.getAuthorString()); contentValues.put(TIME, note.getTime().getMillis()); contentValues.put(TEXT, note.getText()); getWritableDatabase().replace(TASK_NOTES_TABLE, null, contentValues); } static void createTable(SQLiteDatabase database); void addOrUpdate(Note note, String taskId); List<Note> getNotesByTask(String taskId); } | @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(stringArgumentCaptor.capture(), stringArgumentCaptor.capture(), contentValuesArgumentCaptor.capture()); assertEquals(2, stringArgumentCaptor.getAllValues().size()); Iterator<String> iterator = stringArgumentCaptor.getAllValues().iterator(); assertEquals(TASK_NOTES_TABLE, iterator.next()); assertNull(iterator.next()); ContentValues contentValues = contentValuesArgumentCaptor.getValue(); assertEquals(4, contentValues.size()); assertEquals("task22132", contentValues.getAsString("task_id")); assertEquals("Should be completed by End of November", contentValues.getAsString("text")); assertEquals("jdoe", contentValues.getAsString("author")); assertEquals(now, contentValues.getAsLong("time")); } |
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()) { notes.add(readCursor(cursor)); } } catch (Exception e) { Timber.e(e); } finally { if (cursor != null) cursor.close(); } return notes; } static void createTable(SQLiteDatabase database); void addOrUpdate(Note note, String taskId); List<Note> getNotesByTask(String taskId); } | @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 String[]{"task22132"}); assertEquals(1, notes.size()); assertEquals("Should be completed by End of November", notes.get(0).getText()); assertEquals("jdoe", notes.get(0).getAuthorString()); assertEquals(1543232476345l, notes.get(0).getTime().getMillis()); } |
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>> getTasksByPlanAndGroup(String planId, String groupId); Task getTaskByIdentifier(String identifier); Set<Task> getTasksByEntityAndCode(String planId, String groupId, String forEntity, String code); Set<Task> getTasksByPlanAndEntity(String planId, String forEntity); Set<Task> getTasksByEntity(String forEntity); Set<Task> getTasksByEntityAndStatus(String planId, String forEntity, TaskStatus taskStatus); Task readCursor(Cursor cursor); List<TaskUpdate> getUnSyncedTaskStatus(); void markTaskAsSynced(String taskID); List<Task> getAllUnsynchedCreatedTasks(); boolean updateTaskStructureIdFromClient(List<Client> clients, String attribute); boolean updateTaskStructureIdFromStructure(List<Location> locations); boolean updateTaskStructureIdsFromExistingStructures(); boolean updateTaskStructureIdsFromExistingClients(String clientTable); boolean batchInsertTasks(JSONArray array); @Nullable JsonData getTasks(long lastRowId, int limit, String jurisdictionId); void cancelTasksForEntity(@NonNull String entityId); void archiveTasksForEntity(@NonNull String entityId); int getUnsyncedCreatedTasksAndTaskStatusCount(); } | @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.getAllValues().iterator(); assertEquals(TASK_TABLE, iterator.next()); assertNull(iterator.next()); ContentValues contentValues = contentValuesArgumentCaptor.getValue(); assertEquals(21, contentValues.size()); assertEquals("tsk11231jh22", contentValues.getAsString("_id")); assertEquals("IRS_2018_S1", contentValues.getAsString("plan_id")); assertEquals("2018_IRS-3734", contentValues.getAsString("group_id")); verify(taskNotesRepository).addOrUpdate(task.getNotes().get(0), task.getIdentifier()); }
@Test(expected = IllegalArgumentException.class) public void testAddOrUpdateShouldThrowException() { Task task = new Task(); taskRepository.addOrUpdate(task); } |
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 element); static int getIndexForFormName(String formName, String[] formNames); FormSubmission generateFormSubmisionFromXMLString(String entity_id, String formData,
String formName, JSONObject
overrides); String generateXMLInputForFormWithEntityId(String entityId, String formName, String
overrides); Object getObjectAtPath(String[] path, JSONObject jsonObject); JSONArray getPopulatedFieldsForArray(JSONObject fieldsDefinition, String entityId,
JSONObject jsonObject, JSONObject overrides); String retrieveValueForLinkedRecord(String link, JSONObject entityJson); JSONArray getFieldsArrayForSubFormDefinition(JSONObject fieldsDefinition); JSONObject getFieldValuesForSubFormDefinition(JSONObject fieldsDefinition, String
relationalId, String entityId, JSONObject jsonObject, JSONObject overrides); String getValueForPath(String[] path, JSONObject jsonObject); JSONObject getFormJson(String formIdentity); static final String TAG; static final String ecClientRelationships; } | @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 %s WHERE %s=? AND %s =? AND %s NOT IN (%s)", TASK_TABLE, PLAN_ID, GROUP_ID, STATUS, TextUtils.join(",", Collections.nCopies(INACTIVE_TASK_STATUS.length, "?"))), ArrayUtils.addAll(params, INACTIVE_TASK_STATUS)); while (cursor.moveToNext()) { Set<Task> taskSet; Task task = readCursor(cursor); if (tasks.containsKey(task.getStructureId())) taskSet = tasks.get(task.getStructureId()); else taskSet = new HashSet<>(); taskSet.add(task); tasks.put(task.getStructureId(), taskSet); } } catch (Exception e) { Timber.e(e); } finally { if (cursor != null) cursor.close(); } return tasks; } TaskRepository(TaskNotesRepository taskNotesRepository); static void createTable(SQLiteDatabase database); void addOrUpdate(Task task); void addOrUpdate(Task task, boolean updateOnly); Map<String, Set<Task>> getTasksByPlanAndGroup(String planId, String groupId); Task getTaskByIdentifier(String identifier); Set<Task> getTasksByEntityAndCode(String planId, String groupId, String forEntity, String code); Set<Task> getTasksByPlanAndEntity(String planId, String forEntity); Set<Task> getTasksByEntity(String forEntity); Set<Task> getTasksByEntityAndStatus(String planId, String forEntity, TaskStatus taskStatus); Task readCursor(Cursor cursor); List<TaskUpdate> getUnSyncedTaskStatus(); void markTaskAsSynced(String taskID); List<Task> getAllUnsynchedCreatedTasks(); boolean updateTaskStructureIdFromClient(List<Client> clients, String attribute); boolean updateTaskStructureIdFromStructure(List<Location> locations); boolean updateTaskStructureIdsFromExistingStructures(); boolean updateTaskStructureIdsFromExistingClients(String clientTable); boolean batchInsertTasks(JSONArray array); @Nullable JsonData getTasks(long lastRowId, int limit, String jurisdictionId); void cancelTasksForEntity(@NonNull String entityId); void archiveTasksForEntity(@NonNull String entityId); int getUnsyncedCreatedTasksAndTaskStatusCount(); } | @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.getTasksByPlanAndGroup("IRS_2018_S1", "2018_IRS-3734"); verify(sqLiteDatabase).rawQuery(stringArgumentCaptor.capture(), argsCaptor.capture()); assertEquals("SELECT * FROM task WHERE plan_id=? AND group_id =? AND status NOT IN (?,?)", stringArgumentCaptor.getValue()); assertEquals("IRS_2018_S1", argsCaptor.getValue()[0]); assertEquals("2018_IRS-3734", argsCaptor.getValue()[1]); assertEquals(CANCELLED.name(), argsCaptor.getValue()[2]); assertEquals(ARCHIVED.name(), argsCaptor.getValue()[3]); assertEquals(1, allTasks.size()); assertEquals(1, allTasks.get("structure._id.33efadf1-feda-4861-a979-ff4f7cec9ea7").size()); Task task = allTasks.get("structure._id.33efadf1-feda-4861-a979-ff4f7cec9ea7").iterator().next(); assertEquals("tsk11231jh22", task.getIdentifier()); assertEquals("2018_IRS-3734", task.getGroupIdentifier()); assertEquals(READY, task.getStatus()); assertEquals("Not Visited", task.getBusinessStatus()); assertEquals(3, task.getPriority()); assertEquals("IRS", task.getCode()); assertEquals("Spray House", task.getDescription()); assertEquals("IRS Visit", task.getFocus()); assertEquals("location.properties.uid:41587456-b7c8-4c4e-b433-23a786f742fc", task.getForEntity()); assertEquals("2018-11-10T2200", task.getExecutionStartDate().toString(formatter)); assertNull(task.getExecutionEndDate()); assertEquals("2018-10-31T0700", task.getAuthoredOn().toString(formatter)); assertEquals("2018-10-31T0700", task.getLastModified().toString(formatter)); assertEquals("demouser", task.getOwner()); } |
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(",", Collections.nCopies(INACTIVE_TASK_STATUS.length, "?"))) , ArrayUtils.addAll(new String[]{planId, groupId, forEntity, code}, INACTIVE_TASK_STATUS)); } TaskRepository(TaskNotesRepository taskNotesRepository); static void createTable(SQLiteDatabase database); void addOrUpdate(Task task); void addOrUpdate(Task task, boolean updateOnly); Map<String, Set<Task>> getTasksByPlanAndGroup(String planId, String groupId); Task getTaskByIdentifier(String identifier); Set<Task> getTasksByEntityAndCode(String planId, String groupId, String forEntity, String code); Set<Task> getTasksByPlanAndEntity(String planId, String forEntity); Set<Task> getTasksByEntity(String forEntity); Set<Task> getTasksByEntityAndStatus(String planId, String forEntity, TaskStatus taskStatus); Task readCursor(Cursor cursor); List<TaskUpdate> getUnSyncedTaskStatus(); void markTaskAsSynced(String taskID); List<Task> getAllUnsynchedCreatedTasks(); boolean updateTaskStructureIdFromClient(List<Client> clients, String attribute); boolean updateTaskStructureIdFromStructure(List<Location> locations); boolean updateTaskStructureIdsFromExistingStructures(); boolean updateTaskStructureIdsFromExistingClients(String clientTable); boolean batchInsertTasks(JSONArray array); @Nullable JsonData getTasks(long lastRowId, int limit, String jurisdictionId); void cancelTasksForEntity(@NonNull String entityId); void archiveTasksForEntity(@NonNull String entityId); int getUnsyncedCreatedTasksAndTaskStatusCount(); } | @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(), ARCHIVED.name()})).thenReturn(getCursor()); Set<Task> allTasks = taskRepository.getTasksByEntityAndCode("IRS_2018_S1", "2018_IRS-3734", "location.properties.uid:41587456-b7c8-4c4e-b433-23a786f742fc", "IRS"); verify(sqLiteDatabase).rawQuery(stringArgumentCaptor.capture(), argsCaptor.capture()); assertEquals("SELECT * FROM task WHERE plan_id=? AND group_id =? AND for =? AND code =? AND status NOT IN (?,?)", stringArgumentCaptor.getValue()); assertEquals("IRS_2018_S1", argsCaptor.getValue()[0]); assertEquals("2018_IRS-3734", argsCaptor.getValue()[1]); assertEquals("location.properties.uid:41587456-b7c8-4c4e-b433-23a786f742fc", argsCaptor.getValue()[2]); assertEquals("IRS", argsCaptor.getValue()[3]); assertEquals(CANCELLED.name(), argsCaptor.getValue()[4]); assertEquals(ARCHIVED.name(), argsCaptor.getValue()[5]); assertEquals(1, allTasks.size()); Task task = allTasks.iterator().next(); assertEquals("tsk11231jh22", task.getIdentifier()); assertEquals("2018_IRS-3734", task.getGroupIdentifier()); assertEquals(READY, task.getStatus()); assertEquals("Not Visited", task.getBusinessStatus()); assertEquals(3, task.getPriority()); assertEquals("IRS", task.getCode()); assertEquals("Spray House", task.getDescription()); assertEquals("IRS Visit", task.getFocus()); assertEquals("location.properties.uid:41587456-b7c8-4c4e-b433-23a786f742fc", task.getForEntity()); assertEquals("2018-11-10T2200", task.getExecutionStartDate().toString(formatter)); assertNull(task.getExecutionEndDate()); assertEquals("2018-10-31T0700", task.getAuthoredOn().toString(formatter)); assertEquals("2018-10-31T0700", task.getLastModified().toString(formatter)); assertEquals("demouser", task.getOwner()); } |
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(e); } return null; } TaskRepository(TaskNotesRepository taskNotesRepository); static void createTable(SQLiteDatabase database); void addOrUpdate(Task task); void addOrUpdate(Task task, boolean updateOnly); Map<String, Set<Task>> getTasksByPlanAndGroup(String planId, String groupId); Task getTaskByIdentifier(String identifier); Set<Task> getTasksByEntityAndCode(String planId, String groupId, String forEntity, String code); Set<Task> getTasksByPlanAndEntity(String planId, String forEntity); Set<Task> getTasksByEntity(String forEntity); Set<Task> getTasksByEntityAndStatus(String planId, String forEntity, TaskStatus taskStatus); Task readCursor(Cursor cursor); List<TaskUpdate> getUnSyncedTaskStatus(); void markTaskAsSynced(String taskID); List<Task> getAllUnsynchedCreatedTasks(); boolean updateTaskStructureIdFromClient(List<Client> clients, String attribute); boolean updateTaskStructureIdFromStructure(List<Location> locations); boolean updateTaskStructureIdsFromExistingStructures(); boolean updateTaskStructureIdsFromExistingClients(String clientTable); boolean batchInsertTasks(JSONArray array); @Nullable JsonData getTasks(long lastRowId, int limit, String jurisdictionId); void cancelTasksForEntity(@NonNull String entityId); void archiveTasksForEntity(@NonNull String entityId); int getUnsyncedCreatedTasksAndTaskStatusCount(); } | @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()); assertEquals("SELECT * FROM task WHERE _id =?", stringArgumentCaptor.getValue()); assertEquals(1, argsCaptor.getValue().length); assertEquals("tsk11231jh22", argsCaptor.getValue()[0]); assertEquals("tsk11231jh22", task.getIdentifier()); assertEquals("2018_IRS-3734", task.getGroupIdentifier()); assertEquals(READY, task.getStatus()); assertEquals("Not Visited", task.getBusinessStatus()); assertEquals(3, task.getPriority()); assertEquals("IRS", task.getCode()); assertEquals("Spray House", task.getDescription()); assertEquals("IRS Visit", task.getFocus()); assertEquals("location.properties.uid:41587456-b7c8-4c4e-b433-23a786f742fc", task.getForEntity()); assertEquals("2018-11-10T2200", task.getExecutionStartDate().toString(formatter)); assertNull(task.getExecutionEndDate()); assertEquals("2018-10-31T0700", task.getAuthoredOn().toString(formatter)); assertEquals("2018-10-31T0700", task.getLastModified().toString(formatter)); assertEquals("demouser", task.getOwner()); } |
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 =?", TASK_TABLE, SYNC_STATUS), new String[]{BaseRepository.TYPE_Unsynced}); while (cursor.moveToNext()) { taskUpdates.add(readUpdateCursor(cursor)); } } catch (Exception e) { Timber.e(e); } finally { if (cursor != null) cursor.close(); } return taskUpdates; } TaskRepository(TaskNotesRepository taskNotesRepository); static void createTable(SQLiteDatabase database); void addOrUpdate(Task task); void addOrUpdate(Task task, boolean updateOnly); Map<String, Set<Task>> getTasksByPlanAndGroup(String planId, String groupId); Task getTaskByIdentifier(String identifier); Set<Task> getTasksByEntityAndCode(String planId, String groupId, String forEntity, String code); Set<Task> getTasksByPlanAndEntity(String planId, String forEntity); Set<Task> getTasksByEntity(String forEntity); Set<Task> getTasksByEntityAndStatus(String planId, String forEntity, TaskStatus taskStatus); Task readCursor(Cursor cursor); List<TaskUpdate> getUnSyncedTaskStatus(); void markTaskAsSynced(String taskID); List<Task> getAllUnsynchedCreatedTasks(); boolean updateTaskStructureIdFromClient(List<Client> clients, String attribute); boolean updateTaskStructureIdFromStructure(List<Location> locations); boolean updateTaskStructureIdsFromExistingStructures(); boolean updateTaskStructureIdsFromExistingClients(String clientTable); boolean batchInsertTasks(JSONArray array); @Nullable JsonData getTasks(long lastRowId, int limit, String jurisdictionId); void cancelTasksForEntity(@NonNull String entityId); void archiveTasksForEntity(@NonNull String entityId); int getUnsyncedCreatedTasksAndTaskStatusCount(); } | @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.format("UPDATE %s SET %s = ? WHERE %s = ? AND %s IS NULL", TASK_TABLE, STRUCTURE_ID, FOR, STRUCTURE_ID); updateStatement = getWritableDatabase().compileStatement(updateTaskSructureIdQuery); for (Client client : clients) { String taskFor = client.getBaseEntityId(); if (client.getAttribute(attribute) == null) { continue; } String structureId = client.getAttribute(attribute).toString(); updateStatement.bindString(1, structureId); updateStatement.bindString(2, taskFor); updateStatement.executeUpdateDelete(); } getWritableDatabase().setTransactionSuccessful(); getWritableDatabase().endTransaction(); return true; } catch (SQLException e) { Timber.e(e); getWritableDatabase().endTransaction(); return false; } finally { if (updateStatement != null) updateStatement.close(); } } TaskRepository(TaskNotesRepository taskNotesRepository); static void createTable(SQLiteDatabase database); void addOrUpdate(Task task); void addOrUpdate(Task task, boolean updateOnly); Map<String, Set<Task>> getTasksByPlanAndGroup(String planId, String groupId); Task getTaskByIdentifier(String identifier); Set<Task> getTasksByEntityAndCode(String planId, String groupId, String forEntity, String code); Set<Task> getTasksByPlanAndEntity(String planId, String forEntity); Set<Task> getTasksByEntity(String forEntity); Set<Task> getTasksByEntityAndStatus(String planId, String forEntity, TaskStatus taskStatus); Task readCursor(Cursor cursor); List<TaskUpdate> getUnSyncedTaskStatus(); void markTaskAsSynced(String taskID); List<Task> getAllUnsynchedCreatedTasks(); boolean updateTaskStructureIdFromClient(List<Client> clients, String attribute); boolean updateTaskStructureIdFromStructure(List<Location> locations); boolean updateTaskStructureIdsFromExistingStructures(); boolean updateTaskStructureIdsFromExistingClients(String clientTable); boolean batchInsertTasks(JSONArray array); @Nullable JsonData getTasks(long lastRowId, int limit, String jurisdictionId); void cancelTasksForEntity(@NonNull String entityId); void archiveTasksForEntity(@NonNull String entityId); int getUnsyncedCreatedTasksAndTaskStatusCount(); } | @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 saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.