io.vertx.junit5.VertxTestContext Java Examples

The following examples show how to use io.vertx.junit5.VertxTestContext. 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: KafkaUserQuotasIT.java    From strimzi-kafka-operator with Apache License 2.0 6 votes vote down vote up
public void testReconcileCreatesUserWithQuotas(String username, VertxTestContext testContext)  {
    KafkaUserQuotas quotas = new KafkaUserQuotas();
    quotas.setConsumerByteRate(2_000_000);
    quotas.setProducerByteRate(1_000_000);
    quotas.setRequestPercentage(50);

    assertThat(kuq.exists(username), is(false));

    Checkpoint async = testContext.checkpoint();
    kuq.reconcile(username, quotas)
        .onComplete(testContext.succeeding(rr -> testContext.verify(() -> {
            assertThat(kuq.exists(username), is(true));
            assertThat(kuq.getQuotas(username).getJsonObject("config").getString("consumer_byte_rate"), is("2000000"));
            assertThat(kuq.getQuotas(username).getJsonObject("config").getString("producer_byte_rate"), is("1000000"));
            assertThat(kuq.getQuotas(username).getJsonObject("config").getString("request_percentage"), is("50"));
            assertThat(kuq.isPathExist("/config/users/" + kuq.encodeUsername(username)), is(true));
            async.flag();
        })));
}
 
Example #2
Source File: RouterFactoryIntegrationTest.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
@Test
public void testDefaultIntQueryParameter(Vertx vertx, VertxTestContext testContext) {
  loadFactoryAndStartServer(vertx, VALIDATION_SPEC, testContext, routerFactory -> {
    routerFactory
      .operation("testDefaultInt")
      .handler(routingContext ->
        routingContext.response().setStatusMessage(
          ((RequestParameters)routingContext.get("parsedParameters")).queryParameter("parameter").getInteger().toString()
        ).end()
      );
  }).onComplete(h ->
    testRequest(client, HttpMethod.GET, "/queryTests/defaultInt")
      .expect(statusCode(200), statusMessage("1"))
      .send(testContext)
  );
}
 
Example #3
Source File: CacheBasedDeviceConnectionServiceTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that the <em>getLastKnownGatewayForDevice</em> operation fails if no such entry is associated
 * with the given device.
 *
 * @param ctx The vert.x context.
 */
@Test
public void testGetLastKnownGatewayForDeviceNotFound(final VertxTestContext ctx) {

    final String deviceId = "testDevice";
    when(cache.getLastKnownGatewayForDevice(anyString(), anyString(), any(Span.class)))
        .thenReturn(Future.failedFuture(new ClientErrorException(HttpURLConnection.HTTP_NOT_FOUND)));

    givenAStartedService()
    .compose(ok -> svc.getLastKnownGatewayForDevice(Constants.DEFAULT_TENANT, deviceId, span))
    .onComplete(ctx.succeeding(deviceConnectionResult -> {
        ctx.verify(() -> {
            assertThat(deviceConnectionResult.getStatus()).isEqualTo(HttpURLConnection.HTTP_NOT_FOUND);
            assertThat(deviceConnectionResult.getPayload()).isNull();
        });
        ctx.completeNow();
    }));
}
 
Example #4
Source File: HttpBasedMessageMappingTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that the result returned by the mapping service contains the
 * original payload and target address if no mapper has been defined for
 * the gateway.
 *
 * @param ctx The helper to use for running tests on vert.x.
 */
@Test
public void testMapMessageSucceedsIfNoMapperIsSet(final VertxTestContext ctx) {

    config.setMapperEndpoints(Map.of("mapper", MapperEndpoint.from("host", 1234, "/uri", false)));
    final ResourceIdentifier targetAddress = ResourceIdentifier.from(TelemetryConstants.TELEMETRY_ENDPOINT, TEST_TENANT_ID, "gateway");
    final MqttPublishMessage message = newMessage(MqttQoS.AT_LEAST_ONCE, TelemetryConstants.TELEMETRY_ENDPOINT);
    final MqttContext context = newContext(message, new Device(TEST_TENANT_ID, "gateway"));

    messageMapping.mapMessage(context, targetAddress, new JsonObject())
        .onComplete(ctx.succeeding(mappedMessage -> {
            ctx.verify(() -> {
                assertThat(mappedMessage.getTargetAddress()).isEqualTo(targetAddress);
                assertThat(mappedMessage.getPayload()).isEqualTo(message.payload());
                assertThat(mappedMessage.getAdditionalProperties()).isEmpty();
                verify(mapperWebClient, never()).post(anyInt(), anyString(), anyString());
            });
            ctx.completeNow();
        }));
}
 
