Java Code Examples for org.awaitility.Duration

The following examples show how to use org.awaitility.Duration. These examples are extracted from open source projects. 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 Project: data-highway   Source File: RoadEndpointsIntegrationTest.java    License: Apache License 2.0 6 votes vote down vote up
@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 2
Source Project: connector-sdk   Source File: TestUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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 3
@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 4
Source Project: synapse   Source File: SqsMessageQueueIntegrationTest.java    License: Apache License 2.0 6 votes vote down vote up
@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 5
@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 6
@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 7
@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 8
@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 9
Source Project: reactor-core   Source File: MonoDetachTest.java    License: Apache License 2.0 6 votes vote down vote up
@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 10
@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 11
@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 12
@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 13
Source Project: james-project   Source File: DistributedTaskManagerTest.java    License: Apache License 2.0 6 votes vote down vote up
@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 14
@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 15
Source Project: james-project   Source File: DistributedTaskManagerTest.java    License: Apache License 2.0 6 votes vote down vote up
@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 16
@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 17
@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 18
Source Project: james-project   Source File: ExternalSession.java    License: Apache License 2.0 6 votes vote down vote up
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 19
Source Project: james-project   Source File: MockSMTPServerTest.java    License: Apache License 2.0 6 votes vote down vote up
@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 20
Source Project: james-project   Source File: ESReporterContract.java    License: Apache License 2.0 6 votes vote down vote up
@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 21
Source Project: data-highway   Source File: RoadEndpointsIntegrationTest.java    License: Apache License 2.0 5 votes vote down vote up
@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 22
Source Project: data-highway   Source File: RoadEndpointsIntegrationTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void updateRoadMetadata() throws Exception {
  String roadName = "updated_road";
  List<PatchOperation> patchOperations = new ArrayList<>();
  patchOperations.add(new PatchOperation(Operation.REPLACE, "/contactEmail", "[email protected]"));
  patchOperations.add(new PatchOperation(Operation.REPLACE, "/description", "desc"));
  patchOperations.add(new PatchOperation(Operation.REPLACE, "/teamName", "team a1"));

  Road road = new Road();
  road.setName(roadName);
  road.setEnabled(true);
  road.setDescription("description2");

  KafkaStore<String, Road> kafkaStore = kafkaStore();
  kafkaStore.put(roadName, road);

  MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
  headers.add("Content-Type", "application/json");

  rest.exchange(put(uri("/paver/v1/roads/updated_road"))
      .header(AUTHORIZATION, "Basic " + Base64.getEncoder().encodeToString("user:pass".getBytes(UTF_8)))
      .header("Content-Type", "application/json-patch+json")
      .body(patchOperations), StandardResponse.class);

  Awaitility.await().atMost(Duration.FIVE_SECONDS).until(() -> {
    String expected = "{\"documentId\":\"updated_road\",\"operations\":[{\"op\":\"replace\",\"path\":\"/contactEmail\",\"value\":\"[email protected]\"},{\"op\":\"replace\",\"path\":\"/description\",\"value\":\"desc\"},{\"op\":\"replace\",\"path\":\"/teamName\",\"value\":\"team a1\"}]}";
    String actual = readRecords(patchConsumer, 1).get(0);
    assertJsonEquals(expected, actual);
  });

}
 
Example 23
Source Project: feign-reactive   Source File: ReactivityTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldRunReactively() throws JsonProcessingException {

  IceCreamOrder orderGenerated = new OrderGenerator().generate(1);
  String orderStr = TestUtils.MAPPER.writeValueAsString(orderGenerated);

  wireMockRule.stubFor(get(urlEqualTo("/icecream/orders/1"))
          .withHeader("Accept", equalTo("application/json"))
          .willReturn(aResponse().withStatus(200)
                  .withHeader("Content-Type", "application/json")
                  .withBody(orderStr)
                  .withFixedDelay(DELAY_IN_MILLIS)));

  IcecreamServiceApi client = builder()
          .target(IcecreamServiceApi.class,
                  "http://localhost:" + wireMockRule.port());

  AtomicInteger counter = new AtomicInteger();

  new Thread(() -> {
    for (int i = 0; i < CALLS_NUMBER; i++) {
      client.findFirstOrder()
              .doOnNext(order -> counter.incrementAndGet())
              .subscribe();
    }
  }).start();

  waitAtMost(new Duration(timeToCompleteReactively(), TimeUnit.MILLISECONDS))
          .until(() -> counter.get() == CALLS_NUMBER);
}
 
