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

The following examples show how to use io.vertx.junit5.VertxTestContext#verify() . 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: CoapTestBase.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that a number of messages uploaded to Hono's CoAP adapter
 * can be successfully consumed via the AMQP Messaging Network.
 *
 * @param ctx The test context.
 * @throws InterruptedException if the test fails.
 */
@Test
public void testUploadMessagesAnonymously(final VertxTestContext ctx) throws InterruptedException {

    final Tenant tenant = new Tenant();

    final VertxTestContext setup = new VertxTestContext();
    helper.registry.addDeviceForTenant(tenantId, tenant, deviceId, SECRET)
    .onComplete(setup.completing());
    ctx.verify(() -> assertThat(setup.awaitCompletion(5, TimeUnit.SECONDS)).isTrue());

    final CoapClient client = getCoapClient();
    testUploadMessages(ctx, tenantId,
            () -> warmUp(client, createCoapRequest(Code.PUT, getPutResource(tenantId, deviceId), 0)),
            count -> {
                final Promise<OptionSet> result = Promise.promise();
                final Request request = createCoapRequest(Code.PUT, getPutResource(tenantId, deviceId), count);
                client.advanced(getHandler(result), request);
                return result.future();
            });
}
 
Example 2
Source File: MqttPublishTestBase.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
private void assertMessageProperties(final VertxTestContext ctx, final Message msg) {
    ctx.verify(() -> {
        assertThat(MessageHelper.getDeviceId(msg)).isNotNull();
        assertThat(MessageHelper.getTenantIdAnnotation(msg)).isNotNull();
        assertThat(MessageHelper.getDeviceIdAnnotation(msg)).isNotNull();
        assertThat(MessageHelper.getRegistrationAssertion(msg)).isNull();
        assertThat(msg.getCreationTime()).isGreaterThan(0);
    });
    assertAdditionalMessageProperties(ctx, msg);
}
 
Example 3
Source File: KafkaUpdateTest.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
@Test
public void upgradeMinorToPrevWithEmptyConfig(VertxTestContext context) throws IOException {
    try {
        testUpgradeMinorToPrevMessageFormatConfig(context, emptyMap(), true);
    } catch (UpgradeException e) {
        context.verify(() -> assertThat(e.getCause() instanceof KafkaUpgradeException, is(true)));
        context.verify(() -> assertThat(e.states.isEmpty(), is(true)));
    }
}
 
Example 4
Source File: KafkaConnectorIT.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
private void assertConnectorIsRunning(VertxTestContext context, KubernetesClient client, String namespace, String connectorName) {
    context.verify(() -> {
        KafkaConnector kafkaConnector = Crds.kafkaConnectorOperation(client).inNamespace(namespace).withName(connectorName).get();
        assertThat(kafkaConnector, notNullValue());
        assertThat(kafkaConnector.getStatus(), notNullValue());
        assertThat(kafkaConnector.getStatus().getTasksMax(), is(1));
        assertThat(kafkaConnector.getStatus().getConnectorStatus(), notNullValue());
        assertThat(kafkaConnector.getStatus().getConnectorStatus().get("connector"), instanceOf(Map.class));
        assertThat(((Map) kafkaConnector.getStatus().getConnectorStatus().get("connector")).get("state"), is("RUNNING"));
    });
}
 
Example 5
Source File: CommandAndControlAmqpIT.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
private ProtonMessageHandler createNotSendingDeliveryUpdateCommandConsumer(final VertxTestContext ctx,
        final ProtonReceiver receiver, final AtomicInteger receivedMessagesCounter) {
    return (delivery, msg) -> {
        receivedMessagesCounter.incrementAndGet();
        ctx.verify(() -> {
            assertThat(msg.getReplyTo()).isNotNull();
            assertThat(msg.getSubject()).isNotNull();
            assertThat(msg.getCorrelationId()).isNotNull();
        });
        final String command = msg.getSubject();
        final Object correlationId = msg.getCorrelationId();
        log.debug("received command [name: {}, reply-to: {}, correlation-id: {}]", command, msg.getReplyTo(), correlationId);
        receiver.flow(1);
    };
}
 
Example 6
Source File: CommandAndControlAmqpIT.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
private ProtonMessageHandler createCommandConsumer(final VertxTestContext ctx, final ProtonReceiver cmdReceiver,
        final ProtonSender cmdResponseSender) {

    return (delivery, msg) -> {
        ctx.verify(() -> {
            assertThat(msg.getReplyTo()).isNotNull();
            assertThat(msg.getSubject()).isNotNull();
            assertThat(msg.getCorrelationId()).isNotNull();
        });
        final String command = msg.getSubject();
        final Object correlationId = msg.getCorrelationId();
        log.debug("received command [name: {}, reply-to: {}, correlation-id: {}]", command, msg.getReplyTo(), correlationId);
        ProtonHelper.accepted(delivery, true);
        cmdReceiver.flow(1);
        // send response
        final Message commandResponse = ProtonHelper.message(command + " ok");
        commandResponse.setAddress(msg.getReplyTo());
        commandResponse.setCorrelationId(correlationId);
        commandResponse.setContentType("text/plain");
        MessageHelper.addProperty(commandResponse, MessageHelper.APP_PROPERTY_STATUS, HttpURLConnection.HTTP_OK);
        log.debug("sending response [to: {}, correlation-id: {}]", commandResponse.getAddress(), commandResponse.getCorrelationId());
        cmdResponseSender.send(commandResponse, updatedDelivery -> {
            if (!Accepted.class.isInstance(updatedDelivery.getRemoteState())) {
                log.error("AMQP adapter did not accept command response [remote state: {}]",
                        updatedDelivery.getRemoteState().getClass().getSimpleName());
            }
        });
    };
}
 