Example #5
Source File: KafkaAvailabilityTest.java    From strimzi-kafka-operator with Apache License 2.0 6 votes vote down vote up
@Test
public void testMinIsrMoreThanReplicas(VertxTestContext context) {
    KSB ksb = new KSB()
            .addNewTopic("A", false)
                .addToConfig(TopicConfig.MIN_IN_SYNC_REPLICAS_CONFIG, "2")
                .addNewPartition(0)
                    .replicaOn(0)
                    .leader(0)
                    .isr(0)
                .endPartition()
            .endTopic()
            .addBroker(3);

    KafkaAvailability kafkaAvailability = new KafkaAvailability(ksb.ac());

    Checkpoint a = context.checkpoint(ksb.brokers.size());
    for (Integer brokerId : ksb.brokers.keySet()) {
        kafkaAvailability.canRoll(brokerId).onComplete(context.succeeding(canRoll -> context.verify(() -> {
            assertTrue(canRoll,
                    "broker " + brokerId + " should be rollable, being minisr = 2, but only 1 replicas");

            a.flag();
        })));
    }
}
 
Example #6
Source File: PartialRollingUpdateTest.java    From strimzi-kafka-operator with Apache License 2.0 6 votes vote down vote up
@Test
public void testReconcileOfPartiallyRolledZookeeperCluster(VertxTestContext context) {
    zkSts.getSpec().getTemplate().getMetadata().getAnnotations().put(StatefulSetOperator.ANNO_STRIMZI_IO_GENERATION, "3");
    zkPod0.getMetadata().getAnnotations().put(StatefulSetOperator.ANNO_STRIMZI_IO_GENERATION, "3");
    zkPod1.getMetadata().getAnnotations().put(StatefulSetOperator.ANNO_STRIMZI_IO_GENERATION, "2");
    zkPod2.getMetadata().getAnnotations().put(StatefulSetOperator.ANNO_STRIMZI_IO_GENERATION, "1");

    // Now start the KafkaAssemblyOperator with those pods and that statefulset
    startKube();

    LOGGER.info("Recovery reconciliation");
    Checkpoint async = context.checkpoint();
    kco.reconcile(new Reconciliation("test-trigger", Kafka.RESOURCE_KIND, NAMESPACE, CLUSTER_NAME)).onComplete(ar -> {
        if (ar.failed()) ar.cause().printStackTrace();
        context.verify(() -> assertThat(ar.succeeded(), is(true)));
        for (int i = 0; i <= 2; i++) {
            Pod pod = mockClient.pods().inNamespace(NAMESPACE).withName(ZookeeperCluster.zookeeperPodName(CLUSTER_NAME, i)).get();
            String generation = pod.getMetadata().getAnnotations().get(StatefulSetOperator.ANNO_STRIMZI_IO_GENERATION);
            int finalI = i;
            context.verify(() -> assertThat("Pod " + finalI + " had unexpected generation " + generation, generation, is("3")));
        }
        async.flag();
    });
}
 
Example #7
Source File: PrometheusBasedResourceLimitChecksTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that the connection limit check returns {@code true} if the limit
 * is reached.
 *
 * @param ctx The vert.x test context.
 */
@Test
@SuppressWarnings("unchecked")
public void testConnectionLimitIsReached(final VertxTestContext ctx) {

    givenCurrentConnections(10);
    final TenantObject tenant = TenantObject.from(Constants.DEFAULT_TENANT, true)
            .setResourceLimits(new ResourceLimits().setMaxConnections(10));

    limitChecksImpl.isConnectionLimitReached(tenant, mock(SpanContext.class)).onComplete(
            ctx.succeeding(response -> {
                ctx.verify(() -> {
                    assertTrue(response);
                    verify(request).send(any(Handler.class));
                });
                ctx.completeNow();
            }));
}
 
