method2testcases
stringlengths 118
3.08k
|
---|
### Question:
Solr4X509ServletFilter extends X509ServletFilterBase { MBeanServer mxServer() { return ofNullable((MBeanServerFactory.findMBeanServer(null))) .filter(servers -> !servers.isEmpty()) .map(Collection::iterator) .map(Iterator::next) .orElseThrow(NoSuchElementException::new); } }### Answer:
@Test(expected = NoSuchElementException.class) public void mxServerNotFound() { MBeanServerFactory.releaseMBeanServer(mxServer); cut.mxServer(); }
|
### Question:
Solr4X509ServletFilter extends X509ServletFilterBase { int getHttpsPort() { return connectorMBeanName().map(extractPortNumber).orElse(NOT_FOUND_HTTPS_PORT_NUMBER); } }### Answer:
@Test public void oneAvailableHttpsConnector() throws Exception { final int expectedPort = 8443; registerConnector("https", expectedPort); assertEquals(expectedPort, cut.getHttpsPort()); }
@Test public void httpAndHttpsConnectors() throws Exception { final int expectedPort = 8443; registerConnector("http", 80); registerConnector("https", expectedPort); assertEquals(expectedPort, cut.getHttpsPort()); }
@Test public void cannotGetHttpsPort() throws Exception { registerTouchyHttpsConnector(); assertEquals(Solr4X509ServletFilter.NOT_FOUND_HTTPS_PORT_NUMBER, cut.getHttpsPort()); }
|
### Question:
ExplicitShardIdWithStaticPropertyRouter extends ComposableDocRouter { @Override public Boolean routeAcl(int shardCount, int shardInstance, Acl acl) { return true; } ExplicitShardIdWithStaticPropertyRouter(); ExplicitShardIdWithStaticPropertyRouter(boolean isInStandaloneMode); @Override Boolean routeAcl(int shardCount, int shardInstance, Acl acl); @Override Boolean routeNode(int shardCount, int shardInstance, Node node); }### Answer:
@Test public void aclsAreReplicatedAcrossShards() { range(0, 100).forEach(index -> assertTrue(router.routeAcl(randomPositiveInteger(), randomPositiveInteger(), acl))); }
|
### Question:
ExplicitShardIdWithStaticPropertyRouter extends ComposableDocRouter { @Override public Boolean routeNode(int shardCount, int shardInstance, Node node) { Integer explicitShardId = node.getExplicitShardId(); if (explicitShardId == null) { debug("ExplicitShardId property is not set for node {} ", node.getNodeRef()); return negativeReturnValue(); } return explicitShardId.equals(shardInstance); } ExplicitShardIdWithStaticPropertyRouter(); ExplicitShardIdWithStaticPropertyRouter(boolean isInStandaloneMode); @Override Boolean routeAcl(int shardCount, int shardInstance, Acl acl); @Override Boolean routeNode(int shardCount, int shardInstance, Node node); }### Answer:
@Test public void standaloneModeExplicitShardIdIsNull_shouldReturnFalse() { int shardCount = randomShardCountGreaterThanOne(); int shardInstance = randomPositiveInteger(); when(node.getExplicitShardId()).thenReturn(null); assertFalse(router.routeNode(shardCount, shardInstance, node)); }
@Test public void composableModeExplicitShardIdIsNull_shouldReturnFalse() { router = new ExplicitShardIdWithStaticPropertyRouter(false); int shardCount = randomShardCountGreaterThanOne(); int shardInstance = randomPositiveInteger(); when(node.getExplicitShardId()).thenReturn(null); assertNull(router.routeNode(shardCount, shardInstance, node)); }
@Test public void explicitShardMatchesShardInstance() { int shardCount = randomShardCountGreaterThanOne(); int shardInstance = randomPositiveInteger(); when(node.getExplicitShardId()).thenReturn(shardInstance); assertTrue(router.routeNode(shardCount, shardInstance, node)); }
@Test public void explicitShardDoesntMatchShardInstance() { int shardCount = randomShardCountGreaterThanOne(); int shardInstance = randomPositiveInteger(); when(node.getExplicitShardId()).thenReturn(shardInstance); assertFalse(router.routeNode(shardCount, shardInstance + 1, node)); }
|
### Question:
DBIDRouter implements DocRouter { @Override public Boolean routeAcl(int shardCount, int shardInstance, Acl acl) { return true; } @Override Boolean routeAcl(int shardCount, int shardInstance, Acl acl); @Override Boolean routeNode(int shardCount, int shardInstance, Node node); }### Answer:
@Test public void aclsAreReplicatedAcrossShards() { range(0, 100).forEach(index -> assertTrue(router.routeAcl(randomShardCountGreaterThanOne(), randomPositiveInteger(), acl))); }
|
### Question:
DBIDRouter implements DocRouter { @Override public Boolean routeNode(int shardCount, int shardInstance, Node node) { if(shardCount <= 1) { return true; } String dbid = Long.toString(node.getId()); return (Math.abs(Hash.murmurhash3_x86_32(dbid, 0, dbid.length(), 77)) % shardCount) == shardInstance; } @Override Boolean routeAcl(int shardCount, int shardInstance, Acl acl); @Override Boolean routeNode(int shardCount, int shardInstance, Node node); }### Answer:
@Test public void multipleShardsInTheCluster_shouldBalanceNodes() { int [] shardIdentifiers = range(0,15).toArray(); int shardCount = shardIdentifiers.length; int howManyDocumentsPerShard = 10000; Map<Integer, Integer> nodeDistributionMap = new HashMap<>(); range(0, shardCount * howManyDocumentsPerShard) .mapToLong(Long::valueOf) .forEach(id -> { Node node = new Node(); node.setId(id); stream(shardIdentifiers) .forEach(shardId -> { if (router.routeNode(shardCount, shardId, node)) { nodeDistributionMap.merge(shardId, 1, Integer::sum); } }); }); StandardDeviation sd = new StandardDeviation(); double deviation = sd.evaluate(nodeDistributionMap.values().stream().mapToDouble(Number::doubleValue).toArray()); double norm = deviation/(howManyDocumentsPerShard) * 100; assertEquals(shardIdentifiers.length, nodeDistributionMap.size()); assertTrue( nodeDistributionMap.values().toString() + ", SD = " + deviation + ", SD_NORM = " + norm + "%", norm < 30); }
|
### Question:
MetadataTracker extends ActivatableTracker { public List<Node> getFullNodesForDbTransaction(Long txid) { try { GetNodesParameters gnp = new GetNodesParameters(); ArrayList<Long> txs = new ArrayList<>(); txs.add(txid); gnp.setTransactionIds(txs); gnp.setStoreProtocol(storeRef.getProtocol()); gnp.setStoreIdentifier(storeRef.getIdentifier()); gnp.setCoreName(coreName); return client.getNodes(gnp, Integer.MAX_VALUE); } catch (IOException | AuthenticationException | JSONException e) { throw new AlfrescoRuntimeException("Failed to get nodes", e); } } MetadataTracker(Properties p, SOLRAPIClient client, String coreName,
InformationServer informationServer); MetadataTracker( Properties p, SOLRAPIClient client, String coreName,
InformationServer informationServer, boolean checkRepoServicesAvailability); MetadataTracker(); @Override Semaphore getWriteLock(); @Override Semaphore getRunLock(); void maintenance(); boolean hasMaintenance(); @Override NodeReport checkNode(Long dbid); NodeReport checkNode(Node node); List<Node> getFullNodesForDbTransaction(Long txid); IndexHealthReport checkIndex(Long toTx, Long fromTime, Long toTime); void addTransactionToPurge(Long txId); void addNodeToPurge(Long nodeId); void addTransactionToReindex(Long txId); void addNodeToReindex(Long nodeId); void addTransactionToIndex(Long txId); void addNodeToIndex(Long nodeId); void invalidateState(); void addQueryToReindex(String query); }### Answer:
@Test @Ignore("Superseded by AlfrescoSolrTrackerTest") public void testGetFullNodesForDbTransaction() throws AuthenticationException, IOException, JSONException { List<Node> nodes = getNodes(); when(repositoryClient.getNodes(any(GetNodesParameters.class), anyInt())).thenReturn(nodes); List<Node> nodes4Tx = this.metadataTracker.getFullNodesForDbTransaction(TX_ID); assertSame(nodes4Tx, nodes); }
|
### Question:
SolrTrackerScheduler { public void shutdown() throws SchedulerException { this.scheduler.shutdown(false); } SolrTrackerScheduler(AlfrescoCoreAdminHandler adminHandler); void schedule(Tracker tracker, String coreName, Properties props); void shutdown(); void deleteTrackerJobs(String coreName, Collection<Tracker> trackers); void deleteJobForTrackerInstance(String coreName, Tracker tracker); void deleteTrackerJob(String coreName, Tracker tracker); boolean isShutdown(); void pauseAll(); int getJobsCount(); static final String SOLR_JOB_GROUP; }### Answer:
@Test public void testShutdown() throws SchedulerException { this.trackerScheduler.shutdown(); assertTrue(trackerScheduler.isShutdown()); }
|
### Question:
SolrTrackerScheduler { public void deleteTrackerJobs(String coreName, Collection<Tracker> trackers) throws SchedulerException { for (Tracker tracker : trackers) { deleteTrackerJob(coreName, tracker); } } SolrTrackerScheduler(AlfrescoCoreAdminHandler adminHandler); void schedule(Tracker tracker, String coreName, Properties props); void shutdown(); void deleteTrackerJobs(String coreName, Collection<Tracker> trackers); void deleteJobForTrackerInstance(String coreName, Tracker tracker); void deleteTrackerJob(String coreName, Tracker tracker); boolean isShutdown(); void pauseAll(); int getJobsCount(); static final String SOLR_JOB_GROUP; }### Answer:
@Test public void testDeleteTrackerJobs() throws SchedulerException { ContentTracker contentTracker = new ContentTracker(); MetadataTracker metadataTracker = new MetadataTracker(); AclTracker aclTracker = new AclTracker(); this.trackerScheduler.deleteTrackerJobs(CORE_NAME, Arrays.asList(new Tracker[] { contentTracker, metadataTracker, aclTracker })); verify(spiedQuartzScheduler, times(3)).deleteJob(any(JobKey.class)); }
|
### Question:
SolrTrackerScheduler { public void deleteTrackerJob(String coreName, Tracker tracker) throws SchedulerException { String jobName = this.getJobName(tracker, coreName); this.scheduler.deleteJob(new JobKey(jobName, SOLR_JOB_GROUP)); } SolrTrackerScheduler(AlfrescoCoreAdminHandler adminHandler); void schedule(Tracker tracker, String coreName, Properties props); void shutdown(); void deleteTrackerJobs(String coreName, Collection<Tracker> trackers); void deleteJobForTrackerInstance(String coreName, Tracker tracker); void deleteTrackerJob(String coreName, Tracker tracker); boolean isShutdown(); void pauseAll(); int getJobsCount(); static final String SOLR_JOB_GROUP; }### Answer:
@Test public void testDeleteTrackerJob() throws SchedulerException { ModelTracker modelTracker = new ModelTracker(); this.trackerScheduler.deleteTrackerJob(CORE_NAME, modelTracker); verify(spiedQuartzScheduler).deleteJob(any(JobKey.class)); }
|
### Question:
SolrTrackerScheduler { public boolean isShutdown() throws SchedulerException { return this.scheduler.isShutdown(); } SolrTrackerScheduler(AlfrescoCoreAdminHandler adminHandler); void schedule(Tracker tracker, String coreName, Properties props); void shutdown(); void deleteTrackerJobs(String coreName, Collection<Tracker> trackers); void deleteJobForTrackerInstance(String coreName, Tracker tracker); void deleteTrackerJob(String coreName, Tracker tracker); boolean isShutdown(); void pauseAll(); int getJobsCount(); static final String SOLR_JOB_GROUP; }### Answer:
@Test public void newSchedulerIsNotShutdown() throws SchedulerException { assertFalse(trackerScheduler.isShutdown()); }
|
### Question:
SolrTrackerScheduler { public void pauseAll() throws SchedulerException { this.scheduler.pauseAll(); } SolrTrackerScheduler(AlfrescoCoreAdminHandler adminHandler); void schedule(Tracker tracker, String coreName, Properties props); void shutdown(); void deleteTrackerJobs(String coreName, Collection<Tracker> trackers); void deleteJobForTrackerInstance(String coreName, Tracker tracker); void deleteTrackerJob(String coreName, Tracker tracker); boolean isShutdown(); void pauseAll(); int getJobsCount(); static final String SOLR_JOB_GROUP; }### Answer:
@Test public void testPauseAll() throws SchedulerException { this.trackerScheduler.pauseAll(); verify(this.spiedQuartzScheduler).pauseAll(); }
|
### Question:
DBIDRangeRouter implements DocRouter { @Override public Boolean routeAcl(int shardCount, int shardInstance, Acl acl) { return true; } DBIDRangeRouter(long startRange, long endRange); void setEndRange(long endRange); void setExpanded(boolean expanded); void setInitialized(boolean initialized); boolean getInitialized(); long getEndRange(); long getStartRange(); boolean getExpanded(); @Override Boolean routeAcl(int shardCount, int shardInstance, Acl acl); @Override Boolean routeNode(int shardCount, int shardInstance, Node node); @Override Map<String, String> getProperties(Optional<QName> shardProperty); }### Answer:
@Test public void aclsAreReplicatedAcrossShards() { range(0, 100).forEach(index -> assertTrue(router.routeAcl(randomizer.nextInt(), randomizer.nextInt(), acl))); }
|
### Question:
DBIDRangeRouter implements DocRouter { @Override public Boolean routeNode(int shardCount, int shardInstance, Node node) { long dbid = node.getId(); return dbid >= startRange && dbid < expandableRange.longValue(); } DBIDRangeRouter(long startRange, long endRange); void setEndRange(long endRange); void setExpanded(boolean expanded); void setInitialized(boolean initialized); boolean getInitialized(); long getEndRange(); long getStartRange(); boolean getExpanded(); @Override Boolean routeAcl(int shardCount, int shardInstance, Acl acl); @Override Boolean routeNode(int shardCount, int shardInstance, Node node); @Override Map<String, String> getProperties(Optional<QName> shardProperty); }### Answer:
@Test public void outOfBoundsShouldRejectTheNode() { when(node.getId()).thenReturn(199L); assertFalse(router.routeNode(randomizer.nextInt(), randomizer.nextInt(), node)); when(node.getId()).thenReturn(20000L); assertFalse(router.routeNode(randomizer.nextInt(), randomizer.nextInt(), node)); }
@Test public void inRange_shouldAcceptTheNode() { when(node.getId()).thenReturn(200L); assertTrue(router.routeNode(randomizer.nextInt(), randomizer.nextInt(), node)); when(node.getId()).thenReturn(543L); assertTrue(router.routeNode(randomizer.nextInt(), randomizer.nextInt(), node)); }
|
### Question:
ActivatableTracker extends AbstractTracker { public boolean isEnabled() { return isEnabled.get(); } protected ActivatableTracker(Type type); protected ActivatableTracker(Properties properties, SOLRAPIClient client, String coreName, InformationServer informationServer, Type type); final void disable(); final void enable(); @Override void track(); boolean isEnabled(); boolean isDisabled(); }### Answer:
@Test public void enabledShouldBeTheDefaultState() { assertTrue(tracker.isEnabled()); }
|
### Question:
ExplicitShardIdWithDynamicPropertyRouter extends ComposableDocRouter { @Override public Boolean routeAcl(int shardCount, int shardInstance, Acl acl) { return true; } ExplicitShardIdWithDynamicPropertyRouter(); ExplicitShardIdWithDynamicPropertyRouter(boolean isInStandaloneMode); @Override Boolean routeAcl(int shardCount, int shardInstance, Acl acl); @Override Boolean routeNode(int shardCount, int shardInstance, Node node); @Override Map<String, String> getProperties(Optional<QName> shardProperty); }### Answer:
@Test public void aclsAreReplicatedAcrossShards() { range(0, 100).forEach(index -> assertTrue(router.routeAcl(randomPositiveInteger(), randomPositiveInteger(), acl))); }
|
### Question:
TrackerJob implements Job { @Override public void execute(JobExecutionContext jec) throws JobExecutionException { Tracker tracker = getTracker(jec); tracker.track(); } @Override void execute(JobExecutionContext jec); static final String JOBDATA_TRACKER_KEY; }### Answer:
@Test public void canExecuteTrackerJob() throws JobExecutionException { trackerJob.execute(jec); verify(tracker).track(); }
|
### Question:
TrackerRegistry { public Set<String> getCoreNames() { return this.trackers.keySet(); } Set<String> getCoreNames(); Collection<Tracker> getTrackersForCore(String coreName); boolean hasTrackersForCore(String coreName); @SuppressWarnings("unchecked") T getTrackerForCore(String coreName, Class<T> trackerClass); synchronized void register(String coreName, Tracker tracker); boolean removeTrackersForCore(String coreName); ModelTracker getModelTracker(); void setModelTracker(ModelTracker modelTracker); }### Answer:
@Test public void testGetCoreNames() { Set<String> coreNames = reg.getCoreNames(); assertNotNull(coreNames); assertTrue(coreNames.contains(CORE_NAME)); assertEquals(1, coreNames.size()); registerTrackers(CORE2_NAME); coreNames = reg.getCoreNames(); assertNotNull(coreNames); assertTrue(coreNames.contains(CORE_NAME)); assertFalse(coreNames.contains(NOT_A_CORE_NAME)); assertEquals(2, coreNames.size()); }
|
### Question:
TrackerRegistry { public Collection<Tracker> getTrackersForCore(String coreName) { ConcurrentHashMap<Class<? extends Tracker>, Tracker> coreTrackers = this.trackers.get(coreName); return ((coreTrackers == null) ? Collections.emptyList() : coreTrackers.values()); } Set<String> getCoreNames(); Collection<Tracker> getTrackersForCore(String coreName); boolean hasTrackersForCore(String coreName); @SuppressWarnings("unchecked") T getTrackerForCore(String coreName, Class<T> trackerClass); synchronized void register(String coreName, Tracker tracker); boolean removeTrackersForCore(String coreName); ModelTracker getModelTracker(); void setModelTracker(ModelTracker modelTracker); }### Answer:
@Test public void testGetTrackersForCore() { Collection<Tracker> trackersForCore = reg.getTrackersForCore(CORE_NAME); assertNotNull(trackersForCore); assertFalse(trackersForCore.isEmpty()); assertTrue(trackersForCore.contains(aclTracker)); assertTrue(trackersForCore.contains(contentTracker)); assertTrue(trackersForCore.contains(modelTracker)); assertTrue(trackersForCore.contains(metadataTracker)); trackersForCore = reg.getTrackersForCore(NOT_A_CORE_NAME); assertTrue(trackersForCore.isEmpty()); }
|
### Question:
TrackerRegistry { public boolean hasTrackersForCore(String coreName) { return this.trackers.containsKey(coreName); } Set<String> getCoreNames(); Collection<Tracker> getTrackersForCore(String coreName); boolean hasTrackersForCore(String coreName); @SuppressWarnings("unchecked") T getTrackerForCore(String coreName, Class<T> trackerClass); synchronized void register(String coreName, Tracker tracker); boolean removeTrackersForCore(String coreName); ModelTracker getModelTracker(); void setModelTracker(ModelTracker modelTracker); }### Answer:
@Test public void testHasTrackersForCore() { assertTrue(reg.hasTrackersForCore(CORE_NAME)); assertFalse(reg.hasTrackersForCore(NOT_A_CORE_NAME)); }
|
### Question:
TrackerRegistry { @SuppressWarnings("unchecked") public <T extends Tracker> T getTrackerForCore(String coreName, Class<T> trackerClass) { Map<Class<? extends Tracker>, Tracker> coreTrackers = this.trackers.get(coreName); return null == coreTrackers ? null : (T) coreTrackers.get(trackerClass); } Set<String> getCoreNames(); Collection<Tracker> getTrackersForCore(String coreName); boolean hasTrackersForCore(String coreName); @SuppressWarnings("unchecked") T getTrackerForCore(String coreName, Class<T> trackerClass); synchronized void register(String coreName, Tracker tracker); boolean removeTrackersForCore(String coreName); ModelTracker getModelTracker(); void setModelTracker(ModelTracker modelTracker); }### Answer:
@Test public void testGetTrackerForCore() { assertEquals(aclTracker, reg.getTrackerForCore(CORE_NAME, AclTracker.class)); assertEquals(contentTracker, reg.getTrackerForCore(CORE_NAME, ContentTracker.class)); assertEquals(metadataTracker, reg.getTrackerForCore(CORE_NAME, MetadataTracker.class)); assertEquals(modelTracker, reg.getTrackerForCore(CORE_NAME, ModelTracker.class)); }
|
### Question:
GcmScheduler extends Scheduler { @Override public int schedule(JobInfo job) { context.sendBroadcast(getScheduleIntent(job)); return RESULT_SUCCESS; } GcmScheduler(Context context); @Override int schedule(JobInfo job); @Override void cancel(int jobId); @Override void cancelAll(); @NonNull @Override String getTag(); static final String TAG; }### Answer:
@Test public void testScheduleBroadcasts() { JobInfo job = JobCreator.create(application) .setMinimumLatency(TimeUnit.HOURS.toMillis(2)) .setOverrideDeadline(TimeUnit.DAYS.toMillis(1)) .setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY) .setPersisted(true) .build(); scheduler.schedule(job); Intent intent = getLastBroadcastIntent(); assertNotNull(intent); assertIntentMatchesJobInfo(intent, job); PersistableBundle extras = new PersistableBundle(); extras.putString("test", "test"); job = JobCreator.create(application) .setExtras(extras) .setPeriodic(TimeUnit.MINUTES.toMillis(30)) .setRequiresCharging(true) .setRequiresDeviceIdle(true) .setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED) .build(); scheduler.schedule(job); intent = getLastBroadcastIntent(); assertNotNull(intent); assertIntentMatchesJobInfo(intent, job); job = JobCreator.create(application) .setRequiredNetworkType(JobInfo.NETWORK_TYPE_NOT_ROAMING) .addTriggerContentUri(new JobInfo.TriggerContentUri(Uri.parse("doist.com"), 0)) .addTriggerContentUri(new JobInfo.TriggerContentUri( Uri.parse("todoist.com"), JobInfo.TriggerContentUri.FLAG_NOTIFY_FOR_DESCENDANTS)) .addTriggerContentUri(new JobInfo.TriggerContentUri(Uri.parse("twist.com"), 0)) .build(); scheduler.schedule(job); intent = getLastBroadcastIntent(); assertNotNull(intent); assertIntentMatchesJobInfo(intent, job); }
|
### Question:
GcmScheduler extends Scheduler { @Override public void cancel(int jobId) { context.sendBroadcast(getCancelIntent(jobId)); } GcmScheduler(Context context); @Override int schedule(JobInfo job); @Override void cancel(int jobId); @Override void cancelAll(); @NonNull @Override String getTag(); static final String TAG; }### Answer:
@Test public void testCancelBroadcasts() { scheduler.cancel(0); Intent intent = getLastBroadcastIntent(); assertNotNull(intent); assertEquals(GcmScheduler.ACTION_SCHEDULE, intent.getAction()); assertEquals(GcmScheduler.PACKAGE_GMS, intent.getPackage()); assertEquals(GcmScheduler.SCHEDULER_ACTION_CANCEL_TASK, intent.getStringExtra(GcmScheduler.BUNDLE_PARAM_SCHEDULER_ACTION)); assertThat(intent.getParcelableExtra(GcmScheduler.BUNDLE_PARAM_TOKEN), instanceOf(PendingIntent.class)); ComponentName component = intent.getParcelableExtra(GcmScheduler.PARAM_COMPONENT); assertNotNull(component); assertEquals(GcmJobService.class.getName(), component.getClassName()); }
|
### Question:
GcmScheduler extends Scheduler { @Override public void cancelAll() { context.sendBroadcast(getCancelAllIntent()); } GcmScheduler(Context context); @Override int schedule(JobInfo job); @Override void cancel(int jobId); @Override void cancelAll(); @NonNull @Override String getTag(); static final String TAG; }### Answer:
@Test public void testCancelAllBroadcasts() { scheduler.cancelAll(); Intent intent = getLastBroadcastIntent(); assertNotNull(intent); assertEquals(GcmScheduler.ACTION_SCHEDULE, intent.getAction()); assertEquals(GcmScheduler.PACKAGE_GMS, intent.getPackage()); assertEquals(GcmScheduler.SCHEDULER_ACTION_CANCEL_ALL, intent.getStringExtra(GcmScheduler.BUNDLE_PARAM_SCHEDULER_ACTION)); assertThat(intent.getParcelableExtra(GcmScheduler.BUNDLE_PARAM_TOKEN), instanceOf(PendingIntent.class)); ComponentName component = intent.getParcelableExtra(GcmScheduler.PARAM_COMPONENT); assertNotNull(component); assertEquals(GcmJobService.class.getName(), component.getClassName()); }
|
### Question:
AlarmScheduler extends Scheduler { @Override public int schedule(JobInfo job) { AlarmJobService.start(context); return RESULT_SUCCESS; } AlarmScheduler(Context context); @Override int schedule(JobInfo job); @Override void cancel(int jobId); @Override void cancelAll(); @Override void onJobCompleted(int jobId, boolean needsReschedule); @NonNull @Override String getTag(); @Override void onJobRescheduled(JobStatus newJob, JobStatus failedJob); static final String TAG; }### Answer:
@Test public void testScheduleRunsService() { scheduler.schedule(job); assertEquals(shadowOf(application).getNextStartedService().getComponent().getClassName(), AlarmJobService.class.getName()); }
|
### Question:
AlarmScheduler extends Scheduler { @Override public void cancel(int jobId) { AlarmJobService.start(context); } AlarmScheduler(Context context); @Override int schedule(JobInfo job); @Override void cancel(int jobId); @Override void cancelAll(); @Override void onJobCompleted(int jobId, boolean needsReschedule); @NonNull @Override String getTag(); @Override void onJobRescheduled(JobStatus newJob, JobStatus failedJob); static final String TAG; }### Answer:
@Test public void testCancelRunsService() { scheduler.cancel(0); assertEquals(shadowOf(application).getNextStartedService().getComponent().getClassName(), AlarmJobService.class.getName()); }
|
### Question:
AlarmScheduler extends Scheduler { @Override public void cancelAll() { AlarmJobService.start(context); } AlarmScheduler(Context context); @Override int schedule(JobInfo job); @Override void cancel(int jobId); @Override void cancelAll(); @Override void onJobCompleted(int jobId, boolean needsReschedule); @NonNull @Override String getTag(); @Override void onJobRescheduled(JobStatus newJob, JobStatus failedJob); static final String TAG; }### Answer:
@Test public void testCancelAllRunsService() { scheduler.cancelAll(); assertEquals(shadowOf(application).getNextStartedService().getComponent().getClassName(), AlarmJobService.class.getName()); }
|
### Question:
AlarmScheduler extends Scheduler { @Override public void onJobCompleted(int jobId, boolean needsReschedule) { AlarmJobService.start(context); } AlarmScheduler(Context context); @Override int schedule(JobInfo job); @Override void cancel(int jobId); @Override void cancelAll(); @Override void onJobCompleted(int jobId, boolean needsReschedule); @NonNull @Override String getTag(); @Override void onJobRescheduled(JobStatus newJob, JobStatus failedJob); static final String TAG; }### Answer:
@Test public void testJobFinishedRunsService() { scheduler.onJobCompleted(0, false); assertEquals(shadowOf(application).getNextStartedService().getComponent().getClassName(), AlarmJobService.class.getName()); scheduler.onJobCompleted(0, true); assertEquals(shadowOf(application).getNextStartedService().getComponent().getClassName(), AlarmJobService.class.getName()); }
|
### Question:
AlarmScheduler extends Scheduler { @Override public void onJobRescheduled(JobStatus newJob, JobStatus failedJob) { if (failedJob.hasContentTriggerConstraint() && newJob.hasContentTriggerConstraint()) { newJob.changedAuthorities = failedJob.changedAuthorities; newJob.changedUris = failedJob.changedUris; } } AlarmScheduler(Context context); @Override int schedule(JobInfo job); @Override void cancel(int jobId); @Override void cancelAll(); @Override void onJobCompleted(int jobId, boolean needsReschedule); @NonNull @Override String getTag(); @Override void onJobRescheduled(JobStatus newJob, JobStatus failedJob); static final String TAG; }### Answer:
@Test public void testJobRescheduledPassesUriAuthorityForward() { Uri changedUri = job.getTriggerContentUris()[0].getUri(); String changedAuthority = changedUri.getAuthority(); JobStatus failedJobStatus = new JobStatus(job, AlarmScheduler.TAG, 0, 0); failedJobStatus.changedUris = Collections.singleton(changedUri); failedJobStatus.changedAuthorities = Collections.singleton(changedAuthority); JobStatus newJobStatus = new JobStatus(job, AlarmScheduler.TAG, 0, 0); scheduler.onJobRescheduled(newJobStatus, failedJobStatus); assertThat(newJobStatus.changedUris, hasItem(changedUri)); assertThat(newJobStatus.changedAuthorities, hasItem(changedAuthority)); }
|
### Question:
AlarmReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { AlarmJobService.start(context); } @Override void onReceive(Context context, Intent intent); }### Answer:
@SuppressWarnings("deprecation") @Test public void testReceiversStartService() { new AlarmReceiver().onReceive(application, new Intent(Intent.ACTION_BOOT_COMPLETED)); assertEquals(shadowOf(application).getNextStartedService().getComponent().getClassName(), AlarmJobService.class.getName()); new AlarmReceiver.BatteryReceiver().onReceive(application, new Intent(Intent.ACTION_POWER_CONNECTED)); assertEquals(shadowOf(application).getNextStartedService().getComponent().getClassName(), AlarmJobService.class.getName()); new AlarmReceiver.StorageReceiver().onReceive(application, new Intent(Intent.ACTION_DEVICE_STORAGE_LOW)); assertEquals(shadowOf(application).getNextStartedService().getComponent().getClassName(), AlarmJobService.class.getName()); new AlarmReceiver.ConnectivityReceiver().onReceive( application, new Intent(ConnectivityManager.CONNECTIVITY_ACTION)); assertEquals(shadowOf(application).getNextStartedService().getComponent().getClassName(), AlarmJobService.class.getName()); }
|
### Question:
JobSchedulerJobService extends android.app.job.JobService implements JobService.Binder.Callback { @Override public boolean onStopJob(android.app.job.JobParameters params) { Connection connection = connections.get(params.getJobId()); if (connection != null) { JobService.Binder binder = connection.binder; boolean needsReschedule = binder != null && binder.stopJob(toLocalParameters(connection.params, connection.transientExtras)); stopJob(connection, needsReschedule); return needsReschedule; } else { return false; } } @Override void onCreate(); @Override boolean onStartJob(android.app.job.JobParameters params); @Override boolean onStopJob(android.app.job.JobParameters params); @Override void jobFinished(JobParameters params, boolean needsReschedule); }### Answer:
@Test public void testStopJobStopsJob() { DeviceTestUtils.setCharging(application, true); JobInfo job = JobCreator.create(application, 2000).setRequiresCharging(true).build(); JobStatus jobStatus = JobStatus.createFromJobInfo(job, getSchedulerTag()); jobStore.add(jobStatus); executeService(job.getId()); assertBoundServiceCount(1); service.onStopJob(ShadowJobParameters.newInstance(jobStore.getJob(job.getId()))); assertBoundServiceCount(0); }
|
### Question:
JobScheduler { public void cancel(int jobId) { synchronized (JobStore.LOCK) { JobStatus jobStatus = jobStore.getJob(jobId); if (jobStatus != null) { jobStore.remove(jobId); getSchedulerForTag(context, jobStatus.getSchedulerTag()).cancel(jobId); } } } private JobScheduler(Context context); static synchronized JobScheduler get(Context context); int schedule(JobInfo job); void cancel(int jobId); void cancelAll(); @NonNull List<JobInfo> getAllPendingJobs(); @Nullable JobInfo getPendingJob(int jobId); @RestrictTo(RestrictTo.Scope.LIBRARY) void onJobCompleted(int jobId, boolean needsReschedule); @RestrictTo(RestrictTo.Scope.LIBRARY) List<JobStatus> getJobsByScheduler(String scheduler); @RestrictTo(RestrictTo.Scope.LIBRARY) JobStatus getJob(int jobId); @RestrictTo(RestrictTo.Scope.LIBRARY) void addJob(JobStatus jobStatus); @RestrictTo(RestrictTo.Scope.LIBRARY) void removeJob(int jobId); static final int RESULT_FAILURE; static final int RESULT_SUCCESS; }### Answer:
@Test public void testCancel() { JobInfo job = JobCreator.create(application).setRequiresDeviceIdle(true).build(); jobScheduler.schedule(job); JobInfo job2 = JobCreator.create(application).setRequiresDeviceIdle(true).build(); jobScheduler.schedule(job2); assertJobSchedulerContains(job.getId(), job2.getId()); jobScheduler.cancel(job.getId()); assertJobSchedulerContains(job2.getId()); jobScheduler.cancel(job2.getId()); assertJobSchedulerContains(); }
|
### Question:
JobScheduler { public void cancelAll() { synchronized (JobStore.LOCK) { Set<String> tags = new HashSet<>(); for (JobStatus jobStatus : jobStore.getJobs()) { tags.add(jobStatus.getSchedulerTag()); } jobStore.clear(); for (String tag : tags) { getSchedulerForTag(context, tag).cancelAll(); } } } private JobScheduler(Context context); static synchronized JobScheduler get(Context context); int schedule(JobInfo job); void cancel(int jobId); void cancelAll(); @NonNull List<JobInfo> getAllPendingJobs(); @Nullable JobInfo getPendingJob(int jobId); @RestrictTo(RestrictTo.Scope.LIBRARY) void onJobCompleted(int jobId, boolean needsReschedule); @RestrictTo(RestrictTo.Scope.LIBRARY) List<JobStatus> getJobsByScheduler(String scheduler); @RestrictTo(RestrictTo.Scope.LIBRARY) JobStatus getJob(int jobId); @RestrictTo(RestrictTo.Scope.LIBRARY) void addJob(JobStatus jobStatus); @RestrictTo(RestrictTo.Scope.LIBRARY) void removeJob(int jobId); static final int RESULT_FAILURE; static final int RESULT_SUCCESS; }### Answer:
@Test public void testCancelAll() { JobInfo job = JobCreator.create(application).setMinimumLatency(TimeUnit.HOURS.toMillis(1)).build(); jobScheduler.schedule(job); JobInfo job2 = JobCreator.create(application).setMinimumLatency(TimeUnit.HOURS.toMillis(1)).build(); jobScheduler.schedule(job2); JobInfo job3 = JobCreator.create(application).setMinimumLatency(TimeUnit.HOURS.toMillis(1)).build(); jobScheduler.schedule(job3); assertJobSchedulerContains(job.getId(), job2.getId(), job3.getId()); jobScheduler.cancelAll(); assertJobSchedulerContains(); }
|
### Question:
JobScheduler { @RestrictTo(RestrictTo.Scope.LIBRARY) public void onJobCompleted(int jobId, boolean needsReschedule) { synchronized (JobStore.LOCK) { JobStatus jobStatus = jobStore.getJob(jobId); if (jobStatus != null) { jobStore.remove(jobId); if (needsReschedule) { jobStore.add(getRescheduleJobForFailure(jobStatus)); } else if (jobStatus.isPeriodic()) { jobStore.add(getRescheduleJobForPeriodic(jobStatus)); } getSchedulerForTag(context, jobStatus.getSchedulerTag()).onJobCompleted(jobId, needsReschedule); } } } private JobScheduler(Context context); static synchronized JobScheduler get(Context context); int schedule(JobInfo job); void cancel(int jobId); void cancelAll(); @NonNull List<JobInfo> getAllPendingJobs(); @Nullable JobInfo getPendingJob(int jobId); @RestrictTo(RestrictTo.Scope.LIBRARY) void onJobCompleted(int jobId, boolean needsReschedule); @RestrictTo(RestrictTo.Scope.LIBRARY) List<JobStatus> getJobsByScheduler(String scheduler); @RestrictTo(RestrictTo.Scope.LIBRARY) JobStatus getJob(int jobId); @RestrictTo(RestrictTo.Scope.LIBRARY) void addJob(JobStatus jobStatus); @RestrictTo(RestrictTo.Scope.LIBRARY) void removeJob(int jobId); static final int RESULT_FAILURE; static final int RESULT_SUCCESS; }### Answer:
@Test public void testJobFinishedSuccess() { JobInfo job = JobCreator.create(application).setRequiresCharging(true).build(); JobStatus jobStatus = JobStatus.createFromJobInfo(job, noopScheduler.getTag()); jobStore.add(jobStatus); jobScheduler.onJobCompleted(job.getId(), false); assertJobSchedulerContains(); }
|
### Question:
MediaStoreRequestHandler extends ContentStreamRequestHandler { static PicassoKind getPicassoKind(int targetWidth, int targetHeight) { if (targetWidth <= MICRO.width && targetHeight <= MICRO.height) { return MICRO; } else if (targetWidth <= MINI.width && targetHeight <= MINI.height) { return MINI; } return FULL; } MediaStoreRequestHandler(Context context); @Override boolean canHandleRequest(Request data); @Override Result load(Request request, int networkPolicy); }### Answer:
@Test public void getPicassoKindMicro() throws Exception { assertThat(getPicassoKind(96, 96)).isEqualTo(MICRO); assertThat(getPicassoKind(95, 95)).isEqualTo(MICRO); }
@Test public void getPicassoKindMini() throws Exception { assertThat(getPicassoKind(512, 384)).isEqualTo(MINI); assertThat(getPicassoKind(100, 100)).isEqualTo(MINI); }
@Test public void getPicassoKindFull() throws Exception { assertThat(getPicassoKind(513, 385)).isEqualTo(FULL); assertThat(getPicassoKind(1000, 1000)).isEqualTo(FULL); assertThat(getPicassoKind(1000, 384)).isEqualTo(FULL); assertThat(getPicassoKind(1000, 96)).isEqualTo(FULL); assertThat(getPicassoKind(96, 1000)).isEqualTo(FULL); }
|
### Question:
Picasso { Bitmap quickMemoryCacheCheck(String key) { Bitmap cached = cache.get(key); if (cached != null) { stats.dispatchCacheHit(); } else { stats.dispatchCacheMiss(); } return cached; } Picasso(Context context, Dispatcher dispatcher, Cache cache, Listener listener,
RequestTransformer requestTransformer, List<RequestHandler> extraRequestHandlers, Stats stats,
Bitmap.Config defaultBitmapConfig, boolean indicatorsEnabled, boolean loggingEnabled); void cancelRequest(@NonNull ImageView view); void cancelRequest(@NonNull Target target); void cancelRequest(@NonNull RemoteViews remoteViews, @IdRes int viewId); void cancelTag(@NonNull Object tag); void pauseTag(@NonNull Object tag); void resumeTag(@NonNull Object tag); RequestCreator load(@Nullable Uri uri); RequestCreator load(@Nullable String path); RequestCreator load(@NonNull File file); RequestCreator load(@DrawableRes int resourceId); void invalidate(@Nullable Uri uri); void invalidate(@Nullable String path); void invalidate(@NonNull File file); @SuppressWarnings("UnusedDeclaration") void setIndicatorsEnabled(boolean enabled); @SuppressWarnings("UnusedDeclaration") boolean areIndicatorsEnabled(); @SuppressWarnings("UnusedDeclaration") // Public API. void setLoggingEnabled(boolean enabled); boolean isLoggingEnabled(); @SuppressWarnings("UnusedDeclaration") StatsSnapshot getSnapshot(); void shutdown(); static Picasso with(@NonNull Context context); static void setSingletonInstance(@NonNull Picasso picasso); }### Answer:
@Test public void quickMemoryCheckReturnsBitmapIfInCache() { when(cache.get(URI_KEY_1)).thenReturn(bitmap); Bitmap cached = picasso.quickMemoryCacheCheck(URI_KEY_1); assertThat(cached).isEqualTo(bitmap); verify(stats).dispatchCacheHit(); }
@Test public void quickMemoryCheckReturnsNullIfNotInCache() { Bitmap cached = picasso.quickMemoryCacheCheck(URI_KEY_1); assertThat(cached).isNull(); verify(stats).dispatchCacheMiss(); }
|
### Question:
Picasso { void resumeAction(Action action) { Bitmap bitmap = null; if (shouldReadFromMemoryCache(action.memoryPolicy)) { bitmap = quickMemoryCacheCheck(action.getKey()); } if (bitmap != null) { deliverAction(bitmap, MEMORY, action, null); if (loggingEnabled) { log(OWNER_MAIN, VERB_COMPLETED, action.request.logId(), "from " + MEMORY); } } else { enqueueAndSubmit(action); if (loggingEnabled) { log(OWNER_MAIN, VERB_RESUMED, action.request.logId()); } } } Picasso(Context context, Dispatcher dispatcher, Cache cache, Listener listener,
RequestTransformer requestTransformer, List<RequestHandler> extraRequestHandlers, Stats stats,
Bitmap.Config defaultBitmapConfig, boolean indicatorsEnabled, boolean loggingEnabled); void cancelRequest(@NonNull ImageView view); void cancelRequest(@NonNull Target target); void cancelRequest(@NonNull RemoteViews remoteViews, @IdRes int viewId); void cancelTag(@NonNull Object tag); void pauseTag(@NonNull Object tag); void resumeTag(@NonNull Object tag); RequestCreator load(@Nullable Uri uri); RequestCreator load(@Nullable String path); RequestCreator load(@NonNull File file); RequestCreator load(@DrawableRes int resourceId); void invalidate(@Nullable Uri uri); void invalidate(@Nullable String path); void invalidate(@NonNull File file); @SuppressWarnings("UnusedDeclaration") void setIndicatorsEnabled(boolean enabled); @SuppressWarnings("UnusedDeclaration") boolean areIndicatorsEnabled(); @SuppressWarnings("UnusedDeclaration") // Public API. void setLoggingEnabled(boolean enabled); boolean isLoggingEnabled(); @SuppressWarnings("UnusedDeclaration") StatsSnapshot getSnapshot(); void shutdown(); static Picasso with(@NonNull Context context); static void setSingletonInstance(@NonNull Picasso picasso); }### Answer:
@Test public void resumeActionTriggersSubmitOnPausedAction() { Action action = mockAction(URI_KEY_1, URI_1); picasso.resumeAction(action); verify(dispatcher).dispatchSubmit(action); }
|
### Question:
OkHttp3Downloader implements Downloader { @Override public void shutdown() { if (!sharedClient) { if (cache != null) { try { cache.close(); } catch (IOException ignored) { } } } } OkHttp3Downloader(final Context context); OkHttp3Downloader(final File cacheDir); OkHttp3Downloader(final Context context, final long maxSize); OkHttp3Downloader(final File cacheDir, final long maxSize); OkHttp3Downloader(OkHttpClient client); OkHttp3Downloader(Call.Factory client); @Override Response load(@NonNull Uri uri, int networkPolicy); @Override void shutdown(); }### Answer:
@Test public void shutdownDoesNotCloseCacheIfSharedClient() throws Exception { okhttp3.Cache cache = new okhttp3.Cache(temporaryFolder.getRoot(), 100); OkHttpClient client = new OkHttpClient.Builder().cache(cache).build(); new OkHttp3Downloader(client).shutdown(); assertThat(cache.isClosed()).isFalse(); }
|
### Question:
Picasso { Request transformRequest(Request request) { Request transformed = requestTransformer.transformRequest(request); if (transformed == null) { throw new IllegalStateException("Request transformer " + requestTransformer.getClass().getCanonicalName() + " returned null for " + request); } return transformed; } Picasso(Context context, Dispatcher dispatcher, Cache cache, Listener listener,
RequestTransformer requestTransformer, List<RequestHandler> extraRequestHandlers, Stats stats,
Bitmap.Config defaultBitmapConfig, boolean indicatorsEnabled, boolean loggingEnabled); void cancelRequest(@NonNull ImageView view); void cancelRequest(@NonNull Target target); void cancelRequest(@NonNull RemoteViews remoteViews, @IdRes int viewId); void cancelTag(@NonNull Object tag); void pauseTag(@NonNull Object tag); void resumeTag(@NonNull Object tag); RequestCreator load(@Nullable Uri uri); RequestCreator load(@Nullable String path); RequestCreator load(@NonNull File file); RequestCreator load(@DrawableRes int resourceId); void invalidate(@Nullable Uri uri); void invalidate(@Nullable String path); void invalidate(@NonNull File file); @SuppressWarnings("UnusedDeclaration") void setIndicatorsEnabled(boolean enabled); @SuppressWarnings("UnusedDeclaration") boolean areIndicatorsEnabled(); @SuppressWarnings("UnusedDeclaration") // Public API. void setLoggingEnabled(boolean enabled); boolean isLoggingEnabled(); @SuppressWarnings("UnusedDeclaration") StatsSnapshot getSnapshot(); void shutdown(); static Picasso with(@NonNull Context context); static void setSingletonInstance(@NonNull Picasso picasso); }### Answer:
@Test public void whenTransformRequestReturnsNullThrows() { try { when(transformer.transformRequest(any(Request.class))).thenReturn(null); picasso.transformRequest(new Request.Builder(URI_1).build()); fail("Returning null from transformRequest() should throw"); } catch (IllegalStateException expected) { } }
|
### Question:
Picasso { @SuppressWarnings("UnusedDeclaration") public StatsSnapshot getSnapshot() { return stats.createSnapshot(); } Picasso(Context context, Dispatcher dispatcher, Cache cache, Listener listener,
RequestTransformer requestTransformer, List<RequestHandler> extraRequestHandlers, Stats stats,
Bitmap.Config defaultBitmapConfig, boolean indicatorsEnabled, boolean loggingEnabled); void cancelRequest(@NonNull ImageView view); void cancelRequest(@NonNull Target target); void cancelRequest(@NonNull RemoteViews remoteViews, @IdRes int viewId); void cancelTag(@NonNull Object tag); void pauseTag(@NonNull Object tag); void resumeTag(@NonNull Object tag); RequestCreator load(@Nullable Uri uri); RequestCreator load(@Nullable String path); RequestCreator load(@NonNull File file); RequestCreator load(@DrawableRes int resourceId); void invalidate(@Nullable Uri uri); void invalidate(@Nullable String path); void invalidate(@NonNull File file); @SuppressWarnings("UnusedDeclaration") void setIndicatorsEnabled(boolean enabled); @SuppressWarnings("UnusedDeclaration") boolean areIndicatorsEnabled(); @SuppressWarnings("UnusedDeclaration") // Public API. void setLoggingEnabled(boolean enabled); boolean isLoggingEnabled(); @SuppressWarnings("UnusedDeclaration") StatsSnapshot getSnapshot(); void shutdown(); static Picasso with(@NonNull Context context); static void setSingletonInstance(@NonNull Picasso picasso); }### Answer:
@Test public void getSnapshotInvokesStats() { picasso.getSnapshot(); verify(stats).createSnapshot(); }
|
### Question:
Picasso { public RequestCreator load(@Nullable Uri uri) { return new RequestCreator(this, uri, 0); } Picasso(Context context, Dispatcher dispatcher, Cache cache, Listener listener,
RequestTransformer requestTransformer, List<RequestHandler> extraRequestHandlers, Stats stats,
Bitmap.Config defaultBitmapConfig, boolean indicatorsEnabled, boolean loggingEnabled); void cancelRequest(@NonNull ImageView view); void cancelRequest(@NonNull Target target); void cancelRequest(@NonNull RemoteViews remoteViews, @IdRes int viewId); void cancelTag(@NonNull Object tag); void pauseTag(@NonNull Object tag); void resumeTag(@NonNull Object tag); RequestCreator load(@Nullable Uri uri); RequestCreator load(@Nullable String path); RequestCreator load(@NonNull File file); RequestCreator load(@DrawableRes int resourceId); void invalidate(@Nullable Uri uri); void invalidate(@Nullable String path); void invalidate(@NonNull File file); @SuppressWarnings("UnusedDeclaration") void setIndicatorsEnabled(boolean enabled); @SuppressWarnings("UnusedDeclaration") boolean areIndicatorsEnabled(); @SuppressWarnings("UnusedDeclaration") // Public API. void setLoggingEnabled(boolean enabled); boolean isLoggingEnabled(); @SuppressWarnings("UnusedDeclaration") StatsSnapshot getSnapshot(); void shutdown(); static Picasso with(@NonNull Context context); static void setSingletonInstance(@NonNull Picasso picasso); }### Answer:
@Test public void loadThrowsWithInvalidInput() { try { picasso.load(""); fail("Empty URL should throw exception."); } catch (IllegalArgumentException expected) { } try { picasso.load(" "); fail("Empty URL should throw exception."); } catch (IllegalArgumentException expected) { } try { picasso.load(0); fail("Zero resourceId should throw exception."); } catch (IllegalArgumentException expected) { } }
|
### Question:
Picasso { List<RequestHandler> getRequestHandlers() { return requestHandlers; } Picasso(Context context, Dispatcher dispatcher, Cache cache, Listener listener,
RequestTransformer requestTransformer, List<RequestHandler> extraRequestHandlers, Stats stats,
Bitmap.Config defaultBitmapConfig, boolean indicatorsEnabled, boolean loggingEnabled); void cancelRequest(@NonNull ImageView view); void cancelRequest(@NonNull Target target); void cancelRequest(@NonNull RemoteViews remoteViews, @IdRes int viewId); void cancelTag(@NonNull Object tag); void pauseTag(@NonNull Object tag); void resumeTag(@NonNull Object tag); RequestCreator load(@Nullable Uri uri); RequestCreator load(@Nullable String path); RequestCreator load(@NonNull File file); RequestCreator load(@DrawableRes int resourceId); void invalidate(@Nullable Uri uri); void invalidate(@Nullable String path); void invalidate(@NonNull File file); @SuppressWarnings("UnusedDeclaration") void setIndicatorsEnabled(boolean enabled); @SuppressWarnings("UnusedDeclaration") boolean areIndicatorsEnabled(); @SuppressWarnings("UnusedDeclaration") // Public API. void setLoggingEnabled(boolean enabled); boolean isLoggingEnabled(); @SuppressWarnings("UnusedDeclaration") StatsSnapshot getSnapshot(); void shutdown(); static Picasso with(@NonNull Context context); static void setSingletonInstance(@NonNull Picasso picasso); }### Answer:
@Test public void builderWithoutRequestHandler() { Picasso picasso = new Picasso.Builder(RuntimeEnvironment.application).build(); assertThat(picasso.getRequestHandlers()).isNotEmpty().doesNotContain(requestHandler); }
@Test public void builderWithRequestHandler() { Picasso picasso = new Picasso.Builder(RuntimeEnvironment.application) .addRequestHandler(requestHandler).build(); assertThat(picasso.getRequestHandlers()).isNotNull().isNotEmpty().contains(requestHandler); }
|
### Question:
Picasso { @SuppressWarnings("UnusedDeclaration") public boolean areIndicatorsEnabled() { return indicatorsEnabled; } Picasso(Context context, Dispatcher dispatcher, Cache cache, Listener listener,
RequestTransformer requestTransformer, List<RequestHandler> extraRequestHandlers, Stats stats,
Bitmap.Config defaultBitmapConfig, boolean indicatorsEnabled, boolean loggingEnabled); void cancelRequest(@NonNull ImageView view); void cancelRequest(@NonNull Target target); void cancelRequest(@NonNull RemoteViews remoteViews, @IdRes int viewId); void cancelTag(@NonNull Object tag); void pauseTag(@NonNull Object tag); void resumeTag(@NonNull Object tag); RequestCreator load(@Nullable Uri uri); RequestCreator load(@Nullable String path); RequestCreator load(@NonNull File file); RequestCreator load(@DrawableRes int resourceId); void invalidate(@Nullable Uri uri); void invalidate(@Nullable String path); void invalidate(@NonNull File file); @SuppressWarnings("UnusedDeclaration") void setIndicatorsEnabled(boolean enabled); @SuppressWarnings("UnusedDeclaration") boolean areIndicatorsEnabled(); @SuppressWarnings("UnusedDeclaration") // Public API. void setLoggingEnabled(boolean enabled); boolean isLoggingEnabled(); @SuppressWarnings("UnusedDeclaration") StatsSnapshot getSnapshot(); void shutdown(); static Picasso with(@NonNull Context context); static void setSingletonInstance(@NonNull Picasso picasso); }### Answer:
@Test public void builderWithDebugIndicators() { Picasso picasso = new Picasso.Builder(RuntimeEnvironment.application).indicatorsEnabled(true).build(); assertThat(picasso.areIndicatorsEnabled()).isTrue(); }
|
### Question:
Picasso { public void invalidate(@Nullable Uri uri) { if (uri != null) { cache.clearKeyUri(uri.toString()); } } Picasso(Context context, Dispatcher dispatcher, Cache cache, Listener listener,
RequestTransformer requestTransformer, List<RequestHandler> extraRequestHandlers, Stats stats,
Bitmap.Config defaultBitmapConfig, boolean indicatorsEnabled, boolean loggingEnabled); void cancelRequest(@NonNull ImageView view); void cancelRequest(@NonNull Target target); void cancelRequest(@NonNull RemoteViews remoteViews, @IdRes int viewId); void cancelTag(@NonNull Object tag); void pauseTag(@NonNull Object tag); void resumeTag(@NonNull Object tag); RequestCreator load(@Nullable Uri uri); RequestCreator load(@Nullable String path); RequestCreator load(@NonNull File file); RequestCreator load(@DrawableRes int resourceId); void invalidate(@Nullable Uri uri); void invalidate(@Nullable String path); void invalidate(@NonNull File file); @SuppressWarnings("UnusedDeclaration") void setIndicatorsEnabled(boolean enabled); @SuppressWarnings("UnusedDeclaration") boolean areIndicatorsEnabled(); @SuppressWarnings("UnusedDeclaration") // Public API. void setLoggingEnabled(boolean enabled); boolean isLoggingEnabled(); @SuppressWarnings("UnusedDeclaration") StatsSnapshot getSnapshot(); void shutdown(); static Picasso with(@NonNull Context context); static void setSingletonInstance(@NonNull Picasso picasso); }### Answer:
@Test public void invalidateString() { picasso.invalidate("http: verify(cache).clearKeyUri("http: }
@Test public void invalidateFile() { picasso.invalidate(new File("/foo/bar/baz")); verify(cache).clearKeyUri("file: }
@Test public void invalidateUri() { picasso.invalidate(Uri.parse("mock: verify(cache).clearKeyUri("mock: }
|
### Question:
Dispatcher { void shutdown() { if (service instanceof PicassoExecutorService) { service.shutdown(); } downloader.shutdown(); dispatcherThread.quit(); Picasso.HANDLER.post(new Runnable() { @Override public void run() { receiver.unregister(); } }); } Dispatcher(Context context, ExecutorService service, Handler mainThreadHandler,
Downloader downloader, Cache cache, Stats stats); }### Answer:
@Test public void shutdownStopsService() { dispatcher.shutdown(); verify(service).shutdown(); }
@Test public void shutdownStopsDownloader() { dispatcher.shutdown(); verify(downloader).shutdown(); }
@Test public void shutdownUnregistersReceiver() { dispatcher.shutdown(); verify(context).unregisterReceiver(dispatcher.receiver); }
|
### Question:
Dispatcher { void performComplete(BitmapHunter hunter) { if (shouldWriteToMemoryCache(hunter.getMemoryPolicy())) { cache.set(hunter.getKey(), hunter.getResult()); } hunterMap.remove(hunter.getKey()); batch(hunter); if (hunter.getPicasso().loggingEnabled) { log(OWNER_DISPATCHER, VERB_BATCHED, getLogIdsForHunter(hunter), "for completion"); } } Dispatcher(Context context, ExecutorService service, Handler mainThreadHandler,
Downloader downloader, Cache cache, Stats stats); }### Answer:
@Test public void performCompleteSetsResultInCache() { BitmapHunter hunter = mockHunter(URI_KEY_1, bitmap1, 0, null); dispatcher.performComplete(hunter); verify(cache).set(hunter.getKey(), hunter.getResult()); }
@Test public void performCompleteWithNoStoreMemoryPolicy() { int memoryPolicy = 0; memoryPolicy |= MemoryPolicy.NO_STORE.index; BitmapHunter hunter = mockHunter(URI_KEY_1, bitmap1, memoryPolicy, null); dispatcher.performComplete(hunter); assertThat(dispatcher.hunterMap).isEmpty(); verifyZeroInteractions(cache); }
@Test public void performCompleteCleansUpAndAddsToBatch() { BitmapHunter hunter = mockHunter(URI_KEY_1, bitmap1, false); dispatcher.performComplete(hunter); assertThat(dispatcher.hunterMap).isEmpty(); assertThat(dispatcher.batch).hasSize(1); }
@Test public void performCompleteCleansUpAndDoesNotAddToBatchIfCancelled() { BitmapHunter hunter = mockHunter(URI_KEY_1, bitmap1, false); when(hunter.isCancelled()).thenReturn(true); dispatcher.performComplete(hunter); assertThat(dispatcher.hunterMap).isEmpty(); assertThat(dispatcher.batch).isEmpty(); }
|
### Question:
Dispatcher { void performError(BitmapHunter hunter, boolean willReplay) { if (hunter.getPicasso().loggingEnabled) { log(OWNER_DISPATCHER, VERB_BATCHED, getLogIdsForHunter(hunter), "for error" + (willReplay ? " (will replay)" : "")); } hunterMap.remove(hunter.getKey()); batch(hunter); } Dispatcher(Context context, ExecutorService service, Handler mainThreadHandler,
Downloader downloader, Cache cache, Stats stats); }### Answer:
@Test public void performErrorCleansUpAndAddsToBatch() { BitmapHunter hunter = mockHunter(URI_KEY_1, bitmap1, false); dispatcher.hunterMap.put(hunter.getKey(), hunter); dispatcher.performError(hunter, false); assertThat(dispatcher.hunterMap).isEmpty(); assertThat(dispatcher.batch).hasSize(1); }
@Test public void performErrorCleansUpAndDoesNotAddToBatchIfCancelled() { BitmapHunter hunter = mockHunter(URI_KEY_1, bitmap1, false); when(hunter.isCancelled()).thenReturn(true); dispatcher.hunterMap.put(hunter.getKey(), hunter); dispatcher.performError(hunter, false); assertThat(dispatcher.hunterMap).isEmpty(); assertThat(dispatcher.batch).isEmpty(); }
|
### Question:
Dispatcher { void performBatchComplete() { List<BitmapHunter> copy = new ArrayList<>(batch); batch.clear(); mainThreadHandler.sendMessage(mainThreadHandler.obtainMessage(HUNTER_BATCH_COMPLETE, copy)); logBatch(copy); } Dispatcher(Context context, ExecutorService service, Handler mainThreadHandler,
Downloader downloader, Cache cache, Stats stats); }### Answer:
@Test public void performBatchCompleteFlushesHunters() { BitmapHunter hunter1 = mockHunter(URI_KEY_2, bitmap1, false); BitmapHunter hunter2 = mockHunter(URI_KEY_2, bitmap2, false); dispatcher.batch.add(hunter1); dispatcher.batch.add(hunter2); dispatcher.performBatchComplete(); assertThat(dispatcher.batch).isEmpty(); }
|
### Question:
Dispatcher { void performAirplaneModeChange(boolean airplaneMode) { this.airplaneMode = airplaneMode; } Dispatcher(Context context, ExecutorService service, Handler mainThreadHandler,
Downloader downloader, Cache cache, Stats stats); }### Answer:
@Test public void performAirplaneModeChange() { assertThat(dispatcher.airplaneMode).isFalse(); dispatcher.performAirplaneModeChange(true); assertThat(dispatcher.airplaneMode).isTrue(); dispatcher.performAirplaneModeChange(false); assertThat(dispatcher.airplaneMode).isFalse(); }
|
### Question:
Dispatcher { void performResumeTag(Object tag) { if (!pausedTags.remove(tag)) { return; } List<Action> batch = null; for (Iterator<Action> i = pausedActions.values().iterator(); i.hasNext();) { Action action = i.next(); if (action.getTag().equals(tag)) { if (batch == null) { batch = new ArrayList<>(); } batch.add(action); i.remove(); } } if (batch != null) { mainThreadHandler.sendMessage(mainThreadHandler.obtainMessage(REQUEST_BATCH_RESUME, batch)); } } Dispatcher(Context context, ExecutorService service, Handler mainThreadHandler,
Downloader downloader, Cache cache, Stats stats); }### Answer:
@Test public void performResumeTagIsIdempotent() { dispatcher.performResumeTag("tag"); verify(mainThreadHandler, never()).sendMessage(any(Message.class)); }
|
### Question:
Dispatcher { void dispatchNetworkStateChange(NetworkInfo info) { handler.sendMessage(handler.obtainMessage(NETWORK_STATE_CHANGE, info)); } Dispatcher(Context context, ExecutorService service, Handler mainThreadHandler,
Downloader downloader, Cache cache, Stats stats); }### Answer:
@Test public void nullExtrasOnReceiveConnectivityAreOk() { ConnectivityManager connectivityManager = mock(ConnectivityManager.class); NetworkInfo networkInfo = mockNetworkInfo(); when(connectivityManager.getActiveNetworkInfo()).thenReturn(networkInfo); when(context.getSystemService(CONNECTIVITY_SERVICE)).thenReturn(connectivityManager); Dispatcher dispatcher = mock(Dispatcher.class); NetworkBroadcastReceiver receiver = new NetworkBroadcastReceiver(dispatcher); receiver.onReceive(context, new Intent(CONNECTIVITY_ACTION)); verify(dispatcher).dispatchNetworkStateChange(networkInfo); }
|
### Question:
RequestHandler { static boolean requiresInSampleSize(BitmapFactory.Options options) { return options != null && options.inJustDecodeBounds; } abstract boolean canHandleRequest(Request data); @Nullable abstract Result load(Request request, int networkPolicy); }### Answer:
@Test public void requiresComputeInSampleSize() { assertThat(requiresInSampleSize(null)).isFalse(); final BitmapFactory.Options defaultOptions = new BitmapFactory.Options(); assertThat(requiresInSampleSize(defaultOptions)).isFalse(); final BitmapFactory.Options justBounds = new BitmapFactory.Options(); justBounds.inJustDecodeBounds = true; assertThat(requiresInSampleSize(justBounds)).isTrue(); }
|
### Question:
LruCache implements Cache { @Override public Bitmap get(@NonNull String key) { if (key == null) { throw new NullPointerException("key == null"); } Bitmap mapValue; synchronized (this) { mapValue = map.get(key); if (mapValue != null) { hitCount++; return mapValue; } missCount++; } return null; } LruCache(@NonNull Context context); LruCache(int maxSize); @Override Bitmap get(@NonNull String key); @Override void set(@NonNull String key, @NonNull Bitmap bitmap); final void evictAll(); @Override final synchronized int size(); @Override final synchronized int maxSize(); @Override final synchronized void clear(); @Override final synchronized void clearKeyUri(String uri); final synchronized int hitCount(); final synchronized int missCount(); final synchronized int putCount(); final synchronized int evictionCount(); }### Answer:
@Test public void throwsWithNullKey() { LruCache cache = new LruCache(1); try { cache.get(null); fail("Expected NullPointerException"); } catch (NullPointerException expected) { } }
|
### Question:
LruCache implements Cache { public final void evictAll() { trimToSize(-1); } LruCache(@NonNull Context context); LruCache(int maxSize); @Override Bitmap get(@NonNull String key); @Override void set(@NonNull String key, @NonNull Bitmap bitmap); final void evictAll(); @Override final synchronized int size(); @Override final synchronized int maxSize(); @Override final synchronized void clear(); @Override final synchronized void clearKeyUri(String uri); final synchronized int hitCount(); final synchronized int missCount(); final synchronized int putCount(); final synchronized int evictionCount(); }### Answer:
@Test public void evictAll() { LruCache cache = new LruCache(4); cache.set("a", A); cache.set("b", B); cache.set("c", C); cache.evictAll(); assertThat(cache.map).isEmpty(); }
|
### Question:
BitmapHunter implements Runnable { void attach(Action action) { boolean loggingEnabled = picasso.loggingEnabled; Request request = action.request; if (this.action == null) { this.action = action; if (loggingEnabled) { if (actions == null || actions.isEmpty()) { log(OWNER_HUNTER, VERB_JOINED, request.logId(), "to empty hunter"); } else { log(OWNER_HUNTER, VERB_JOINED, request.logId(), getLogIdsForHunter(this, "to ")); } } return; } if (actions == null) { actions = new ArrayList<>(3); } actions.add(action); if (loggingEnabled) { log(OWNER_HUNTER, VERB_JOINED, request.logId(), getLogIdsForHunter(this, "to ")); } Priority actionPriority = action.getPriority(); if (actionPriority.ordinal() > priority.ordinal()) { priority = actionPriority; } } BitmapHunter(Picasso picasso, Dispatcher dispatcher, Cache cache, Stats stats, Action action,
RequestHandler requestHandler); @Override void run(); }### Answer:
@Test public void attachMultipleRequests() { Action action1 = mockAction(URI_KEY_1, URI_1, mockImageViewTarget()); Action action2 = mockAction(URI_KEY_1, URI_1, mockImageViewTarget()); BitmapHunter hunter = new TestableBitmapHunter(picasso, dispatcher, cache, stats, action1); assertThat(hunter.actions).isNull(); hunter.attach(action2); assertThat(hunter.actions).isNotNull().hasSize(1); }
|
### Question:
ImageViewAction extends Action<ImageView> { @Override void cancel() { super.cancel(); if (callback != null) { callback = null; } } ImageViewAction(Picasso picasso, ImageView imageView, Request data, int memoryPolicy,
int networkPolicy, int errorResId, Drawable errorDrawable, String key, Object tag,
Callback callback, boolean noFade); @Override void complete(Bitmap result, Picasso.LoadedFrom from); @Override void error(Exception e); }### Answer:
@Test public void clearsCallbackOnCancel() throws Exception { Picasso picasso = mock(Picasso.class); ImageView target = mockImageViewTarget(); Callback callback = mockCallback(); ImageViewAction request = new ImageViewAction(picasso, target, null, 0, 0, 0, null, URI_KEY_1, null, callback, false); request.cancel(); assertThat(request.callback).isNull(); }
|
### Question:
AssetRequestHandler extends RequestHandler { static String getFilePath(Request request) { return request.uri.toString().substring(ASSET_PREFIX_LENGTH); } AssetRequestHandler(Context context); @Override boolean canHandleRequest(Request data); @Override Result load(Request request, int networkPolicy); }### Answer:
@Test public void truncatesFilePrefix() throws IOException { Uri uri = Uri.parse("file: Request request = new Request.Builder(uri).build(); String actual = AssetRequestHandler.getFilePath(request); assertThat(actual).isEqualTo("foo/bar.png"); }
|
### Question:
RemoteViewsAction extends Action<RemoteViewsAction.RemoteViewsTarget> { @Override void complete(Bitmap result, Picasso.LoadedFrom from) { remoteViews.setImageViewBitmap(viewId, result); update(); if (callback != null) { callback.onSuccess(); } } RemoteViewsAction(Picasso picasso, Request data, RemoteViews remoteViews, int viewId,
int errorResId, int memoryPolicy, int networkPolicy, Object tag, String key,
Callback callback); @Override void error(Exception e); }### Answer:
@Test public void completeSetsBitmapOnRemoteViews() throws Exception { Callback callback = mockCallback(); Bitmap bitmap = makeBitmap(); RemoteViewsAction action = createAction(callback); action.complete(bitmap, NETWORK); verify(remoteViews).setImageViewBitmap(1, bitmap); verify(callback).onSuccess(); }
|
### Question:
RemoteViewsAction extends Action<RemoteViewsAction.RemoteViewsTarget> { @Override public void error(Exception e) { if (errorResId != 0) { setImageResource(errorResId); } if (callback != null) { callback.onError(e); } } RemoteViewsAction(Picasso picasso, Request data, RemoteViews remoteViews, int viewId,
int errorResId, int memoryPolicy, int networkPolicy, Object tag, String key,
Callback callback); @Override void error(Exception e); }### Answer:
@Test public void errorWithNoResourceIsNoop() throws Exception { Callback callback = mockCallback(); RemoteViewsAction action = createAction(callback); Exception e = new RuntimeException(); action.error(e); verifyZeroInteractions(remoteViews); verify(callback).onError(e); }
@Test public void errorWithResourceSetsResource() throws Exception { Callback callback = mockCallback(); RemoteViewsAction action = createAction(1, callback); Exception e = new RuntimeException(); action.error(e); verify(remoteViews).setImageViewResource(1, 1); verify(callback).onError(e); }
|
### Question:
RemoteViewsAction extends Action<RemoteViewsAction.RemoteViewsTarget> { @Override void cancel() { super.cancel(); if (callback != null) { callback = null; } } RemoteViewsAction(Picasso picasso, Request data, RemoteViews remoteViews, int viewId,
int errorResId, int memoryPolicy, int networkPolicy, Object tag, String key,
Callback callback); @Override void error(Exception e); }### Answer:
@Test public void clearsCallbackOnCancel() throws Exception { Picasso picasso = mock(Picasso.class); ImageView target = mockImageViewTarget(); Callback callback = mockCallback(); ImageViewAction request = new ImageViewAction(picasso, target, null, 0, 0, 0, null, URI_KEY_1, null, callback, false); request.cancel(); assertThat(request.callback).isNull(); }
|
### Question:
Utils { static boolean isWebPFile(InputStream stream) throws IOException { byte[] fileHeaderBytes = new byte[WEBP_FILE_HEADER_SIZE]; boolean isWebPFile = false; if (stream.read(fileHeaderBytes, 0, WEBP_FILE_HEADER_SIZE) == WEBP_FILE_HEADER_SIZE) { isWebPFile = WEBP_FILE_HEADER_RIFF.equals(new String(fileHeaderBytes, 0, 4, "US-ASCII")) && WEBP_FILE_HEADER_WEBP.equals(new String(fileHeaderBytes, 8, 4, "US-ASCII")); } return isWebPFile; } private Utils(); }### Answer:
@Test public void detectedWebPFile() throws Exception { assertThat(isWebPFile(new ByteArrayInputStream("RIFFxxxxWEBP".getBytes("US-ASCII")))).isTrue(); assertThat( isWebPFile(new ByteArrayInputStream("RIFFxxxxxWEBP".getBytes("US-ASCII")))).isFalse(); assertThat(isWebPFile(new ByteArrayInputStream("ABCDxxxxWEBP".getBytes("US-ASCII")))).isFalse(); assertThat(isWebPFile(new ByteArrayInputStream("RIFFxxxxABCD".getBytes("US-ASCII")))).isFalse(); assertThat(isWebPFile(new ByteArrayInputStream("RIFFxxWEBP".getBytes("US-ASCII")))).isFalse(); }
|
### Question:
BitmapHunter implements Runnable { void detach(Action action) { boolean detached = false; if (this.action == action) { this.action = null; detached = true; } else if (actions != null) { detached = actions.remove(action); } if (detached && action.getPriority() == priority) { priority = computeNewPriority(); } if (picasso.loggingEnabled) { log(OWNER_HUNTER, VERB_REMOVED, action.request.logId(), getLogIdsForHunter(this, "from ")); } } BitmapHunter(Picasso picasso, Dispatcher dispatcher, Cache cache, Stats stats, Action action,
RequestHandler requestHandler); @Override void run(); }### Answer:
@Test public void detachSingleRequest() { Action action = mockAction(URI_KEY_1, URI_1, mockImageViewTarget()); BitmapHunter hunter = new TestableBitmapHunter(picasso, dispatcher, cache, stats, action); assertThat(hunter.action).isNotNull(); hunter.detach(action); assertThat(hunter.action).isNull(); }
|
### Question:
NetworkRequestHandler extends RequestHandler { @Override boolean shouldRetry(boolean airplaneMode, NetworkInfo info) { return info == null || info.isConnected(); } NetworkRequestHandler(Downloader downloader, Stats stats); @Override boolean canHandleRequest(Request data); @Override @Nullable Result load(Request request, int networkPolicy); }### Answer:
@Test public void shouldRetryTwiceWithAirplaneModeOffAndNoNetworkInfo() throws Exception { Action action = TestUtils.mockAction(URI_KEY_1, URI_1); BitmapHunter hunter = new BitmapHunter(picasso, dispatcher, cache, stats, action, networkHandler); assertThat(hunter.shouldRetry(false, null)).isTrue(); assertThat(hunter.shouldRetry(false, null)).isTrue(); assertThat(hunter.shouldRetry(false, null)).isFalse(); }
@Test public void shouldRetryWithUnknownNetworkInfo() throws Exception { assertThat(networkHandler.shouldRetry(false, null)).isTrue(); assertThat(networkHandler.shouldRetry(true, null)).isTrue(); }
@Test public void shouldRetryWithConnectedNetworkInfo() throws Exception { NetworkInfo info = mockNetworkInfo(); when(info.isConnected()).thenReturn(true); assertThat(networkHandler.shouldRetry(false, info)).isTrue(); assertThat(networkHandler.shouldRetry(true, info)).isTrue(); }
@Test public void shouldNotRetryWithDisconnectedNetworkInfo() throws Exception { NetworkInfo info = mockNetworkInfo(); when(info.isConnectedOrConnecting()).thenReturn(false); assertThat(networkHandler.shouldRetry(false, info)).isFalse(); assertThat(networkHandler.shouldRetry(true, info)).isFalse(); }
|
### Question:
TargetAction extends Action<Target> { @Override void complete(Bitmap result, Picasso.LoadedFrom from) { if (result == null) { throw new AssertionError( String.format("Attempted to complete action with no result!\n%s", this)); } Target target = getTarget(); if (target != null) { target.onBitmapLoaded(result, from); if (result.isRecycled()) { throw new IllegalStateException("Target callback must not recycle bitmap!"); } } } TargetAction(Picasso picasso, Target target, Request data, int memoryPolicy, int networkPolicy,
Drawable errorDrawable, String key, Object tag, int errorResId); }### Answer:
@Test(expected = AssertionError.class) public void throwsErrorWithNullResult() throws Exception { TargetAction request = new TargetAction(mock(Picasso.class), mockTarget(), null, 0, 0, null, URI_KEY_1, null, 0); request.complete(null, MEMORY); }
@Test public void invokesSuccessIfTargetIsNotNull() throws Exception { Bitmap bitmap = makeBitmap(); Target target = mockTarget(); TargetAction request = new TargetAction(mock(Picasso.class), target, null, 0, 0, null, URI_KEY_1, null, 0); request.complete(bitmap, MEMORY); verify(target).onBitmapLoaded(bitmap, MEMORY); }
@Test public void recyclingInSuccessThrowsException() { Target bad = new Target() { @Override public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) { bitmap.recycle(); } @Override public void onBitmapFailed(Exception e, Drawable errorDrawable) { throw new AssertionError(); } @Override public void onPrepareLoad(Drawable placeHolderDrawable) { throw new AssertionError(); } }; Picasso picasso = mock(Picasso.class); Bitmap bitmap = makeBitmap(); TargetAction tr = new TargetAction(picasso, bad, null, 0, 0, null, URI_KEY_1, null, 0); try { tr.complete(bitmap, MEMORY); fail(); } catch (IllegalStateException ignored) { } }
|
### Question:
TargetAction extends Action<Target> { @Override void error(Exception e) { Target target = getTarget(); if (target != null) { if (errorResId != 0) { target.onBitmapFailed(e, picasso.context.getResources().getDrawable(errorResId)); } else { target.onBitmapFailed(e, errorDrawable); } } } TargetAction(Picasso picasso, Target target, Request data, int memoryPolicy, int networkPolicy,
Drawable errorDrawable, String key, Object tag, int errorResId); }### Answer:
@Test public void invokesOnBitmapFailedIfTargetIsNotNullWithErrorDrawable() throws Exception { Drawable errorDrawable = mock(Drawable.class); Target target = mockTarget(); TargetAction request = new TargetAction(mock(Picasso.class), target, null, 0, 0, errorDrawable, URI_KEY_1, null, 0); Exception e = new RuntimeException(); request.error(e); verify(target).onBitmapFailed(e, errorDrawable); }
@Test public void invokesOnBitmapFailedIfTargetIsNotNullWithErrorResourceId() throws Exception { Drawable errorDrawable = mock(Drawable.class); Target target = mockTarget(); Context context = mock(Context.class); Picasso picasso = new Picasso(context, mock(Dispatcher.class), Cache.NONE, null, IDENTITY, null, mock(Stats.class), ARGB_8888, false, false); Resources res = mock(Resources.class); TargetAction request = new TargetAction(picasso, target, null, 0, 0, null, URI_KEY_1, null, RESOURCE_ID_1); when(context.getResources()).thenReturn(res); when(res.getDrawable(RESOURCE_ID_1)).thenReturn(errorDrawable); Exception e = new RuntimeException(); request.error(e); verify(target).onBitmapFailed(e, errorDrawable); }
|
### Question:
DecorationDelegate extends RecyclerView.ItemDecoration { @Override public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) { int adapterPosition = parent.getChildAdapterPosition(view); if (adapterPosition < 0) { return; } adapter.getDecorationOffset(outRect, view, parent, state, adapterPosition); } DecorationDelegate(MultiViewAdapter adapter); @Override void onDraw(@NonNull Canvas canvas, @NonNull RecyclerView parent,
@NonNull RecyclerView.State state); @Override void onDrawOver(@NonNull Canvas canvas, @NonNull RecyclerView parent,
@NonNull RecyclerView.State state); @Override void getItemOffsets(@NonNull Rect outRect, @NonNull View view,
@NonNull RecyclerView parent, @NonNull RecyclerView.State state); }### Answer:
@Test public void getItemOffsets_test() { when(recyclerView.getChildAdapterPosition(child)).thenReturn(1); testAdapter.getItemDecoration().getItemOffsets(outRect, child, recyclerView, state); verify(testAdapter).getDecorationOffset(outRect, child, recyclerView, state, 1); }
@Test public void getItemOffsets_invalid_adapterPosition() { when(recyclerView.getChildAdapterPosition(child)).thenReturn(-1); testAdapter.getItemDecoration().getItemOffsets(outRect, child, recyclerView, state); verify(testAdapter, never()).getDecorationOffset(outRect, child, recyclerView, state, -1); }
|
### Question:
DecorationDelegate extends RecyclerView.ItemDecoration { @Override public void onDraw(@NonNull Canvas canvas, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) { int childCount = parent.getChildCount(); for (int i = 0; i < childCount; i++) { View child = parent.getChildAt(i); int adapterPosition = parent.getChildAdapterPosition(child); if (adapterPosition < 0) { return; } adapter.drawDecoration(canvas, parent, state, child, adapterPosition); } } DecorationDelegate(MultiViewAdapter adapter); @Override void onDraw(@NonNull Canvas canvas, @NonNull RecyclerView parent,
@NonNull RecyclerView.State state); @Override void onDrawOver(@NonNull Canvas canvas, @NonNull RecyclerView parent,
@NonNull RecyclerView.State state); @Override void getItemOffsets(@NonNull Rect outRect, @NonNull View view,
@NonNull RecyclerView parent, @NonNull RecyclerView.State state); }### Answer:
@Test public void onDraw_invalid_adapterPosition() { when(recyclerView.getChildAt(anyInt())).thenReturn(child); when(recyclerView.getChildCount()).thenReturn(3); when(recyclerView.getChildAdapterPosition(child)).thenReturn(-1); testAdapter.getItemDecoration().onDraw(canvas, recyclerView, state); verify(testAdapter, never()).drawDecoration(canvas, recyclerView, state, child, -1); }
@Test public void onDraw_test() { when(recyclerView.getChildCount()).thenReturn(10); when(recyclerView.getChildAdapterPosition(child)).thenReturn(0); when(recyclerView.getChildAt(anyInt())).thenReturn(child); testAdapter.getItemDecoration().onDraw(canvas, recyclerView, state); verify(testAdapter, times(10)).drawDecoration(eq(canvas), eq(recyclerView), eq(state), eq(child), anyInt()); }
|
### Question:
DecorationDelegate extends RecyclerView.ItemDecoration { @Override public void onDrawOver(@NonNull Canvas canvas, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) { int childCount = parent.getChildCount(); for (int i = 0; i < childCount; i++) { View child = parent.getChildAt(i); int adapterPosition = parent.getChildAdapterPosition(child); if (adapterPosition < 0) { return; } adapter.drawDecorationOver(canvas, parent, state, child, adapterPosition); } } DecorationDelegate(MultiViewAdapter adapter); @Override void onDraw(@NonNull Canvas canvas, @NonNull RecyclerView parent,
@NonNull RecyclerView.State state); @Override void onDrawOver(@NonNull Canvas canvas, @NonNull RecyclerView parent,
@NonNull RecyclerView.State state); @Override void getItemOffsets(@NonNull Rect outRect, @NonNull View view,
@NonNull RecyclerView parent, @NonNull RecyclerView.State state); }### Answer:
@Test public void onDrawOver_test() { decorationDelegate.onDrawOver(canvas, recyclerView, state); verifyZeroInteractions(testAdapter); }
|
### Question:
AppConfigProvider implements Provider<AppConfig> { @Override public AppConfig get() { return appConfig; } @Inject AppConfigProvider(@Named("config") String configFile, ObjectMapper mapper); @Override AppConfig get(); }### Answer:
@Test public void testReadAppConfig() throws Exception { ObjectMapper mapper = fixSerializationHelper(fixtures); AppConfigProvider configProvider = new AppConfigProvider(CORRECT_APP_CONFIG, mapper); AppConfig appConfig = configProvider.get(); assertThat(appConfig.global(), notNullValue()); assertThat(appConfig.global().configurationsPath(), equalTo("configurationsPath")); assertThat(appConfig.global().connectorsPath(), equalTo("connectorsPath")); assertThat(appConfig.global().runOnce(), equalTo(false)); assertThat(appConfig.global().updateConfigurationIntervalMillis(), equalTo(2L)); assertThat(appConfig.hazelcast(), notNullValue()); assertThat(appConfig.hazelcast().isEnabled(), equalTo(true)); assertThat(appConfig.hazelcast().config(), equalTo("config")); assertThat(appConfig.alert(), notNullValue()); assertThat(appConfig.alert().isEnabled(), equalTo(true)); assertThat(appConfig.alert().checkIntervalMillis(), equalTo(3L)); assertThat(appConfig.alert().thresholds(), hasEntry("thresholds", 4.0d)); }
|
### Question:
RefocusClient extends AbstractRemoteClient<RefocusService> { public List<Aspect> getAspects(List<String> fields) throws UnauthorizedException { return executeAndRetrieveBody(svc().getAspects(authorizationHeader(), fields), null); } RefocusClient(EndpointConnector connector); @Override boolean isAuthenticated(); Sample getSample(String key, List<String> fields); List<Sample> getSamples(String name); boolean upsertSamplesBulk(List<Sample> samples); Sample deleteSample(String key); List<Subject> getSubjects(List<String> fields); Subject getSubject(String key, List<String> fields); Subject getSubjectHierarchy(String key, String status); Subject postSubject(Subject subject); Subject patchSubject(Subject subject); Subject putSubject(Subject subject); Subject deleteSubject(String subjectKey); List<Aspect> getAspects(List<String> fields); Aspect getAspect(String key, List<String> fields); Aspect postAspect(Aspect aspect); Aspect patchAspect(Aspect aspect); }### Answer:
@Test public void getAspects() throws Exception { Aspect aspect = ImmutableAspect.builder().name("name").build(); Response<List<Aspect>>response = Response.success(Collections.singletonList(aspect)); @SuppressWarnings("unchecked") Call<Aspect>responseCall = mock(Call.class); doReturn(response).when(responseCall).execute(); doReturn(request).when(responseCall).request(); doReturn(responseCall).when(svc).getAspects(any(), any()); List<Aspect>results = refocus.getAspects(fields); assertThat(results.get(0).name(), is("name")); }
|
### Question:
RefocusClient extends AbstractRemoteClient<RefocusService> { public Aspect getAspect(String key, List<String> fields) throws UnauthorizedException { Preconditions.checkNotNull(key, "Key should not be null"); return executeAndRetrieveBody(svc().getAspect(authorizationHeader(), key, fields), null); } RefocusClient(EndpointConnector connector); @Override boolean isAuthenticated(); Sample getSample(String key, List<String> fields); List<Sample> getSamples(String name); boolean upsertSamplesBulk(List<Sample> samples); Sample deleteSample(String key); List<Subject> getSubjects(List<String> fields); Subject getSubject(String key, List<String> fields); Subject getSubjectHierarchy(String key, String status); Subject postSubject(Subject subject); Subject patchSubject(Subject subject); Subject putSubject(Subject subject); Subject deleteSubject(String subjectKey); List<Aspect> getAspects(List<String> fields); Aspect getAspect(String key, List<String> fields); Aspect postAspect(Aspect aspect); Aspect patchAspect(Aspect aspect); }### Answer:
@Test public void getAspect() throws Exception { Aspect aspect = ImmutableAspect.builder().name("name").build(); Response<Aspect>response = Response.success(aspect); @SuppressWarnings("unchecked") Call<Aspect>responseCall = mock(Call.class); doReturn(response).when(responseCall).execute(); doReturn(request).when(responseCall).request(); doReturn(responseCall).when(svc).getAspect(any(), anyString(), anyList()); Aspect result = refocus.getAspect("name", fields); assertThat(result.name(), is("name")); }
|
### Question:
RefocusClient extends AbstractRemoteClient<RefocusService> { public Aspect postAspect(Aspect aspect) throws UnauthorizedException { Preconditions.checkNotNull(aspect, "Aspect should not be null"); return executeAndRetrieveBody(svc().postAspect(authorizationHeader(), aspect), null); } RefocusClient(EndpointConnector connector); @Override boolean isAuthenticated(); Sample getSample(String key, List<String> fields); List<Sample> getSamples(String name); boolean upsertSamplesBulk(List<Sample> samples); Sample deleteSample(String key); List<Subject> getSubjects(List<String> fields); Subject getSubject(String key, List<String> fields); Subject getSubjectHierarchy(String key, String status); Subject postSubject(Subject subject); Subject patchSubject(Subject subject); Subject putSubject(Subject subject); Subject deleteSubject(String subjectKey); List<Aspect> getAspects(List<String> fields); Aspect getAspect(String key, List<String> fields); Aspect postAspect(Aspect aspect); Aspect patchAspect(Aspect aspect); }### Answer:
@Test public void postAspect() throws Exception { Aspect aspect = ImmutableAspect.builder().name("name").build(); Response<Aspect>response = Response.success(aspect); @SuppressWarnings("unchecked") Call<Aspect>responseCall = mock(Call.class); doReturn(response).when(responseCall).execute(); doReturn(request).when(responseCall).request(); doReturn(responseCall).when(svc).postAspect(any(), any()); Aspect result = refocus.postAspect(aspect); assertThat(result.name(), is("name")); }
|
### Question:
RefocusClient extends AbstractRemoteClient<RefocusService> { public Aspect patchAspect(Aspect aspect) throws UnauthorizedException { Preconditions.checkNotNull(aspect, "Aspect should not be null"); return executeAndRetrieveBody(svc().patchAspect(authorizationHeader(), aspect.name(), aspect), null); } RefocusClient(EndpointConnector connector); @Override boolean isAuthenticated(); Sample getSample(String key, List<String> fields); List<Sample> getSamples(String name); boolean upsertSamplesBulk(List<Sample> samples); Sample deleteSample(String key); List<Subject> getSubjects(List<String> fields); Subject getSubject(String key, List<String> fields); Subject getSubjectHierarchy(String key, String status); Subject postSubject(Subject subject); Subject patchSubject(Subject subject); Subject putSubject(Subject subject); Subject deleteSubject(String subjectKey); List<Aspect> getAspects(List<String> fields); Aspect getAspect(String key, List<String> fields); Aspect postAspect(Aspect aspect); Aspect patchAspect(Aspect aspect); }### Answer:
@Test public void patchAspect() throws Exception { Aspect aspect = ImmutableAspect.builder().name("name").build(); Response<Aspect>response = Response.success(aspect); @SuppressWarnings("unchecked") Call<Aspect>responseCall = mock(Call.class); doReturn(response).when(responseCall).execute(); doReturn(request).when(responseCall).request(); doReturn(responseCall).when(svc).patchAspect(any(), anyString(), any()); Aspect result = refocus.patchAspect(aspect); assertThat(result.name(), is("name")); }
|
### Question:
DuctMain { public static void main(String... args) { execute(AppBootstrap.class, args); } private DuctMain(); static void main(String... args); static void setProgramName(String programName); static void execute(Class<T> cls, String... args); }### Answer:
@Test(timeOut = 5000L) public void testAppRuns() throws Exception { Path configurations = Files.createTempDirectory("test-configurations"); Path connectors = createConnector(); Path appConfig = createAppConfig(configurations, connectors); DuctMain.main("--config", appConfig.toAbsolutePath().toString()); }
|
### Question:
SimpleConnectorProvider implements Provider<List<EndpointConnector>> { @Override public List<EndpointConnector> get() { return connectors; } @Inject SimpleConnectorProvider(AppConfig appConfig, ObjectMapper mapper); @Override List<EndpointConnector> get(); }### Answer:
@Test public void testProviderLoadsOneConnector() throws Exception { fixtures.appConfigMocks() .connectorsPath(ConnectorTest.ONE_CONNECTOR); Injector injector = fixtures.initializeFixtures().injector(); SimpleConnectorProvider provider = injector.getProvider(SimpleConnectorProvider.class).get(); List<EndpointConnector> connectors = provider.get(); assertThat(connectors, notNullValue()); assertThat(connectors, hasSize(1)); }
@Test public void testProviderReturnsEmptyListWithoutPath() throws Exception { Injector injector = fixtures.initializeFixtures().injector(); SimpleConnectorProvider provider = injector.getProvider(SimpleConnectorProvider.class).get(); List<EndpointConnector> connectors = provider.get(); assertThat(connectors, notNullValue()); assertThat(connectors, empty()); }
|
### Question:
Cluster { public boolean isMaster() { if (!clusterEnabled) { return true; } guardAgainstInitializationFailures(); Set<Member> members = hazelcast.getCluster().getMembers(); Member member = members.iterator().next(); return member.localMember(); } @Inject Cluster(AppConfig appConfig, ShutdownHook shutdownHook); void registerListener(MembershipListener membershipListener); void registerListener(MigrationListener clusterMigrationListener); IMap<K, V> distributedMap(String name); boolean isMaster(); boolean isEnabled(); }### Answer:
@Test public void testIsAlwaysMaster() throws Exception { assertThat("Expecting isMaster=true, when Hazelcast is not running", cluster.isMaster(), equalTo(true)); verify(shutdownHook, times(0)).registerOperation(any()); }
|
### Question:
Cluster { public <K, V> IMap<K, V> distributedMap(String name) { guardAgainstInitializationFailures(); return hazelcast.getMap(name); } @Inject Cluster(AppConfig appConfig, ShutdownHook shutdownHook); void registerListener(MembershipListener membershipListener); void registerListener(MigrationListener clusterMigrationListener); IMap<K, V> distributedMap(String name); boolean isMaster(); boolean isEnabled(); }### Answer:
@Test public void testDistributedMap() throws Exception { try { cluster.distributedMap("map"); fail("Expecting this to fail"); } catch (NullPointerException e) { verify(cluster, times(1)).guardAgainstInitializationFailures(); } }
|
### Question:
FormatUtils { public static Number parseNumber(String value) throws ParseException { return NumberFormat.getInstance().parse(value); } private FormatUtils(); static ZonedDateTime parseUTCTime(String value); static Number parseNumber(String value); static String formatNumber(Number value); static String formatNumberFiveCharLimit(Number value); static String formatMillisOrSeconds(Number value); static String generateDefaultValueMessage(String metric, Number value); }### Answer:
@Test public void testParseNumber() throws Exception { Number dblVal = FormatUtils.parseNumber("1.23"); Number intVal = FormatUtils.parseNumber("1"); try { FormatUtils.parseNumber("invalid"); fail("Should be unable to parse string value 'invalid'"); } catch (ParseException e) { } assertThat(dblVal, instanceOf(Double.class)); assertThat("Expecting parsed value to be equal to 1.23", Double.compare((Double) dblVal, 1.23d), is(0)); assertThat(intVal, instanceOf(Long.class)); assertThat("Expecting parsed value to be equal to 1L", Long.compare((Long) intVal, 1L), is(0)); }
|
### Question:
AppConfigFileLoader { public static String loadFromCLI(String programName, String... args) throws ConfigParseException { ArgumentParser parser = ArgumentParsers.newArgumentParser("java -jar " + programName + "-[VERSION].jar").defaultHelp(true); parser.addArgument("--config").metavar("/path/to/app-config.json").required(true).help("Path to configuration file"); try { Namespace cli = parser.parseArgs(args); return cli.getString("config"); } catch (ArgumentParserException e) { parser.handleError(e); throw new ConfigParseException(e); } } private AppConfigFileLoader(); static String loadFromCLI(String programName, String... args); }### Answer:
@Test public void testLoadConfigParameter() throws Exception { String[] args = new String[]{"--config", "config"}; String configName = AppConfigFileLoader.loadFromCLI("programName", args); assertThat(configName, equalTo("config")); }
@Test(expectedExceptions = ConfigParseException.class) public void testFailWithoutCorrectParam() throws Exception { String[] args = new String[]{"--invalid"}; AppConfigFileLoader.loadFromCLI("programName", args); }
|
### Question:
FormatUtils { public static String formatNumber(Number value) { return decimalFormatDefault.get().format(value); } private FormatUtils(); static ZonedDateTime parseUTCTime(String value); static Number parseNumber(String value); static String formatNumber(Number value); static String formatNumberFiveCharLimit(Number value); static String formatMillisOrSeconds(Number value); static String generateDefaultValueMessage(String metric, Number value); }### Answer:
@Test public void testFormatNumber() throws Exception { String decimalString = FormatUtils.formatNumber(new Double("1.234599")); String integerString = FormatUtils.formatNumber(1); assertThat(decimalString, equalTo("1.2346")); assertThat(integerString, equalTo("1.00")); }
|
### Question:
FormatUtils { public static String formatMillisOrSeconds(Number value) { if (value.doubleValue() < 1000) { return decimalFormatSeconds.get().format(value) + "ms"; } else { return decimalFormatSeconds.get().format(value.doubleValue()/1000) + "s"; } } private FormatUtils(); static ZonedDateTime parseUTCTime(String value); static Number parseNumber(String value); static String formatNumber(Number value); static String formatNumberFiveCharLimit(Number value); static String formatMillisOrSeconds(Number value); static String generateDefaultValueMessage(String metric, Number value); }### Answer:
@Test public void testFormatMillis() throws Exception { Double input = 500.00d; String output = FormatUtils.formatMillisOrSeconds(input); assertThat(output, equalTo("500ms")); }
@Test public void testFormatMillisWithDecimal() throws Exception { Double input = 500.1d; String output = FormatUtils.formatMillisOrSeconds(input); assertThat(output, equalTo("500.1ms")); }
@Test public void testFormatSeconds() throws Exception { Double input = 1500.1d; String output = FormatUtils.formatMillisOrSeconds(input); assertThat(output, equalTo("1.5s")); }
@Test public void testFormatSecondsDoubleDigits() throws Exception { Double input = 12345.67d; String output = FormatUtils.formatMillisOrSeconds(input); assertThat(output, equalTo("12.35s")); }
|
### Question:
FormatUtils { public static String generateDefaultValueMessage(String metric, Number value) { return String.format(DEFAULT_VALUE_MESSAGE_TEMPLATE, metric, formatNumber(value)); } private FormatUtils(); static ZonedDateTime parseUTCTime(String value); static Number parseNumber(String value); static String formatNumber(Number value); static String formatNumberFiveCharLimit(Number value); static String formatMillisOrSeconds(Number value); static String generateDefaultValueMessage(String metric, Number value); }### Answer:
@Test public void testGenerateDefaultValueMessage() throws Exception { String defaultMessage = FormatUtils.generateDefaultValueMessage("metric", 1234); assertThat(defaultMessage, allOf(containsString("metric"), containsString("1234"))); }
|
### Question:
SensitiveByteArraySerializer extends JsonSerializer<byte[]> { @Override public void serialize(byte[] bytes, JsonGenerator jsonGenerator, SerializerProvider provider) throws IOException { jsonGenerator.writeUTF8String(bytes, 0, bytes.length); } @Override void serialize(byte[] bytes, JsonGenerator jsonGenerator, SerializerProvider provider); }### Answer:
@Test public void testSerialize() throws Exception { byte[] bytes = "bytes".getBytes(Charset.defaultCharset()); serializer.serialize(bytes, generator, provider); verify(generator).writeUTF8String(bytes, 0, bytes.length); }
|
### Question:
CollectionUtils { public static <T> List<T> immutableOrEmptyList(List<T> input) { return Optional.ofNullable(input).map(ArrayList::new).map(Collections::unmodifiableList).orElse(Collections.emptyList()); } private CollectionUtils(); static T[] nullableArrayCopy(T[] input); static double[] nullableArrayCopy(double... input); static long[] nullableArrayCopy(long... input); static byte[] nullableArrayCopy(byte... input); static void nullOutByteArray(byte... input); static List<T> immutableOrEmptyList(List<T> input); static List<T> immutableListOrNull(List<T> input); static List<T> mutableListCopyOrNull(List<T> input); static Map<K, V> immutableOrEmptyMap(Map<K, V> input); static Map<K, V> immutableMapOrNull(Map<K, V> input); static SortedMap<K, V> immutableSortedOrEmptyMap(SortedMap<K, V> input); static SortedMap<K, V> immutableSortedMapOrNull(SortedMap<K, V> input); static Set<T> immutableOrEmptySet(Set<T> input); static Set<T> immutableSetOrNull(Set<T> input); }### Answer:
@Test public void testImmutableOrEmptyList() throws Exception { List<String> nullInput = null; List<String> input = Arrays.asList("name1", "name2"); List<String> emptyOutput = CollectionUtils.immutableOrEmptyList(nullInput); List<String> output = CollectionUtils.immutableOrEmptyList(input); assertThat(emptyOutput, hasSize(0)); assertThat(output.size(), equalTo(input.size())); assertThat(output, not(sameInstance(input))); attemptModifyListAndExpectFailure(output, "nope"); }
|
### Question:
CollectionUtils { public static <T> List<T> immutableListOrNull(List<T> input) { return Optional.ofNullable(input).map(ArrayList::new).map(Collections::unmodifiableList).orElse(null); } private CollectionUtils(); static T[] nullableArrayCopy(T[] input); static double[] nullableArrayCopy(double... input); static long[] nullableArrayCopy(long... input); static byte[] nullableArrayCopy(byte... input); static void nullOutByteArray(byte... input); static List<T> immutableOrEmptyList(List<T> input); static List<T> immutableListOrNull(List<T> input); static List<T> mutableListCopyOrNull(List<T> input); static Map<K, V> immutableOrEmptyMap(Map<K, V> input); static Map<K, V> immutableMapOrNull(Map<K, V> input); static SortedMap<K, V> immutableSortedOrEmptyMap(SortedMap<K, V> input); static SortedMap<K, V> immutableSortedMapOrNull(SortedMap<K, V> input); static Set<T> immutableOrEmptySet(Set<T> input); static Set<T> immutableSetOrNull(Set<T> input); }### Answer:
@Test public void testImmutableListOrNull() throws Exception { List<String> nullInput = null; List<String> input = Arrays.asList("name1", "name2"); List<String> nullOutput = CollectionUtils.immutableListOrNull(nullInput); List<String> output = CollectionUtils.immutableListOrNull(input); assertThat(nullOutput, nullValue()); assertThat(output.size(), equalTo(input.size())); assertThat(output, not(sameInstance(input))); attemptModifyListAndExpectFailure(output, "nope"); }
|
### Question:
CollectionUtils { public static <T> List<T> mutableListCopyOrNull(List<T> input) { return Optional.ofNullable(input).map(ArrayList::new).map(l -> (List<T>)l).orElse(null); } private CollectionUtils(); static T[] nullableArrayCopy(T[] input); static double[] nullableArrayCopy(double... input); static long[] nullableArrayCopy(long... input); static byte[] nullableArrayCopy(byte... input); static void nullOutByteArray(byte... input); static List<T> immutableOrEmptyList(List<T> input); static List<T> immutableListOrNull(List<T> input); static List<T> mutableListCopyOrNull(List<T> input); static Map<K, V> immutableOrEmptyMap(Map<K, V> input); static Map<K, V> immutableMapOrNull(Map<K, V> input); static SortedMap<K, V> immutableSortedOrEmptyMap(SortedMap<K, V> input); static SortedMap<K, V> immutableSortedMapOrNull(SortedMap<K, V> input); static Set<T> immutableOrEmptySet(Set<T> input); static Set<T> immutableSetOrNull(Set<T> input); }### Answer:
@Test public void testMutableListCopyOrNull() throws Exception { List<String> nullInput = null; List<String> input = Arrays.asList("name1", "name2"); List<String> nullOutput = CollectionUtils.mutableListCopyOrNull(nullInput); List<String> output = CollectionUtils.mutableListCopyOrNull(input); assertThat(nullOutput, nullValue()); assertThat(output.size(), equalTo(input.size())); assertThat(output, not(sameInstance(input))); attemptModifyListAndExpectSuccess(output, "yup"); }
|
### Question:
CollectionUtils { public static <K, V> Map<K, V> immutableOrEmptyMap(Map<K, V> input) { return Optional.ofNullable(input).map(HashMap::new).map(Collections::unmodifiableMap).orElse(Collections.emptyMap()); } private CollectionUtils(); static T[] nullableArrayCopy(T[] input); static double[] nullableArrayCopy(double... input); static long[] nullableArrayCopy(long... input); static byte[] nullableArrayCopy(byte... input); static void nullOutByteArray(byte... input); static List<T> immutableOrEmptyList(List<T> input); static List<T> immutableListOrNull(List<T> input); static List<T> mutableListCopyOrNull(List<T> input); static Map<K, V> immutableOrEmptyMap(Map<K, V> input); static Map<K, V> immutableMapOrNull(Map<K, V> input); static SortedMap<K, V> immutableSortedOrEmptyMap(SortedMap<K, V> input); static SortedMap<K, V> immutableSortedMapOrNull(SortedMap<K, V> input); static Set<T> immutableOrEmptySet(Set<T> input); static Set<T> immutableSetOrNull(Set<T> input); }### Answer:
@Test public void testImmutableOrEmptyMap() throws Exception { Map<String, String> nullInput = null; Map<String, String> input = Collections.singletonMap("key", "val"); Map<String, String> emptyOutput = CollectionUtils.immutableOrEmptyMap(nullInput); Map<String, String> output = CollectionUtils.immutableOrEmptyMap(input); assertThat(emptyOutput.size(), is(0)); assertThat(output.size(), equalTo(input.size())); assertThat(output, not(sameInstance(input))); attemptModifyMapAndExpectFailure(output, "key2", "val2"); }
|
### Question:
CollectionUtils { public static <K, V> Map<K, V> immutableMapOrNull(Map<K, V> input) { return Optional.ofNullable(input).map(HashMap::new).map(Collections::unmodifiableMap).orElse(null); } private CollectionUtils(); static T[] nullableArrayCopy(T[] input); static double[] nullableArrayCopy(double... input); static long[] nullableArrayCopy(long... input); static byte[] nullableArrayCopy(byte... input); static void nullOutByteArray(byte... input); static List<T> immutableOrEmptyList(List<T> input); static List<T> immutableListOrNull(List<T> input); static List<T> mutableListCopyOrNull(List<T> input); static Map<K, V> immutableOrEmptyMap(Map<K, V> input); static Map<K, V> immutableMapOrNull(Map<K, V> input); static SortedMap<K, V> immutableSortedOrEmptyMap(SortedMap<K, V> input); static SortedMap<K, V> immutableSortedMapOrNull(SortedMap<K, V> input); static Set<T> immutableOrEmptySet(Set<T> input); static Set<T> immutableSetOrNull(Set<T> input); }### Answer:
@Test public void testImmutableMapOrNull() throws Exception { Map<String, String> nullInput = null; Map<String, String> input = Collections.singletonMap("key", "val"); Map<String, String> nullOutput = CollectionUtils.immutableMapOrNull(nullInput); Map<String, String> output = CollectionUtils.immutableMapOrNull(input); assertThat(nullOutput, nullValue()); assertThat(output.size(), equalTo(input.size())); assertThat(output, not(sameInstance(input))); attemptModifyMapAndExpectFailure(output, "key2", "val2"); }
|
### Question:
CollectionUtils { public static <K, V> SortedMap<K, V> immutableSortedOrEmptyMap(SortedMap<K, V> input) { return Optional.ofNullable(input).map(TreeMap::new).map(Collections::unmodifiableSortedMap).orElse(Collections.emptySortedMap()); } private CollectionUtils(); static T[] nullableArrayCopy(T[] input); static double[] nullableArrayCopy(double... input); static long[] nullableArrayCopy(long... input); static byte[] nullableArrayCopy(byte... input); static void nullOutByteArray(byte... input); static List<T> immutableOrEmptyList(List<T> input); static List<T> immutableListOrNull(List<T> input); static List<T> mutableListCopyOrNull(List<T> input); static Map<K, V> immutableOrEmptyMap(Map<K, V> input); static Map<K, V> immutableMapOrNull(Map<K, V> input); static SortedMap<K, V> immutableSortedOrEmptyMap(SortedMap<K, V> input); static SortedMap<K, V> immutableSortedMapOrNull(SortedMap<K, V> input); static Set<T> immutableOrEmptySet(Set<T> input); static Set<T> immutableSetOrNull(Set<T> input); }### Answer:
@Test public void testImmutableSortedOrEmptyMap() throws Exception { SortedMap<String, String> nullInput = null; SortedMap<String, String> input = new TreeMap<>(Collections.singletonMap("key", "val")); SortedMap<String, String> emptyOutput = CollectionUtils.immutableSortedOrEmptyMap(nullInput); SortedMap<String, String> output = CollectionUtils.immutableSortedOrEmptyMap(input); assertThat(emptyOutput.size(), is(0)); assertThat(output.size(), equalTo(input.size())); assertThat(output, not(sameInstance(input))); attemptModifyMapAndExpectFailure(output, "key2", "val2"); }
|
### Question:
CollectionUtils { public static <K, V> SortedMap<K, V> immutableSortedMapOrNull(SortedMap<K, V> input) { return Optional.ofNullable(input).map(TreeMap::new).map(Collections::unmodifiableSortedMap).orElse(null); } private CollectionUtils(); static T[] nullableArrayCopy(T[] input); static double[] nullableArrayCopy(double... input); static long[] nullableArrayCopy(long... input); static byte[] nullableArrayCopy(byte... input); static void nullOutByteArray(byte... input); static List<T> immutableOrEmptyList(List<T> input); static List<T> immutableListOrNull(List<T> input); static List<T> mutableListCopyOrNull(List<T> input); static Map<K, V> immutableOrEmptyMap(Map<K, V> input); static Map<K, V> immutableMapOrNull(Map<K, V> input); static SortedMap<K, V> immutableSortedOrEmptyMap(SortedMap<K, V> input); static SortedMap<K, V> immutableSortedMapOrNull(SortedMap<K, V> input); static Set<T> immutableOrEmptySet(Set<T> input); static Set<T> immutableSetOrNull(Set<T> input); }### Answer:
@Test public void testImmutableSortedMapOrNull() throws Exception { SortedMap<String, String> nullInput = null; SortedMap<String, String> input = new TreeMap<>(Collections.singletonMap("key", "val")); SortedMap<String, String> nullOutput = CollectionUtils.immutableSortedMapOrNull(nullInput); SortedMap<String, String> output = CollectionUtils.immutableSortedMapOrNull(input); assertThat(nullOutput, nullValue()); assertThat(output.size(), equalTo(input.size())); assertThat(output, not(sameInstance(input))); attemptModifyMapAndExpectFailure(output, "key2", "val2"); }
|
### Question:
CollectionUtils { public static <T> Set<T> immutableOrEmptySet(Set<T> input) { return Optional.ofNullable(input).map(HashSet::new).map(Collections::unmodifiableSet).orElse(Collections.emptySet()); } private CollectionUtils(); static T[] nullableArrayCopy(T[] input); static double[] nullableArrayCopy(double... input); static long[] nullableArrayCopy(long... input); static byte[] nullableArrayCopy(byte... input); static void nullOutByteArray(byte... input); static List<T> immutableOrEmptyList(List<T> input); static List<T> immutableListOrNull(List<T> input); static List<T> mutableListCopyOrNull(List<T> input); static Map<K, V> immutableOrEmptyMap(Map<K, V> input); static Map<K, V> immutableMapOrNull(Map<K, V> input); static SortedMap<K, V> immutableSortedOrEmptyMap(SortedMap<K, V> input); static SortedMap<K, V> immutableSortedMapOrNull(SortedMap<K, V> input); static Set<T> immutableOrEmptySet(Set<T> input); static Set<T> immutableSetOrNull(Set<T> input); }### Answer:
@Test public void testImmutableOrEmptySet() throws Exception { Set<String> nullInput = null; Set<String> input = Collections.singleton("key"); Set<String> emptyOutput = CollectionUtils.immutableOrEmptySet(nullInput); Set<String> output = CollectionUtils.immutableOrEmptySet(input); assertThat(emptyOutput.size(), is(0)); assertThat(output.size(), equalTo(input.size())); assertThat(output, not(sameInstance(input))); attemptModifySetAndExpectFailure(output, "key2"); }
|
### Question:
AbstractRemoteClient implements RemoteClient { protected <T> Headers executeAndRetrieveHeaders(Call<T> call) throws UnauthorizedException { return Optional.ofNullable(executeCallInternal(call)) .map(Response::headers) .orElse(null); } protected AbstractRemoteClient(EndpointConnector connector, Class<S> cls); boolean authenticate(); static String prefixTokenHeader(byte[] token, @Nonnull String prefix); S svc(); static char[] byteToCharArray(byte[] bytes); final EndpointConnector connector(); @Override String endpoint(); }### Answer:
@Test public void testExecuteAndRetrieveHeaders() throws Exception { Response<String> failure = createSuccessfulResponseWithHeaders(); doReturn(failure).when(call).execute(); Headers headers = client.executeAndRetrieveHeaders(call); assertThat(headers.size(), is(1)); assertThat(headers.names(), hasItem("Custom")); assertThat(headers.get("Custom"), is("Header")); }
|
### Question:
AbstractRemoteClient implements RemoteClient { public S svc() { return svc; } protected AbstractRemoteClient(EndpointConnector connector, Class<S> cls); boolean authenticate(); static String prefixTokenHeader(byte[] token, @Nonnull String prefix); S svc(); static char[] byteToCharArray(byte[] bytes); final EndpointConnector connector(); @Override String endpoint(); }### Answer:
@Test public void testClientWithProxy() throws Exception { connector = ImmutableConnector.builder().from(connector) .proxyHost("127.0.0.1") .proxyPort(8901) .build(); client = new AbstractRemoteClientImpl(connector, AbstractRemoteClientImpl.RetroService.class); Call<String> remoteCall = client.svc().get(); try { remoteCall.execute(); fail("This should not succeed! If it does, check any running processes that bind the specified port!"); } catch (ConnectException e) { assertThat("Service was correctly initialized", client.svc(), notNullValue()); assertThat("Attempting to execute the call, should result in a proxy connect failure", e.getMessage(), containsString("127.0.0.1:8901")); } }
|
### Question:
AbstractRemoteClient implements RemoteClient { @Override public String endpoint() { return connector.id(); } protected AbstractRemoteClient(EndpointConnector connector, Class<S> cls); boolean authenticate(); static String prefixTokenHeader(byte[] token, @Nonnull String prefix); S svc(); static char[] byteToCharArray(byte[] bytes); final EndpointConnector connector(); @Override String endpoint(); }### Answer:
@Test public void testCacheKey() throws Exception { String cacheKey = client.endpoint(); assertThat("Cache key should be the connector id", cacheKey, equalTo("connector")); }
|
### Question:
CacheEntry { public T value() { return value; } CacheEntry(T value, long expireMillis); T value(); boolean expired(); }### Answer:
@Test public void testValue() throws Exception { CacheEntry<Double> entry = new CacheEntry<>(1.0d, 86400); Double value = entry.value(); boolean isExpired = entry.expired(); assertThat("Value is different to what was passed in", value, equalTo(1.0d)); assertThat("Cache entry should not have expired", isExpired, is(false)); }
|
### Question:
ConfigurationIntake { List<String> getAllConfigurationsFromDisk(String dir) throws IOException { if (isNull(dir)) { logger.warn("Null configuration dir passed, returning empty configuration list"); return Collections.emptyList(); } try (DirectoryStream<Path> configurationsDirectory = Files.newDirectoryStream(Paths.get(dir))) { return StreamSupport.stream(configurationsDirectory.spliterator(), true) .filter(ConfigurationIntake::isJsonFile) .map(Path::toAbsolutePath) .map(Path::toString) .collect(Collectors.toList()); } } @Inject ConfigurationIntake(ObjectMapper mapper); Set<Configuration> parseAll(String configurationsPath); void throwRuntimeExceptionOnErrors(); static final String CONFIGURATIONS_READ_ERROR; }### Answer:
@Test public void testNullConfigurationsDir() throws Exception { ObjectMapper mapper = fixSerializationHelper(fixtures); ConfigurationIntake configurationIntake = new ConfigurationIntake(mapper); List<String> configurations = configurationIntake.getAllConfigurationsFromDisk(null); assertThat(configurations, empty()); }
@Test(expectedExceptions = IOException.class) public void testNonExistentConfigurationsDir() throws Exception { ObjectMapper mapper = fixSerializationHelper(fixtures); ConfigurationIntake configurationIntake = new ConfigurationIntake(mapper); configurationIntake.getAllConfigurationsFromDisk("/invalid/dir/should/throw/IOException"); }
|
### Question:
CacheEntry { public boolean expired() { return System.currentTimeMillis() >= expiresAt; } CacheEntry(T value, long expireMillis); T value(); boolean expired(); }### Answer:
@Test public void testExpired() throws Exception { CacheEntry<Double> entry = new CacheEntry<>(1.0d, 1); await().atLeastMs(2); boolean isExpired = entry.expired(); assertThat("Cache entry should have expired already", isExpired, is(true)); }
|
### Question:
ConcurrentCacheMap implements Cache<T> { @Override public T isCached(final String key) { final SoftReference<CacheEntry<T>> entryRef = cache.get(key); if (isNull(entryRef)) { return null; } CacheEntry<T> entry = entryRef.get(); if (isNull(entry) || entry.expired()) { cache.remove(key, entryRef); return null; } return entry.value(); } @Override void cache(T object, long millis); @Override T isCached(final String key); }### Answer:
@Test public void testCacheKeyNotFound() throws Exception { Cacheable actual = cache.isCached("invalidKey"); assertThat("There should be no object cached for that key", actual, is(nullValue())); }
|
### Question:
HighestValue implements Transform { @Override public List<List<Transmutation>> apply(List<List<Transmutation>> stageInput) { final List<Transmutation> stageResult = new ArrayList<>(); stageInput.stream().flatMap(Collection::stream) .max(Comparator.comparing(result -> new BigDecimal(result.value().toString()))) .ifPresent(transformResultStage -> stageResult.add(processMetadata(transformResultStage))); return Collections.singletonList(stageResult); } @Nullable @JsonProperty("messageCodeSource") abstract Display tagMessageCode(); @Nullable abstract Display tagMessageBody(); @Override List<List<Transmutation>> apply(List<List<Transmutation>> stageInput); }### Answer:
@Test public void testOriginalDateIsAddedToMessageBody() throws Exception { HighestValue transform = ImmutableHighestValue.of(null, HighestValue.Display.ORIGINAL_TIMESTAMP); List<List<Transmutation>> results = transform.apply(transformationResults); assertThat(results, not(empty())); assertThat(results.get(0), not(empty())); Transmutation result = results.get(0).get(0); assertThat("The result should contain the original time", result.metadata().messages(), hasItem(containsString(NOW.toString()))); }
|
### Question:
RefocusClient extends AbstractRemoteClient<RefocusService> { public Sample getSample(String key, List<String> fields) throws UnauthorizedException { Preconditions.checkNotNull(key, "Key should not be null"); return executeAndRetrieveBody(svc().getSample(authorizationHeader(), key, fields), null); } RefocusClient(EndpointConnector connector); @Override boolean isAuthenticated(); Sample getSample(String key, List<String> fields); List<Sample> getSamples(String name); boolean upsertSamplesBulk(List<Sample> samples); Sample deleteSample(String key); List<Subject> getSubjects(List<String> fields); Subject getSubject(String key, List<String> fields); Subject getSubjectHierarchy(String key, String status); Subject postSubject(Subject subject); Subject patchSubject(Subject subject); Subject putSubject(Subject subject); Subject deleteSubject(String subjectKey); List<Aspect> getAspects(List<String> fields); Aspect getAspect(String key, List<String> fields); Aspect postAspect(Aspect aspect); Aspect patchAspect(Aspect aspect); }### Answer:
@Test public void getSample() throws Exception { Response<Sample> response = Response.success(sample); @SuppressWarnings("unchecked") Call<ResponseBody> responseCall = mock(Call.class); doReturn(response).when(responseCall).execute(); doReturn(request).when(responseCall).request(); doReturn(responseCall).when(svc).getSample(any(), any(), anyList()); Sample result = refocus.getSample("name", fields); assertThat(result.name(), is("name")); assertThat(result.value(), is("value")); assertThat(result.id(), is("id")); }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.