Java Code Examples for io.vertx.junit5.VertxTestContext#completeNow()

The following examples show how to use io.vertx.junit5.VertxTestContext#completeNow() . 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: HonoConnectionImplTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that the client tries to connect a limited
 * number of times only.
 *
 * @param ctx The vert.x test client.
 */
@Test
public void testConnectFailsAfterMaxConnectionAttempts(final VertxTestContext ctx) {

    // GIVEN a client that is configured to reconnect
    // two times before failing
    props.setReconnectAttempts(2);
    props.setConnectTimeout(10);
    // expect three unsuccessful connection attempts
    connectionFactory = new DisconnectHandlerProvidingConnectionFactory(con)
            .setExpectedFailingConnectionAttempts(3);
    honoConnection = new HonoConnectionImpl(vertx, connectionFactory, props);

    // WHEN the client tries to connect
    honoConnection.connect().onComplete(ctx.failing(t -> {
        // THEN the connection attempt fails
        ctx.verify(() -> assertThat(((ServerErrorException) t).getErrorCode()).isEqualTo(HttpURLConnection.HTTP_UNAVAILABLE));
    }));
    // and the client has indeed tried three times in total before giving up
    ctx.verify(() -> assertThat(connectionFactory.awaitFailure()).isTrue());
    ctx.completeNow();
}
 
Example 2
Source File: PlatformFeaturesAvailabilityTest.java    From strimzi-kafka-operator with Apache License 2.0 6 votes vote down vote up
@Test
public void versionInfoFromMap(VertxTestContext context) throws ParseException {
    String version =  "major=1\n" +
            "minor=16\n" +
            "gitVersion=v1.16.2\n" +
            "gitCommit=c97fe5036ef3df2967d086711e6c0c405941e14b\n" +
            "gitTreeState=clean\n" +
            "buildDate=2019-10-15T19:09:08Z\n" +
            "goVersion=go1.12.10\n" +
            "compiler=gc\n" +
            "platform=linux/amd64";

    VersionInfo vi = new VersionInfo(Util.parseMap(version));

    context.verify(() -> {
        assertThat(vi.getMajor(), is("1"));
        assertThat(vi.getMinor(), is("16"));
    });
    context.completeNow();
}
 
Example 3
Source File: ConsumerTest.java    From strimzi-kafka-bridge with Apache License 2.0 6 votes vote down vote up
@Test
void createConsumerWithGeneratedName(VertxTestContext context) throws InterruptedException, ExecutionException, TimeoutException {
    JsonObject json = new JsonObject();
    AtomicReference<String> name = new AtomicReference<>();

    CompletableFuture<Boolean> create = new CompletableFuture<>();
    consumerService()
        .createConsumerRequest(groupId, json)
            .as(BodyCodec.jsonObject())
            .sendJsonObject(json, ar -> {
                context.verify(() -> {
                    assertThat(ar.succeeded(), is(true));
                    HttpResponse<JsonObject> response = ar.result();
                    assertThat(response.statusCode(), is(HttpResponseStatus.OK.code()));
                    JsonObject bridgeResponse = response.body();
                    String consumerInstanceId = bridgeResponse.getString("instance_id");
                    name.set(consumerInstanceId);
                    assertThat(consumerInstanceId.startsWith(config.get(BridgeConfig.BRIDGE_ID).toString()), is(true));
                    create.complete(true);
                });
            });
    create.get(TEST_TIMEOUT, TimeUnit.SECONDS);
    consumerService()
        .deleteConsumer(context, groupId, name.get());
    context.completeNow();
}
 
Example 4
Source File: ConsumerTest.java    From strimzi-kafka-bridge with Apache License 2.0 5 votes vote down vote up
@Test
void createConsumer(VertxTestContext context) throws InterruptedException, TimeoutException, ExecutionException {
    // create consumer
    consumerService().createConsumer(context, groupId, consumerWithEarliestReset);

    context.completeNow();
    assertThat(context.awaitCompletion(TEST_TIMEOUT, TimeUnit.SECONDS), is(true));
    consumerService()
        .deleteConsumer(context, groupId, name);
}
 