Example #8
Source File: RouterFactoryIntegrationTest.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
@Test
public void mountNotImplementedHandler(Vertx vertx, VertxTestContext testContext) {
  Checkpoint checkpoint = testContext.checkpoint();
  loadFactoryAndStartServer(vertx, "src/test/resources/specs/router_factory_test.yaml", testContext, routerFactory -> {
    routerFactory.setOptions(
      new RouterFactoryOptions()
        .setRequireSecurityHandlers(false)
        .setMountNotImplementedHandler(true)
    );
    routerFactory.operation("showPetById").handler(RoutingContext::next);
  }).onComplete(h ->
    testRequest(client, HttpMethod.GET, "/pets")
      .expect(statusCode(501), statusMessage("Not Implemented"))
      .send(testContext, checkpoint)
  );
}
 
Example #9
Source File: HonoClientImplIT.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that a connection attempt where the TLS handshake cannot be finished successfully fails after two
 * retries with a ClientErrorException with status code 400.
 *
 * @param ctx The vert.x test context.
 */
@Test
@Timeout(value = 10, timeUnit = TimeUnit.SECONDS)
public void testConnectFailsWithClientErrorIfTlsHandshakeFails(final VertxTestContext ctx) {

    // GIVEN a client that is configured to try to connect using TLS to a port that does not support TLS
    final ClientConfigProperties downstreamProps = new ClientConfigProperties();
    downstreamProps.setHost(IntegrationTestSupport.DOWNSTREAM_HOST);
    downstreamProps.setPort(IntegrationTestSupport.DOWNSTREAM_PORT);
    downstreamProps.setTlsEnabled(true);
    downstreamProps.setReconnectAttempts(2);

    clientFactory = IntegrationTestApplicationClientFactory.create(HonoConnection.newConnection(vertx, downstreamProps));
    // WHEN the client tries to connect
    clientFactory.connect().onComplete(ctx.failing(t -> {
        // THEN the connection attempt fails due to lack of authorization
        ctx.verify(() -> {
            assertThat(ServiceInvocationException.extractStatusCode(t)).isEqualTo(HttpURLConnection.HTTP_BAD_REQUEST);
        });
        ctx.completeNow();
    }));
}
 
Example #10
Source File: KafkaUserQuotasIT.java    From strimzi-kafka-operator with Apache License 2.0 6 votes vote down vote up
public void testReconcileUpdatesUserQuotaValues(String username, VertxTestContext testContext)  {
    KafkaUserQuotas initialQuotas = new KafkaUserQuotas();
    initialQuotas.setConsumerByteRate(2_000_000);
    initialQuotas.setProducerByteRate(1_000_000);
    initialQuotas.setRequestPercentage(50);

    kuq.createOrUpdate(username, initialQuotas);
    assertThat(kuq.exists(username), is(true));

    KafkaUserQuotas updatedQuotas = new KafkaUserQuotas();
    updatedQuotas.setConsumerByteRate(4_000_000);
    updatedQuotas.setProducerByteRate(3_000_000);
    updatedQuotas.setRequestPercentage(75);

    Checkpoint async = testContext.checkpoint();
    kuq.reconcile(username, updatedQuotas)
        .onComplete(testContext.succeeding(rr -> testContext.verify(() -> {
            assertThat(kuq.exists(username), is(true));
            assertThat(kuq.getQuotas(username).getJsonObject("config").getString("consumer_byte_rate"), is("4000000"));
            assertThat(kuq.getQuotas(username).getJsonObject("config").getString("producer_byte_rate"), is("3000000"));
            assertThat(kuq.getQuotas(username).getJsonObject("config").getString("request_percentage"), is("75"));
            assertThat(kuq.isPathExist("/config/users/" + kuq.encodeUsername(username)), is(true));
            async.flag();
        })));
}
 
Example #11
Source File: ConsumerTest.java    From strimzi-kafka-bridge with Apache License 2.0 6 votes vote down vote up
@Test
void recordsConsumerDoesNotExist(VertxTestContext context) {
    // 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_FOUND.code()));
                assertThat(error.getCode(), is(HttpResponseStatus.NOT_FOUND.code()));
                assertThat(error.getMessage(), is("The specified consumer instance was not found."));
            });
            context.completeNow();
        });
}
 