Example 24
Source Project: feign-reactive   Source File: ReactivityTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldRunReactively() throws JsonProcessingException {

  IceCreamOrder orderGenerated = new OrderGenerator().generate(1);
  String orderStr = TestUtils.MAPPER.writeValueAsString(orderGenerated);

  wireMockRule.stubFor(get(urlEqualTo("/icecream/orders/1"))
      .withHeader("Accept", equalTo("application/json"))
      .willReturn(aResponse().withStatus(200)
          .withHeader("Content-Type", "application/json")
          .withBody(orderStr)
          .withFixedDelay(DELAY_IN_MILLIS)));

  IcecreamServiceApi client = builder()
      .target(IcecreamServiceApi.class,
          "http://localhost:" + wireMockRule.port());

  AtomicInteger counter = new AtomicInteger();

  new Thread(() -> {
    for (int i = 0; i < CALLS_NUMBER; i++) {
      client.findFirstOrder()
          .doOnSuccess(order -> counter.incrementAndGet())
          .subscribe();
    }
  }).start();

  int timeToCompleteReactively = CALLS_NUMBER * DELAY_IN_MILLIS / REACTIVE_GAIN_RATIO;
  waitAtMost(new Duration(timeToCompleteReactively, TimeUnit.MILLISECONDS))
      .until(() -> counter.get() == CALLS_NUMBER);
}
 
Example 25
Source Project: james-project   Source File: MetricableBlobStoreContract.java    License: Apache License 2.0 5 votes vote down vote up
@Test
default void deleteBucketShouldPublishDeleteBucketTimerMetrics() {
    BlobStore store = testee();

    BucketName bucketName = BucketName.of("custom");
    Mono.from(store.save(BucketName.DEFAULT, BYTES_CONTENT, LOW_COST)).block();
    Mono.from(store.save(bucketName, BYTES_CONTENT, LOW_COST)).block();

    Mono.from(store.deleteBucket(bucketName)).block();

    await().atMost(Duration.FIVE_SECONDS)
        .untilAsserted(() ->  assertThat(metricsTestExtension.getMetricFactory().executionTimesFor(DELETE_BUCKET_TIMER_NAME))
            .hasSize(1));
}
 
Example 26
Source Project: feign-reactive   Source File: ReactivityTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldRunReactively() throws JsonProcessingException {

  IceCreamOrder orderGenerated = new OrderGenerator().generate(1);
  String orderStr = TestUtils.MAPPER.writeValueAsString(orderGenerated);

  wireMockRule.stubFor(get(urlEqualTo("/icecream/orders/1"))
      .withHeader("Accept", equalTo("application/json"))
      .willReturn(aResponse().withStatus(200)
          .withHeader("Content-Type", "application/json")
          .withBody(orderStr)
          .withFixedDelay(DELAY_IN_MILLIS)));

  IcecreamServiceApi client = builder()
      .target(IcecreamServiceApi.class,
          "http://localhost:" + wireMockRule.port());

  AtomicInteger counter = new AtomicInteger();

  new Thread(() -> {
    for (int i = 0; i < CALLS_NUMBER; i++) {
      client.findFirstOrder()
          .doOnNext(order -> counter.incrementAndGet())
          .subscribe();
    }
  }).start();

  int timeToCompleteReactively = CALLS_NUMBER * DELAY_IN_MILLIS / REACTIVE_GAIN_RATIO;
  waitAtMost(new Duration(timeToCompleteReactively, TimeUnit.MILLISECONDS))
      .until(() -> counter.get() == CALLS_NUMBER);
}
 
Example 27
@Test
public void GrpcContextPropagatesAcrossSchedulers() {
    final Context.Key<String> contextKey = Context.key("key");

    final AtomicBoolean done = new AtomicBoolean();

    Context.current().withValue(contextKey, "foo").wrap(new Runnable() {
        @Override
        public void run() {
            Observable.just(1, 2, 3)
                    .observeOn(Schedulers.computation())
                    .subscribeOn(Schedulers.io())
                    .subscribe(
                            new Consumer<Integer>() {
                                @Override
                                public void accept(Integer i) throws Exception {
                                    System.out.println(i);
                                    assertThat(contextKey.get()).isEqualTo("foo");
                                }
                            },
                            new Consumer<Throwable>() {
                                @Override
                                public void accept(Throwable throwable) throws Exception {

                                }
                            },
                            new Action() {
                                @Override
                                public void run() throws Exception {
                                    done.set(true);
                                }
                            });
        }
    }).run();

    await().atMost(Duration.FIVE_HUNDRED_MILLISECONDS).untilTrue(done);
}
 