Example 5
Source File: ConsumerTest.java    From strimzi-kafka-bridge with Apache License 2.0 5 votes vote down vote up
@Test
void createConsumerWithInvalidFormat(VertxTestContext context) throws InterruptedException, ExecutionException, TimeoutException {
    CompletableFuture<Boolean> create = new CompletableFuture<>();

    JsonObject requestHeader = new JsonObject();
    requestHeader.put("name", name);

    LOGGER.info("Adding invalid value 'biary' to 'format' property configuration to invoke |422| status code");

    requestHeader.put("format", "biary");

    consumerService()
            .createConsumerRequest(groupId, requestHeader)
            .as(BodyCodec.jsonObject())
            .sendJsonObject(requestHeader, ar -> {
                context.verify(() -> {
                    assertThat(ar.succeeded(), is(true));
                    HttpResponse<JsonObject> response = ar.result();
                    assertThat("Response status code is not '422'", response.statusCode(), is(HttpResponseStatus.UNPROCESSABLE_ENTITY.code()));
                    HttpBridgeError error = HttpBridgeError.fromJson(response.body());
                    assertThat("Response status code is not '422'", HttpResponseStatus.UNPROCESSABLE_ENTITY.code(), is(error.getCode()));
                    LOGGER.info("This is message -> " + error.getMessage());
                    assertThat("Body message doesn't contain 'Invalid format type.'", error.getMessage(), equalTo("Invalid format type."));
                });
                create.complete(true);
            });
    create.get(TEST_TIMEOUT, TimeUnit.SECONDS);
    context.completeNow();
}
 
Example 6
Source File: ConsumerTest.java    From strimzi-kafka-bridge with Apache License 2.0 5 votes vote down vote up
@DisabledIfEnvironmentVariable(named = "BRIDGE_EXTERNAL_ENV", matches = "((?i)FALSE(?-i))")
@Test
void createConsumerEmptyBody(VertxTestContext context) throws InterruptedException, TimeoutException, ExecutionException {
    AtomicReference<String> name = new AtomicReference<>();
    // create consumer
    CompletableFuture<Boolean> create = new CompletableFuture<>();
    consumerService().createConsumerRequest(groupId, null)
            .send(ar -> {
                context.verify(() -> {
                    assertThat(ar.succeeded(), is(true));
                    HttpResponse<JsonObject> response = ar.result();
                    assertThat(response.statusCode(), is(HttpResponseStatus.OK.code()));
                    JsonObject bridgeResponse = response.body();
                    String consumerInstanceId = bridgeResponse.getString("instance_id");
                    name.set(consumerInstanceId);
                    String consumerBaseUri = bridgeResponse.getString("base_uri");
                    assertThat(consumerInstanceId.startsWith(config.get(BridgeConfig.BRIDGE_ID).toString()), is(true));
                    assertThat(consumerBaseUri, is(Urls.consumerInstance(groupId, consumerInstanceId)));
                });
                create.complete(true);
            });

    create.get(TEST_TIMEOUT, TimeUnit.SECONDS);
    consumerService()
        .deleteConsumer(context, groupId, name.get());
    context.completeNow();
    assertThat(context.awaitCompletion(TEST_TIMEOUT, TimeUnit.SECONDS), is(true));
}
 
Example 7
Source File: SimpleAclOperatorIT.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
@Test
public void testNoAclRules(VertxTestContext context) {
    Set<SimpleAclRule> acls = simpleAclOperator.getAcls("no-acls-user");
    context.verify(() -> {
        assertThat(acls, IsEmptyCollection.empty());
    });
    context.completeNow();
}
 
Example 8
Source File: HonoConnectionImplTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Verifies that the delay between reconnect attempts conforms
 * to how it is configured in the ClientConfigProperties.
 *
 * @param ctx The vert.x test client.
 */
@Test
public void testReconnectDelay(final VertxTestContext ctx) {

    // GIVEN a client that is configured to reconnect 5 times with custom delay times.
    final int reconnectAttempts = 5;
    props.setReconnectAttempts(reconnectAttempts);
    props.setReconnectMinDelay(10);
    props.setReconnectMaxDelay(1000);
    props.setReconnectDelayIncrement(100);
    props.setConnectTimeout(10);
    // expect 6 unsuccessful connection attempts
    connectionFactory = new DisconnectHandlerProvidingConnectionFactory(con)
            .setExpectedFailingConnectionAttempts(reconnectAttempts + 1);
    honoConnection = new HonoConnectionImpl(vertx, connectionFactory, props);

    // WHEN the client tries to connect
    honoConnection.connect().onComplete(ctx.failing(t -> {
        // THEN the connection attempt fails
        ctx.verify(() -> assertThat(((ServerErrorException) t).getErrorCode()).isEqualTo(HttpURLConnection.HTTP_UNAVAILABLE));
    }));
    // and the client has indeed tried 6 times in total before giving up
    ctx.verify(() -> {
        assertThat(connectionFactory.awaitFailure()).isTrue();
        final ArgumentCaptor<Long> delayValueCaptor = ArgumentCaptor.forClass(Long.class);
        verify(vertx, times(reconnectAttempts)).setTimer(delayValueCaptor.capture(), VertxMockSupport.anyHandler());
        // and the first delay period is the minDelay value
        assertThat(delayValueCaptor.getAllValues().get(0)).isEqualTo(10L);
    });
    ctx.completeNow();
}
 