Example #12
Source File: DeviceRegistrationApiTests.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that the registry fails a non-existing gateway's request to assert a
 * device's registration status with a 403 error code.
 *
 * @param ctx The vert.x test context.
 */
@Timeout(value = 5, timeUnit = TimeUnit.SECONDS)
@Test
public void testAssertRegistrationFailsForNonExistingGateway(final VertxTestContext ctx) {

    final String deviceId = getHelper().getRandomDeviceId(Constants.DEFAULT_TENANT);

    getHelper().registry
    .registerDevice(Constants.DEFAULT_TENANT, deviceId)
    .compose(r -> getClient(Constants.DEFAULT_TENANT))
    .compose(client -> client.assertRegistration(deviceId, NON_EXISTING_GATEWAY_ID))
    .onComplete(ctx.failing(t -> {
        ctx.verify(() -> assertErrorCode(t, HttpURLConnection.HTTP_FORBIDDEN));
        ctx.completeNow();
    }));
}
 
Example #13
Source File: KuraProtocolAdapterTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that the adapter maps control messages with QoS 1 published from a Kura gateway to
 * the Event endpoint.
 *
 * @param ctx The helper to use for running tests on vert.x.
 */
@Test
public void testMapTopicMapsKuraControlMessagesToEventApi(final VertxTestContext ctx) {

    // GIVEN an adapter configured to use the standard topic.control-prefix $EDC

    // WHEN a message is published to a topic with the Kura $EDC prefix as endpoint
    final MqttContext context = newContext(MqttQoS.AT_LEAST_ONCE, "$EDC/my-scope/4711");
    adapter.mapTopic(context).onComplete(ctx.succeeding(msg -> {
            ctx.verify(() -> {
                // THEN the message is mapped to the event API
                assertAddress(msg, EventConstants.EVENT_ENDPOINT, "my-scope", "4711");
                // and has the control message content type
                assertThat(context.contentType()).isEqualTo(config.getCtrlMsgContentType());
            });
            ctx.completeNow();
        }));
}
 
Example #14
Source File: PrometheusBasedResourceLimitChecksTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 *
 * Verifies that the message limit check returns {@code false} if the limit is not exceeded.
 *
 * @param ctx The vert.x test context.
 */
@SuppressWarnings("unchecked")
@Test
public void testMessageLimitNotExceeded(final VertxTestContext ctx) {

    givenDataVolumeUsageInBytes(90);
    final long incomingMessageSize = 10;
    final TenantObject tenant = TenantObject.from("tenant", true)
            .setResourceLimits(new ResourceLimits()
                    .setDataVolume(new DataVolume()
                            .setMaxBytes(100L)
                            .setEffectiveSince(Instant.parse("2019-01-03T14:30:00Z"))
                            .setPeriod(new ResourceLimitsPeriod()
                                    .setMode("days")
                                    .setNoOfDays(30))));

    limitChecksImpl.isMessageLimitReached(tenant, incomingMessageSize, mock(SpanContext.class))
            .onComplete(ctx.succeeding(response -> {
                ctx.verify(() -> {
                    assertFalse(response);
                    verify(request).send(any(Handler.class));
                });
                ctx.completeNow();
            }));
}
 
Example #15
Source File: ConnectionFactoryImplTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that the given result handler is invoked if a connection attempt times out.
 *
 * @param ctx The vert.x test context.
 */
@Test
@Timeout(value = 5, timeUnit = TimeUnit.SECONDS)
public void testConnectInvokesHandlerOnConnectTimeout(final VertxTestContext ctx) {

    // GIVEN a factory configured to connect to a server with a mocked ProtonClient that won't actually try to connect
    props.setConnectTimeout(10);
    final ConnectionFactoryImpl factory = new ConnectionFactoryImpl(vertx, props);
    final ProtonClient protonClientMock = mock(ProtonClient.class);
    factory.setProtonClient(protonClientMock);

    // WHEN trying to connect to the server
    factory.connect(null, null, null, ctx.failing(t -> {
        // THEN the connection attempt fails with a TimeoutException and the given handler is invoked
        ctx.verify(() -> assertTrue(t instanceof ConnectTimeoutException));
        ctx.completeNow();
    }));
}
 
