org.awaitility.Duration Java Examples
The following examples show how to use
org.awaitility.Duration.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MonoDetachTest.java From reactor-core with Apache License 2.0 | 6 votes |
@Test public void justUnsubscribed() throws Exception { o = new Object(); WeakReference<Object> wr = new WeakReference<>(o); AssertSubscriber<Object> ts = new AssertSubscriber<>(0); Mono.just(o) .onTerminateDetach() .subscribe(ts); ts.cancel(); o = null; Awaitility.with().pollDelay(Duration.ZERO).pollInterval(Duration.ONE_MILLISECOND) .await() .atMost(Duration.FIVE_SECONDS) .untilAsserted(() -> { System.gc(); Object garbage = new Object(); Assert.assertNull("Object retained!", wr.get()); garbage.toString(); }); }
Example #2
Source File: MockSMTPServerTest.java From james-project with Apache License 2.0 | 6 votes |
@Test void serverShouldActLikeDefaultAfterGettingEnoughMatches() { int numberOfAnswer = 4; MockSMTPBehavior behavior = new MockSMTPBehavior( MAIL_FROM, Condition.MATCH_ALL, new Response(SERVICE_NOT_AVAILABLE_421, "mock response"), MockSMTPBehavior.NumberOfAnswersPolicy.times(numberOfAnswer)); behaviorRepository.setBehaviors(behavior); sendMessageIgnoreError(mail1); sendMessageIgnoreError(mail1); sendMessageIgnoreError(mail1); sendMessageIgnoreError(mail1); sendMessageIgnoreError(mail1); Awaitility.await().atMost(Duration.TEN_SECONDS) .untilAsserted(() -> assertThat(mailRepository.list()).hasSize(1)); }
Example #3
Source File: ESReporterContract.java From james-project with Apache License 2.0 | 6 votes |
@BeforeEach void setUp(DockerElasticSearch elasticSearch) { RestAssured.baseURI = String.format("http://%s:%d", elasticSearch.getHttpHost().getHostName(), elasticSearch.getHttpHost().getPort()); await().atMost(Duration.ONE_MINUTE) .untilAsserted(this::elasticSearchStarted); registry = new MetricRegistry(); timer = new Timer(); esMetricReporter = new ESMetricReporter( ESReporterConfiguration.builder() .enabled() .onHost(elasticSearch.getHttpHost().getHostName(), elasticSearch.getHttpHost().getPort()) .onIndex(INDEX) .periodInSecond(PERIOD_IN_SECOND) .build(), registry); esMetricReporter.start(); }
Example #4
Source File: TestUtils.java From connector-sdk with Apache License 2.0 | 6 votes |
/** * Waits for the item with the given ID to be deleted. * * @throws org.awaitility.core.ConditionTimeoutException if the item is not deleted before the * timeout */ // TODO(jlacey): Resolve this one-off to support the verifier repository (as of commit 20b0d95) // into a consistent design. public void waitUntilDeleted(String itemId, Duration timeout, Duration pollInterval) { Awaitility.await() .atMost(timeout) .pollInterval(pollInterval) .until(() -> { try { service.getItem(itemId); return false; } catch (GoogleJsonResponseException e) { if (e.getStatusCode() == HTTP_NOT_FOUND) { return true; } throw e; } }); }
Example #5
Source File: RoadEndpointsIntegrationTest.java From data-highway with Apache License 2.0 | 6 votes |
@Test public void updateRoadSchema() throws Exception { // Create Road with schema String roadName = "metaroad"; createRoadWithSchema(roadName, true, new SchemaVersion(schema1, 1, false)); // Add another schema to road. ResponseEntity<StandardResponse> schemaResult = rest.exchange(post(uri("/paver/v1/roads/metaroad/schemas")) .header(AUTHORIZATION, "Basic " + Base64.getEncoder().encodeToString("user:pass".getBytes(UTF_8))) .contentType(APPLICATION_JSON_UTF8) .body(schema2.toString()), StandardResponse.class); assertThat(schemaResult.getStatusCode(), is(HttpStatus.OK)); assertThat(schemaResult.getBody().getMessage(), is("Request to add a new schema received.")); Awaitility.await().atMost(Duration.FIVE_SECONDS).until(() -> { String expectedPatch = "{\"documentId\":\"metaroad\",\"operations\":[{\"op\":\"add\",\"path\":\"/schemas/2\",\"value\":{\"schema\":{\"type\":\"record\",\"name\":\"record\",\"fields\":[{\"name\":\"field\",\"type\":\"boolean\"}]},\"version\":2,\"deleted\":false}}]}"; assertJsonEquals(expectedPatch, readRecords(patchConsumer, 1).get(0)); }); }
Example #6
Source File: AbstractMessageSearchIndexTest.java From james-project with Apache License 2.0 | 6 votes |
@Test void copiedMessageShouldAllBeIndexed() throws Exception { MailboxPath newBoxPath = MailboxPath.forUser(USERNAME, "newBox"); MailboxId newBoxId = storeMailboxManager.createMailbox(newBoxPath, session).get(); storeMailboxManager.copyMessages(MessageRange.all(), inboxMessageManager.getId(), newBoxId, session); SearchQuery searchQuery = SearchQuery.matchAll(); StoreMessageManager newBox = (StoreMessageManager) storeMailboxManager.getMailbox(newBoxId, session); Awaitility.with() .pollInterval(Duration.ONE_HUNDRED_MILLISECONDS) .and().with() .pollDelay(new Duration(1, TimeUnit.MILLISECONDS)) .await() .atMost(30, TimeUnit.SECONDS) .until( () -> messageSearchIndex.search(session, newBox.getMailboxEntity(), searchQuery).count() == 9); }
Example #7
Source File: ExternalSession.java From james-project with Apache License 2.0 | 6 votes |
private boolean tryReadFromSocket() throws IOException, InterruptedException { final MutableInt status = new MutableInt(0); Awaitility .waitAtMost(Duration.ONE_MINUTE) .pollDelay(new Duration(10, TimeUnit.MILLISECONDS)) .until(() -> { int read = socket.read(readBuffer); status.setValue(read); return read != 0; }); if (status.intValue() == -1) { monitor.debug("Error reading, got -1"); return false; } return true; }
Example #8
Source File: ElasticSearchListeningMessageSearchIndexTest.java From james-project with Apache License 2.0 | 6 votes |
@Test void updateShouldPropagateExceptionWhenExceptionOccurs() throws Exception { elasticSearch.getDockerElasticSearch().pause(); Thread.sleep(Duration.FIVE_SECONDS.getValueInMS()); // Docker pause is asynchronous and we found no way to poll for it Flags newFlags = new Flags(Flags.Flag.ANSWERED); UpdatedFlags updatedFlags = UpdatedFlags.builder() .uid(MESSAGE_UID_1) .modSeq(MOD_SEQ) .oldFlags(new Flags()) .newFlags(newFlags) .build(); assertThatThrownBy(() -> testee.update(session, mailbox.getMailboxId(), Lists.newArrayList(updatedFlags)).block()) .hasCauseInstanceOf(IOException.class); elasticSearch.getDockerElasticSearch().unpause(); }
Example #9
Source File: PubSubJsonPayloadSampleApplicationTests.java From spring-cloud-gcp with Apache License 2.0 | 6 votes |
@Test public void testReceivesJsonPayload() { Map<String, String> params = new MapBuilder<String, String>() .put("name", "Bob") .put("age", "25") .build(); this.testRestTemplate.postForObject( "/createPerson?name={name}&age={age}", null, String.class, params); await().atMost(Duration.TEN_SECONDS).untilAsserted(() -> { ResponseEntity<List<Person>> response = this.testRestTemplate.exchange( "/listPersons", HttpMethod.GET, null, new ParameterizedTypeReference<List<Person>>() { }); assertThat(response.getBody()).containsExactly(new Person("Bob", 25)); }); }
Example #10
Source File: VaultTokenRenewalAutoConfigurationTest.java From spring-cloud-services-starters with Apache License 2.0 | 6 votes |
@Test public void scheduledVaultTokenRefresh() { contextRunner.withPropertyValues("spring.cloud.config.token=footoken", "vault.token.renew.rate=1000", "spring.cloud.config.client.oauth2.clientId=" + CLIENT_ID, "spring.cloud.config.client.oauth2.clientSecret=" + CLIENT_SECRET, "spring.cloud.config.client.oauth2.accessTokenUri=" + TOKEN_URI).run(context -> { RestTemplate restTemplate = context.getBean("mockRestTemplate", RestTemplate.class); await().atMost(Duration.FIVE_SECONDS).untilAsserted(() -> { verify(restTemplate, atLeast(4)).postForObject(anyString(), any(HttpEntity.class), any()); assertThat(restTemplate.getInterceptors()).hasSize(1); assertThat(restTemplate.getInterceptors().get(0)) .isInstanceOf(OAuth2AuthorizedClientHttpRequestInterceptor.class); OAuth2AuthorizedClientHttpRequestInterceptor interceptor = (OAuth2AuthorizedClientHttpRequestInterceptor) restTemplate .getInterceptors().get(0); ClientRegistration clientRegistration = interceptor.clientRegistration; assertThat(clientRegistration.getClientId()).isEqualTo(CLIENT_ID); assertThat(clientRegistration.getClientSecret()).isEqualTo(CLIENT_SECRET); assertThat(clientRegistration.getProviderDetails().getTokenUri()).isEqualTo(TOKEN_URI); assertThat(clientRegistration.getAuthorizationGrantType()) .isEqualTo(AuthorizationGrantType.CLIENT_CREDENTIALS); }); }); }
Example #11
Source File: TestStandalonePipelineManager.java From datacollector with Apache License 2.0 | 6 votes |
@Test public void testExpiry() throws Exception { pipelineStoreTask.create("user", "aaaa", "label","blah", false, false, new HashMap<String, Object>()); Runner runner = pipelineManager.getRunner("aaaa", "0"); pipelineStateStore.saveState("user", "aaaa", "0", PipelineStatus.RUNNING_ERROR, "blah", null, ExecutionMode.STANDALONE, null, 0, 0); assertEquals(PipelineStatus.RUNNING_ERROR, runner.getState().getStatus()); pipelineStateStore.saveState("user", "aaaa", "0", PipelineStatus.RUN_ERROR, "blah", null, ExecutionMode.STANDALONE, null, 0, 0); pipelineManager.stop(); pipelineStoreTask.stop(); pipelineStateStore.saveState("user", "aaaa", "0", PipelineStatus.RUNNING_ERROR, "blah", null, ExecutionMode .STANDALONE, null, 0, 0); pipelineManager = null; setUpManager(100, 0, false, false); await().atMost(Duration.FIVE_SECONDS).until(new Callable<Boolean>() { @Override public Boolean call() throws Exception { return !((StandaloneAndClusterPipelineManager) pipelineManager).isRunnerPresent("aaaa", "0"); } }); }
Example #12
Source File: DistributedTaskManagerTest.java From james-project with Apache License 2.0 | 6 votes |
@Test void givenTwoTaskManagerAndATaskRanPerTaskManagerListingThemOnEachShouldShowBothTasks() { try (EventSourcingTaskManager taskManager1 = taskManager(); EventSourcingTaskManager taskManager2 = taskManager(HOSTNAME_2)) { TaskId taskId1 = taskManager1.submit(new CompletedTask()); TaskId taskId2 = taskManager2.submit(new CompletedTask()); Awaitility.await() .atMost(Duration.ONE_SECOND) .pollInterval(100L, TimeUnit.MILLISECONDS) .untilAsserted(() -> { List<TaskExecutionDetails> listOnTaskManager1 = taskManager1.list(); List<TaskExecutionDetails> listOnTaskManager2 = taskManager2.list(); assertThat(listOnTaskManager1) .hasSize(2) .isEqualTo(listOnTaskManager2) .allSatisfy(taskExecutionDetails -> assertThat(taskExecutionDetails.getStatus()).isEqualTo(TaskManager.Status.COMPLETED)) .extracting(TaskExecutionDetails::getTaskId) .containsExactlyInAnyOrder(taskId1, taskId2); }); } }
Example #13
Source File: TrackableTimerTester.java From AILibs with GNU Affero General Public License v3.0 | 6 votes |
@Test public void testInterruptTask() throws InterruptedException { TrackableTimer tt = new TrackableTimer(); Thread t = new Thread() { @Override public void run() { while (!Thread.interrupted()) { Awaitility.await().atLeast(Duration.ONE_HUNDRED_MILLISECONDS); } } }; TrackableTimerTask it = new InterruptionTimerTask("test interrupt", t); tt.schedule(it, 1000); assertFalse(tt.hasTaskBeenExecutedInPast(it)); assertTrue(tt.willTaskBeExecutedInFuture(it)); assertTrue(tt.hasOpenTasks()); /* conduct several tests on execution */ Thread.sleep(1500); assertFalse(it.isCanceled()); assertTrue(tt.hasTaskBeenExecutedInPast(it)); assertFalse(tt.willTaskBeExecutedInFuture(it)); assertFalse(tt.hasOpenTasks()); }
Example #14
Source File: RabbitMQWebAdminServerIntegrationTest.java From james-project with Apache License 2.0 | 6 votes |
@Test void postShouldDoMigrationAndUpdateCurrentVersion() { String taskId = with() .body(String.valueOf(CassandraSchemaVersionManager.MAX_VERSION.getValue())) .post(UPGRADE_VERSION) .jsonPath() .get("taskId"); with() .get("/tasks/" + taskId + "/await") .then() .body("status", is("completed")); Awaitility.await() .atMost(Duration.TEN_SECONDS) .await() .untilAsserted(() -> when() .get(VERSION) .then() .statusCode(HttpStatus.OK_200) .contentType(JSON_CONTENT_TYPE) .body(is("{\"version\":" + CassandraSchemaVersionManager.MAX_VERSION.getValue() + "}"))); }
Example #15
Source File: SqsMessageQueueReceiverEndpointTest.java From synapse with Apache License 2.0 | 6 votes |
@Test public void shouldNotConsumeMessagesDroppedByInterceptor() { // given: addSqsMessagesToQueue(sqsMessage("some of", PAYLOAD_1), sqsMessage("some of", PAYLOAD_2)); interceptorRegistry.register( receiverChannelsWith(message -> message.getPayload().equals(PAYLOAD_1) ? null : message) ); // when: consumption is started sqsQueueReceiver.consume(); // then: // wait some time await() .atMost(Duration.FIVE_SECONDS) .until(() -> messages.size() == 1); // and: // expect the payload to be the added messages assertThat(messages.size(), is(1)); assertThat(messages.get(0).getPayload(), is(PAYLOAD_2)); }
Example #16
Source File: SqsMessageQueueReceiverEndpointTest.java From synapse with Apache License 2.0 | 6 votes |
@Test public void shouldInterceptMessages() { // given: addSqsMessagesToQueue(sqsMessage("some of", PAYLOAD_1)); interceptorRegistry.register( receiverChannelsWith(message -> TextMessage.of(message.getKey(), message.getHeader(), INTERCEPTED_PAYLOAD)) ); // when: consumption is started sqsQueueReceiver.consume(); // then: // wait some time await() .atMost(Duration.FIVE_SECONDS) .until(() -> messages.size() == 1); // and: // expect the payload to be the added messages assertThat(messages.size(), is(1)); assertThat(messages.get(0).getPayload(), is(INTERCEPTED_PAYLOAD)); }
Example #17
Source File: RabbitMQReindexingWithEventDeadLettersTest.java From james-project with Apache License 2.0 | 6 votes |
@BeforeEach void setUp(GuiceJamesServer jamesServer) throws Exception { jamesServer.getProbe(DataProbeImpl.class) .fluent() .addDomain(DOMAIN) .addUser(ALICE.asString(), ALICE_PASSWORD); Port jmapPort = jamesServer.getProbe(JmapGuiceProbe.class).getJmapPort(); RestAssured.requestSpecification = jmapRequestSpecBuilder .setPort(jmapPort.getValue()) .build(); RestAssured.defaultParser = Parser.JSON; webAdminApi = WebAdminUtils.spec(jamesServer.getProbe(WebAdminGuiceProbe.class).getWebAdminPort()); aliceAccessToken = authenticateJamesUser(LocalHostURIBuilder.baseUri(jmapPort), ALICE, ALICE_PASSWORD); dockerElasticSearch.getDockerES().pause(); Thread.sleep(Duration.TEN_SECONDS.getValueInMS()); // Docker pause is asynchronous and we found no way to poll for it }
Example #18
Source File: SqsMessageQueueReceiverEndpointTest.java From synapse with Apache License 2.0 | 6 votes |
@Test public void shouldOnlyConsumeMessagesWithMatchingKey() { // given: addSqsMessagesToQueue( sqsMessage("matching-of", PAYLOAD_1), sqsMessage("matching-of", PAYLOAD_2), sqsMessage("non-matching-of", PAYLOAD_3)); sqsQueueReceiver = new SqsMessageQueueReceiverEndpoint("channelName", new MessageInterceptorRegistry(), sqsAsyncClient, newSingleThreadExecutor(), null); sqsQueueReceiver.register(MessageConsumer.of("matching-of", String.class, (message) -> messages.add(message))); // when: consumption is started sqsQueueReceiver.consume(); // then: // wait some time await() .atMost(Duration.FIVE_SECONDS) .until(() -> messages.size() >= EXPECTED_NUMBER_OF_ENTRIES-1); // and: // expect the payload to be the added messages assertThat(messages.size(), is(2)); assertThat(messages.get(0).getKey(), is(Key.of("matching-of"))); assertThat(messages.get(1).getKey(), is(Key.of("matching-of"))); }
Example #19
Source File: SqsMessageQueueIntegrationTest.java From synapse with Apache License 2.0 | 6 votes |
@Test public void consumeDataFromSqs() { // when writeToStream("users_small1.txt"); // then sqsMessageQueue.consume(); await() .atMost(Duration.FIVE_SECONDS) .until(() -> messages.size() >= EXPECTED_NUMBER_OF_ENTRIES_IN_FIRST_SET); sqsMessageQueue.stop(); assertThat(messages.get(0).getKey(), is(Key.of("some-message-0"))); assertThat(messages.get(0).getHeader().getShardPosition(), is(Optional.empty())); assertThat(messages.get(0).getHeader().get("synapse_msg_key"), is("some-message-0")); }
Example #20
Source File: DistributedTaskManagerTest.java From james-project with Apache License 2.0 | 6 votes |
@Test void givenTwoTaskManagersAndTwoTaskOnlyOneTaskShouldRunAtTheSameTime() { CountDownLatch waitingForFirstTaskLatch = new CountDownLatch(1); try (EventSourcingTaskManager taskManager1 = taskManager(); EventSourcingTaskManager taskManager2 = taskManager(HOSTNAME_2)) { taskManager1.submit(new MemoryReferenceTask(() -> { waitingForFirstTaskLatch.await(); return Task.Result.COMPLETED; })); TaskId waitingTaskId = taskManager1.submit(new CompletedTask()); awaitUntilTaskHasStatus(waitingTaskId, TaskManager.Status.WAITING, taskManager2); waitingForFirstTaskLatch.countDown(); Awaitility.await() .atMost(Duration.ONE_SECOND) .pollInterval(100L, TimeUnit.MILLISECONDS) .until(() -> taskManager1.await(waitingTaskId, TIMEOUT).getStatus() == TaskManager.Status.COMPLETED); } }
Example #21
Source File: ESReporterContract.java From james-project with Apache License 2.0 | 5 votes |
@Test void esMetricReporterShouldProduceDocumentsOnAnElasticsearchContainerWhenRecordingTimeMetric() { TimeMetric metric = new DropWizardMetricFactory(registry).timer("itstime"); TimerTask timerTask = new TimerTask() { @Override public void run() { metric.stopAndPublish(); } }; timer.schedule(timerTask, DELAY_IN_MS, PERIOD_IN_MS); await().atMost(Duration.TEN_MINUTES) .untilAsserted(() -> done()); }
Example #22
Source File: RoadEndpointsIntegrationTest.java From data-highway with Apache License 2.0 | 5 votes |
@Test public void createRoadAndSchemas() throws Exception { // create Road String roadName = "a1"; BasicRoadModel basicRoadModel = new BasicRoadModel(roadName, "a1 road", "a1 team", "[email protected]", true, "", null, Maps.newHashMap()); ResponseEntity<StandardResponse> createRoadResult = rest.exchange(post(uri("/paver/v1/roads")) .header(AUTHORIZATION, "Basic " + Base64.getEncoder().encodeToString("user:pass".getBytes(UTF_8))) .contentType(APPLICATION_JSON_UTF8) .body(basicRoadModel), StandardResponse.class); assertThat(createRoadResult.getStatusCode(), is(HttpStatus.OK)); assertThat(createRoadResult.getBody().getMessage(), is("Request to create road \"a1\" received")); Awaitility.await().atMost(Duration.FIVE_SECONDS).until(() -> { String expected = "{\"documentId\":\"a1\",\"operations\":[{\"op\":\"add\",\"path\":\"\",\"value\":{\"name\":\"a1\",\"topicName\":null,\"description\":\"a1 road\",\"teamName\":\"a1 team\",\"contactEmail\":\"[email protected]\",\"enabled\":true,\"partitionPath\":\"\",\"metadata\":{},\"schemas\":{},\"destinations\":{},\"status\":null,\"compatibilityMode\":\"CAN_READ_ALL\"}}]}"; String actual = readRecords(patchConsumer, 1).get(0); assertJsonEquals(expected, actual); }); // Emulate TollBooth to process the above patch and create road for us. Map<String, Road> kafkaStore = kafkaStore(); Road road = new Road(); road.setName(roadName); kafkaStore.put(roadName, road); // Add schema to road. ResponseEntity<StandardResponse> schemaResult = rest.exchange(post(uri("/paver/v1/roads/a1/schemas")) .header(AUTHORIZATION, "Basic " + Base64.getEncoder().encodeToString("user:pass".getBytes(UTF_8))) .contentType(APPLICATION_JSON_UTF8) .body(schema1.toString()), StandardResponse.class); assertThat(schemaResult.getStatusCode(), is(HttpStatus.OK)); assertThat(schemaResult.getBody().getMessage(), is("Request to add a new schema received.")); Awaitility.await().atMost(Duration.FIVE_SECONDS).until(() -> { List<String> records = readRecords(patchConsumer, 1); String expectedPatch = "{\"documentId\":\"a1\",\"operations\":[{\"op\":\"add\",\"path\":\"/schemas/1\",\"value\":{\"schema\":{\"type\":\"record\",\"name\":\"record\",\"fields\":[{\"name\":\"field\",\"type\":\"boolean\"}]},\"version\":1,\"deleted\":false}}]}"; assertJsonEquals(expectedPatch, records.get(0)); }); }
Example #23
Source File: MetricableBlobStoreContract.java From james-project with Apache License 2.0 | 5 votes |
@Test default void saveBytesShouldPublishSaveBytesTimerMetrics() { BlobStore store = testee(); Mono.from(store.save(store.getDefaultBucketName(), BYTES_CONTENT, LOW_COST)).block(); Mono.from(store.save(store.getDefaultBucketName(), BYTES_CONTENT, LOW_COST)).block(); await().atMost(Duration.FIVE_SECONDS) .untilAsserted(() -> assertThat(metricsTestExtension.getMetricFactory().executionTimesFor(SAVE_BYTES_TIMER_NAME)) .hasSize(2)); }
Example #24
Source File: SpamAssassinContract.java From james-project with Apache License 2.0 | 5 votes |
@Test default void imapCopiesToSpamMailboxShouldBeConsideredAsSpam(GuiceJamesServer jamesServer, SpamAssassinExtension.SpamAssassin spamAssassin) throws Exception { spamAssassin.train(ALICE); AccessToken aliceAccessToken = accessTokenFor(jamesServer, ALICE, ALICE_PASSWORD); AccessToken bobAccessToken = accessTokenFor(jamesServer, BOB, BOB_PASSWORD); // Bob is sending a message to Alice given() .header("Authorization", bobAccessToken.asString()) .body(setMessageCreate(bobAccessToken)) .when() .post("/jmap"); calmlyAwait.atMost(Duration.ONE_MINUTE).untilAsserted(() -> assertMessagesFoundInMailbox(aliceAccessToken, getInboxId(aliceAccessToken), 1)); calmlyAwait.atMost(Duration.ONE_MINUTE).untilAsserted(() -> assertEveryListenerGotCalled(jamesServer)); // Alice is copying this message to Spam -> learning in SpamAssassin try (TestIMAPClient testIMAPClient = new TestIMAPClient()) { testIMAPClient.connect(LOCALHOST_IP, jamesServer.getProbe(ImapGuiceProbe.class).getImapPort()) .login(ALICE, ALICE_PASSWORD) .select(TestIMAPClient.INBOX); testIMAPClient.copyFirstMessage("Spam"); } calmlyAwait.atMost(Duration.ONE_MINUTE).untilAsserted(() -> assertMessagesFoundInMailbox(aliceAccessToken, getSpamId(aliceAccessToken), 1)); // Bob is sending again the same message to Alice given() .header("Authorization", bobAccessToken.asString()) .body(setMessageCreate(bobAccessToken)) .when() .post("/jmap"); // This message is delivered in Alice Spam mailbox (she now must have 2 messages in her Spam mailbox) calmlyAwait.atMost(Duration.ONE_MINUTE).untilAsserted(() -> assertMessagesFoundInMailbox(aliceAccessToken, getSpamId(aliceAccessToken), 2)); }
Example #25
Source File: MetricableBlobStoreContract.java From james-project with Apache License 2.0 | 5 votes |
@Test default void readBytesShouldPublishReadBytesTimerMetrics() { BlobStore store = testee(); BlobId blobId = Mono.from(store.save(store.getDefaultBucketName(), BYTES_CONTENT, LOW_COST)).block(); Mono.from(store.readBytes(store.getDefaultBucketName(), blobId)).block(); Mono.from(store.readBytes(store.getDefaultBucketName(), blobId)).block(); await().atMost(Duration.FIVE_SECONDS) .untilAsserted(() -> assertThat(metricsTestExtension.getMetricFactory().executionTimesFor(READ_BYTES_TIMER_NAME)) .hasSize(2)); }
Example #26
Source File: KinesisSourceIT.java From datacollector with Apache License 2.0 | 5 votes |
@Test public void testConsume() throws Exception { KinesisConsumerConfigBean config = getKinesisConsumerConfig(streamName); final Map<String, String> lastSourceOffsets = new HashMap<>(); for (int i = 0; i < 2; i++) { KinesisSource kinesisSource = new KinesisSource(config); PushSourceRunner runner = new PushSourceRunner.Builder(KinesisDSource.class, kinesisSource).addOutputLane("lane") .setOnRecordError(OnRecordError.TO_ERROR) .build(); runner.runInit(); kinesisSource.setDynamoDBClient(getDynamoDBClient()); kinesisSource.setMetricsFactory(new NullMetricsFactory()); final List<Record> records = new ArrayList<>(numRecords); final AtomicBoolean isDone = new AtomicBoolean(false); try { runner.runProduce(lastSourceOffsets, 5, output -> { records.addAll(output.getRecords().get("lane")); if (records.size() == numRecords) { isDone.set(true); runner.setStop(); } }); // This stage doesn't produce empty batches, so timeout the test // if it doesn't run to completion in a reasonable amount of time. await().atMost(Duration.TWO_MINUTES).untilTrue(isDone); runner.waitOnProduce(); assertEquals(numErrorRecords, runner.getErrorRecords().size()); } finally { runner.runDestroy(); } assertEquals(numRecords, records.size()); } }
Example #27
Source File: TestWebServerTask.java From datacollector with Apache License 2.0 | 5 votes |
@Test public void testTraceHttpDisabled() throws Exception { RuntimeInfo runtimeInfo = new StandaloneRuntimeInfo( RuntimeInfo.SDC_PRODUCT, RuntimeModule.SDC_PROPERTY_PREFIX, new MetricRegistry(), Collections.emptyList() ) { @Override public String getConfigDir() { return new File("target").getAbsolutePath(); } }; Configuration conf = new Configuration(); StartFlag flag = new StartFlag(); WebServerTask webServerTask = createWebServerTask(runtimeInfo, conf, Collections.<WebAppProvider>emptySet()); webServerTask.addToPostStart(flag::setStarted); try { webServerTask.initTask(); webServerTask.runTask(); await().atMost(Duration.TEN_SECONDS).until(flag.hasStarted()); String url = webServerTask.getHttpUrl(); Response response = ClientBuilder.newClient() .target(url) .request() .trace(); Assert.assertEquals(HttpURLConnection.HTTP_BAD_METHOD, response.getStatus()); } finally { webServerTask.stopTask(); } }
Example #28
Source File: ElasticSearchListeningMessageSearchIndexTest.java From james-project with Apache License 2.0 | 5 votes |
@Test void addShouldPropagateExceptionWhenExceptionOccurs() throws Exception { elasticSearch.getDockerElasticSearch().pause(); Thread.sleep(Duration.FIVE_SECONDS.getValueInMS()); // Docker pause is asynchronous and we found no way to poll for it assertThatThrownBy(() -> testee.add(session, mailbox, MESSAGE_1).block()) .hasCauseInstanceOf(IOException.class); elasticSearch.getDockerElasticSearch().unpause(); }
Example #29
Source File: MetricableBlobStoreContract.java From james-project with Apache License 2.0 | 5 votes |
@Test default void saveStringShouldPublishSaveBytesTimerMetrics() { BlobStore store = testee(); Mono.from(store.save(store.getDefaultBucketName(), STRING_CONTENT, LOW_COST)).block(); Mono.from(store.save(store.getDefaultBucketName(), STRING_CONTENT, LOW_COST)).block(); await().atMost(Duration.FIVE_SECONDS) .untilAsserted(() -> assertThat(metricsTestExtension.getMetricFactory().executionTimesFor(SAVE_BYTES_TIMER_NAME)) .hasSize(2)); }
Example #30
Source File: MetricableBlobStoreContract.java From james-project with Apache License 2.0 | 5 votes |
@Test default void saveInputStreamShouldPublishSaveInputStreamTimerMetrics() { BlobStore store = testee(); Mono.from(store.save(store.getDefaultBucketName(), new ByteArrayInputStream(BYTES_CONTENT), LOW_COST)).block(); Mono.from(store.save(store.getDefaultBucketName(), new ByteArrayInputStream(BYTES_CONTENT), LOW_COST)).block(); await().atMost(Duration.FIVE_SECONDS) .untilAsserted(() -> assertThat(metricsTestExtension.getMetricFactory().executionTimesFor(SAVE_INPUT_STREAM_TIMER_NAME)) .hasSize(2)); }