Example 9
Source File: ConsumerTest.java    From strimzi-kafka-bridge with Apache License 2.0 5 votes vote down vote up
@Test
void createConsumerWithForwardedPathHeader(VertxTestContext context) throws InterruptedException, TimeoutException, ExecutionException {
    // this test emulates a create consumer request coming from an API gateway/proxy
    String forwarded = "host=my-api-gateway-host:443;proto=https";
    String xForwardedPath = "/my-bridge/consumers/" + groupId;

    String baseUri = "https://my-api-gateway-host:443/my-bridge/consumers/" + groupId + "/instances/" + name;

    CompletableFuture<Boolean> create = new CompletableFuture<>();
    consumerService().createConsumerRequest(groupId, consumerWithEarliestReset)
            .putHeader(FORWARDED, forwarded)
            .putHeader("X-Forwarded-Path", xForwardedPath)
            .sendJsonObject(consumerWithEarliestReset, ar -> {
                context.verify(() -> {
                    assertThat(ar.succeeded(), is(true));
                    HttpResponse<JsonObject> response = ar.result();
                    assertThat(response.statusCode(), is(HttpResponseStatus.OK.code()));
                    JsonObject bridgeResponse = response.body();
                    String consumerInstanceId = bridgeResponse.getString("instance_id");
                    String consumerBaseUri = bridgeResponse.getString("base_uri");
                    assertThat(consumerInstanceId, is(name));
                    assertThat(consumerBaseUri, is(baseUri));
                });
                create.complete(true);
            });

    create.get(TEST_TIMEOUT, TimeUnit.SECONDS);
    consumerService()
        .deleteConsumer(context, groupId, name);
    context.completeNow();
    assertThat(context.awaitCompletion(TEST_TIMEOUT, TimeUnit.SECONDS), is(true));
}
 
Example 10
Source File: ConsumerGeneratedNameTest.java    From strimzi-kafka-bridge with Apache License 2.0 5 votes vote down vote up
@Test
void createConsumerNameIsNotSetAndBridgeIdNotSet(VertxTestContext context) throws InterruptedException, ExecutionException, TimeoutException {
    JsonObject json = new JsonObject();

    CompletableFuture<Boolean> create = new CompletableFuture<>();
    consumerService()
        .createConsumerRequest(groupId, json)
            .as(BodyCodec.jsonObject())
            .sendJsonObject(json, ar -> {
                context.verify(() -> {
                    LOGGER.info("Verifying that consumer name is created with 'kafka-bridge-consumer-' plus random hashcode");
                    assertThat(ar.succeeded(), is(true));
                    HttpResponse<JsonObject> response = ar.result();
                    LOGGER.info("Response code from the Bridge is " + response.statusCode());
                    assertThat(response.statusCode(), is(HttpResponseStatus.OK.code()));
                    JsonObject bridgeResponse = response.body();
                    consumerInstanceId = bridgeResponse.getString("instance_id");
                    LOGGER.info("Consumer instance of the consumer is " + consumerInstanceId);
                    assertThat(consumerInstanceId.startsWith("kafka-bridge-consumer-"), is(true));
                    create.complete(true);
                });
            });
    create.get(TEST_TIMEOUT, TimeUnit.SECONDS);
    consumerService()
        .deleteConsumer(context, groupId, consumerInstanceId);
    context.completeNow();
}
 
Example 11
Source File: ConsumerTest.java    From strimzi-kafka-bridge with Apache License 2.0 5 votes vote down vote up
@Test
void createConsumerWithWrongEnableAutoCommit(VertxTestContext context) throws InterruptedException, TimeoutException, ExecutionException {
    checkCreatingConsumer("enable.auto.commit", "foo", HttpResponseStatus.BAD_REQUEST,
            "Validation error on: body.enable.auto.commit - $.enable.auto.commit: string found, boolean expected", context);

    context.completeNow();
    assertThat(context.awaitCompletion(TEST_TIMEOUT, TimeUnit.SECONDS), is(true));
}
 
Example 12
Source File: KafkaRebalanceStateMachineTest.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
private static void checkOptimizationResults(AsyncResult<KafkaRebalanceStatus> result, VertxTestContext context, boolean shouldBeEmpty) {
    if (result.succeeded()) {
        assertEquals(shouldBeEmpty, result.result().getOptimizationResult().isEmpty());
        context.completeNow();
    } else {
        context.failNow(result.cause());
    }
}
 