Example #16
Source File: CoapTestBase.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that the CoAP adapter rejects messages from a disabled device.
 *
 * @param ctx The test context
 */
@Test
@Timeout(value = 10, timeUnit = TimeUnit.SECONDS)
public void testUploadMessageFailsForDisabledDevice(final VertxTestContext ctx) {

    // GIVEN a disabled device
    final Tenant tenant = new Tenant();
    final Device deviceData = new Device();
    deviceData.setEnabled(false);

    helper.registry.addPskDeviceForTenant(tenantId, tenant, deviceId, deviceData, SECRET)
    .compose(ok -> {

        // WHEN the device tries to upload a message
        final CoapClient client = getCoapsClient(deviceId, tenantId, SECRET);
        final Promise<OptionSet> result = Promise.promise();
        client.advanced(getHandler(result, ResponseCode.NOT_FOUND), createCoapsRequest(Code.POST, getPostResource(), 0));
        return result.future();
    })
    .onComplete(ctx.completing());
}
 
Example #17
Source File: KafkaConnectAssemblyOperatorMockTest.java    From strimzi-kafka-operator with Apache License 2.0 6 votes vote down vote up
private Future<Void> createConnectCluster(VertxTestContext context, KafkaConnectApi kafkaConnectApi) {
    PlatformFeaturesAvailability pfa = new PlatformFeaturesAvailability(true, KubernetesVersion.V1_9);
    ResourceOperatorSupplier supplier = new ResourceOperatorSupplier(vertx, this.mockClient,
            new ZookeeperLeaderFinder(vertx, new SecretOperator(vertx, this.mockClient),
                // Retry up to 3 times (4 attempts), with overall max delay of 35000ms
                () -> new BackOff(5_000, 2, 4)),
            new DefaultAdminClientProvider(),
            new DefaultZookeeperScalerProvider(),
            ResourceUtils.metricsProvider(),
            pfa, 60_000L);
    ClusterOperatorConfig config = ResourceUtils.dummyClusterOperatorConfig(VERSIONS);
    this.kco = new KafkaConnectAssemblyOperator(vertx, pfa, supplier, config, foo -> kafkaConnectApi);

    Promise created = Promise.promise();

    LOGGER.info("Reconciling initially -> create");
    kco.reconcile(new Reconciliation("test-trigger", KafkaConnect.RESOURCE_KIND, NAMESPACE, CLUSTER_NAME))
        .onComplete(context.succeeding(v -> context.verify(() -> {
            assertThat(mockClient.apps().deployments().inNamespace(NAMESPACE).withName(KafkaConnectResources.deploymentName(CLUSTER_NAME)).get(), is(notNullValue()));
            assertThat(mockClient.configMaps().inNamespace(NAMESPACE).withName(KafkaConnectResources.metricsAndLogConfigMapName(CLUSTER_NAME)).get(), is(notNullValue()));
            assertThat(mockClient.services().inNamespace(NAMESPACE).withName(KafkaConnectResources.serviceName(CLUSTER_NAME)).get(), is(notNullValue()));
            assertThat(mockClient.policy().podDisruptionBudget().inNamespace(NAMESPACE).withName(KafkaConnectResources.deploymentName(CLUSTER_NAME)).get(), is(notNullValue()));
            created.complete();
        })));
    return created.future();
}
 
Example #18
Source File: CorsIT.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that the HTTP adapter returns matching CORS headers in response to a
 * CORS preflight request for putting a command response.
 *
 * @param ctx The vert.x test context.
 */
@Test
public void testCorsPreflightRequestForPuttingCommandResponse(final VertxTestContext ctx) {

    httpClient.options(
            String.format("/%s/res/%s/%s/%s", CommandConstants.COMMAND_ENDPOINT, "my-tenant", "my-device", "cmd-request-id"),
            MultiMap.caseInsensitiveMultiMap()
                .add(HttpHeaders.ORIGIN, CrudHttpClient.ORIGIN_URI)
                .add(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpMethod.PUT.name()),
            status -> status == HttpURLConnection.HTTP_OK)
    .onComplete(ctx.succeeding(headers -> {
        ctx.verify(() -> {
            assertAccessControlHeaders(headers, HttpMethod.PUT);
            assertThat(headers.get(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS)).contains(Constants.HEADER_COMMAND_RESPONSE_STATUS);
        });
        ctx.completeNow();
    }));
}
 
