Refine search
@Test public void fromCompletionStageSupplier() { AtomicInteger source = new AtomicInteger(); Supplier<CompletableFuture<Integer>> supplier = () -> CompletableFuture.completedFuture(source.incrementAndGet()); Mono<Number> mono = Mono.fromCompletionStage(supplier); Assertions.assertThat(source).hasValue(0); Assertions.assertThat(mono.block()) .isEqualTo(source.get()) .isEqualTo(1); Assertions.assertThat(mono.block()) .isEqualTo(source.get()) .isEqualTo(2); }
@Test public void fromFutureSupplier() { AtomicInteger source = new AtomicInteger(); Supplier<CompletableFuture<Integer>> supplier = () -> CompletableFuture.completedFuture(source.incrementAndGet()); Mono<Number> mono = Mono.fromFuture(supplier); Assertions.assertThat(source).hasValue(0); Assertions.assertThat(mono.block()) .isEqualTo(source.get()) .isEqualTo(1); Assertions.assertThat(mono.block()) .isEqualTo(source.get()) .isEqualTo(2); }
@Test public void transferSuccess() { @SuppressWarnings("unchecked") final AsyncMethodCallback<String> callback = mock(AsyncMethodCallback.class); AsyncMethodCallbacks.transfer(completedFuture("foo"), callback); verify(callback, only()).onComplete("foo"); }
@Test public void transferCallbackError() { @SuppressWarnings("unchecked") final AsyncMethodCallback<String> callback = mock(AsyncMethodCallback.class); doThrow(new AnticipatedException()).when(callback).onComplete(any()); AsyncMethodCallbacks.transfer(completedFuture("foo"), callback); verify(callback, only()).onComplete("foo"); } }
/** * Tests dynamically loading of handlers such as {@link JarUploadHandler}. */ @Test public void testLoadWebSubmissionExtension() throws Exception { final Configuration configuration = new Configuration(); configuration.setString(JobManagerOptions.ADDRESS, "localhost"); final WebMonitorExtension webMonitorExtension = WebMonitorUtils.loadWebSubmissionExtension( CompletableFuture::new, Time.seconds(10), Collections.emptyMap(), CompletableFuture.completedFuture("localhost:12345"), Paths.get("/tmp"), Executors.directExecutor(), configuration); assertThat(webMonitorExtension, is(not(nullValue()))); } }
@Test public void propagateLastResponseWhenNextRetryIsAfterTimeout() throws Exception { final RetryStrategyWithContent<RpcResponse> strategy = (ctx, response) -> CompletableFuture.completedFuture(Backoff.fixed(10000000)); final HelloService.Iface client = helloClient(strategy, 100); when(serviceHandler.hello(anyString())).thenThrow(new IllegalArgumentException()); final Throwable thrown = catchThrowable(() -> client.hello("hello")); assertThat(thrown).isInstanceOf(TApplicationException.class); assertThat(((TApplicationException) thrown).getType()).isEqualTo(TApplicationException.INTERNAL_ERROR); verify(serviceHandler, only()).hello("hello"); }
@Test public void returnsEmptyListWhenNoTasks() { ECSAsyncClient ecs = mock(ECSAsyncClient.class); when(ecs.listTasks(any())) .thenReturn( CompletableFuture.completedFuture(ListTasksResponse.builder().taskArns().build())); TaskLister tasks = new TaskLister(ecs, CLUSTER_ARN); List<ClusterSnapshot.Task> describe = tasks.describe().join(); assertThat(describe, empty()); }
@Test public void returnsEmptyListWhenNoContainerInstances() { ECSAsyncClient ecs = mock(ECSAsyncClient.class); when(ecs.listContainerInstances(any())) .thenReturn( CompletableFuture.completedFuture( ListContainerInstancesResponse.builder().containerInstanceArns().build())); ContainerInstanceLister containerInstances = new ContainerInstanceLister(ecs, CLUSTER_1); List<ClusterSnapshot.ContainerInstance> describe = containerInstances.describe().join(); assertThat(describe, empty()); }
@Test public void invokesManagerAsynchronouslyForAllClusters() throws Exception { when(data.listClusters(any())) .thenReturn(new ListClustersResponse(Arrays.asList(CLUSTER1, CLUSTER2))); when(manager.triggerAsync(input.capture())).thenReturn(CompletableFuture.completedFuture(null)); ReconcilerHandler handler = new ReconcilerHandler(data, manager); handler.handleRequest(new CloudWatchEvent<>(), null); assertThat( input.getAllValues(), hasItems(new ManagerInput(CLUSTER1), new ManagerInput(CLUSTER2))); } }
@Test public void shouldUseCustomPrefix() { //Given AsyncRetryRegistry retryRegistry = AsyncRetryRegistry.ofDefaults(); AsyncRetry retry = retryRegistry.retry("testName"); metricRegistry.registerAll(AsyncRetryMetrics.ofAsyncRetryRegistry("testPrefix",retryRegistry)); // Given the HelloWorldService returns Hello world BDDMockito.given(helloWorldService.returnHelloWorld()).willReturn(CompletableFuture.completedFuture("Hello world")); String value = awaitResult(retry.executeCompletionStage(scheduler, helloWorldService::returnHelloWorld)); //Then assertThat(value).isEqualTo("Hello world"); // Then the helloWorldService should be invoked 1 time BDDMockito.then(helloWorldService).should(times(1)).returnHelloWorld(); assertThat(metricRegistry.getMetrics()).hasSize(4); assertThat(metricRegistry.getGauges().get("testPrefix.testName." + SUCCESSFUL_CALLS_WITH_RETRY).getValue()).isEqualTo(0L); assertThat(metricRegistry.getGauges().get("testPrefix.testName." + SUCCESSFUL_CALLS_WITHOUT_RETRY).getValue()).isEqualTo(1L); assertThat(metricRegistry.getGauges().get("testPrefix.testName." + FAILED_CALLS_WITH_RETRY).getValue()).isEqualTo(0L); assertThat(metricRegistry.getGauges().get("testPrefix.testName." + FAILED_CALLS_WITHOUT_RETRY).getValue()).isEqualTo(0L); }
/** * Tests disposal with a JAR file. */ @Test public void testDisposeWithJar() throws Exception { replaceStdOutAndStdErr(); final CompletableFuture<String> disposeSavepointFuture = new CompletableFuture<>(); final DisposeSavepointClusterClient clusterClient = new DisposeSavepointClusterClient( (String savepointPath) -> { disposeSavepointFuture.complete(savepointPath); return CompletableFuture.completedFuture(Acknowledge.get()); }, getConfiguration()); try { CliFrontend frontend = new MockedCliFrontend(clusterClient); // Fake JAR file File f = tmp.newFile(); ZipOutputStream out = new ZipOutputStream(new FileOutputStream(f)); out.close(); final String disposePath = "any-path"; String[] parameters = { "-d", disposePath, "-j", f.getAbsolutePath() }; frontend.savepoint(parameters); final String actualSavepointPath = disposeSavepointFuture.get(); assertEquals(disposePath, actualSavepointPath); } finally { clusterClient.shutdown(); restoreStdOutAndStdErr(); } }
@Test public void shouldRegisterMetricsWithoutRetry() { //Given AsyncRetryRegistry retryRegistry = AsyncRetryRegistry.ofDefaults(); AsyncRetry retry = retryRegistry.retry("testName"); metricRegistry.registerAll(AsyncRetryMetrics.ofAsyncRetryRegistry(retryRegistry)); // Given the HelloWorldService returns Hello world BDDMockito.given(helloWorldService.returnHelloWorld()) .willReturn(CompletableFuture.completedFuture("Hello world")); // Setup circuitbreaker with retry String value = awaitResult(retry.executeCompletionStage(scheduler, helloWorldService::returnHelloWorld)); //Then assertThat(value).isEqualTo("Hello world"); // Then the helloWorldService should be invoked 1 time BDDMockito.then(helloWorldService).should(times(1)).returnHelloWorld(); assertThat(metricRegistry.getMetrics()).hasSize(4); assertThat(metricRegistry.getGauges().get("resilience4j.retry.testName." + SUCCESSFUL_CALLS_WITH_RETRY).getValue()).isEqualTo(0L); assertThat(metricRegistry.getGauges().get("resilience4j.retry.testName." + SUCCESSFUL_CALLS_WITHOUT_RETRY).getValue()).isEqualTo(1L); assertThat(metricRegistry.getGauges().get("resilience4j.retry.testName." + FAILED_CALLS_WITH_RETRY).getValue()).isEqualTo(0L); assertThat(metricRegistry.getGauges().get("resilience4j.retry.testName." + FAILED_CALLS_WITHOUT_RETRY).getValue()).isEqualTo(0L); }
/** * Tests that the send operation is being retried. */ @Test public void testRetriableSendOperationIfConnectionErrorOrServiceUnavailable() throws Exception { final PingRestHandler pingRestHandler = new PingRestHandler( FutureUtils.completedExceptionally(new RestHandlerException("test exception", HttpResponseStatus.SERVICE_UNAVAILABLE)), CompletableFuture.completedFuture(EmptyResponseBody.getInstance())); try (final TestRestServerEndpoint restServerEndpoint = createRestServerEndpoint(pingRestHandler)) { RestClusterClient<?> restClusterClient = createRestClusterClient(restServerEndpoint.getServerAddress().getPort()); try { final AtomicBoolean firstPollFailed = new AtomicBoolean(); failHttpRequest = (messageHeaders, messageParameters, requestBody) -> messageHeaders instanceof PingRestHandlerHeaders && !firstPollFailed.getAndSet(true); restClusterClient.sendRequest(PingRestHandlerHeaders.INSTANCE).get(); } finally { restClusterClient.shutdown(); } } }
@Test public void testJarSubmission() throws Exception { final TestingDispatcherGateway restfulGateway = new TestingDispatcherGateway.Builder() .setBlobServerPort(blobServerResource.getBlobServerPort()) .setSubmitFunction(jobGraph -> CompletableFuture.completedFuture(Acknowledge.get())) .build(); final JarHandlers handlers = new JarHandlers(temporaryFolder.newFolder().toPath(), restfulGateway); final JarUploadHandler uploadHandler = handlers.uploadHandler; final JarListHandler listHandler = handlers.listHandler; final JarPlanHandler planHandler = handlers.planHandler; final JarRunHandler runHandler = handlers.runHandler; final JarDeleteHandler deleteHandler = handlers.deleteHandler; // targetDir property is set via surefire configuration final Path originalJar = Paths.get(System.getProperty("targetDir")).resolve("test-program.jar"); final Path jar = Files.copy(originalJar, temporaryFolder.getRoot().toPath().resolve("test-program.jar")); final String storedJarPath = uploadJar(uploadHandler, jar, restfulGateway); final String storedJarName = Paths.get(storedJarPath).getFileName().toString(); final JarListInfo postUploadListResponse = listJars(listHandler, restfulGateway); Assert.assertEquals(1, postUploadListResponse.jarFileList.size()); final JarListInfo.JarFileInfo listEntry = postUploadListResponse.jarFileList.iterator().next(); Assert.assertEquals(jar.getFileName().toString(), listEntry.name); Assert.assertEquals(storedJarName, listEntry.id); final JobPlanInfo planResponse = showPlan(planHandler, storedJarName, restfulGateway); // we're only interested in the core functionality so checking for a small detail is sufficient Assert.assertThat(planResponse.getJsonPlan(), containsString("TestProgram.java:29")); runJar(runHandler, storedJarName, restfulGateway); deleteJar(deleteHandler, storedJarName, restfulGateway); final JarListInfo postDeleteListResponse = listJars(listHandler, restfulGateway); Assert.assertEquals(0, postDeleteListResponse.jarFileList.size()); }
@Test public void shouldConsumeOnSuccessEvent() throws Exception { CompletableFuture<String> failedFuture = new CompletableFuture<>(); failedFuture.completeExceptionally(new WebServiceException("BAM!")); CountDownLatch latch = new CountDownLatch(1); // Given the HelloWorldService returns Hello world given(helloWorldService.returnHelloWorld()) .willReturn(failedFuture) .willReturn(completedFuture("Hello world")); retry.getEventPublisher() .onSuccess(event -> { logger.info(event.getEventType().toString()); latch.countDown(); }); String result = awaitResult(retry.executeCompletionStage(scheduler, () -> helloWorldService.returnHelloWorld())); assertThat(latch.await(10, TimeUnit.SECONDS)).isTrue(); assertThat(result).isEqualTo("Hello world"); then(helloWorldService).should(times(2)).returnHelloWorld(); then(logger).should(times(1)).info("SUCCESS"); }
@Test public void testDisposeSavepointSuccess() throws Exception { replaceStdOutAndStdErr(); String savepointPath = "expectedSavepointPath"; ClusterClient clusterClient = new DisposeSavepointClusterClient( (String path) -> CompletableFuture.completedFuture(Acknowledge.get()), getConfiguration()); try { CliFrontend frontend = new MockedCliFrontend(clusterClient); String[] parameters = { "-d", savepointPath }; frontend.savepoint(parameters); String outMsg = buffer.toString(); assertTrue(outMsg.contains(savepointPath)); assertTrue(outMsg.contains("disposed")); } finally { clusterClient.shutdown(); restoreStdOutAndStdErr(); } }
@Test public void shouldRetryInCaseOfAnExceptionAtAsyncStage() { CompletableFuture<String> failedFuture = new CompletableFuture<>(); failedFuture.completeExceptionally(new WebServiceException("BAM!")); // Given the HelloWorldService throws an exception BDDMockito.given(helloWorldService.returnHelloWorld()) .willReturn(failedFuture) .willReturn(completedFuture("Hello world")); // Create a Retry with default configuration AsyncRetry retryContext = AsyncRetry.ofDefaults("id"); // Decorate the invocation of the HelloWorldService Supplier<CompletionStage<String>> supplier = AsyncRetry.decorateCompletionStage( retryContext, scheduler, () -> helloWorldService.returnHelloWorld()); // When String result = awaitResult(supplier.get()); // Then the helloWorldService should be invoked 2 times BDDMockito.then(helloWorldService).should(Mockito.times(2)).returnHelloWorld(); Assertions.assertThat(result).isEqualTo("Hello world"); }
@Test public void shouldNotRetry() throws InterruptedException, ExecutionException, TimeoutException { // Given the HelloWorldService returns Hello world BDDMockito.given(helloWorldService.returnHelloWorld()) .willReturn(completedFuture("Hello world")); // Create a Retry with default configuration AsyncRetry retryContext = AsyncRetry.ofDefaults("id"); // Decorate the invocation of the HelloWorldService Supplier<CompletionStage<String>> supplier = AsyncRetry.decorateCompletionStage( retryContext, scheduler, () -> helloWorldService.returnHelloWorld()); // When String result = awaitResult(supplier); // Then the helloWorldService should be invoked 1 time BDDMockito.then(helloWorldService).should(Mockito.times(1)).returnHelloWorld(); Assertions.assertThat(result).isEqualTo("Hello world"); }
@Test @SuppressWarnings("unchecked") public void invokesSchedulerForAllEnvironments() throws Exception { when(dataService.listEnvironments(ListEnvironmentsRequest.builder().cluster(CLUSTER).build())) .thenReturn( ListEnvironmentsResponse.builder() .environmentIds(Arrays.asList(FIRST_ENVIRONMENT_ID, SECOND_ENVIRONMENT_ID)) .build()); when(scheduler.callAsync(schedulerArgument.capture())) .thenReturn( CompletableFuture.completedFuture( new SchedulerOutput(CLUSTER_NAME, FIRST_ENVIRONMENT_ID, 1, 1))); ManagerHandler handler = new ManagerHandler(dataService, ecs, scheduler); handler.handleRequest(new ManagerInput(CLUSTER), null); assertThat( schedulerArgument.getAllValues(), contains( hasProperty("environmentId", is(FIRST_ENVIRONMENT_ID)), hasProperty("environmentId", is(SECOND_ENVIRONMENT_ID)))); } }
@Test public void shouldRetryInCaseOfExceptionAtSyncStage() { // Given the HelloWorldService throws an exception BDDMockito.given(helloWorldService.returnHelloWorld()) .willThrow(new WebServiceException("BAM!")) .willReturn(completedFuture("Hello world")); // Create a Retry with default configuration AsyncRetry retryContext = AsyncRetry.ofDefaults("id"); // Decorate the invocation of the HelloWorldService Supplier<CompletionStage<String>> supplier = AsyncRetry.decorateCompletionStage( retryContext, scheduler, () -> helloWorldService.returnHelloWorld()); // When String result = awaitResult(supplier.get()); // Then the helloWorldService should be invoked 2 times BDDMockito.then(helloWorldService).should(Mockito.times(2)).returnHelloWorld(); Assertions.assertThat(result).isEqualTo("Hello world"); }