Example 13
Source File: AmqpBridgeTest.java    From strimzi-kafka-bridge with Apache License 2.0 5 votes vote down vote up
@Disabled
@Test
void rawMessageConverterNullKeyTest(VertxTestContext context) {
    MessageConverter rawMessageConverter = new AmqpRawMessageConverter();
    context.verify(() -> assertThat(convertedMessageWithNullKey(rawMessageConverter), nullValue()));
    context.completeNow();
}
 
Example 14
Source File: CommandAndControlAmqpIT.java    From hono with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Verifies that the adapter forwards the <em>released</em> disposition back to the
 * application if the device hasn't sent a disposition update for the delivery of
 * the command message sent to the device.
 *
 * @param ctx The vert.x test context.
 * @throws InterruptedException if not all commands and responses are exchanged in time.
 */
@Test
@Timeout(timeUnit = TimeUnit.SECONDS, value = 10)
public void testSendCommandFailsForCommandNotAcknowledgedByDevice(
        final VertxTestContext ctx) throws InterruptedException {

    final AmqpCommandEndpointConfiguration endpointConfig = new AmqpCommandEndpointConfiguration(SubscriberRole.DEVICE);
    final String commandTargetDeviceId = endpointConfig.isSubscribeAsGateway()
            ? helper.setupGatewayDeviceBlocking(tenantId, deviceId, 5)
            : deviceId;

    final AtomicInteger receivedMessagesCounter = new AtomicInteger(0);
    // command handler won't send a disposition update
    connectAndSubscribe(ctx, commandTargetDeviceId, endpointConfig,
            (cmdReceiver, cmdResponseSender) -> createNotSendingDeliveryUpdateCommandConsumer(ctx, cmdReceiver, receivedMessagesCounter));

    final int totalNoOfCommandsToSend = 2;
    final CountDownLatch commandsFailed = new CountDownLatch(totalNoOfCommandsToSend);
    final AtomicInteger commandsSent = new AtomicInteger(0);
    final AtomicLong lastReceivedTimestamp = new AtomicLong();
    final long start = System.currentTimeMillis();

    final VertxTestContext commandClientCreation = new VertxTestContext();
    final Future<CommandClient> commandClient = helper.applicationClientFactory.getOrCreateCommandClient(tenantId, "test-client")
            .onSuccess(c -> c.setRequestTimeout(1300)) // have to wait more than AmqpAdapterProperties.DEFAULT_SEND_MESSAGE_TO_DEVICE_TIMEOUT (1000ms) for the first command message
            .onComplete(commandClientCreation.completing());

    assertThat(commandClientCreation.awaitCompletion(5, TimeUnit.SECONDS)).isTrue();
    if (commandClientCreation.failed()) {
        ctx.failNow(commandClientCreation.causeOfFailure());
    }

    while (commandsSent.get() < totalNoOfCommandsToSend) {
        final CountDownLatch commandSent = new CountDownLatch(1);
        context.runOnContext(go -> {
            final Buffer msg = Buffer.buffer("value: " + commandsSent.getAndIncrement());
            final Future<BufferResult> sendCmdFuture = commandClient.result().sendCommand(commandTargetDeviceId, "setValue", "text/plain",
                    msg, null);
            sendCmdFuture.onComplete(sendAttempt -> {
                if (sendAttempt.succeeded()) {
                    log.debug("sending command {} succeeded unexpectedly", commandsSent.get());
                } else {
                    if (sendAttempt.cause() instanceof ServerErrorException
                            && ((ServerErrorException) sendAttempt.cause()).getErrorCode() == HttpURLConnection.HTTP_UNAVAILABLE) {
                        log.debug("sending command {} failed as expected: {}", commandsSent.get(),
                                sendAttempt.cause().toString());
                        lastReceivedTimestamp.set(System.currentTimeMillis());
                        commandsFailed.countDown();
                        if (commandsFailed.getCount() % 20 == 0) {
                            log.info("commands failed as expected: {}",
                                    totalNoOfCommandsToSend - commandsFailed.getCount());
                        }
                    } else {
                        log.debug("sending command {} failed with an unexpected error", commandsSent.get(),
                                sendAttempt.cause());
                    }
                }
                if (commandsSent.get() % 20 == 0) {
                    log.info("commands sent: " + commandsSent.get());
                }
                commandSent.countDown();
            });
        });

        commandSent.await();
    }

    // have to wait more than AmqpAdapterProperties.DEFAULT_SEND_MESSAGE_TO_DEVICE_TIMEOUT (1000ms) for each command message
    final long timeToWait = 300 + (totalNoOfCommandsToSend * 1300);
    if (!commandsFailed.await(timeToWait, TimeUnit.MILLISECONDS)) {
        log.info("Timeout of {} milliseconds reached, stop waiting for commands", timeToWait);
    }
    assertThat(receivedMessagesCounter.get()).isEqualTo(totalNoOfCommandsToSend);
    final long commandsCompleted = totalNoOfCommandsToSend - commandsFailed.getCount();
    log.info("commands sent: {}, commands failed: {} after {} milliseconds",
            commandsSent.get(), commandsCompleted, lastReceivedTimestamp.get() - start);
    if (commandsCompleted == commandsSent.get()) {
        ctx.completeNow();
    } else {
        ctx.failNow(new IllegalStateException("did not complete all commands sent"));
    }
}
 