Example #19
Source File: AbstractTenantServiceTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that a updating a tenant with an empty resource version succeed.
 * @param ctx The vert.x test context.
 */
@Test
public void testUpdateTenantWithEmptyResourceVersionSucceed(final VertxTestContext ctx) {

    addTenant("tenant")
    .map(cr -> {
        getTenantManagementService().updateTenant(
                "tenant",
                buildTenantPayload(),
                Optional.empty(),
                NoopSpan.INSTANCE)
                .onComplete(ctx.succeeding(s -> {
                    ctx.verify(() -> assertEquals(HttpURLConnection.HTTP_NO_CONTENT, s.getStatus()));
                    ctx.completeNow();
                })
        );
        return null;
    });
}
 
Example #20
Source File: DeviceConnectionApiTests.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that a request to remove the command-handling adapter instance for a device succeeds with
 * a <em>true</em> value if there was a matching adapter instance entry.
 *
 * @param ctx The vert.x test context.
 */
@Timeout(value = 5, timeUnit = TimeUnit.SECONDS)
@Test
public void testRemoveCommandHandlingAdapterInstanceSucceeds(final VertxTestContext ctx) {

    final String deviceId = randomId();
    final String adapterInstance = randomId();

    getClient(Constants.DEFAULT_TENANT)
            // add the entry
            .compose(client -> client
                    .setCommandHandlingAdapterInstance(deviceId, adapterInstance, null, null)
                    .map(client))
            // then remove it
            .compose(client -> client.removeCommandHandlingAdapterInstance(deviceId, adapterInstance, null))
            .onComplete(ctx.succeeding(result -> {
                ctx.verify(() -> assertThat(result).isTrue());
                ctx.completeNow();
            }));
}
 
Example #21
Source File: ConsumerService.java    From strimzi-kafka-bridge with Apache License 2.0 6 votes vote down vote up
public ConsumerService subscribeConsumer(VertxTestContext context, String groupId, String name, JsonObject jsonObject) throws InterruptedException, ExecutionException, TimeoutException {
    CompletableFuture<Boolean> subscribe = new CompletableFuture<>();
    postRequest(Urls.consumerInstanceSubscription(groupId, name))
            .putHeader(CONTENT_LENGTH.toString(), String.valueOf(jsonObject.toBuffer().length()))
            .putHeader(CONTENT_TYPE.toString(), BridgeContentType.KAFKA_JSON)
            .as(BodyCodec.jsonObject())
            .sendJsonObject(jsonObject, ar -> {
                context.verify(() -> {
                    assertThat(ar.succeeded(), is(true));
                    assertThat(ar.result().statusCode(), is(HttpResponseStatus.NO_CONTENT.code()));
                });
                subscribe.complete(true);
            });
    subscribe.get(HTTP_REQUEST_TIMEOUT, TimeUnit.SECONDS);
    return this;
}
 
Example #22
Source File: TopicOperatorTest.java    From strimzi-kafka-operator with Apache License 2.0 6 votes vote down vote up
/**
 * Test reconciliation when a resource has been deleted while the operator
 * wasn't running
 */
@Test
public void testReconcile_noResource_withKafka_withPrivate(VertxTestContext context) throws InterruptedException {
    Topic kubeTopic = null;
    Topic kafkaTopic = new Topic.Builder(topicName.toString(), 10, (short) 2, map("cleanup.policy", "bar")).build();
    Topic privateTopic = kafkaTopic;

    CountDownLatch async0 = new CountDownLatch(2);
    mockKafka.createTopic(kafkaTopic).onComplete(ar -> async0.countDown());
    mockKafka.setDeleteTopicResponse(topicName, null);
    mockTopicStore.setCreateTopicResponse(topicName, null);
    mockTopicStore.create(kafkaTopic).onComplete(ar -> async0.countDown());
    mockTopicStore.setDeleteTopicResponse(topicName, null);
    async0.await();
    LogContext logContext = LogContext.periodic(topicName.toString());
    Checkpoint async = context.checkpoint();
    topicOperator.reconcile(reconciliation(), logContext, null, kubeTopic, kafkaTopic, privateTopic).onComplete(reconcileResult -> {
        assertSucceeded(context, reconcileResult);
        mockTopicStore.assertNotExists(context, topicName);
        mockK8s.assertNotExists(context, topicName.asKubeName());
        mockKafka.assertNotExists(context, topicName);
        mockK8s.assertNoEvents(context);
        async.flag();
    });
}
 