Example 28
@Test
public void contextTransfersOneHopAsync() throws Exception {
    Metadata.Key<String> ctxKey = Metadata.Key.of("ctx-context-key", Metadata.ASCII_STRING_MARSHALLER);
    String expectedCtxValue = "context-value";
    AtomicReference<String> ctxValue = new AtomicReference<>();

    // Service
    GreeterGrpc.GreeterImplBase svc = new GreeterGrpc.GreeterImplBase() {
        @Override
        public void sayHello(HelloRequest request, StreamObserver<HelloResponse> responseObserver) {
            ctxValue.set(AmbientContext.current().get(ctxKey));
            responseObserver.onNext(HelloResponse.newBuilder().setMessage("Hello " + request.getName()).build());
            responseObserver.onCompleted();
        }
    };

    // Plumbing
    serverRule1.getServiceRegistry().addService(ServerInterceptors
            .intercept(svc, new AmbientContextServerInterceptor("ctx-")));
    GreeterGrpc.GreeterFutureStub stub = GreeterGrpc
            .newFutureStub(serverRule1.getChannel())
            .withInterceptors(new AmbientContextClientInterceptor("ctx-"));

    // Test
    AmbientContext.initialize(Context.current()).run(() -> {
        AmbientContext.current().put(ctxKey, expectedCtxValue);
        ListenableFuture<HelloResponse> futureResponse = stub.sayHello(HelloRequest.newBuilder().setName("world").build());

        // Verify response callbacks still have context
        MoreFutures.onSuccess(
                futureResponse,
                response -> assertThat(AmbientContext.current().get(ctxKey)).isEqualTo(expectedCtxValue),
                Context.currentContextExecutor(Executors.newSingleThreadExecutor()));

        await().atMost(Duration.ONE_SECOND).until(futureResponse::isDone);
    });

    assertThat(ctxValue.get()).isEqualTo(expectedCtxValue);
}
 
Example 29
@Test
public void testPubSubTemplatePull() {
	pubSubTest((PubSubTemplate pubSubTemplate, String subscriptionName, String topicName) -> {

		pubSubTemplate.publish(topicName, "message");
		Logger logger = new Logger();
		await().atMost(Duration.TEN_SECONDS).untilAsserted(() -> {
			// tag::pull[]
			int maxMessages = 10;
			boolean returnImmediately = false;
			List<AcknowledgeablePubsubMessage> messages = pubSubTemplate.pull(subscriptionName, maxMessages,
					returnImmediately);
			// end::pull[]

			assertThat(messages).hasSize(1);

			// tag::pull[]

			//acknowledge the messages
			pubSubTemplate.ack(messages);

			messages.forEach(message -> logger.info(message.getPubsubMessage().getData().toStringUtf8()));

			// end::pull[]

			assertThat(logger.getMessages()).containsExactly("message");

		});

	});
}
 
Example 30
@Test
public void testPubSubTemplateLoadsMessageConverter() {
	pubSubTest((PubSubTemplate pubSubTemplate, String subscriptionName, String topicName) -> {
		// tag::json_publish[]
		TestUser user = new TestUser();
		user.setUsername("John");
		user.setPassword("password");
		pubSubTemplate.publish(topicName, user);
		// end::json_publish[]

		await().atMost(Duration.TEN_SECONDS).untilAsserted(() -> {
			// tag::json_pull[]
			int maxMessages = 1;
			boolean returnImmediately = false;
			List<ConvertedAcknowledgeablePubsubMessage<TestUser>> messages = pubSubTemplate.pullAndConvert(
					subscriptionName, maxMessages, returnImmediately, TestUser.class);
			// end::json_pull[]

			assertThat(messages).hasSize(1);

			// tag::json_pull[]

			ConvertedAcknowledgeablePubsubMessage<TestUser> message = messages.get(0);

			//acknowledge the message
			message.ack();

			TestUser receivedTestUser = message.getPayload();
			// end::json_pull[]

			assertThat(receivedTestUser.username).isEqualTo("John");
			assertThat(receivedTestUser.password).isEqualTo("password");
		});

	}, JsonPayloadTestConfiguration.class);
}