Example 7
Source File: KafkaUpdateTest.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
@Test
public void downgradeLatestToPrevWithLatestMessageFormatConfig(VertxTestContext context) throws IOException {
    try {
        testDowngradeLatestToPrevMessageFormatConfig(context, singletonMap(LOG_MESSAGE_FORMAT_VERSION,
                KafkaVersionTestUtils.LATEST_FORMAT_VERSION), true);
        context.failNow(new Throwable());
    } catch (UpgradeException e) {
        context.verify(() -> assertThat(e.getCause() instanceof KafkaUpgradeException, is(true)));
        context.verify(() -> assertThat(e.states.isEmpty(), is(true)));
    }
}
 
Example 8
Source File: KafkaAssemblyOperatorMockTest.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
private void assertVolumes(VertxTestContext context, String statefulSetName, List<Volume> originalVolumes) {
    context.verify(() -> {
        StatefulSet statefulSet = client.apps().statefulSets().inNamespace(NAMESPACE).withName(statefulSetName).get();
        assertThat(statefulSet, is(notNullValue()));
        List<Volume> volumes = statefulSet.getSpec().getTemplate().getSpec().getVolumes();
        assertThat(originalVolumes.size(), is(volumes.size()));
        assertThat(originalVolumes, is(volumes));
    });
}
 
Example 9
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 10
Source File: AbstractVertxBasedMqttProtocolAdapterTest.java    From hono with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Verifies that the adapter does not send a PUBACK package to the device if an event message has not been accepted
 * by the peer.
 *
 * @param ctx The vert.x test context.
 */
@Test
public void testOnUnauthenticatedMessageDoesNotSendPubAckOnFailure(final VertxTestContext ctx) {

    // GIVEN an adapter with a downstream event consumer
    final Promise<ProtonDelivery> outcome = Promise.promise();
    givenAnEventSenderForOutcome(outcome);
    final MqttServer server = getMqttServer(false);
    final AbstractVertxBasedMqttProtocolAdapter<MqttProtocolAdapterProperties> adapter = getAdapter(server);

    // WHEN a device publishes an event
    final Buffer payload = Buffer.buffer("some payload");
    final MqttEndpoint endpoint = mockEndpoint();
    when(endpoint.isConnected()).thenReturn(Boolean.TRUE);
    final MqttPublishMessage messageFromDevice = mock(MqttPublishMessage.class);
    when(messageFromDevice.qosLevel()).thenReturn(MqttQoS.AT_LEAST_ONCE);
    when(messageFromDevice.messageId()).thenReturn(5555555);
    when(messageFromDevice.topicName()).thenReturn("e/tenant/device");
    final MqttContext context = newMqttContext(messageFromDevice, endpoint);

    adapter.uploadEventMessage(context, "my-tenant", "4712", payload).onComplete(ctx.failing());

    // and the peer rejects the message
    outcome.fail(new ClientErrorException(HttpURLConnection.HTTP_BAD_REQUEST));

    ctx.verify(() -> {
        // THEN the device has not received a PUBACK
        verify(endpoint, never()).publishAcknowledge(anyInt());
        // and the message has not been reported as forwarded
        verify(metrics, never()).reportTelemetry(
                any(MetricsTags.EndpointType.class),
                anyString(),
                any(),
                eq(MetricsTags.ProcessingOutcome.FORWARDED),
                any(MetricsTags.QoS.class),
                anyInt(),
                any());
    });
    ctx.completeNow();

}
 
Example 11
Source File: KafkaRebalanceAssemblyOperatorTest.java    From strimzi-kafka-operator with Apache License 2.0 4 votes vote down vote up
private void assertState(VertxTestContext context, KubernetesClient kubernetesClient, String namespace, String resource, KafkaRebalanceAssemblyOperator.State state) {
    context.verify(() -> {
        KafkaRebalance kafkaRebalance = Crds.kafkaRebalanceOperation(kubernetesClient).inNamespace(namespace).withName(resource).get();
        assertState(kafkaRebalance, state);
    });
}
 