Example #23
Source File: RouteWithBeanParamTest.java    From rest.vertx with Apache License 2.0 6 votes vote down vote up
@Test
void postBean(VertxTestContext context) {

    client.post(PORT, HOST, "/bean/read/result;one=1;enum=two?query=1").as(BodyCodec.string())
            .putHeader("MyHeader", "true")
            .putHeader("Cookie", "chocolate=tasty")
            .send(context.succeeding(response -> context.verify(() -> {

                assertEquals(200, response.statusCode());
                assertEquals("Header: true, " +
                        "Path: result;one=1;enum=two, " +
                        "Query: 1, " +
                        "Cookie: tasty, " +
                        "Matrix: two, " +
                        "one: 1, " +
                        "Body: empty", response.body());

                context.completeNow();
            })));
}
 
Example #24
Source File: PlatformFeaturesAvailabilityTest.java    From strimzi-kafka-operator with Apache License 2.0 6 votes vote down vote up
@Test
public void testApiDetectionOce(VertxTestContext context) throws InterruptedException {
    List<String> apis = new ArrayList<>();
    apis.add("/apis/route.openshift.io/v1");
    apis.add("/apis/build.openshift.io/v1");

    HttpServer mockHttp = startMockApi(context, apis);

    KubernetesClient client = new DefaultKubernetesClient("127.0.0.1:" + mockHttp.actualPort());

    Checkpoint async = context.checkpoint();

    PlatformFeaturesAvailability.create(vertx, client).onComplete(context.succeeding(pfa -> context.verify(() -> {
        assertThat(pfa.hasRoutes(), is(true));
        assertThat(pfa.hasBuilds(), is(true));
        assertThat(pfa.hasImages(), is(false));
        assertThat(pfa.hasApps(), is(false));
        stopMockApi(context, mockHttp);
        async.flag();
    })));
}
 
Example #25
Source File: VertxBasedHttpProtocolAdapterTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that a POST request to the event URI results in a message that is sent downstream.
 *
 * @param ctx The vert.x test context.
 */
@Test
public void testPostEventSendsMessageDownstream(final VertxTestContext ctx) {

    mockSuccessfulAuthentication("DEFAULT_TENANT", "device_1");

    httpClient.post("/event")
            .putHeader(HttpHeaders.CONTENT_TYPE.toString(), HttpUtils.CONTENT_TYPE_JSON)
            .basicAuthentication("testuser@DEFAULT_TENANT", "password123")
            .putHeader(HttpHeaders.ORIGIN.toString(), "hono.eclipse.org")
            .expect(ResponsePredicate.status(HttpURLConnection.HTTP_ACCEPTED))
            .expect(this::assertCorsHeaders)
            .sendJsonObject(new JsonObject(), ctx.succeeding(r -> {
                ctx.verify(() -> verify(eventSender).sendAndWaitForOutcome(any(Message.class), any(SpanContext.class)));
                ctx.completeNow();
            }));
}
 
Example #26
Source File: CacheBasedDeviceConnectionInfoTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that the <em>getCommandHandlingAdapterInstances</em> operation fails if no matching instance
 * has been registered. An adapter instance has been registered for another device of the same tenant though.
 *
 * @param extraUnusedViaGateways Test values.
 * @param ctx The vert.x context.
 */
