@Test public void testNetworkPartionMessage() throws Exception { try { initMocks(true); System.setProperty(GMSJoinLeave.BYPASS_DISCOVERY_PROPERTY, "true"); gmsJoinLeave.join(); installView(1, gmsJoinLeaveMemberId, createMemberList(mockMembers[0], mockMembers[1], mockMembers[2], gmsJoinLeaveMemberId, mockMembers[3])); for (int i = 1; i < 4; i++) { RemoveMemberMessage msg = new RemoveMemberMessage(gmsJoinLeaveMemberId, mockMembers[i], "crashed"); msg.setSender(gmsJoinLeaveMemberId); gmsJoinLeave.processMessage(msg); } Timeout to = new Timeout(3 * ServiceConfig.MEMBER_REQUEST_COLLECTION_INTERVAL, new Times(1)); verify(messenger, to).send(isA(NetworkPartitionMessage.class)); } finally { System.getProperties().remove(GMSJoinLeave.BYPASS_DISCOVERY_PROPERTY); } }
@Test public void testViewIgnoredAfterShutdown() throws Exception { try { initMocks(true); System.setProperty(GMSJoinLeave.BYPASS_DISCOVERY_PROPERTY, "true"); gmsJoinLeave.join(); installView(1, gmsJoinLeaveMemberId, createMemberList(mockMembers[0], mockMembers[1], mockMembers[2], gmsJoinLeaveMemberId, mockMembers[3])); gmsJoinLeave.stop(); for (int i = 1; i < 4; i++) { RemoveMemberMessage msg = new RemoveMemberMessage(gmsJoinLeaveMemberId, mockMembers[i], "crashed"); msg.setSender(gmsJoinLeaveMemberId); gmsJoinLeave.processMessage(msg); } Timeout to = new Timeout(2 * ServiceConfig.MEMBER_REQUEST_COLLECTION_INTERVAL, never()); verify(messenger, to).send(isA(NetworkPartitionMessage.class)); } finally { System.getProperties().remove(GMSJoinLeave.BYPASS_DISCOVERY_PROPERTY); } }
@Test public void shouldLaunchUriWithFallbackIfCustomTabIntentFails() throws Exception { doThrow(ActivityNotFoundException.class) .doNothing() .when(context).startActivity(any(Intent.class)); controller.launchUri(uri); verify(context, new Timeout(MAX_TEST_WAIT_TIME_MS, VerificationModeFactory.times(2))).startActivity(launchIntentCaptor.capture()); List<Intent> intents = launchIntentCaptor.getAllValues(); Intent customTabIntent = intents.get(0); assertThat(customTabIntent.getAction(), is(Intent.ACTION_VIEW)); assertThat(customTabIntent.getData(), is(uri)); assertThat(customTabIntent, not(hasFlag(Intent.FLAG_ACTIVITY_NO_HISTORY))); assertThat(customTabIntent.hasExtra(CustomTabsIntent.EXTRA_SESSION), is(true)); assertThat(customTabIntent.hasExtra(CustomTabsIntent.EXTRA_TITLE_VISIBILITY_STATE), is(true)); assertThat(customTabIntent.hasExtra(CustomTabsIntent.EXTRA_TOOLBAR_COLOR), is(false)); assertThat(customTabIntent.getIntExtra(CustomTabsIntent.EXTRA_TITLE_VISIBILITY_STATE, CustomTabsIntent.NO_TITLE), is(CustomTabsIntent.NO_TITLE)); Intent fallbackIntent = intents.get(1); assertThat(fallbackIntent.getAction(), is(Intent.ACTION_VIEW)); assertThat(fallbackIntent.getData(), is(uri)); assertThat(fallbackIntent, hasFlag(Intent.FLAG_ACTIVITY_NO_HISTORY)); assertThat(fallbackIntent.hasExtra(CustomTabsIntent.EXTRA_SESSION), is(false)); assertThat(fallbackIntent.hasExtra(CustomTabsIntent.EXTRA_TITLE_VISIBILITY_STATE), is(false)); }
private void cancelAllPendingOrders() throws Exception { Thread.sleep(1000); // let the orders arrive int numPending = orderListener.ordersToCancel.size(); if (numPending > 0) { userStream.batch().cancelOrders(orderListener.ordersToCancel).send(); orderListener.ordersToCancel.forEach( cancelSpec -> verify(orderListener, timeout(1000)) .onOrderCancelled(new OrderCancelled(cancelSpec.getClientOrderId())) ); verify(accountStateListener, new Timeout(1000, atLeastOnce())).onAccountState(any()); } }
private static void verifyNothingDeployed(ExecutionGraph eg, TaskManagerGateway[] taskManagers) { // job should still be running assertEquals(JobStatus.RUNNING, eg.getState()); // none of the TaskManager should have gotten a deployment call, yet for (TaskManagerGateway gateway : taskManagers) { verify(gateway, new Timeout(50, times(0))).submitTask(any(TaskDeploymentDescriptor.class), any(Time.class)); } }
@Test @Ignore // this test is unstable public void testPutJob() { final TaskGraph tg = new TaskGraph(); tg.addTask(this.A); tg.addTask(this.B); tg.addTask(this.C, this.A); tg.addTask(this.D, this.A); final TaskGraph tg2 = new TaskGraph(); tg2.addTask(this.A); tg2.addTask(this.B); tg2.addTask(this.C, this.A); tg2.addTask(this.D, this.A); final TaskGraph tg3 = new TaskGraph(); tg3.addTask(this.A); tg3.addTask(this.B); tg3.addTask(this.C, this.A); tg3.addTask(this.D, this.A); @SuppressWarnings("unchecked") final List<String> mockList = mock(List.class); JobEngine.getEngine().addJobCompletionListener(new JobCompletionListener() { @Override public void completed(Job job) { mockList.add(job.getName()); } }); Runnable job1Runnable = new Runnable() { @Override public void run() { JobQueuer.getInstance().putJob(new JobRequest("Job-parallel-nested1", tg, false)); } }; Runnable job2Runnable = new Runnable() { @Override public void run() { JobQueuer.getInstance().putJob(new JobRequest("Job-parallel-nested2", tg2, false)); } }; Runnable job3Runnable = new Runnable() { @Override public void run() { JobQueuer.getInstance().putJob(new JobRequest("Job-parallel-nested3", tg3, false)); } }; new Thread(job1Runnable).start(); try { Thread.sleep(1000); } catch (InterruptedException e1) { e1.printStackTrace(); } new Thread(job2Runnable).start(); new Thread(job3Runnable).start(); InOrder inOrder = inOrder(mockList); verify(mockList, new Timeout(5000, new InOrderWrapper(new Times(1), (InOrderImpl) inOrder))).add( "Job-parallel-nested1"); verify(mockList, new Timeout(5000, new InOrderWrapper(new Times(1), (InOrderImpl) inOrder))).add( "Job-parallel-nested2"); verify(mockList, new Timeout(5000, new InOrderWrapper(new Times(1), (InOrderImpl) inOrder))).add( "Job-parallel-nested3"); verifyNoMoreInteractions(mockList); }
@Test(enabled = TESTS_ENABLED) public void testPlacingModifyingAndCancelingSingleOrder() throws Exception { // this test will work correctly with 100 BTC balance // given long clOrId = System.currentTimeMillis(); BigDecimal price = $("0.1"); OrderSide side = OrderSide.SELL; int qty = 5; // when userStream.placeOrder(new LimitOrderSpec( clOrId, FUTURES_INSTRUMENT_ID, side, qty, price )); // then verify(orderListener, timeout(1000)).onOrderPlaced(new OrderPlaced( clOrId, FUTURES_INSTRUMENT_ID, price, side, qty, qty )); // and then // when int newQty = 4; BigDecimal newPrice = $("0.05"); userStream.modifyOrder(new OrderModificationSpec(clOrId, newQty, newPrice)); // then verify(orderListener, timeout(1000)).onOrderModified(new OrderModified(clOrId)); // and then // when userStream.cancelOrder(new OrderCancelSpec(clOrId)); // then verify(orderListener, timeout(1000)).onOrderCancelled(new OrderCancelled(clOrId)); verify(accountStateListener, new Timeout(1000, atLeastOnce())).onAccountState(any()); verify(streamFailureListener, never()).onStreamFailure(any()); }
/** * Tests that with scheduling futures and pipelined deployment, the target vertex will * not deploy its task before the source vertex does. */ @Test public void testScheduleSourceBeforeTarget() throws Exception { // [pipelined] // we construct a simple graph (source) ----------------> (target) final int parallelism = 1; final JobVertex sourceVertex = new JobVertex("source"); sourceVertex.setParallelism(parallelism); sourceVertex.setInvokableClass(NoOpInvokable.class); final JobVertex targetVertex = new JobVertex("target"); targetVertex.setParallelism(parallelism); targetVertex.setInvokableClass(NoOpInvokable.class); targetVertex.connectNewDataSetAsInput(sourceVertex, DistributionPattern.ALL_TO_ALL, ResultPartitionType.PIPELINED); final JobID jobId = new JobID(); final JobGraph jobGraph = new JobGraph(jobId, "test", sourceVertex, targetVertex); final CompletableFuture<LogicalSlot> sourceFuture = new CompletableFuture<>(); final CompletableFuture<LogicalSlot> targetFuture = new CompletableFuture<>(); ProgrammedSlotProvider slotProvider = new ProgrammedSlotProvider(parallelism); slotProvider.addSlot(sourceVertex.getID(), 0, sourceFuture); slotProvider.addSlot(targetVertex.getID(), 0, targetFuture); final ExecutionGraph eg = createExecutionGraph(jobGraph, slotProvider); // set up two TaskManager gateways and slots final TaskManagerGateway gatewaySource = createTaskManager(); final TaskManagerGateway gatewayTarget = createTaskManager(); final SimpleSlot sourceSlot = createSlot(gatewaySource, jobId); final SimpleSlot targetSlot = createSlot(gatewayTarget, jobId); eg.setScheduleMode(ScheduleMode.EAGER); eg.setQueuedSchedulingAllowed(true); eg.scheduleForExecution(); // job should be running assertEquals(JobStatus.RUNNING, eg.getState()); // we fulfill the target slot before the source slot // that should not cause a deployment or deployment related failure targetFuture.complete(targetSlot); verify(gatewayTarget, new Timeout(50, times(0))).submitTask(any(TaskDeploymentDescriptor.class), any(Time.class)); assertEquals(JobStatus.RUNNING, eg.getState()); // now supply the source slot sourceFuture.complete(sourceSlot); // by now, all deployments should have happened verify(gatewaySource, timeout(1000)).submitTask(any(TaskDeploymentDescriptor.class), any(Time.class)); verify(gatewayTarget, timeout(1000)).submitTask(any(TaskDeploymentDescriptor.class), any(Time.class)); assertEquals(JobStatus.RUNNING, eg.getState()); }
@Test public void testChatBotResult() throws Exception { TelegramService service = currentMockService(); ArgumentCaptor<OutgoingTextMessage> captor = ArgumentCaptor.forClass(OutgoingTextMessage.class); verify(service, new Timeout(5000, times(2))).sendMessage(eq("mock-token"), captor.capture()); List<OutgoingTextMessage> msgs = captor.getAllValues(); assertCollectionSize(msgs, 2); assertTrue(msgs.stream().anyMatch(m -> "echo from the bot: Hello World!".equals(m.getText()))); assertTrue(msgs.stream().anyMatch(m -> "echo from the bot: taken".equals(m.getText()))); assertTrue(msgs.stream().noneMatch(m -> m.getParseMode() != null)); }
/** * Allows verifying with timeout. May be useful for testing in concurrent conditions. * <p> * It feels this feature should be used rarely - figure out a better way of testing your multi-threaded system * <p> * Not yet implemented to work with InOrder verification. * <pre> * //passes when someMethod() is called within given time span * verify(mock, timeout(100)).someMethod(); * //above is an alias to: * verify(mock, timeout(100).times(1)).someMethod(); * * //passes when someMethod() is called *exactly* 2 times within given time span * verify(mock, timeout(100).times(2)).someMethod(); * * //passes when someMethod() is called *at lest* 2 times within given time span * verify(mock, timeout(100).atLeast(2)).someMethod(); * * //verifies someMethod() within given time span using given verification mode * //useful only if you have your own custom verification modes. * verify(mock, new Timeout(100, yourOwnVerificationMode)).someMethod(); * </pre> * * See examples in javadoc for {@link Mockito} class * * @param millis - time span in millis * * @return verification mode */ public static VerificationWithTimeout timeout(int millis) { return new Timeout(millis, VerificationModeFactory.times(1)); }
/** * Allows verifying with timeout. It causes a verify to wait for a specified period of time for a desired * interaction rather than fails immediately if has not already happened. May be useful for testing in concurrent * conditions. * <p> * This differs from {@link Mockito#after after()} in that after() will wait the full period, unless * the final test result is known early (e.g. if a never() fails), whereas timeout() will stop early as soon * as verification passes, producing different behaviour when used with times(2), for example, which can pass * and then later fail. In that case, timeout would pass as soon as times(2) passes, whereas after would run until * times(2) failed, and then fail. * <p> * It feels this feature should be used rarely - figure out a better way of testing your multi-threaded system * <p> * Not yet implemented to work with InOrder verification. * <pre class="code"><code class="java"> * //passes when someMethod() is called within given time span * verify(mock, timeout(100)).someMethod(); * //above is an alias to: * verify(mock, timeout(100).times(1)).someMethod(); * * //passes as soon as someMethod() has been called 2 times before the given timeout * verify(mock, timeout(100).times(2)).someMethod(); * * //equivalent: this also passes as soon as someMethod() has been called 2 times before the given timeout * verify(mock, timeout(100).atLeast(2)).someMethod(); * * //verifies someMethod() within given time span using given verification mode * //useful only if you have your own custom verification modes. * verify(mock, new Timeout(100, yourOwnVerificationMode)).someMethod(); * </code></pre> * * See examples in javadoc for {@link Mockito} class * * @param millis - time span in milliseconds * * @return verification mode */ public static VerificationWithTimeout timeout(int millis) { return new Timeout(millis, VerificationModeFactory.times(1)); }