src_fm_fc_ms_ff stringlengths 43 86.8k | target stringlengths 20 276k |
|---|---|
LocationHelper { public List<String> generateDefaultLocationHierarchy(List<String> allowedLevels) { if (Utils.isEmptyCollection(allowedLevels)) { return new ArrayList<>(); } try { String defaultLocationUuid = allSharedPreferences.fetchDefaultLocalityId(allSharedPreferences.fetchRegisteredANM()); LinkedHashMap<String, T... | @Test public void testGenerateDefaultLocationHierarchy() { ArrayList<String> allowedLevels = new ArrayList<>(); allowedLevels.add("District"); allowedLevels.add("Rural Health Centre"); allowedLevels.add("Village"); allowedLevels.add("Canton"); allowedLevels.add("Sub-district"); AllSharedPreferences spiedAllSharedPrefer... |
LocationHelper { public List<FormLocation> generateLocationHierarchyTree(boolean withOtherOption, List<String> allowedLevels) { LinkedHashMap<String, TreeNode<String, Location>> map = map(); return generateLocationHierarchyTree(withOtherOption, allowedLevels, map); } private LocationHelper(List<String> allowedLevels, ... | @Test public void testGenerateLocationHierarchyTreeShouldReturnEmptyList() { String locationData = anmLocation1; ArrayList<String> allowedLevels = new ArrayList<>(); allowedLevels.add("Canton"); LinkedHashMap<String, TreeNode<String, Location>> map = AssetHandler.jsonStringToJava(locationData, LocationTree.class).getLo... |
LocationHelper { public String getOpenMrsReadableName(String name) { if (StringUtils.isBlank(name)) { return ""; } String readableName = name; try { Pattern prefixPattern = Pattern.compile("^[a-z]{2} (.*)$"); Matcher prefixMatcher = prefixPattern.matcher(readableName); if (prefixMatcher.find()) { readableName = prefixM... | @Test public void testGetOpenMrsReadableName() { assertEquals("Zambia", locationHelper.getOpenMrsReadableName("ra Zambia")); } |
LocationHelper { public String getOpenMrsLocationName(String locationId) { if (StringUtils.isBlank(locationId)) { Timber.e("Location id is null"); return null; } String response = locationId; try { LinkedHashMap<String, TreeNode<String, Location>> map = map(); if (!Utils.isEmptyMap(map)) { for (Map.Entry<String, TreeNo... | @Test public void testGetOpenMrsLocationName() { ANMLocationController anmLocationController = Mockito.spy(CoreLibrary.getInstance().context().anmLocationController()); ReflectionHelpers.setField(CoreLibrary.getInstance().context(), "anmLocationController", anmLocationController); Mockito.doReturn(anmLocation2) .when(a... |
LocationHelper { public List<String> getAdvancedDataCaptureStrategies() { return ADVANCED_DATA_CAPTURE_LEVELS; } private LocationHelper(List<String> allowedLevels, String defaultLocationLevel); private LocationHelper(List<String> allowedLevels, String defaultLocationLevel, List<String> advancedDataCaptureStrategies);... | @Test public void testGetAdvancedDataCaptureStrategies() { ReflectionHelpers.setStaticField(LocationHelper.class, "instance", null); String advancedDataStrategyType = "Mobile Clinic"; ArrayList<String> allowedLevels = new ArrayList<>(); allowedLevels.add("County"); allowedLevels.add("Ward"); allowedLevels.add("Facility... |
AbstractDao { public static SimpleDateFormat getDobDateFormat() { if (DOB_DATE_FORMAT == null) DOB_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH); return DOB_DATE_FORMAT; } static SimpleDateFormat getDobDateFormat(); static SimpleDateFormat getNativeFormsDateFormat(); static @Nullable List<Map<String... | @Test public void testGetDateFormat() { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Date now = new Date(); Assert.assertEquals(sdf.format(now), AbstractDao.getDobDateFormat().format(now)); } |
AbstractDao { public static SimpleDateFormat getNativeFormsDateFormat() { if (NATIVE_FORMS_DATE_FORMAT == null) NATIVE_FORMS_DATE_FORMAT = new SimpleDateFormat("dd-MM-yyyy", Locale.ENGLISH); return NATIVE_FORMS_DATE_FORMAT; } static SimpleDateFormat getDobDateFormat(); static SimpleDateFormat getNativeFormsDateFormat(... | @Test public void testGetNativeFormsDateFormat() { SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy"); Date now = new Date(); Assert.assertEquals(sdf.format(now), AbstractDao.getNativeFormsDateFormat().format(now)); } |
AbstractDao { protected static void setRepository(Repository repository) { AbstractDao.repository = repository; } static SimpleDateFormat getDobDateFormat(); static SimpleDateFormat getNativeFormsDateFormat(); static @Nullable List<Map<String, Object>> readData(String query, String[] selectionArgs); } | @Test public void testObjectsConstructedEqualsCursorSize() { MatrixCursor cursor = new MatrixCursor(new String[]{"count"}); cursor.addRow(new Object[]{"1"}); Mockito.doReturn(cursor).when(sqLiteDatabase).rawQuery(Mockito.anyString(), Mockito.any(String[].class)); SampleAbstractDaoImp.setRepository(repository); int coun... |
AbstractDao { protected static void updateDB(String sql) { try { SQLiteDatabase db = getRepository().getWritableDatabase(); db.rawExecSQL(sql); } catch (Exception e) { Timber.e(e); } } static SimpleDateFormat getDobDateFormat(); static SimpleDateFormat getNativeFormsDateFormat(); static @Nullable List<Map<String, Obje... | @Test public void testUpdateDB() { String sql = "update table set col1 = 'value' where id = x"; AbstractDao.setRepository(repository); AbstractDao.updateDB(sql); Mockito.verify(sqLiteDatabase).rawExecSQL(sql); } |
LocationsDao extends AbstractDao { public static List<Location> getLocationsByTags(Set<String> tags) { String sql = String.format("SELECT uuid, location.name as location_name, parent_id\n" + "FROM location\n" + " INNER JOIN location_tag on location.uuid = location_tag.location_id\n" + "WHERE location_tag.name IN ('%s')... | @Test public void testGetLocationsByTags() { LocationsDao.setRepository(repository); MatrixCursor matrixCursor = new MatrixCursor(new String[]{"uuid", "location_name", "parent_id"}); matrixCursor.addRow(new Object[]{"fb7ed5db-138d-4e6f-94d8-bc443b58dadb", "Tabata Dampo", "bcf5a36d-fb53-4de9-9813-01f1d480e3fe"}); matrix... |
BottomNavigationHelper { protected Bitmap convertDrawableResToBitmap(@DrawableRes int drawableId, Resources resources) { Drawable drawable = resources.getDrawable(drawableId); if (drawable instanceof BitmapDrawable) { return ((BitmapDrawable) drawable).getBitmap(); } else if (drawable instanceof GradientDrawable) { Gra... | @Test public void testConvertDrawableToBitmap() { BottomNavigationHelper spyBottomNavigationHelper = Mockito.spy(bottomNavigationHelper); Resources resources = Mockito.mock(Resources.class); Assert.assertNotNull(resources); Mockito.doReturn(drawable).when(resources).getDrawable(INITIALS_RESOURCE_ID); Assert.assertNotNu... |
SmartRegisterPaginatedAdapter extends BaseAdapter { public int pageCount() { return pageCount; } SmartRegisterPaginatedAdapter(SmartRegisterClientsProvider listItemProvider); SmartRegisterPaginatedAdapter(int clientsPerPage, SmartRegisterClientsProvider
listItemProvider); void refreshClients(SmartRegisterC... | @Test public void assertshouldReturn3PageCountFor50Clients() { SmartRegisterPaginatedAdapter adapter = getAdapterWithFakeClients(FIFTY); Assert.assertEquals(adapter.pageCount(), THREE); } |
SmartRegisterPaginatedAdapter extends BaseAdapter { @Override public Object getItem(int i) { return filteredClients.get(i); } SmartRegisterPaginatedAdapter(SmartRegisterClientsProvider listItemProvider); SmartRegisterPaginatedAdapter(int clientsPerPage, SmartRegisterClientsProvider
listItemProvider); void ... | @Test public void assertgetItemShouldReturnRespectiveItem() { SmartRegisterPaginatedAdapter adapter = getAdapterWithFakeClients(FIFTY); Assert.assertEquals(((ECClient) adapter.getItem(ZERO)).name(), NameZERO); Assert.assertEquals(((ECClient) adapter.getItem(FOURTYNINE)).name(), NameFOURTYNINE); } |
SmartRegisterPaginatedAdapter extends BaseAdapter { @Override public View getView(int i, View parentView, ViewGroup viewGroup) { return listItemProvider .getView((SmartRegisterClient) getItem(actualPosition(i)), parentView, viewGroup); } SmartRegisterPaginatedAdapter(SmartRegisterClientsProvider listItemProvider); Sma... | @Test public void assertgetViewShouldDelegateCallToProviderGetViewWithProperClient() { FakeClientsProvider fakeClientsProvider = new FakeClientsProvider(getSmartRegisterClients(FIFTY)); SmartRegisterPaginatedAdapter adapter = getAdapter(fakeClientsProvider); adapter.getView(ZERO, null, null); Assert.assertEquals(NameZE... |
ServiceLocationsAdapter extends BaseAdapter { @Override public int getCount() { return locationNames.size(); } ServiceLocationsAdapter(Context context, List<String> locationNames); @Override int getCount(); @Override Object getItem(int position); @Override long getItemId(int position); @Override View getView(int positi... | @Test public void testGetCount() { ServiceLocationsAdapter adapter = getAdapterWithFakeClients(); Assert.assertEquals(adapter.getCount(), 3); } |
ServiceLocationsAdapter extends BaseAdapter { @Override public long getItemId(int position) { return position + 2321; } ServiceLocationsAdapter(Context context, List<String> locationNames); @Override int getCount(); @Override Object getItem(int position); @Override long getItemId(int position); @Override View getView(i... | @Test public void testGetItemId() { ServiceLocationsAdapter adapter = getAdapterWithFakeClients(); Assert.assertEquals(adapter.getItemId(0), 2321); } |
ServiceLocationsAdapter extends BaseAdapter { public String getLocationAt(int position) { return locationNames.get(position); } ServiceLocationsAdapter(Context context, List<String> locationNames); @Override int getCount(); @Override Object getItem(int position); @Override long getItemId(int position); @Override View g... | @Test public void testGetLocationAt() { ServiceLocationsAdapter adapter = getAdapterWithFakeClients(); Assert.assertEquals(adapter.getLocationAt(0), "test1"); } |
ServiceLocationsAdapter extends BaseAdapter { public List<String> getLocationNames() { return locationNames; } ServiceLocationsAdapter(Context context, List<String> locationNames); @Override int getCount(); @Override Object getItem(int position); @Override long getItemId(int position); @Override View getView(int positi... | @Test public void testGetLocationNames() { ServiceLocationsAdapter adapter = getAdapterWithFakeClients(); List<String> names = adapter.getLocationNames(); Assert.assertEquals(names.get(0), "test1"); } |
IntegerUtil { public static int compare(int lhs, int rhs) { return lhs < rhs ? -1 : (lhs == rhs ? 0 : 1); } static Integer tryParse(String value, int defaultValue); static String tryParse(String value, String defaultValue); static int compare(int lhs, int rhs); } | @Test public void assertIntegerCompareReturnsInt() { Assert.assertEquals(IntegerUtil.compare(1, 2), -1); Assert.assertEquals(IntegerUtil.compare(2, 2), 0); Assert.assertEquals(IntegerUtil.compare(3, 2), 1); } |
ServiceLocationsAdapter extends BaseAdapter { @Override public View getView(int position, View convertView, ViewGroup parent) { if (!views.containsKey(locationNames.get(position))) { LayoutInflater inflater = (LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE); View view = inflater.inflate(R.lay... | @Test public void testGetView() { ServiceLocationsAdapter adapter = getAdapterWithFakeClients(); itemsListView.setAdapter(adapter); when(applicationContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).thenReturn(layoutInflater); Mockito.doReturn(linearLayout).when(layoutInflater).inflate(R.layout.location_picker_... |
SyncTaskServiceJob extends BaseJob { @NonNull @Override protected Result onRunJob(@NonNull Params params) { Intent intent = new Intent(getApplicationContext(), serviceClass); getApplicationContext().startService(intent); return params != null && params.getExtras().getBoolean(AllConstants.INTENT_KEY.TO_RESCHEDULE, false... | @Test public void testOnRunJobStartsCorrectService() { SyncTaskServiceJob syncTaskServiceJob = new SyncTaskServiceJob(SyncTaskIntentService.class); SyncTaskServiceJob syncTaskServiceJobSpy = Mockito.spy(syncTaskServiceJob); ArgumentCaptor<Intent> intent = ArgumentCaptor.forClass(Intent.class); Mockito.doReturn(context)... |
ValidateSyncDataServiceJob extends BaseJob { @NonNull @Override protected Result onRunJob(@NonNull Params params) { Intent intent = new Intent(getApplicationContext(), ValidateIntentService.class); getApplicationContext().startService(intent); return params != null && params.getExtras().getBoolean(AllConstants.INTENT_K... | @Test public void testOnRunJobStartsCorrectService() { ValidateSyncDataServiceJob validateSyncDataServiceJob = new ValidateSyncDataServiceJob(); ValidateSyncDataServiceJob validateSyncDataServiceJobSpy = Mockito.spy(validateSyncDataServiceJob); ArgumentCaptor<Intent> intent = ArgumentCaptor.forClass(Intent.class); Mock... |
CampaignServiceJob extends BaseJob { @NonNull @Override protected Result onRunJob(@NonNull Params params) { Intent intent = new Intent(getApplicationContext(), CampaignIntentService.class); getApplicationContext().startService(intent); return params != null && params.getExtras().getBoolean(AllConstants.INTENT_KEY.TO_RE... | @Test public void testOnRunJobStartsCorrectService() { CampaignServiceJob campaignServiceJob = new CampaignServiceJob(); CampaignServiceJob campaignServiceJobJobSpy = Mockito.spy(campaignServiceJob); ArgumentCaptor<Intent> intent = ArgumentCaptor.forClass(Intent.class); Mockito.doReturn(context).when(campaignServiceJob... |
PullUniqueIdsServiceJob extends BaseJob { @NonNull @Override protected Result onRunJob(@NonNull Params params) { Intent intent = new Intent(getApplicationContext(), PullUniqueIdsIntentService.class); getApplicationContext().startService(intent); return params != null && params.getExtras().getBoolean(AllConstants.INTENT... | @Test public void testOnRunJobStartsCorrectService() { PullUniqueIdsServiceJob pullUniqueIdsServiceJob = new PullUniqueIdsServiceJob(); PullUniqueIdsServiceJob pullUniqueIdsServiceJobSpy = Mockito.spy(pullUniqueIdsServiceJob); ArgumentCaptor<Intent> intent = ArgumentCaptor.forClass(Intent.class); Mockito.doReturn(conte... |
ExtendedSyncServiceJob extends BaseJob { @NonNull @Override protected Result onRunJob(@NonNull Params params) { Intent intent = new Intent(getApplicationContext(), ExtendedSyncIntentService.class); getApplicationContext().startService(intent); return params != null && params.getExtras().getBoolean(AllConstants.INTENT_K... | @Test public void testOnRunJobStartsCorrectService() { ExtendedSyncServiceJob extendedSyncServiceJob = new ExtendedSyncServiceJob(); ExtendedSyncServiceJob syncServiceJobSpy = Mockito.spy(extendedSyncServiceJob); ArgumentCaptor<Intent> intent = ArgumentCaptor.forClass(Intent.class); Mockito.doReturn(context).when(syncS... |
SyncLocationsByLevelAndTagsServiceJob extends BaseJob { @NonNull @Override protected Result onRunJob(@NonNull Params params) { Intent intent = new Intent(getApplicationContext(), SyncLocationsByLevelAndTagsIntentService.class); getApplicationContext().startService(intent); return params != null && params.getExtras().ge... | @Test public void testOnRunJobStartsCorrectService() { SyncLocationsByLevelAndTagsServiceJob syncLocationsByLevelAndTagsServiceJob = new SyncLocationsByLevelAndTagsServiceJob(); SyncLocationsByLevelAndTagsServiceJob syncLocationsByLevelAndTagsServiceJobSpy = Mockito.spy(syncLocationsByLevelAndTagsServiceJob); ArgumentC... |
DocumentConfigurationServiceJob extends BaseJob { @NonNull @Override protected Result onRunJob(@NonNull Params params) { Intent intent = new Intent(getApplicationContext(), serviceClass); getApplicationContext().startService(intent); return params != null && params.getExtras().getBoolean(AllConstants.INTENT_KEY.TO_RESC... | @Test public void testOnRunJobStartsCorrectService() { DocumentConfigurationServiceJob documentConfigurationServiceJob = new DocumentConfigurationServiceJob(DocumentConfigurationIntentService.class); DocumentConfigurationServiceJob documentConfigurationServiceJobSpy = Mockito.spy(documentConfigurationServiceJob); Argum... |
SyncServiceJob extends BaseJob { @NonNull @Override protected Result onRunJob(@NonNull Params params) { Intent intent = new Intent(getApplicationContext(), serviceClass); getApplicationContext().startService(intent); return params != null && params.getExtras().getBoolean(AllConstants.INTENT_KEY.TO_RESCHEDULE, false) ? ... | @Test public void testOnRunJobStartsCorrectService() { SyncServiceJob syncServiceJob = new SyncServiceJob(SyncIntentService.class); SyncServiceJob syncServiceJobSpy = Mockito.spy(syncServiceJob); ArgumentCaptor<Intent> intent = ArgumentCaptor.forClass(Intent.class); Mockito.doReturn(context).when(syncServiceJobSpy).get... |
SyncLocationsByTeamIdsJob extends BaseJob { @NonNull @Override protected Result onRunJob(@NonNull Params params) { Intent intent = new Intent(getApplicationContext(), SyncLocationsByTeamIdsIntentService.class); getApplicationContext().startService(intent); return params != null && params.getExtras().getBoolean(AllConst... | @Test public void testOnRunJobStartsCorrectService() { SyncLocationsByTeamIdsJob syncLocationsByTeamIdsJob = new SyncLocationsByTeamIdsJob(); SyncLocationsByTeamIdsJob syncLocationsByTeamIdsJobSpy = Mockito.spy(syncLocationsByTeamIdsJob); ArgumentCaptor<Intent> intent = ArgumentCaptor.forClass(Intent.class); Mockito.do... |
DateUtil { public static String getDuration(DateTime dateTime) { return getDuration(CoreLibrary.getInstance().context().applicationContext(), dateTime); } static void fakeIt(LocalDate fakeDayAsToday); static void setDefaultDateFormat(String defaultDateFormat); static LocalDate today(); static String formatDateForTimel... | @Test public void assertGetDurationTest() { Locale locale = RuntimeEnvironment.application.getApplicationContext().getResources().getConfiguration().locale; Assert.assertEquals("1d", DateUtil.getDuration(100000000l, locale)); Assert.assertEquals("5w 1d", DateUtil.getDuration(3110400000l, locale)); Assert.assertEquals("... |
SyncAllLocationsServiceJob extends BaseJob { @NonNull @Override protected Result onRunJob(@NonNull Params params) { Intent intent = new Intent(getApplicationContext(), SyncAllLocationsIntentService.class); getApplicationContext().startService(intent); return params != null && params.getExtras().getBoolean(AllConstants.... | @Test public void testOnRunJobStartsCorrectService() { SyncAllLocationsServiceJob syncAllLocationsServiceJob = new SyncAllLocationsServiceJob(); SyncAllLocationsServiceJob spy = Mockito.spy(syncAllLocationsServiceJob); ArgumentCaptor<Intent> intent = ArgumentCaptor.forClass(Intent.class); Mockito.doReturn(context).when... |
Campaign { public String getTitle() { return title; } String getIdentifier(); void setIdentifier(String identifier); String getTitle(); void setTitle(String title); String getDescription(); void setDescription(String description); TaskStatus getStatus(); void setStatus(TaskStatus status); ExecutionPeriod getExecutionP... | @Test public void testSerialize() { Campaign campaign = gson.fromJson(campaignJson, Campaign.class); assertEquals(campaignJson, gson.toJson(campaign)); assertEquals(campaign.getTitle(),"2019 IRS Season 1"); } |
ClientProcessorForJava { public Boolean closeCase(Client client, List<String> closesCase) { try { if (closesCase == null || closesCase.isEmpty()) { return false; } String baseEntityId = client.getBaseEntityId(); for (String tableName : closesCase) { closeCase(tableName, baseEntityId); updateFTSsearch(tableName, baseEnt... | @Test public void testCloseCaseShouldReturnFalseIfCloseCaseIsEmpty() { ClientProcessorForJava clientProcessor = new ClientProcessorForJava(context); assertFalse(clientProcessor.closeCase(new Client("1233-2"), new ArrayList<>())); }
@Test public void testCloseCaseShouldPassCorrectValuesToCloseCase() { ClientProcessorFor... |
ClientProcessorForJava { public Table getColumnMappings(String registerName) { try { ClientField clientField = assetJsonToJava(CoreLibrary.getInstance().getEcClientFieldsFile(), ClientField.class); if (clientField == null) { return null; } List<Table> bindObjects = clientField.bindobjects; for (Table bindObject : bindO... | @Test public void testGetColumnMappingsShouldReturnTheCorrectTable() throws IOException { ReflectionHelpers.setStaticField(CoreLibrary.class, "instance", coreLibrary); Mockito.when(coreLibrary.getEcClientFieldsFile()).thenReturn("ec_client_fields.json"); AssetManager assetManager = Mockito.mock(AssetManager.class); Moc... |
ClientProcessorForJava { public void updateClientDetailsTable(Event event, Client client) { try { Timber.d("Started updateClientDetailsTable"); if (CoreLibrary.getInstance().getSyncConfiguration().updateClientDetailsTable()) { String baseEntityId = client.getBaseEntityId(); Long timestamp = getEventDate(event.getEventD... | @Test public void testUpdateClientDetailsTableShouldNotSaveClientDetailsIdConfigIsFalse() { ReflectionHelpers.setStaticField(CoreLibrary.class, "instance", coreLibrary); DetailsRepository detailsRepository = Mockito.mock(DetailsRepository.class); SyncConfiguration syncConfiguration = Mockito.mock(SyncConfiguration.clas... |
ClientProcessorForJava { public Boolean processField(org.smartregister.domain.jsonmapping.Field field, Event event, Client client) { try { if (field == null) { return false; } String dataSegment = null; String fieldName = field.field; String fieldValue = field.field_value; String responseKey = null; if (fieldName != nu... | @Test public void processFieldShouldReturnFalse() { assertFalse(clientProcessor.processField(null, null, null)); } |
ClientProcessorForJava { public Boolean processCaseModel(Event event, Client client, List<String> createsCase) { try { if (createsCase == null || createsCase.isEmpty()) { return false; } for (String clientType : createsCase) { Table table = getColumnMappings(clientType); List<Column> columns = table.columns; String bas... | @Test public void processCaseModelShouldReturnFalseWhenCreatesCaseParamIsNull() { assertFalse(clientProcessor.processCaseModel(null, null, null)); }
@Test public void processCaseModelWhenGivenColumnConfigurationFromEventObsShouldPopulateContentValuesAsPerColumnConfiguration() { String eventJson = "{\"baseEntityId\":\"0... |
DateUtil { public static boolean checkIfDateThreeMonthsOlder(Date date) { Calendar cal = Calendar.getInstance(); cal.setTime(cal.getTime()); cal.add(Calendar.DATE, -90); Date dateBefore90Days = cal.getTime(); return date.before(dateBefore90Days); } static void fakeIt(LocalDate fakeDayAsToday); static void setDefaultDa... | @Test public void assertCheckIfDateThreeMonthsOlderReturnsBoolean() { Assert.assertEquals(DateUtil.checkIfDateThreeMonthsOlder(new Date()), false); } |
ClientProcessorForJava { public Boolean processClientClass(ClassificationRule clientClass, Event event, Client client) { try { if (clientClass == null) { return false; } if (event == null) { return false; } if (client == null) { return false; } Rule rule = clientClass.rule; List<org.smartregister.domain.jsonmapping.Fie... | @Test public void processClientClassShouldFalseWhenClassificationRuleIsNull() { Event event = new Event(); Client client = new Client("bei"); Assert.assertFalse(clientProcessor.processClientClass(null, event, client)); }
@Test public void processClientClassShouldFalseWhenEventIsNull() { Client client = new Client("bei"... |
ClientProcessor { public synchronized void processClient() throws Exception { AllSharedPreferences allSharedPreferences = new AllSharedPreferences(preferences); long lastSyncTimeStamp = allSharedPreferences.fetchLastSyncDate(0); Date lastSyncDate = new Date(lastSyncTimeStamp); String clientClassificationStr = getFileCo... | @Test public void processClientTest() throws Exception { JSONArray eventArray = new JSONArray(ClientData.eventJsonArray); final ArrayList<JSONObject> eventList = new ArrayList<JSONObject>(); for (int i = 0; i < eventArray.length(); i++) { eventList.add(eventArray.getJSONObject(i)); } JSONArray clientArray = new JSONArr... |
ClientProcessor { public Boolean processField(JSONObject fieldJson, JSONObject event, JSONObject client) { try { if (fieldJson == null || fieldJson.length() == 0) { return false; } String dataSegment = null; String fieldName = fieldJson.has("field") ? fieldJson.getString("field") : null; String fieldValue = fieldJson.h... | @Test public void assertProcessFieldReturnsTrue() throws Exception { final JSONObject fieldObject = new JSONObject(ClientData.ec_client_fields_json); final ArrayList<JSONObject> eventList = new ArrayList<JSONObject>(); JSONArray eventArray = new JSONArray(ClientData.eventJsonArray); for (int i = 0; i < eventArray.lengt... |
DateUtil { public static boolean isValidDate(String dateString) { if (dateString == null || dateString.length() != "yyyy-MM-dd".length()) { return false; } return dateString.matches("\\d{4}-\\d{2}-\\d{2}"); } static void fakeIt(LocalDate fakeDayAsToday); static void setDefaultDateFormat(String defaultDateFormat); stat... | @Test public void assertIsVaidDateReturnsBoolean() { Assert.assertEquals(DateUtil.isValidDate(null), false); Assert.assertEquals(DateUtil.isValidDate("invaliddate"), false); Assert.assertEquals(DateUtil.isValidDate("2017-10-20"), true); } |
ClientProcessor { public static ClientProcessor getInstance(Context context) { if (instance == null) { instance = new ClientProcessor(context); } return instance; } ClientProcessor(Context context); static ClientProcessor getInstance(Context context); synchronized void processClient(); synchronized void processClient(L... | @Test public void instantiatesSuccessfullyOnConstructorCall() throws Exception { Assert.assertNotNull(new ClientProcessor(context.applicationContext())); Assert.assertNotNull(ClientProcessor.getInstance(context.applicationContext())); } |
ClientProcessor { public Boolean processEvent(JSONObject event, JSONObject clientClassificationJson) throws Exception { try { String baseEntityId = event.getString(baseEntityIdJSONKey); if (event.has("creator")) { Timber.i("EVENT from openmrs"); } JSONObject client = getClient(baseEntityId); if (isNullOrEmptyJSONObject... | @Test public void ProcessEventReturnsNotNull() throws Exception { JSONArray eventArray = new JSONArray(ClientData.eventJsonArray); final ArrayList<JSONObject> eventList = new ArrayList<JSONObject>(); for (int i = 0; i < eventArray.length(); i++) { eventList.add(eventArray.getJSONObject(i)); } JSONArray clientArray = ne... |
ClientProcessor { public Map<String, String> getClientAddressAsMap(JSONObject client) { Map<String, String> addressMap = new HashMap<String, String>(); try { String addressFieldsKey = "addressFields"; String addressesKey = "addresses"; if (client.has(addressesKey)) { JSONArray addressJsonArray = client.getJSONArray(add... | @Test public void getClientAddressAsMapReturnsNotNull() throws Exception { JSONArray eventArray = new JSONArray(ClientData.eventJsonArray); final ArrayList<JSONObject> eventList = new ArrayList<JSONObject>(); for (int i = 0; i < eventArray.length(); i++) { eventList.add(eventArray.getJSONObject(i)); } JSONArray clientA... |
ClientProcessor { public Boolean processCaseModel(JSONObject event, JSONObject client, JSONArray createsCase) { try { if (createsCase == null || createsCase.length() == 0) { return false; } for (int openCase = 0; openCase < createsCase.length(); openCase++) { String clientType = createsCase.getString(openCase); JSONObj... | @Test public void processCaseModelReturnsNotNUll() throws Exception { JSONArray eventArray = new JSONArray(ClientData.eventJsonArray); final ArrayList<JSONObject> eventList = new ArrayList<JSONObject>(); for (int i = 0; i < eventArray.length(); i++) { eventList.add(eventArray.getJSONObject(i)); } JSONArray clientArray ... |
P2pProcessRecordsService extends BaseSyncIntentService { @Override protected void onHandleIntent(@Nullable Intent intent) { super.onHandleIntent(intent); AllSharedPreferences allSharedPreferences = CoreLibrary.getInstance().context().allSharedPreferences(); if (allSharedPreferences.isPeerToPeerUnprocessedEvents()) { Co... | @Test public void onHandleIntentShouldProcessEventsIfPeerToPeerUnprocessedEventsReturnsTrue() throws Exception { p2pProcessRecordsService.onHandleIntent(null); Mockito.verify(eventClientRepository, Mockito.never()).getMaxRowId(Mockito.any(EventClientRepository.Table.class)); Mockito.verify(clientProcessorForJava, Mocki... |
P2pProcessRecordsService extends BaseSyncIntentService { @Override public void onDestroy() { if (CoreLibrary.getInstance().isPeerToPeerProcessing()) { CoreLibrary.getInstance().setPeerToPeerProcessing(false); } super.onDestroy(); } P2pProcessRecordsService(String name); P2pProcessRecordsService(); @Override void onDes... | @Test public void onDestroyShouldSetPeerProcessingToFalse() { CoreLibrary.getInstance().setPeerToPeerProcessing(true); Assert.assertTrue(CoreLibrary.getInstance().isPeerToPeerProcessing()); p2pProcessRecordsService.onDestroy(); Assert.assertFalse(CoreLibrary.getInstance().isPeerToPeerProcessing()); } |
SyncIntentService extends BaseSyncIntentService { protected void init(@NonNull Context context) { this.context = context; httpAgent = CoreLibrary.getInstance().context().getHttpAgent(); syncUtils = new SyncUtils(getBaseContext()); validateAssignmentHelper = new ValidateAssignmentHelper(syncUtils); } SyncIntentService()... | @Test public void testInit() { assertNotNull(Whitebox.getInternalState(syncIntentService, "httpAgent")); assertNotNull(Whitebox.getInternalState(syncIntentService, "syncUtils")); assertNotNull(Whitebox.getInternalState(syncIntentService, "context")); } |
SyncIntentService extends BaseSyncIntentService { protected void handleSync() { sendSyncStatusBroadcastMessage(FetchStatus.fetchStarted); doSync(); } SyncIntentService(); SyncIntentService(String name); @Override int onStartCommand(Intent intent, int flags, int startId); void fetchFailed(int count); int getEventPullLi... | @Test public void testHandleSyncSendFetchStartedBroadCast() throws PackageManager.NameNotFoundException { syncIntentService = spy(syncIntentService); Whitebox.setInternalState(syncIntentService, "syncUtils", syncUtils); when(syncUtils.verifyAuthorization()).thenReturn(true); when(syncUtils.isAppVersionAllowed()).thenRe... |
DateUtil { public static int weekDifference(LocalDate startDate, LocalDate endDate) { try { return Math.abs(Weeks.weeksBetween(startDate, endDate).getWeeks()); } catch (Exception e) { return 0; } } static void fakeIt(LocalDate fakeDayAsToday); static void setDefaultDateFormat(String defaultDateFormat); static LocalDat... | @Test public void assertWeekDifferenceReturnsInt() { LocalDate start = new LocalDate(1447487308000l); LocalDate end = new LocalDate(1510645708000l); Assert.assertEquals(DateUtil.weekDifference(start, end), 104); } |
SyncIntentService extends BaseSyncIntentService { protected void pullECFromServer() { fetchRetry(0, true); } SyncIntentService(); SyncIntentService(String name); @Override int onStartCommand(Intent intent, int flags, int startId); void fetchFailed(int count); int getEventPullLimit(); HTTPAgent getHttpAgent(); Context ... | @Test public void testPullEcFromServerWhenSyncFilterParamIsNull() throws PackageManager.NameNotFoundException { syncIntentService = spy(syncIntentService); syncIntentService.pullECFromServer(); verify(syncIntentService).sendBroadcast(intentArgumentCaptor.capture()); assertEquals(SyncStatusBroadcastReceiver.ACTION_SYNC_... |
SyncIntentService extends BaseSyncIntentService { public void fetchFailed(int count) { if (count < CoreLibrary.getInstance().getSyncConfiguration().getSyncMaxRetries()) { int newCount = count + 1; fetchRetry(newCount, false); } else { complete(FetchStatus.fetchedFailed); } } SyncIntentService(); SyncIntentService(Stri... | @Test public void testFetchFailedWithCountLessThanMaxSyncRetryCallsFetchRetry() { when(syncConfiguration.getSyncMaxRetries()).thenReturn(1); initMocksForPullECFromServerUsingPOST(); syncIntentService = spy(syncIntentService); ResponseStatus responseStatus = ResponseStatus.failure; Mockito.doReturn(new Response<>(respon... |
SyncIntentService extends BaseSyncIntentService { private boolean pushECToServer(EventClientRepository db) { boolean isSuccessfulPushSync = true; int totalEventCount = db.getUnSyncedEventsCount(); int eventsUploadedCount = 0; while (true) { Map<String, Object> pendingEvents = db.getUnSyncedEvents(EVENT_PUSH_LIMIT); if ... | @Test public void testPushECToServer() throws Exception { syncIntentService = spy(syncIntentService); Map<String, Object> pendingEvents = new HashMap<>(); List<JSONObject> clients = new ArrayList<>(); JSONObject client = new JSONObject(clientJson); clients.add(client); List<JSONObject> events = new ArrayList<>(); JSONO... |
DocumentConfigurationIntentService extends BaseSyncIntentService { @Override public int onStartCommand(Intent intent, int flags, int startId) { httpAgent = CoreLibrary.getInstance().context().getHttpAgent(); manifestRepository = CoreLibrary.getInstance().context().getManifestRepository(); clientFormRepository = CoreLib... | @Test public void onStartCommandShouldInstantiateVariables() { Assert.assertNull(ReflectionHelpers.getField(documentConfigurationIntentService, "httpAgent")); Assert.assertNull(ReflectionHelpers.getField(documentConfigurationIntentService, "manifestRepository")); Assert.assertNull(ReflectionHelpers.getField(documentCon... |
DateUtil { public static String formatDate(String unformattedDate) { return formatDate(unformattedDate, DEFAULT_DATE_FORMAT); } static void fakeIt(LocalDate fakeDayAsToday); static void setDefaultDateFormat(String defaultDateFormat); static LocalDate today(); static String formatDateForTimelineEvent(String unformatted... | @Test public void formatDateTest() { Assert.assertEquals("03-10-2019", DateUtil.formatDate(new LocalDate("2019-10-03"), "dd-MM-YYY")); Assert.assertEquals("", DateUtil.formatDate(new LocalDate("2019-10-03"), "KK-TT")); } |
SettingsSyncIntentService extends BaseSyncIntentService { protected boolean processSettings(Intent intent) { Timber.d("In Settings Sync Intent Service..."); boolean isSuccessfulSync = true; if (intent != null) { try { super.onHandleIntent(intent); int count = syncSettingsServiceHelper.processIntent(); if (count > 0) { ... | @Test public void processSettingsShouldReturnTrueWhenIntentIsNull() throws JSONException { settingsSyncIntentService.syncSettingsServiceHelper = Mockito.spy(settingsSyncIntentService.syncSettingsServiceHelper); Assert.assertTrue(settingsSyncIntentService.processSettings(null)); Mockito.verify(settingsSyncIntentService.... |
SettingsSyncIntentService extends BaseSyncIntentService { @Override public void onCreate() { super.onCreate(); Context context = CoreLibrary.getInstance().context(); syncSettingsServiceHelper = new SyncSettingsServiceHelper(context.configuration().dristhiBaseURL(), context.getHttpAgent()); } SettingsSyncIntentService()... | @Test public void onCreateShouldCreateSyncSettingsServiceHelper() { settingsSyncIntentService = Robolectric.buildIntentService(SettingsSyncIntentService.class) .get(); Assert.assertNull(settingsSyncIntentService.syncSettingsServiceHelper); settingsSyncIntentService.onCreate(); Assert.assertNotNull(settingsSyncIntentSer... |
TaskServiceHelper extends BaseHelper { public List<Task> syncTasks() { syncCreatedTaskToServer(); syncTaskStatusToServer(); return fetchTasksFromServer(); } @VisibleForTesting TaskServiceHelper(TaskRepository taskRepository); void setSyncByGroupIdentifier(boolean syncByGroupIdentifier); boolean isSyncByGroupIdentifier... | @Test public void testSyncTasks() { taskServiceHelper.syncTasks(); verify(taskServiceHelper).syncCreatedTaskToServer(); verify(taskServiceHelper).syncTaskStatusToServer(); } |
TaskServiceHelper extends BaseHelper { public void syncTaskStatusToServer() { HTTPAgent httpAgent = getHttpAgent(); List<TaskUpdate> updates = taskRepository.getUnSyncedTaskStatus(); if (!updates.isEmpty()) { String jsonPayload = new Gson().toJson(updates); String baseUrl = CoreLibrary.getInstance().context().configura... | @Test public void testSyncTaskStatusToServer() { TaskUpdate taskUpdate = new TaskUpdate(); taskUpdate.setIdentifier(planId); taskUpdate.setBusinessStatus("Not Visited"); taskUpdate.setStatus("Cancelled"); when(taskRepository.getUnSyncedTaskStatus()).thenReturn(Collections.singletonList(taskUpdate)); Mockito.doReturn(ne... |
TaskServiceHelper extends BaseHelper { public void syncCreatedTaskToServer() { HTTPAgent httpAgent = getHttpAgent(); List<Task> tasks = taskRepository.getAllUnsynchedCreatedTasks(); if (!tasks.isEmpty()) { String jsonPayload = taskGson.toJson(tasks); String baseUrl = CoreLibrary.getInstance().context().configuration().... | @Test public void testSynCreatedTaskToServerSuccessfully() { Task expectedTask = TaskServiceHelper.taskGson.fromJson(taskJSon, new TypeToken<Task>() { }.getType()); expectedTask.setSyncStatus(BaseRepository.TYPE_Created); ArrayList tasks = new ArrayList(); tasks.add(expectedTask); String expectedJsonPayload = TaskServi... |
PlanIntentServiceHelper extends BaseHelper { public void syncPlans() { syncProgress = new SyncProgress(); syncProgress.setSyncEntity(SyncEntity.PLANS); syncProgress.setTotalRecords(totalRecords); int batchFetchCount = batchFetchPlansFromServer(true); syncProgress.setPercentageSynced(Utils.calculatePercentage(totalRecor... | @Test public void testSyncPlansCallsSendSyncProgressDialog() { Whitebox.setInternalState(planIntentServiceHelper, "totalRecords", 10l); planIntentServiceHelper.syncPlans(); verify(planIntentServiceHelper).sendSyncProgressBroadcast(syncProgressArgumentCaptor.capture(),any()); assertEquals(SyncEntity.PLANS, syncProgressA... |
PlanIntentServiceHelper extends BaseHelper { private int batchFetchPlansFromServer(boolean returnCount) { int batchFetchCount = 0; try { long serverVersion = 0; try { serverVersion = Long.parseLong(allSharedPreferences.getPreference(PLAN_LAST_SYNC_DATE)); } catch (NumberFormatException e) { Timber.e(e, "EXCEPTION %s", ... | @Test public void testBatchFetchPlansFromServer() { PlanDefinition expectedPlan = PlanIntentServiceHelper.gson.fromJson(planJson, new TypeToken<PlanDefinition>() { }.getType()); ArrayList plans = new ArrayList(); plans.add(expectedPlan); Mockito.doReturn(new Response<>(ResponseStatus.success, PlanIntentServiceHelper.gs... |
DateUtil { public static LocalDate getLocalDate(String date) { try { SimpleDateFormat format = new SimpleDateFormat(DEFAULT_DATE_FORMAT, Utils.getDefaultLocale()); Date formattedDate = format.parse(date); return new LocalDate(formattedDate); } catch (Exception e) { return null; } } static void fakeIt(LocalDate fakeDay... | @Test public void getLocalDateTest() { Assert.assertEquals(new LocalDate("2019-10-03"), DateUtil.getLocalDate("03/10/2019")); Assert.assertEquals(null, DateUtil.getLocalDate("03-15-2019")); } |
SyncSettingsServiceHelper { public int processIntent() throws JSONException { try { JSONObject response = pushSettingsToServer(); if (response != null && response.has(AllConstants.INTENT_KEY.VALIDATED_RECORDS)) { JSONArray records = response.getJSONArray(AllConstants.INTENT_KEY.VALIDATED_RECORDS); Setting setting; for ... | @Test public void testProcessIntent() throws JSONException { AllSettings allSettings = Mockito.spy(CoreLibrary.getInstance().context().allSettings()); ReflectionHelpers.setField(CoreLibrary.getInstance().context(), "allSettings", allSettings); SettingsRepository settingsRepository = ReflectionHelpers.getField(allSettin... |
ValidateAssignmentHelper extends BaseHelper { @VisibleForTesting protected void removeLocationsFromHierarchy(LocationTree locationTree, Set<String> removedAssignments) throws AuthenticatorException, OperationCanceledException, IOException { for (String removedAssignment : removedAssignments) { locationTree.deleteLocati... | @Test public void testRemoveLocationsFromHierarchyShouldRemoveLocations() throws Exception { Set<String> locations = new HashSet<>(Arrays.asList("853934ee-d1a6-4b69-9191-59047edbc9a8", "4ed8f536-5c08-4203-8a90-a7e13becb01d")); validateAssignmentHelper.removeLocationsFromHierarchy(locationTree, locations); verify(settin... |
ValidateAssignmentHelper extends BaseHelper { public void validateUserAssignment() { boolean keycloakConfigured = allSharedPreferences.getBooleanPreference(IS_KEYCLOAK_CONFIGURED); if (!keycloakConfigured) { return; } try { String assignment = getUserAssignment(); if (StringUtils.isNotBlank(assignment)) { UserAssignmen... | @Test public void testValidateUserAssignmentShouldDoNothingIfKeycloakIsNotEnabled() { validateAssignmentHelper.validateUserAssignment(); verifyNoMoreInteractions(userService); verifyNoMoreInteractions(userService); verifyNoMoreInteractions(locationRepository); }
@Test public void testValidateUserAssignmentShouldDoNothi... |
ECSyncHelper { public boolean saveAllClientsAndEvents(JSONObject jsonObject) { try { if (jsonObject == null) { return false; } JSONArray events = jsonObject.has("events") ? jsonObject.getJSONArray("events") : new JSONArray(); JSONArray clients = jsonObject.has("clients") ? jsonObject.getJSONArray("clients") : new JSONA... | @Test public void testSaveAllClientsAndEventsShouldReturnFalseForNullParam() throws Exception { ECSyncHelper syncHelperSpy = Mockito.spy(syncHelper); boolean result = syncHelperSpy.saveAllClientsAndEvents(null); Assert.assertFalse(result); } |
ECSyncHelper { public List<EventClient> allEventClients(long startSyncTimeStamp, long lastSyncTimeStamp) { try { return eventClientRepository.fetchEventClients(startSyncTimeStamp, lastSyncTimeStamp); } catch (Exception e) { Timber.e(e); } return new ArrayList<>(); } @VisibleForTesting protected ECSyncHelper(Context co... | @Test public void testAllEventClientsInvokesRepositoryFetchEventClientsWithCorrectParams() { ECSyncHelper syncHelperSpy = Mockito.spy(syncHelper); Mockito.doReturn(null).when(eventClientRepository).fetchEventClients(DUMMY_LONG, DUMMY_LONG); List<EventClient> result = syncHelperSpy.allEventClients(DUMMY_LONG, DUMMY_LONG... |
FileUtilities { public void write(String fileName, String data) { File root = Environment.getExternalStorageDirectory(); File outDir = new File(root.getAbsolutePath() + File.separator + "EZ_time_tracker"); if (!outDir.isDirectory()) { outDir.mkdir(); } try { if (!outDir.isDirectory()) { throw new IOException("Unable to... | @Test public void assertWriteWritesSuccessfully() throws Exception { String testData = "string to write"; when(Environment.getExternalStorageDirectory()).thenReturn(existentDirectory); PowerMockito.whenNew(BufferedWriter.class).withAnyArguments().thenReturn(mockWriter); FileUtilities fileUtils = new FileUtilities(); tr... |
LocationServiceHelper extends BaseHelper { public void fetchOpenMrsLocationsByTeamIds() throws NoHttpResponseException, JSONException { HTTPAgent httpAgent = getHttpAgent(); if (httpAgent == null) { throw new IllegalArgumentException(OPENMRS_LOCATION_BY_TEAM_IDS + " http agent is null"); } String baseUrl = getFormatted... | @Test public void fetchOpenMrsLocationsByTeamIds() throws JSONException, NoHttpResponseException { Mockito.doReturn(new Response<>(ResponseStatus.success, "[{\"locations\":[{\"display\":\"Tabata Dampo - Unified\",\"uuid\":\"fb7ed5db-138d-4e6f-94d8-bc443b58dadb\"}]," + "\"team\":{\"location\":{\"display\":\"Madona - Uni... |
LocationServiceHelper extends BaseHelper { public void fetchLocationsByLevelAndTags() throws Exception { HTTPAgent httpAgent = getHttpAgent(); if (httpAgent == null) { throw new IllegalArgumentException(COMMON_LOCATIONS_SERVICE_URL + " http agent is null"); } String baseUrl = getFormattedBaseUrl(); SyncConfiguration co... | @Test public void fetchLocationsByLevelAndTags() throws Exception { Mockito.doReturn(new Response<>(ResponseStatus.success, "[{\"locationId\":\"b949c2b5-d5f6-4a1b-ad03-e82e7abbd47c\",\"name\":\"Ebrahim Haji - Unified\"," + "\"parentLocation\":{\"locationId\":\"620e3393-38aa-4797-85c4-3427cc882e00\",\"name\":\"Ilala MC ... |
LocationServiceHelper extends BaseHelper { public List<Location> fetchLocationsStructures() { syncLocationsStructures(true); List<Location> locations = syncLocationsStructures(false); syncCreatedStructureToServer(); syncUpdatedLocationsToServer(); return locations; } LocationServiceHelper(LocationRepository locationRep... | @Test public void testFetchLocationsStructures() { locationServiceHelper.fetchLocationsStructures(); verify(locationServiceHelper).syncLocationsStructures(true); verify(locationServiceHelper).syncLocationsStructures(false); verify(locationServiceHelper).syncCreatedStructureToServer(); verify(locationServiceHelper).sync... |
LocationServiceHelper extends BaseHelper { public void syncCreatedStructureToServer() { List<Location> locations = structureRepository.getAllUnsynchedCreatedStructures(); if (!locations.isEmpty()) { String jsonPayload = locationGson.toJson(locations); String baseUrl = getFormattedBaseUrl(); Response<String> response = ... | @Test public void testSyncCreatedStructureToServer() { Location expectedStructure = LocationServiceHelper.locationGson.fromJson(structureJSon, new TypeToken<Location>() { }.getType()); expectedStructure.setSyncStatus(BaseRepository.TYPE_Unsynced); List<Location> structures = Collections.singletonList(expectedStructure)... |
LocationServiceHelper extends BaseHelper { public void syncUpdatedLocationsToServer() { HTTPAgent httpAgent = getHttpAgent(); List<Location> locations = locationRepository.getAllUnsynchedLocation(); if (!locations.isEmpty()) { String jsonPayload = locationGson.toJson(locations); String baseUrl = getFormattedBaseUrl(); ... | @Test public void testSyncUpdatedLocationsToServer() { Location expectedLocation = LocationServiceHelper.locationGson.fromJson(locationJSon, new TypeToken<Location>() { }.getType()); expectedLocation.setSyncStatus(BaseRepository.TYPE_Unsynced); List<Location> locations = Collections.singletonList(expectedLocation); whe... |
LocationServiceHelper extends BaseHelper { public void fetchAllLocations() { try { HTTPAgent httpAgent = getHttpAgent(); if (httpAgent == null) { throw new IllegalArgumentException(LOCATION_STRUCTURE_URL + " http agent is null"); } String baseUrl = getFormattedBaseUrl(); JSONObject request = new JSONObject(); request.p... | @Test public void testFetchAllLocations() { Mockito.doReturn(new Response<>(ResponseStatus.success, "[{\"type\":\"Feature\",\"id\":\"c2aa34c2-789b-467e-a0ab-9ea3d61632cf\",\"properties\":{\"status\":\"Active\",\"parentId\":\"\",\"name\":\"Level1\",\"geographicLevel\":1,\"version\":0},\"serverVersion\":0,\"locationTags\... |
P2PSyncAuthorizationService implements P2PAuthorizationService { @Override public void authorizeConnection(@NonNull final Map<String, Object> peerDeviceMap, @NonNull final AuthorizationCallback authorizationCallback) { getAuthorizationDetails(new OnAuthorizationDetailsProvidedCallback() { @Override public void onAuthor... | @Test public void authorizeConnectionShouldCallOnConnectionAuthorizedWhenPeerDeviceTeamIdIsEqualsCurrentDeviceTeamId() { P2PAuthorizationService.AuthorizationCallback authorizationCallback = Mockito.mock(P2PAuthorizationService.AuthorizationCallback.class); HashMap<String, Object> peerDeviceMap = new HashMap<>(); peerD... |
FileUtilities { public static String getFileExtension(String fileName) { String extension = ""; if (fileName != null && !fileName.isEmpty()) { int i = fileName.lastIndexOf('.'); if (i > 0) { extension = fileName.substring(i + 1); } } return extension; } FileUtilities(); static Bitmap retrieveStaticImageFromDisk(String ... | @Test public void assertReturnsCorrectFileExtension() { Assert.assertEquals(FileUtilities.getFileExtension(FILE_NAME), "txt"); } |
OpenSRPClientBroadCastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { try { String action = intent.getAction(); switch (action) { case Intent.ACTION_TIME_CHANGED: Timber.d("timechanged"); forceFullySignOut(); break; case Intent.ACTION_TIMEZONE_CHANGED: Timber.d("ti... | @Test public void onReceiveShouldLogoutUserWhenActionTimeChanged() { Intent intent = new Intent(Intent.ACTION_TIME_CHANGED); openSRPClientBroadCastReceiver.onReceive(RuntimeEnvironment.application, intent); Mockito.verify(drishtiApplication).logoutCurrentUser(); }
@Test public void onReceiveShouldLogoutUserWhenActionTi... |
GZIPCompression implements ICompression { @Override public byte[] compress(String rawString) { try { ByteArrayOutputStream os = new ByteArrayOutputStream(); GZIPOutputStream gos = new GZIPOutputStream(os); gos.write(rawString.getBytes(CharEncoding.UTF_8)); gos.close(); byte[] compressed = os.toByteArray(); os.close(); ... | @Test public void testCompressMethodReturnsACompressedOutput() throws IOException { byte[] original = TEST_STRING.getBytes(CharEncoding.UTF_8); byte[] compressed = gzipCompression.compress(TEST_STRING); Assert.assertTrue(original.length > compressed.length); }
@Test public void testCompressFileMethodReturnsACompressedO... |
Utils { public static String convertDateFormat(String date, boolean suppressException) { try { return UI_DF.format(DB_DF.parse(date)); } catch (ParseException e) { if (!suppressException) throw new RuntimeException(e); } return ""; } static String convertDateFormat(String date, boolean suppressException); static Date ... | @Test public void assertConvertDateFormatTestReturnsDate() throws Exception { assertEquals("20-10-2017", Utils.convertDateFormat("2017-10-20", true)); assertEquals("", Utils.convertDateFormat("20171020", true)); }
@Test public void assertConvertDateFormat() throws Exception { assertEquals("20-10-2017", Utils.convertDat... |
Utils { public static Date toDate(String date, boolean suppressException) { try { return DB_DF.parse(date); } catch (ParseException e) { if (!suppressException) throw new RuntimeException(e); } return null; } static String convertDateFormat(String date, boolean suppressException); static Date toDate(String date, boole... | @Test public void assertToDateReturnsDate() throws Exception { SimpleDateFormat DB_DF = new SimpleDateFormat("yyyy-MM-dd"); Date date = DB_DF.parse("2017-10-20"); org.junit.Assert.assertNotNull(Utils.toDate("2017-10-20", true)); assertNull(Utils.toDate("20171020", true)); assertEquals(date, Utils.toDate("2017-10-20", t... |
Utils { public static String convertDateTimeFormat(String date, boolean suppressException) { try { return UI_DTF.format(DB_DTF.parse(date.replace("T", " "))); } catch (ParseException e) { e.printStackTrace(); if (!suppressException) throw new RuntimeException(e); } return ""; } static String convertDateFormat(String d... | @Test public void assertConvertDateTimeFormatReturnsDate() throws Exception { assertEquals("24-07-1985 00:00:00", Utils.convertDateTimeFormat("1985-07-24T00:00:00.000Z", true)); }
@Test(expected = RuntimeException.class) public void assertConvertDateTimeFormatThrowsExceptionIfUnpasrsableDate() { Utils.convertDateTimeFo... |
Utils { public static void fillValue(TextView v, Map<String, String> cm, String field, boolean humanize) { v.setText(getValue(cm, field, humanize)); } static String convertDateFormat(String date, boolean suppressException); static Date toDate(String date, boolean suppressException); static String convertDateFormat(Str... | @Test public void assertFillValueFromHashMapReturnsValue() { android.widget.TextView view = new android.widget.TextView(RuntimeEnvironment.application); HashMap<String, String> map = new HashMap<String, String>(); String field = "field"; map.put(field, "2017-10-20"); Utils.fillValue(view, map, field, true); assertEqual... |
Utils { public static String formatValue(String value, boolean humanize) { if (value == null) { value = ""; } return humanize ? WordUtils.capitalize(StringUtil.humanize(value)) : value; } static String convertDateFormat(String date, boolean suppressException); static Date toDate(String date, boolean suppressException)... | @Test public void assertFormatValueReturnsValue() { assertEquals("", Utils.formatValue(null, true)); assertEquals("Abc-def", Utils.formatValue("abc-def", true)); assertEquals("abc-def", Utils.formatValue("abc-def", false)); }
@Test public void assertFormatValueObjectReturnsValue() { assertEquals("", Utils.formatValue((... |
Utils { public static String getValue(CommonPersonObjectClient pc, String field, boolean humanize) { return formatValue(pc.getDetails().get(field), humanize); } static String convertDateFormat(String date, boolean suppressException); static Date toDate(String date, boolean suppressException); static String convertDate... | @Test public void assertGetValueReturnsValue() { String field = "field"; HashMap<String, String> map = new HashMap<String, String>(); map.put(field, "2017-10-20"); CommonPersonObjectClient cm = new CommonPersonObjectClient("", map, "NAME"); assertEquals(Utils.getValue(cm, field, "default", true), "2017-10-20"); map.put... |
Utils { public static String nonEmptyValue(Map<String, String> cm, boolean asc, boolean humanize, String... fields) { List<String> l = Arrays.asList(fields); if (!asc) { Collections.reverse(l); } for (String f : l) { String v = getValue(cm, f, humanize); if (v != "") { return v; } } return ""; } static String convertD... | @Test public void assertNotEmptyValueReturnsValue() { String field = "field"; HashMap<String, String> map = new HashMap<String, String>(); map.put(field, "2017-10-20"); assertEquals(Utils.nonEmptyValue(map, false, true, new String[]{field}), "2017-10-20"); map.put(field, ""); assertEquals(Utils.nonEmptyValue(map, false... |
Utils { public static boolean hasAnyEmptyValue(Map<String, String> cm, String postFix, String... fields) { List<String> l = Arrays.asList(fields); for (String f : l) { String v = getValue(cm, f, false); if (v == "" && (StringUtils.isBlank(postFix) || StringUtils.isBlank(getValue(cm, f + postFix, false)))) { return true... | @Test public void assertHasEmptyValueReturnsBoolean() throws Exception { String field = "field"; HashMap<String, String> map = new HashMap<String, String>(); map.put(field, ""); assertEquals(Utils.hasAnyEmptyValue(map, "", new String[]{field}), true); map.put(field, "2017-10-20"); assertEquals(Utils.hasAnyEmptyValue(ma... |
Utils { public static int addAsInts(boolean ignoreEmpty, String... vals) { int i = 0; for (String v : vals) { i += ignoreEmpty && StringUtils.isBlank(v) ? 0 : Integer.parseInt(v); } return i; } static String convertDateFormat(String date, boolean suppressException); static Date toDate(String date, boolean suppressExce... | @Test public void assertAddToIntReturnsSum() { assertEquals(Utils.addAsInts(true, new String[]{""}), 0); assertEquals(Utils.addAsInts(true, new String[]{"1", "1", "1"}), 3); } |
Utils { public static TableRow addToRow(Context context, String value, TableRow row) { return addToRow(context, value, row, false, 1); } static String convertDateFormat(String date, boolean suppressException); static Date toDate(String date, boolean suppressException); static String convertDateFormat(String date, Stri... | @Test public void assertAddToRowReturnsTableRow() { TableRow mockRow = new TableRow(RuntimeEnvironment.application); TableRow row = Utils.addToRow(RuntimeEnvironment.application, "hello world", mockRow); assertEquals(mockRow, row); android.widget.TextView view = (android.widget.TextView) row.getChildAt(0); assertEquals... |
Utils { public static Intent completeSync(FetchStatus fetchStatus) { Intent intent = new Intent(); intent.setAction(SyncStatusBroadcastReceiver.ACTION_SYNC_STATUS); intent.putExtra(SyncStatusBroadcastReceiver.EXTRA_FETCH_STATUS, fetchStatus); intent.putExtra(SyncStatusBroadcastReceiver.EXTRA_COMPLETE_STATUS, true); ret... | @Test public void testCompleteSyncIntent() throws Exception { Intent intent = new Intent(); assertEquals(intent.getExtras(), null); intent.setAction(SyncStatusBroadcastReceiver.ACTION_SYNC_STATUS); intent.putExtra(SyncStatusBroadcastReceiver.EXTRA_FETCH_STATUS, FetchStatus.fetched); intent.putExtra(SyncStatusBroadcastR... |
Utils { public static String kgStringSuffix(Float weight) { return String.format(KG_FORMAT, weight); } static String convertDateFormat(String date, boolean suppressException); static Date toDate(String date, boolean suppressException); static String convertDateFormat(String date, String defaultV, boolean suppressExcep... | @Test public void testKgStringSuffixReturnsCorrectValueIfParamFloat() { String result = Utils.kgStringSuffix(2.5f); Assert.assertNotNull(result); assertEquals("2.5 kg", result); }
@Test public void testKgStringSuffixReturnsCorrectValueIfParamString() { String result = Utils.kgStringSuffix("3.4"); Assert.assertNotNull(r... |
Utils { public static String cmStringSuffix(Float height) { return String.format(CM_FORMAT, height); } static String convertDateFormat(String date, boolean suppressException); static Date toDate(String date, boolean suppressException); static String convertDateFormat(String date, String defaultV, boolean suppressExcep... | @Test public void testCmStringSuffixReturnsCorrectValueIfParamFloat() { String result = Utils.cmStringSuffix(1.5f); Assert.assertNotNull(result); assertEquals("1.5 cm", result); }
@Test public void testCmStringSuffixReturnsCorrectValueIfParamString() { String result = Utils.cmStringSuffix("45.9"); Assert.assertNotNull(... |
Utils { public static long getVersionCode(Context context) throws PackageManager.NameNotFoundException { PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0); return packageInfo.versionCode; } static String convertDateFormat(String date, boolean suppressException); static D... | @Test public void testGetVersionCodeShouldGetCorrectVersionCode() throws PackageManager.NameNotFoundException { Context context = getContext(40); assertEquals(Utils.getVersionCode(context), 40); } |
Utils { public static boolean is2xxSuccessful(int httpStatus) { return httpStatus >= HttpStatus.SC_OK && httpStatus <= HttpStatus.SC_MULTI_STATUS; } static String convertDateFormat(String date, boolean suppressException); static Date toDate(String date, boolean suppressException); static String convertDateFormat(Strin... | @Test public void testIs2xxSuccessfulShouldReturnCorrectStatus() { assertTrue(Utils.is2xxSuccessful(200)); assertTrue(Utils.is2xxSuccessful(203)); assertTrue(Utils.is2xxSuccessful(207)); assertFalse(Utils.is2xxSuccessful(300)); } |
Utils { public static DateTime dobStringToDateTime(String dobString) { try { if (StringUtils.isBlank(dobString)) { return null; } return new DateTime(dobString); } catch (Exception e) { return null; } } static String convertDateFormat(String date, boolean suppressException); static Date toDate(String date, boolean sup... | @Test public void testDobStringToDateTimeShouldReturnCorrectDateTime() { assertEquals(Utils.dobStringToDateTime("2000-12-30").toString(), new DateTime("2000-12-30").toString()); } |
Utils { public static String getFilterValue(LoginResponse loginResponse, SyncFilter syncFilterParam) { String filterValue = ""; LoginResponseData response = loginResponse.payload(); switch (syncFilterParam) { case TEAM: case TEAM_ID: filterValue = response.team.team.uuid; break; case LOCATION: filterValue = response.te... | @Test public void testGetFilterValueShouldGetCorrectFilterValue() { LoginResponseData loginResponseData = getLoginResponseData(); LoginResponse loginResponse = LoginResponse.SUCCESS.withPayload(loginResponseData); assertEquals(loginResponseData.team.team.uuid, Utils.getFilterValue(loginResponse, SyncFilter.TEAM)); asse... |
Utils { public static AppProperties getProperties(Context context) { AppProperties properties = new AppProperties(); try { AssetManager assetManager = context.getAssets(); InputStream inputStream = assetManager.open(APP_PROPERTIES_FILE); properties.load(inputStream); } catch (Exception e) { Timber.e(e); } return proper... | @Test @Ignore public void testGetPropertiesShouldGetPropertyFile() { AppProperties appProperties = Utils.getProperties(RuntimeEnvironment.application); assertTrue(appProperties.getPropertyBoolean("property_4")); assertEquals("property_1", appProperties.getProperty("property_1")); assertEquals("property_2", appPropertie... |
Utils { public static String getUserDefaultTeamId(LoginResponseData userInfo) { try { if (userInfo != null && userInfo.team != null && userInfo.team.team != null) { return userInfo.team.team.uuid; } } catch (Exception e) { Log.v("Error : ", e.getMessage()); } return null; } static String convertDateFormat(String date,... | @Test public void testGetUserDefaultTeamIdShouldGetCorrectTeamId() { LoginResponseData loginResponseData = getLoginResponseData(); assertEquals(loginResponseData.team.team.uuid, Utils.getUserDefaultTeamId(loginResponseData)); } |
Utils { public static boolean isEmptyCollection(Collection collection) { return collection == null || collection.isEmpty(); } static String convertDateFormat(String date, boolean suppressException); static Date toDate(String date, boolean suppressException); static String convertDateFormat(String date, String defaultV... | @Test public void testIsEmptyCollectionShouldReturnCorrectStatus() { List<String> list = new ArrayList<>(); list.add("string"); assertFalse(Utils.isEmptyCollection(list)); list.clear(); assertTrue(Utils.isEmptyCollection(list)); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.