@ParameterizedTest(name = PARAMETERIZED_TEST_NAME_PATTERN)
@MethodSource("extraUnusedViaGateways")
public void testGetCommandHandlingAdapterInstancesFailsForOtherTenantDevice(final Set<String> extraUnusedViaGateways, final VertxTestContext ctx) {
    final String deviceId = "testDevice";
    final String adapterInstance = "adapterInstance";
    final String gatewayId = "gw-1";
    final String otherGatewayId = "gw-2";
    final Set<String> viaGateways = new HashSet<>(Set.of(gatewayId));
    viaGateways.addAll(extraUnusedViaGateways);
    // set command handling adapter instance for other gateway
    info.setCommandHandlingAdapterInstance(Constants.DEFAULT_TENANT, otherGatewayId, adapterInstance, null, span)
    .compose(v -> {
        return info.getCommandHandlingAdapterInstances(Constants.DEFAULT_TENANT, deviceId, viaGateways, span);
    }).onComplete(ctx.failing(t -> ctx.verify(() -> {
        assertThat(t).isInstanceOf(ServiceInvocationException.class);
        assertThat(((ServiceInvocationException) t).getErrorCode()).isEqualTo(HttpURLConnection.HTTP_NOT_FOUND);
        ctx.completeNow();
    })));
}
 
Example #27
Source File: ApiControllerTest.java    From exonum-java-binding with Apache License 2.0 6 votes vote down vote up
@Test
void getCounter(VertxTestContext context) {
  String name = "counter";
  long value = 10L;
  Counter counter = new Counter(name, value);
  when(qaService.getValue(name)).thenReturn(Optional.of(counter));

  String getCounterUri = getCounterUri(name);
  get(getCounterUri)
      .send(context.succeeding(response -> context.verify(() -> {
        assertThat(response.statusCode())
            .isEqualTo(HTTP_OK);

        String body = response.bodyAsString();
        Counter actualCounter = JSON_SERIALIZER.fromJson(body, Counter.class);
        assertThat(actualCounter).isEqualTo(counter);

        context.completeNow();
      })));
}
 
Example #28
Source File: QaServiceImplTest.java    From exonum-java-binding with Apache License 2.0 6 votes vote down vote up
@Test
void getValidatorsTime(TestKit testKit, VertxTestContext context) {
  get(VALIDATORS_TIMES_PATH)
      .send(context.succeeding(response -> context.verify(() -> {
        Map<PublicKey, ZonedDateTime> actual = json().fromJson(response.bodyAsString(),
            new TypeToken<Map<PublicKey, ZonedDateTime>>() {
            }.getType());

        EmulatedNode emulatedNode = testKit.getEmulatedNode();
        PublicKey nodePublicKey = emulatedNode.getServiceKeyPair().getPublicKey();
        Map<PublicKey, ZonedDateTime> expected = ImmutableMap.of(nodePublicKey, INITIAL_TIME);

        assertThat(actual).isEqualTo(expected);

        context.completeNow();
      })));
}
 
Example #29
Source File: RouterFactorySecurityTest.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
@Test
public void mountSingle(Vertx vertx, VertxTestContext testContext) {
  Checkpoint checkpoint = testContext.checkpoint();
  loadFactoryAndStartServer(vertx, SECURITY_TESTS, testContext, routerFactory -> {
    routerFactory.setOptions(FACTORY_OPTIONS);

    routerFactory.operation("listPetsSingleSecurity").handler(routingContext -> routingContext
      .response()
      .setStatusCode(200)
      .setStatusMessage(concatenateRoutingContextEntries(routingContext, "api_key"))
      .end()
    );

    routerFactory.securityHandler("api_key",
      mockSuccessfulAuthHandler(routingContext -> routingContext.put("api_key", "1"))
    );
  }).onComplete(h ->
    testRequest(client, HttpMethod.GET, "/pets_single_security")
      .expect(statusCode(200), statusMessage("1"))
      .send(testContext, checkpoint)
  );
}
 
Example #30
Source File: RouteAsyncTest.java    From rest.vertx with Apache License 2.0 5 votes vote down vote up
@Test
void testAsyncCallWithExecutorPromiseRest(VertxTestContext context) {

    client.get(PORT, HOST, "/async/executor_promise")
            .as(BodyCodec.string())
            .send(context.succeeding(response -> context.verify(() -> {
                assertEquals(200, response.statusCode());
                assertEquals("{\"name\": \"async\", \"value\": \"called\"}", response.body());
                context.completeNow();
            })));

}