Example 15
Source File: BaseRouterFactoryTest.java    From vertx-web with Apache License 2.0 4 votes vote down vote up
@AfterEach
public void tearDown(VertxTestContext testContext) {
  if (client != null) client.close();
  if (server != null) server.close(testContext.completing());
  else testContext.completeNow();
}
 
Example 16
Source File: ConsumerTest.java    From strimzi-kafka-bridge with Apache License 2.0 4 votes vote down vote up
@Test
void tryReceiveNotValidJsonMessage(VertxTestContext context) throws InterruptedException, ExecutionException, TimeoutException {
    String topic = "tryReceiveNotValidJsonMessage";
    kafkaCluster.createTopic(topic, 1, 1);

    String sentBody = "Simple message";
    // send a simple String which is not JSON encoded
    kafkaCluster.produceStrings(topic, sentBody, 1, 0);

    JsonArray topics = new JsonArray();
    topics.add(topic);

    JsonObject topicsRoot = new JsonObject();
    topicsRoot.put("topics", topics);

    // create topic
    // subscribe to a topic
    consumerService()
        .createConsumer(context, groupId, consumerJson)
        .subscribeConsumer(context, groupId, name, topicsRoot);

    CompletableFuture<Boolean> consume = new CompletableFuture<>();
    // consume records
    consumerService()
        .consumeRecordsRequest(groupId, name, BridgeContentType.KAFKA_JSON_JSON)
            .as(BodyCodec.jsonObject())
            .send(ar -> {
                context.verify(() -> {
                    assertThat(ar.succeeded(), is(true));
                    HttpResponse<JsonObject> response = ar.result();
                    HttpBridgeError error = HttpBridgeError.fromJson(response.body());
                    assertThat(response.statusCode(), is(HttpResponseStatus.NOT_ACCEPTABLE.code()));
                    assertThat(error.getCode(), is(HttpResponseStatus.NOT_ACCEPTABLE.code()));
                    assertThat(error.getMessage().startsWith("Failed to decode"), is(true));
                });
                consume.complete(true);
            });

    consume.get(TEST_TIMEOUT, TimeUnit.SECONDS);

    // consumer deletion
    consumerService()
        .deleteConsumer(context, groupId, name);

    context.completeNow();
    assertThat(context.awaitCompletion(TEST_TIMEOUT, TimeUnit.SECONDS), is(true));
}
 
Example 17
Source File: AmqpBridgeTest.java    From strimzi-kafka-bridge with Apache License 2.0 4 votes vote down vote up
@Test
void defaultMessageConverterNullKeyTest(VertxTestContext context) {
    MessageConverter defaultMessageConverter = new AmqpDefaultMessageConverter();
    context.verify(() -> assertThat(convertedMessageWithNullKey(defaultMessageConverter), nullValue()));
    context.completeNow();
}
 
Example 18
Source File: LifecycleExampleTest.java    From vertx-junit5 with Apache License 2.0 4 votes vote down vote up
@Test
@DisplayName("A second test")
void bar(Vertx vertx, VertxTestContext testContext) {
  // (...)
  testContext.completeNow();
}
 
Example 19
Source File: AnalyticsTest.java    From vertx-starter with Apache License 2.0 4 votes vote down vote up
@AfterEach
void afterEach(Vertx vertx, VertxTestContext testContext) {
  client.close();
  testContext.completeNow();
}
 
Example 20
Source File: TenantJmsIT.java    From hono with Eclipse Public License 2.0 2 votes vote down vote up
/**
 * Removes all temporary objects from the registry.
 *
 * @param ctx The vert.x test context.
 * @throws InterruptedException if the current thread is interrupted while waiting for the clean up to finish.
 */
@AfterEach
public void cleanUp(final VertxTestContext ctx) throws InterruptedException {
    helper.deleteObjects(ctx);
    ctx.completeNow();
}