/** * Mocks a subscriber and prepares it to request Long.MAX_VALUE. * @param <T> the value type * @return the mocked subscriber */ @SuppressWarnings("unchecked") public static <T> FlowableSubscriber<T> mockSubscriber() { FlowableSubscriber<T> w = mock(FlowableSubscriber.class); Mockito.doAnswer(new Answer<Object>() { @Override public Object answer(InvocationOnMock a) throws Throwable { Subscription s = a.getArgument(0); s.request(Long.MAX_VALUE); return null; } }).when(w).onSubscribe((Subscription)any()); return w; }
static Resources mockResources(final String resValueString) { Resources resources = mock(Resources.class); doAnswer(new Answer<Void>() { @Override public Void answer(InvocationOnMock invocation) { Object[] args = invocation.getArguments(); ((TypedValue) args[1]).string = resValueString; return null; } }).when(resources).getValue(anyInt(), any(TypedValue.class), anyBoolean()); return resources; }
private static ExecutorService sameThreadExecutor() throws InterruptedException { ExecutorService executor = immediateExecutor(); when( executor.awaitTermination( anyLong(), any() ) ).thenReturn( true ); doAnswer( invocation -> { ((Runnable) invocation.getArgument( 0 )).run(); return null; } ).when( executor ).execute( any() ); return executor; }
@Test public void uploadArtifacts() throws Exception { AtomicOutputStream mockOutputStream = mock(AtomicOutputStream.class); doNothing().when(mockOutputStream).cancel(); final AtomicInteger counter = new AtomicInteger(); final Answer incrementCounter = new Answer() { public Object answer(InvocationOnMock invocation) throws Throwable { counter.addAndGet(1); return null; } }; doAnswer(incrementCounter).when(mockOutputStream).write(anyInt()); doAnswer(incrementCounter).when(mockOutputStream).write(any(byte[].class)); doAnswer(incrementCounter).when(mockOutputStream).write(any(byte[].class), anyInt(), anyInt()); doNothing().when(mockOutputStream).close(); when(mockBlobStore.getBlobMeta(anyString())).thenThrow(new KeyNotFoundException()); when(mockBlobStore.createBlob(anyString(), any(SettableBlobMeta.class))).thenReturn(mockOutputStream); String artifact = "group:artifact:1.0.0"; String expectedBlobKeyForArtifact = "group-artifact-1.0.0.jar"; File mockFile = createTemporaryDummyFile(); Map<String, File> artifacts = new LinkedHashMap<>(); artifacts.put(artifact, mockFile); List<String> keys = sut.uploadArtifacts(artifacts); assertEquals(1, keys.size()); assertTrue(keys.get(0).contains(expectedBlobKeyForArtifact)); assertTrue(counter.get() > 0); verify(mockOutputStream).close(); }
@Test public void testWindowStateNotAvailableToMergingWindows() throws Exception { WindowAssigner<Integer, TimeWindow> mockAssigner = mockMergingAssigner(); Trigger<Integer, TimeWindow> mockTrigger = mockTrigger(); InternalWindowFunction<Iterable<Integer>, Void, Integer, TimeWindow> mockWindowFunction = mockWindowFunction(); KeyedOneInputStreamOperatorTestHarness<Integer, Integer, Void> testHarness = createWindowOperator(mockAssigner, mockTrigger, 20L, mockWindowFunction); testHarness.open(); when(mockTrigger.onElement(anyInt(), anyLong(), anyTimeWindow(), anyTriggerContext())) .thenReturn(TriggerResult.FIRE); when(mockAssigner.assignWindows(anyInt(), anyLong(), anyAssignerContext())) .thenReturn(Arrays.asList(new TimeWindow(0, 20))); doAnswer(new Answer<Object>() { @Override public Object answer(InvocationOnMock invocationOnMock) throws Throwable { InternalWindowFunction.InternalWindowContext context = (InternalWindowFunction.InternalWindowContext) invocationOnMock.getArguments()[2]; context.windowState().getState(valueStateDescriptor).update("hello"); return null; } }).when(mockWindowFunction).process(anyInt(), anyTimeWindow(), anyInternalWindowContext(), anyIntIterable(), WindowOperatorContractTest.<Void>anyCollector()); expectedException.expect(UnsupportedOperationException.class); expectedException.expectMessage("Per-window state is not allowed when using merging windows."); testHarness.processElement(new StreamRecord<>(0, 0L)); }
@Test(expected = CancellationException.class) public void testThrowsCancellationExceptionIfCancelledWhileWaiting() throws ExecutionException, InterruptedException { doAnswer( new Answer<Void>() { @Override public Void answer(InvocationOnMock invocationOnMock) { future.cancel(false); return null; } }) .when(waiter) .waitForTimeout(eq(future), anyLong()); future.get(); }
@Test public void testCallsSourceExecutorEngineIfOptionsIsSet() { doAnswer(new CallSizeReady(100, 100)).when(builder.target) .getSize(any(SizeReadyCallback.class)); SingleRequest<List> request = builder .setUseUnlimitedSourceGeneratorsPool(false) .build(); request.begin(); verify(builder.engine) .load( eq(builder.glideContext), eq(builder.model), eq(builder.signature), anyInt(), anyInt(), eq(Object.class), eq(List.class), any(Priority.class), any(DiskCacheStrategy.class), eq(builder.transformations), anyBoolean(), anyBoolean(), any(Options.class), anyBoolean(), eq(false), /*useAnimationPool=*/ anyBoolean(), anyBoolean(), any(ResourceCallback.class), anyExecutor()); }
@Test public void testCanReRunClearedRequests() { doAnswer(new CallSizeReady(100, 100)).when(builder.target) .getSize(any(SizeReadyCallback.class)); when(builder.engine.load( eq(builder.glideContext), eq(builder.model), eq(Object.class), eq(List.class), any(Priority.class), any(DiskCacheStrategy.class), eq(builder.transformations), anyBoolean(), request.begin(); verify(builder.target, times(2)).onResourceReady(eq(builder.result), anyTransition());
@Before public void setUp() throws UnsupportedEncodingException { MockitoAnnotations.initMocks(this); doAnswer(new WriteDigest("firstKey")).when(firstKey) .updateDiskCacheKey(any(MessageDigest.class)); doAnswer(new WriteDigest("firstSignature")).when(firstSignature) .updateDiskCacheKey(any(MessageDigest.class)); doAnswer(new WriteDigest("secondKey")).when(secondKey) .updateDiskCacheKey(any(MessageDigest.class)); doAnswer(new WriteDigest("secondSignature")).when(secondSignature) .updateDiskCacheKey(any(MessageDigest.class)); }
@Before public void setUp() { MockitoAnnotations.initMocks(this); doAnswer(new AddBitmapPoolAnswer(addedBitmaps)).when(pool).put(any(Bitmap.class)); when(pool.getDirty(anyInt(), anyInt(), any(Bitmap.Config.class))) .thenAnswer(new CreateBitmap()); when(cache.put(any(Key.class), anyResource())) .thenAnswer(new AddBitmapCacheAnswer(addedBitmaps)); }
private static Chunk mockChunkWithReadinessStateAt(final int x, final int y, final int z) { final Chunk chunk = mockChunkAt(x, y, z); AtomicBoolean chunkReady = new AtomicBoolean(); when(chunk.isReady()).thenAnswer(i -> chunkReady.get()); doAnswer(i -> { chunkReady.set(true); return null; }).when(chunk).markReady(); return chunk; }
static ResultSet resultSetReturningMetadata(ResultSetMetaData metadata) throws SQLException { final ResultSet rs = mock(ResultSet.class); when(rs.getMetaData()).thenReturn(metadata); final AtomicInteger counter = new AtomicInteger(1); Mockito.doAnswer(new Answer<Boolean>() { @Override public Boolean answer(InvocationOnMock invocation) throws Throwable { return counter.getAndDecrement() > 0; } }).when(rs).next(); return rs; }
@Test public void transform_withColorDrawable_andUnitBitmapTransformation_recycles() { bitmapPool = mock(BitmapPool.class); Glide.tearDown(); Glide.init(context, new GlideBuilder().setBitmapPool(bitmapPool)); when( bitmapTransformation .transform( any(Context.class), anyBitmapResource(), anyInt(), anyInt())) .thenAnswer(new ReturnGivenResource()); final Resource<Drawable> input = new SimpleResource<Drawable>(colorDrawable); doAnswer(new Answer<Void>() { @Override public Void answer(InvocationOnMock invocationOnMock) throws Throwable { return null; }).when(bitmapPool).put(any(Bitmap.class)); when(bitmapPool.get(anyInt(), anyInt(), any(Bitmap.Config.class))) .thenAnswer(new Answer<Bitmap>() { @Override verify(bitmapPool).put(isA(Bitmap.class));
@Test public void testOnElementPurgeDoesNotCleanupMergingSet() throws Exception { MergingWindowAssigner<Integer, TimeWindow> mockAssigner = mockMergingAssigner(); Trigger<Integer, TimeWindow> mockTrigger = mockTrigger(); InternalWindowFunction<Iterable<Integer>, Void, Integer, TimeWindow> mockWindowFunction = mockWindowFunction(); KeyedOneInputStreamOperatorTestHarness<Integer, Integer, Void> testHarness = createWindowOperator(mockAssigner, mockTrigger, 0L, mockWindowFunction); testHarness.open(); when(mockAssigner.assignWindows(anyInt(), anyLong(), anyAssignerContext())) .thenReturn(Arrays.asList(new TimeWindow(0, 2))); assertEquals(0, testHarness.getOutput().size()); assertEquals(0, testHarness.numKeyedStateEntries()); doAnswer(new Answer<TriggerResult>() { @Override public TriggerResult answer(InvocationOnMock invocation) throws Exception { return TriggerResult.PURGE; } }).when(mockTrigger).onElement(Matchers.<Integer>anyObject(), anyLong(), anyTimeWindow(), anyTriggerContext()); testHarness.processElement(new StreamRecord<>(0, 0L)); assertEquals(1, testHarness.numKeyedStateEntries()); // the merging window set assertEquals(1, testHarness.numEventTimeTimers()); // one cleanup timer assertEquals(0, testHarness.getOutput().size()); }
@Test(expected = InterruptedException.class) public void testThrowsInterruptedExceptionIfThreadInterruptedWhenDoneWaiting() throws InterruptedException, ExecutionException { doAnswer( new Answer<Void>() { @Override public Void answer(InvocationOnMock invocationOnMock) { Thread.currentThread().interrupt(); return null; } }) .when(waiter) .waitForTimeout(eq(future), anyLong()); future.get(); }
@Test public void testCallsSourceUnlimitedExecutorEngineIfOptionsIsSet() { doAnswer(new CallSizeReady(100, 100)).when(builder.target) .getSize(any(SizeReadyCallback.class)); SingleRequest<List> request = builder .setUseUnlimitedSourceGeneratorsPool(true) .build(); request.begin(); verify(builder.engine) .load( eq(builder.glideContext), eq(builder.model), eq(builder.signature), anyInt(), anyInt(), eq(Object.class), eq(List.class), any(Priority.class), any(DiskCacheStrategy.class), eq(builder.transformations), anyBoolean(), anyBoolean(), any(Options.class), anyBoolean(), eq(true), /*useAnimationPool=*/ anyBoolean(), anyBoolean(), any(ResourceCallback.class), anyExecutor()); }
@Before public void setUp() { MockitoAnnotations.initMocks(this); context = RuntimeEnvironment.application; doAnswer(new Util.WriteDigest("first")).when(first) .updateDiskCacheKey(any(MessageDigest.class)); doAnswer(new Util.WriteDigest("second")).when(second) .updateDiskCacheKey(any(MessageDigest.class)); }