Example 12
Source File: PodOperatorTest.java    From strimzi-kafka-operator with Apache License 2.0 4 votes vote down vote up
@Test
public void testCreateReadUpdate(VertxTestContext context) {
    vertx.createSharedWorkerExecutor("kubernetes-ops-pool", 10);
    KubernetesClient client = server.getKubernetesClient();
    PodOperator pr = new PodOperator(vertx, client);

    pr.list(NAMESPACE, Labels.EMPTY);
    context.verify(() -> assertThat(pr.list(NAMESPACE, Labels.EMPTY), is(emptyList())));

    Checkpoint async = context.checkpoint(1);
    pr.createOrUpdate(resource()).onComplete(createResult -> {
        context.verify(() -> assertThat(createResult.succeeded(), is(true)));
        context.verify(() -> assertThat(pr.list(NAMESPACE, Labels.EMPTY).stream()
                    .map(p -> p.getMetadata().getName())
                    .collect(Collectors.toList()), is(singletonList(RESOURCE_NAME))));
        //Pod got = pr.get(NAMESPACE, RESOURCE_NAME);
        //context.assertNotNull(got);
        //context.assertNotNull(got.getMetadata());
        //context.assertEquals(RESOURCE_NAME, got.getMetadata().getName());
        context.verify(() -> assertThat(pr.isReady(NAMESPACE, RESOURCE_NAME), is(false)));
        /*pr.watch(NAMESPACE, RESOURCE_NAME, new Watcher<Pod>() {
            @Override
            public void eventReceived(Action action, Pod resource) {
                if (action == Action.DELETED) {
                    context.assertEquals(RESOURCE_NAME, resource.getMetadata().getName());
                } else {
                    context.fail();
                }
                async.countDown();
            }

            @Override
            public void onClose(KubernetesClientException cause) {

            }
        });*/
        /*Pod modified = resource();
        modified.getSpec().setHostname("bar");
        Async patchAsync = context.async();
        pr.patch(NAMESPACE, RESOURCE_NAME, modified, patchResult -> {
            context.assertTrue(patchResult.succeeded());
            patchAsync.complete();
        });
        patchAsync.await();*/
        pr.reconcile(NAMESPACE, RESOURCE_NAME, null).onComplete(deleteResult -> {
            context.verify(() -> assertThat(deleteResult.succeeded(), is(true)));
            async.flag();
        });

    });
}
 
Example 13
Source File: KafkaConnectS2ICrdOperatorIT.java    From strimzi-kafka-operator with Apache License 2.0 4 votes vote down vote up
@Override
protected void assertReady(VertxTestContext context, KafkaConnectS2I resource) {
    context.verify(() -> assertThat(resource.getStatus()
            .getConditions()
            .get(0), is(READY_CONDITION)));
}
 
Example 14
Source File: MockK8s.java    From strimzi-kafka-operator with Apache License 2.0 4 votes vote down vote up
public void assertNotExists(VertxTestContext context, ResourceName resourceName) {
    context.verify(() -> assertThat(byName.containsKey(resourceName), is(false)));
}
 
Example 15
Source File: KafkaConnectorCrdOperatorIT.java    From strimzi-kafka-operator with Apache License 2.0 4 votes vote down vote up
@Override
protected void assertReady(VertxTestContext context, KafkaConnector resource) {
    context.verify(() -> assertThat(resource.getStatus()
            .getConditions()
            .get(0), is(READY_CONDITION)));
}
 
Example 16
Source File: TopicOperatorTest.java    From strimzi-kafka-operator with Apache License 2.0 4 votes vote down vote up
private <T> void assertSucceeded(VertxTestContext context, AsyncResult<T> ar) {
    if (ar.failed()) {
        ar.cause().printStackTrace();
    }
    context.verify(() -> assertThat(ar.cause() != null ? ar.cause().toString() : "", ar.succeeded(), is(true)));
}
 
Example 17
Source File: MockK8s.java    From strimzi-kafka-operator with Apache License 2.0 4 votes vote down vote up
public void assertNoEvents(VertxTestContext context) {
    context.verify(() -> assertThat(events.isEmpty(), is(true)));
}
 
Example 18
Source File: KafkaUserCrdOperatorIT.java    From strimzi-kafka-operator with Apache License 2.0 4 votes vote down vote up
@Override
protected void assertReady(VertxTestContext context, KafkaUser resource) {
    context.verify(() -> assertThat(resource.getStatus()
            .getConditions()
            .get(0), is(READY_CONDITION)));
}
 
Example 19
Source File: MockTopicStore.java    From strimzi-kafka-operator with Apache License 2.0 4 votes vote down vote up
public void assertContains(VertxTestContext context, Topic topic) {
    context.verify(() -> assertThat(topics.get(topic.getTopicName()), is(topic)));
}
 
Example 20
Source File: CoapTestBase.java    From hono with Eclipse Public License 2.0 3 votes vote down vote up
/**
 * Asserts the status code of a failed CoAP request.
 *
 * @param ctx The test context to verify the status for.
 * @param expectedStatus The expected status.
 * @param t The exception to verify.
 */
protected static void assertStatus(final VertxTestContext ctx, final int expectedStatus, final Throwable t) {
    ctx.verify(() -> {
        assertThat(t).isInstanceOf(CoapResultException.class);
        assertThat(((CoapResultException) t).getErrorCode()).isEqualTo(expectedStatus);
    });
}