io.vertx.junit5.Checkpoint Java Examples

The following examples show how to use io.vertx.junit5.Checkpoint. 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: MqttServerSourceTest.java    From smallrye-reactive-messaging with Apache License 2.0 6 votes vote down vote up
@Test
void testSingle(io.vertx.core.Vertx vertx, VertxTestContext testContext) {
    final Map<String, String> configMap = new HashMap<>();
    configMap.put("port", "0");
    final MqttServerSource source = new MqttServerSource(new Vertx(vertx),
            new MqttServerConnectorIncomingConfiguration(TestUtils.config(configMap)));
    final PublisherBuilder<MqttMessage> mqttMessagePublisherBuilder = source.source();
    final TestMqttMessage testMessage = new TestMqttMessage("hello/topic", 1, "Hello world!",
            EXACTLY_ONCE.value(), false);
    final Checkpoint messageReceived = testContext.checkpoint();
    final Checkpoint messageAcknowledged = testContext.checkpoint();

    mqttMessagePublisherBuilder.forEach(mqttMessage -> {
        testContext.verify(() -> TestUtils.assertMqttEquals(testMessage, mqttMessage));
        messageReceived.flag();
        mqttMessage.ack().thenApply(aVoid -> {
            messageAcknowledged.flag();
            return aVoid;
        });
    }).run();
    TestUtils.sendMqttMessages(Collections.singletonList(testMessage),
            CompletableFuture.supplyAsync(() -> {
                await().until(source::port, port -> port != 0);
                return source.port();
            }), testContext);
}
 
Example #2
Source File: RouteToEBServiceHandlerTest.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
@Test
public void emptyOperationResultTest(Vertx vertx, VertxTestContext testContext) {
  Checkpoint checkpoint = testContext.checkpoint();

  TestService service = new TestServiceImpl(vertx);
  final ServiceBinder serviceBinder = new ServiceBinder(vertx).setAddress("someAddress");
  consumer = serviceBinder.register(TestService.class, service);

  router
    .get("/test")
    .handler(
      ValidationHandler.builder(parser).build()
    ).handler(
      RouteToEBServiceHandler.build(vertx.eventBus(), "someAddress", "testEmptyServiceResponse")
    );

  testRequest(client, HttpMethod.GET, "/test")
    .expect(statusCode(200), statusMessage("OK"))
    .expect(emptyResponse())
    .send(testContext, checkpoint);
}
 
Example #3
Source File: RouterFactoryIntegrationTest.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
/**
 * Test: query_optional_form_explode_object
 */
@Test
public void testQueryOptionalFormExplodeObject(Vertx vertx, VertxTestContext testContext) {
  Checkpoint checkpoint = testContext.checkpoint(2);
  loadFactoryAndStartServer(vertx, VALIDATION_SPEC, testContext, routerFactory -> {
    routerFactory
      .operation("query_form_explode_object")
      .handler(routingContext -> {
        RequestParameters params = routingContext.get("parsedParameters");
        routingContext.response()
          .setStatusCode(200)
          .setStatusMessage("OK")
          .putHeader("content-type", "application/json")
          .end(params.queryParameter("color").getJsonObject().encode());
      });
  }).onComplete(h -> {
    testRequest(client, HttpMethod.GET, "/query/form/explode/object?R=100&G=200&B=150&alpha=50")
      .expect(statusCode(200))
      .expect(jsonBodyResponse(new JsonObject("{\"R\":\"100\",\"G\":\"200\",\"B\":\"150\",\"alpha\":50}")))
      .send(testContext, checkpoint);
    testRequest(client, HttpMethod.GET, "/query/form/explode/object?R=100&G=200&B=150&alpha=aaa")
      .expect(statusCode(400))
      .expect(badParameterResponse(ParameterProcessorException.ParameterProcessorErrorType.PARSING_ERROR, "color", ParameterLocation.QUERY))
      .send(testContext, checkpoint);
  });
}
 
Example #4
Source File: TopicOperatorTest.java    From strimzi-kafka-operator with Apache License 2.0 6 votes vote down vote up
@Test
public void testReconcileMetrics(VertxTestContext context) throws InterruptedException {
    mockKafka.setTopicsListResponse(Future.succeededFuture(emptySet()));
    mockKafka.setUpdateTopicResponse(topicName -> Future.succeededFuture());
    Future<?> reconcileFuture = topicOperator.reconcileAllTopics("periodic");
    resourceAdded(context, null, null);

    Checkpoint async = context.checkpoint();
    reconcileFuture.onComplete(context.succeeding(e -> context.verify(() -> {
        MeterRegistry registry = metrics.meterRegistry();

        assertThat(registry.get(TopicOperator.METRICS_PREFIX + "reconciliations").tag("kind", "KafkaTopic").counter().count(), is(1.0));
        assertThat(registry.get(TopicOperator.METRICS_PREFIX + "reconciliations.successful").tag("kind", "KafkaTopic").counter().count(), is(0.0));
        assertThat(registry.get(TopicOperator.METRICS_PREFIX + "reconciliations.failed").tag("kind", "KafkaTopic").counter().count(), is(0.0));

        assertThat(registry.get(TopicOperator.METRICS_PREFIX + "reconciliations.duration").tag("kind", "KafkaTopic").timer().count(), is(1L));
        assertThat(registry.get(TopicOperator.METRICS_PREFIX + "reconciliations.duration").tag("kind", "KafkaTopic").timer().totalTime(TimeUnit.MILLISECONDS), greaterThan(0.0));

        async.flag();
    })));
}
 
Example #5
Source File: PartialRollingUpdateTest.java    From strimzi-kafka-operator with Apache License 2.0 6 votes vote down vote up
@Test
public void testReconcileOfPartiallyRolledClusterForClientsCaCertificate(VertxTestContext context) {
    clientsCaCert.getMetadata().getAnnotations().put(Ca.ANNO_STRIMZI_IO_CA_CERT_GENERATION, "3");
    kafkaPod0.getMetadata().getAnnotations().put(Ca.ANNO_STRIMZI_IO_CLIENTS_CA_CERT_GENERATION, "3");
    kafkaPod1.getMetadata().getAnnotations().put(Ca.ANNO_STRIMZI_IO_CLIENTS_CA_CERT_GENERATION, "3");
    kafkaPod2.getMetadata().getAnnotations().put(Ca.ANNO_STRIMZI_IO_CLIENTS_CA_CERT_GENERATION, "2");
    kafkaPod3.getMetadata().getAnnotations().put(Ca.ANNO_STRIMZI_IO_CLIENTS_CA_CERT_GENERATION, "1");
    kafkaPod4.getMetadata().getAnnotations().put(Ca.ANNO_STRIMZI_IO_CLIENTS_CA_CERT_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 <= 4; i++) {
            Pod pod = mockClient.pods().inNamespace(NAMESPACE).withName(KafkaCluster.kafkaPodName(CLUSTER_NAME, i)).get();
            String certGeneration = pod.getMetadata().getAnnotations().get(Ca.ANNO_STRIMZI_IO_CLIENTS_CA_CERT_GENERATION);
            int finalI = i;
            context.verify(() -> assertThat("Pod " + finalI + " had unexpected cert generation " + certGeneration, certGeneration, is("3")));
        }
        async.flag();
    });
}
 
Example #6
Source File: RegistrationServiceTests.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that the registry returns 404 when trying to read a device that has been deleted.
 *
 * @param ctx The vert.x test context.
 */
@Test
public void testReadDeviceFailsForDeletedDevice(final VertxTestContext ctx) {

    final String deviceId = randomDeviceId();
    final Checkpoint get = ctx.checkpoint(2);

    createDevice(deviceId, new Device())
        .compose(response -> getDeviceManagementService()
                    .deleteDevice(TENANT, deviceId, Optional.empty(), NoopSpan.INSTANCE))
        .compose(response -> {
            ctx.verify(() -> assertThat(response.getStatus()).isEqualTo(HttpURLConnection.HTTP_NO_CONTENT));
            get.flag();
            return getDeviceManagementService().readDevice(TENANT, deviceId, NoopSpan.INSTANCE);
        }).onComplete(ctx.succeeding(response -> {
            ctx.verify(() -> assertThat(response.getStatus()).isEqualTo(HttpURLConnection.HTTP_NOT_FOUND));
            get.flag();
        }));
}
 
Example #7
Source File: RegistrationServiceTests.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that deleting a device succeeds when the request does not contain a resource version.
 *
 * @param ctx The vert.x test context.
 */
@Test
public void testDeleteDeviceSucceeds(final VertxTestContext ctx) {

    final String deviceId = randomDeviceId();
    final Checkpoint register = ctx.checkpoint(2);

    getDeviceManagementService().createDevice(TENANT, Optional.of(deviceId), new Device(), NoopSpan.INSTANCE)
            .map(response -> {
                ctx.verify(() -> assertThat(response.getStatus()).isEqualTo(HttpURLConnection.HTTP_CREATED));
                register.flag();
                return response;
            }).compose(rr -> getDeviceManagementService()
                    .deleteDevice(TENANT, deviceId, Optional.empty(), NoopSpan.INSTANCE))
            .onComplete(ctx.succeeding(response -> {
                ctx.verify(() -> {
                    assertThat(response.getStatus()).isEqualTo(HttpURLConnection.HTTP_NO_CONTENT);
                });
                register.flag();
            }));
}
 
Example #8
Source File: RegistrationServiceTests.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that deleting a device succeeds when the request contains a resource version that matches
 * the one of the device on record.
 *
 * @param ctx The vert.x test context.
 */
@Test
public void testDeleteDeviceSucceedsForMatchingResourceVersion(final VertxTestContext ctx) {

    final String deviceId = randomDeviceId();
    final Checkpoint register = ctx.checkpoint(2);

    getDeviceManagementService().createDevice(TENANT, Optional.of(deviceId), new Device(), NoopSpan.INSTANCE)
            .map(response -> {
                ctx.verify(() -> assertThat(response.getStatus()).isEqualTo(HttpURLConnection.HTTP_CREATED));
                register.flag();
                return response;
            }).compose(rr -> {
                final String resourceVersion = rr.getResourceVersion().orElse(null);
                return getDeviceManagementService()
                        .deleteDevice(TENANT, deviceId, Optional.of(resourceVersion), NoopSpan.INSTANCE);
            }).onComplete(ctx.succeeding(response -> {
                ctx.verify(() -> {
                    assertThat(response.getStatus()).isEqualTo(HttpURLConnection.HTTP_NO_CONTENT);
                });
                register.flag();
            }));
}
 
Example #9
Source File: RouterFactoryIntegrationTest.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
@Test
public void testAllowEmptyValueBooleanQueryParameter(Vertx vertx, VertxTestContext testContext) {
  Checkpoint checkpoint = testContext.checkpoint(3);
  loadFactoryAndStartServer(vertx, VALIDATION_SPEC, testContext, routerFactory -> {
    routerFactory
      .operation("testDefaultBoolean")
      .handler(routingContext ->
        routingContext.response().setStatusMessage(
          "" + ((RequestParameters)routingContext.get("parsedParameters")).queryParameter("parameter").toString()
        ).end()
      );
  }).onComplete(h -> {
    testRequest(client, HttpMethod.GET, "/queryTests/defaultBoolean?parameter")
      .expect(statusCode(200), statusMessage("false"))
      .send(testContext, checkpoint);
    testRequest(client, HttpMethod.GET, "/queryTests/defaultBoolean")
      .expect(statusCode(200), statusMessage("false"))
      .send(testContext, checkpoint);
    testRequest(client, HttpMethod.GET, "/queryTests/defaultBoolean?parameter=true")
      .expect(statusCode(200), statusMessage("true"))
      .send(testContext, checkpoint);
  });
}
 
Example #10
Source File: RouterFactoryApiServiceIntegrationTest.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
@Test
public void pathAndOperationExtensionMerge(Vertx vertx, VertxTestContext testContext) {
  Checkpoint checkpoint = testContext.checkpoint(2);

  PathExtensionTestService service = new PathExtensionTestServiceImpl();
  final ServiceBinder serviceBinder = new ServiceBinder(vertx).setAddress("address");
  consumers.add(serviceBinder.register(PathExtensionTestService.class, service));

  loadFactoryAndStartServer(vertx, "src/test/resources/specs/extension_test.yaml", testContext, routerFactory -> {
    routerFactory.setOptions(HANDLERS_TESTS_OPTIONS);
    routerFactory.mountServicesFromExtensions();
  }).onComplete(h -> {
    testRequest(client, HttpMethod.GET, "/testMerge")
      .expect(statusCode(200), statusMessage("getPathLevel"))
      .send(testContext, checkpoint);
    testRequest(client, HttpMethod.POST, "/testMerge")
      .expect(statusCode(200), statusMessage("postPathLevel"))
      .send(testContext, checkpoint);
  });
}
 
Example #11
Source File: AbstractNonNamespacedResourceOperatorTest.java    From strimzi-kafka-operator with Apache License 2.0 6 votes vote down vote up
@Test
public void testSuccessfulCreation(VertxTestContext context) {
    T resource = resource();
    Resource mockResource = mock(resourceType());
    when(mockResource.get()).thenReturn(null);
    when(mockResource.create(any())).thenReturn(resource);

    NonNamespaceOperation mockNameable = mock(NonNamespaceOperation.class);
    when(mockNameable.withName(matches(resource.getMetadata().getName()))).thenReturn(mockResource);

    MixedOperation mockCms = mock(MixedOperation.class);
    when(mockCms.withName(matches(RESOURCE_NAME))).thenReturn(mockResource);

    C mockClient = mock(clientType());
    mocker(mockClient, mockCms);

    AbstractNonNamespacedResourceOperator<C, T, L, D, R> op = createResourceOperationsWithMockedReadiness(
            vertx, mockClient);

    Checkpoint async = context.checkpoint();
    op.createOrUpdate(resource).onComplete(context.succeeding(rr -> {
        verify(mockResource).get();
        verify(mockResource).create(eq(resource));
        async.flag();
    }));
}
 
Example #12
Source File: AbstractVertxBasedHttpProtocolAdapterTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that the <em>onStartupSuccess</em> method is invoked if the
 * HTTP server has been started successfully.
 *
 * @param ctx The helper to use for running async tests on vertx.
 */
@Test
public void testStartInvokesOnStartupSuccess(final VertxTestContext ctx) {

    // GIVEN an adapter with a client provided http server
    final HttpServer server = getHttpServer(false);
    final Checkpoint onStartupSuccess = ctx.checkpoint();

    // WHEN starting the adapter
    final AbstractVertxBasedHttpProtocolAdapter<HttpProtocolAdapterProperties> adapter = getAdapter(
            server,
            // THEN the onStartupSuccess method has been invoked
            s -> onStartupSuccess.flag());

    final Promise<Void> startupTracker = Promise.promise();
    startupTracker.future().onComplete(ctx.completing());
    adapter.start(startupTracker);
}
 
Example #13
Source File: TopicOperatorMockTest.java    From strimzi-kafka-operator with Apache License 2.0 6 votes vote down vote up
Topic getFromKafka(VertxTestContext context, String topicName) throws InterruptedException {
    AtomicReference<Topic> ref = new AtomicReference<>();
    Checkpoint async = context.checkpoint();
    Future<TopicMetadata> kafkaMetadata = session.kafka.topicMetadata(new TopicName(topicName));
    kafkaMetadata.map(metadata -> TopicSerialization.fromTopicMetadata(metadata)).onComplete(fromKafka -> {
        if (fromKafka.succeeded()) {
            ref.set(fromKafka.result());
        } else {
            context.failNow(fromKafka.cause());
        }
        async.flag();
    });
    if (!context.awaitCompletion(60, TimeUnit.SECONDS)) {
        context.failNow(new Throwable("Test timeout"));
    }
    return ref.get();
}
 
Example #14
Source File: KafkaRebalanceAssemblyOperatorTest.java    From strimzi-kafka-operator with Apache License 2.0 6 votes vote down vote up
/**
 * Tests the transition from New to ProposalReady
 *
 * 1. A new rebalance resource is created; it is in the New state
 * 2. The operator requests a rebalance proposal to Cruise Control REST API
 * 3. The rebalance proposal is ready on the first call
 * 4. The rebalance resource moves to ProposalReady state
 */
@Test
public void testNewToProposalReadyRebalance(VertxTestContext context) throws IOException, URISyntaxException {

    // Setup the rebalance endpoint with the number of pending calls before a response is received.
    MockCruiseControl.setupCCRebalanceResponse(ccServer, 0);

    KafkaRebalance kr =
            createKafkaRebalance(CLUSTER_NAMESPACE, CLUSTER_NAME, RESOURCE_NAME, new KafkaRebalanceSpecBuilder().build());

    Crds.kafkaRebalanceOperation(kubernetesClient).inNamespace(CLUSTER_NAMESPACE).create(kr);

    when(mockKafkaOps.getAsync(CLUSTER_NAMESPACE, CLUSTER_NAME)).thenReturn(Future.succeededFuture(kafka));
    mockRebalanceOperator(mockRebalanceOps, CLUSTER_NAMESPACE, RESOURCE_NAME, kubernetesClient);

    Checkpoint checkpoint = context.checkpoint();
    kcrao.reconcileRebalance(
            new Reconciliation("test-trigger", KafkaRebalance.RESOURCE_KIND, CLUSTER_NAMESPACE, RESOURCE_NAME),
            kr).onComplete(context.succeeding(v -> {
                // the resource moved from New directly to ProposalReady (no pending calls in the Mock server)
                assertState(context, kubernetesClient, CLUSTER_NAMESPACE, RESOURCE_NAME, KafkaRebalanceAssemblyOperator.State.ProposalReady);
                checkpoint.flag();
            }));
}
 
Example #15
Source File: RouterFactoryApiServiceIntegrationTest.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
@Test
public void pathAndOperationExtensionMapsMerge(Vertx vertx, VertxTestContext testContext) {
  Checkpoint checkpoint = testContext.checkpoint(2);

  PathExtensionTestService service = new PathExtensionTestServiceImpl();
  final ServiceBinder serviceBinder = new ServiceBinder(vertx).setAddress("address");
  consumers.add(serviceBinder.register(PathExtensionTestService.class, service));

  loadFactoryAndStartServer(vertx, "src/test/resources/specs/extension_test.yaml", testContext, routerFactory -> {
    routerFactory.setOptions(HANDLERS_TESTS_OPTIONS);
    routerFactory.mountServicesFromExtensions();
  }).onComplete(h -> {
    testRequest(client, HttpMethod.GET, "/testMerge2")
      .expect(statusCode(200), statusMessage("getPathLevel"))
      .send(testContext, checkpoint);
    testRequest(client, HttpMethod.POST, "/testMerge2")
      .expect(statusCode(200), statusMessage("postPathLevel"))
      .send(testContext, checkpoint);
  });
}
 
Example #16
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 #17
Source File: KafkaAvailabilityTest.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
@Test
public void testAtMinIsr(VertxTestContext context) {
    KSB ksb = new KSB()
        .addNewTopic("A", false)
            .addToConfig(TopicConfig.MIN_IN_SYNC_REPLICAS_CONFIG, "2")
            .addNewPartition(0)
                .replicaOn(0, 1)
                .leader(0)
                .isr(0, 1)
            .endPartition()
        .endTopic()
        .addNewTopic("B", false)
            .addToConfig(TopicConfig.MIN_IN_SYNC_REPLICAS_CONFIG, "2")
            .addNewPartition(0)
                .replicaOn(0, 1)
                .leader(1)
                .isr(0, 1)
            .endPartition()
        .endTopic()

        .addBroker(2);

    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(() -> {
            if (brokerId == 2) {
                assertTrue(canRoll,
                        "broker " + brokerId + " should be rollable, having no partitions");
            } else {
                assertTrue(canRoll,
                        "broker " + brokerId + " should be rollable, because although rolling it will impact availability minisr=|replicas|");
            }
            a.flag();
        })));
    }
}
 
Example #18
Source File: TopicOperatorTest.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
/**
 * Test reconciliation when a resource has been created while the operator wasn't running
 */
@Test
public void testReconcile_withResource_noKafka_noPrivate(VertxTestContext context) throws InterruptedException {

    Topic kubeTopic = new Topic.Builder(topicName.toString(), 10, (short) 2, map("cleanup.policy", "bar")).build();
    Topic kafkaTopic = null;
    Topic privateTopic = null;

    Checkpoint async0 = context.checkpoint();
    mockKafka.setCreateTopicResponse(topicName.toString(), null);
    //mockKafka.setTopicMetadataResponse(topicName, null, null);
    mockKafka.setTopicMetadataResponse(
        topicName -> Future.succeededFuture(Utils.getTopicMetadata(kubeTopic)));

    mockTopicStore.setCreateTopicResponse(topicName, null);
    mockK8s.setCreateResponse(topicName.asKubeName(), null);
    KafkaTopic topicResource = TopicSerialization.toTopicResource(kubeTopic, labels);
    LogContext logContext = LogContext.kubeWatch(Watcher.Action.ADDED, topicResource);
    mockK8s.createResource(topicResource).onComplete(ar -> async0.flag());

    CountDownLatch latch = new CountDownLatch(1);
    Checkpoint async = context.checkpoint(1);
    topicOperator.reconcile(null, logContext, null, kubeTopic, kafkaTopic, privateTopic).onComplete(reconcileResult -> {
        assertSucceeded(context, reconcileResult);
        mockKafka.assertExists(context, kubeTopic.getTopicName());
        mockTopicStore.assertExists(context, kubeTopic.getTopicName());
        mockK8s.assertNoEvents(context);
        mockTopicStore.read(topicName).onComplete(readResult -> {
            assertSucceeded(context, readResult);
            context.verify(() -> assertThat(readResult.result(), is(kubeTopic)));
            async.flag();
            latch.countDown();
        });
    });
    latch.await(30, TimeUnit.SECONDS);
    context.completeNow();
}
 
Example #19
Source File: KafkaConnectApiMockTest.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
@Test
public void testStatusWithBackOffSucceedingImmediately(VertxTestContext context) {
    Queue<Future<Map<String, Object>>> statusResults = new ArrayBlockingQueue<>(1);
    statusResults.add(Future.succeededFuture(Collections.emptyMap()));

    KafkaConnectApi api = new MockKafkaConnectApi(vertx, statusResults);
    Checkpoint async = context.checkpoint();

    api.statusWithBackOff(backOff, "some-host", 8083, "some-connector")
        .onComplete(context.succeeding(res -> async.flag()));
}
 
Example #20
Source File: RouterFactoryApiServiceIntegrationTest.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
@Test
public void operationExtension(Vertx vertx, VertxTestContext testContext) {
  Checkpoint checkpoint = testContext.checkpoint(4);

  TestService service = new TestServiceImpl(vertx);
  final ServiceBinder serviceBinder = new ServiceBinder(vertx).setAddress("address");
  consumers.add(serviceBinder.register(TestService.class, service));

  AnotherTestService anotherService = AnotherTestService.create(vertx);
  final ServiceBinder anotherServiceBinder = new ServiceBinder(vertx).setAddress("anotherAddress");
  consumers.add(anotherServiceBinder.register(AnotherTestService.class, anotherService));

  loadFactoryAndStartServer(vertx, "src/test/resources/specs/extension_test.yaml", testContext, routerFactory -> {
    routerFactory.setOptions(HANDLERS_TESTS_OPTIONS);
    routerFactory.mountServicesFromExtensions();
  }).onComplete(h -> {
    testRequest(client, HttpMethod.POST, "/testA")
      .expect(jsonBodyResponse(new JsonObject().put("result", "Ciao Francesco!")), statusCode(200))
      .sendJson(new JsonObject().put("hello", "Ciao").put("name", "Francesco"), testContext, checkpoint);

    testRequest(client, HttpMethod.POST, "/testB")
      .expect(jsonBodyResponse(new JsonObject().put("result", "Ciao Francesco?")), statusCode(200))
      .sendJson(new JsonObject().put("hello", "Ciao").put("name", "Francesco"), testContext, checkpoint);

    testRequest(client, HttpMethod.POST, "/testC")
      .expect(jsonBodyResponse(new JsonObject().put("content-type", "application/json").put("anotherResult", "Francesco Ciao?")), statusCode(200))
      .sendJson(new JsonObject().put("hello", "Ciao").put("name", "Francesco"), testContext, checkpoint);

    testRequest(client, HttpMethod.POST, "/testD")
      .expect(jsonBodyResponse(new JsonObject().put("content-type", "application/json").put("anotherResult", "Francesco Ciao?")), statusCode(200))
      .sendJson(new JsonObject().put("hello", "Ciao").put("name", "Francesco"), testContext, checkpoint);
  });
}
 
Example #21
Source File: AbstractNonNamespacedResourceOperatorTest.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
public void createWhenExistsIsAPatch(VertxTestContext context, boolean cascade) {
    T resource = resource();
    Resource mockResource = mock(resourceType());
    when(mockResource.get()).thenReturn(resource);
    when(mockResource.cascading(cascade)).thenReturn(mockResource);
    when(mockResource.patch(any())).thenReturn(resource);

    NonNamespaceOperation mockNameable = mock(NonNamespaceOperation.class);
    when(mockNameable.withName(matches(resource.getMetadata().getName()))).thenReturn(mockResource);

    MixedOperation mockCms = mock(MixedOperation.class);
    when(mockCms.withName(matches(RESOURCE_NAME))).thenReturn(mockResource);

    C mockClient = mock(clientType());
    mocker(mockClient, mockCms);

    AbstractNonNamespacedResourceOperator<C, T, L, D, R> op = createResourceOperations(vertx, mockClient);

    Checkpoint async = context.checkpoint();
    op.createOrUpdate(resource())
        .onComplete(context.succeeding(ar -> {
            verify(mockResource).get();
            verify(mockResource).patch(any());
            verify(mockResource, never()).create(any());
            verify(mockResource, never()).createNew();
            verify(mockResource, never()).createOrReplace(any());
            verify(mockCms, never()).createOrReplace(any());
            async.flag();
        }));
}
 
Example #22
Source File: KafkaAvailabilityTest.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
@Test
public void testNoLeader(VertxTestContext context) {
    KSB ksb = new KSB()
            .addNewTopic("A", false)
                .addToConfig(TopicConfig.MIN_IN_SYNC_REPLICAS_CONFIG, "1")
                .addNewPartition(0)
                    .replicaOn(0, 1, 2)
                    //.leader(0)
                    .isr(1, 2)
                .endPartition()
            .endTopic()
            .addNewTopic("B", false)
                .addToConfig(TopicConfig.MIN_IN_SYNC_REPLICAS_CONFIG, "1")
                .addNewPartition(0)
                    .replicaOn(0, 1, 2)
                    //.leader(1)
                    .isr(0)
                .endPartition()
            .endTopic()

            .addBroker(3);

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

    Checkpoint a = context.checkpoint(ksb.brokers.size());
    for (Integer brokerId : ksb.brokers.keySet()) {
        kafkaSorted.canRoll(brokerId).onComplete(context.succeeding(canRoll -> context.verify(() -> {
            if (brokerId == 0) {
                assertFalse(canRoll,
                        "broker " + brokerId + " should not be rollable, because B/0 would be below min isr");
            } else {
                assertTrue(canRoll,
                        "broker " + brokerId + " should be rollable, being minisr = 1 and having two brokers in its isr");
            }
            a.flag();
        })));
    }
}
 
Example #23
Source File: ValidationHandlerProcessorsIntegrationTest.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
@Test
public void testHeaderParamsSimpleTypes(VertxTestContext testContext) {
  Checkpoint checkpoint = testContext.checkpoint(2);

  ValidationHandler validationHandler = ValidationHandlerBuilder
    .create(parser)
    .headerParameter(param("x-a", stringSchema()))
    .headerParameter(param("x-b", booleanSchema()))
    .headerParameter(param("x-c", intSchema()))
    .build();
  router.get("/testHeaderParams")
    .handler(validationHandler)
    .handler(routingContext -> {
      RequestParameters params = routingContext.get("parsedParameters");
      routingContext
        .response()
        .setStatusMessage(String
          .format("%s%s%s", params.headerParameter("x-a"), params.headerParameter("x-b"), params.headerParameter("x-c"))
        ).end();
    });
  String a = "hello";
  String b = "false";
  String c = "10";

  testRequest(client, HttpMethod.GET, "/testHeaderParams")
    .with(requestHeader("x-a", a), requestHeader("x-b", b), requestHeader("x-c", c))
    .expect(statusCode(200), statusMessage(a + b + c))
    .send(testContext, checkpoint);

  testRequest(client, HttpMethod.GET, "/testHeaderParams")
    .with(requestHeader("x-a", a), requestHeader("x-b", "bla"), requestHeader("x-c", c))
    .expect(badParameterResponse(
      ParameterProcessorException.ParameterProcessorErrorType.PARSING_ERROR,
      "x-b",
      ParameterLocation.HEADER
    ))
    .send(testContext, checkpoint);
}
 
Example #24
Source File: KafkaAvailabilityTest.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
@Test
public void testNoMinIsr(VertxTestContext context) {
    KSB ksb = new KSB()
            .addNewTopic("A", false)
                .addNewPartition(0)
                    .replicaOn(0, 1, 2)
                    .leader(0)
                    .isr(0, 1, 2)
                .endPartition()
            .endTopic()
            .addNewTopic("B", false)
                .addNewPartition(0)
                    .replicaOn(0, 1, 2)
                    .leader(1)
                    .isr(1, 0, 2)
                .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 = 1 and having two brokers in its isr");
            a.flag();
        })));
    }
}
 
Example #25
Source File: TopicOperatorTest.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
/** Test what happens when a non-topic KafkaTopic gets created in kubernetes */
@Test
public void testOnKafkaTopicAdded_ignorable(VertxTestContext context) {
    KafkaTopic kafkaTopic = new KafkaTopicBuilder().withMetadata(new ObjectMetaBuilder().withName("non-topic").build()).build();

    Checkpoint async = context.checkpoint();
    K8sTopicWatcher w = new K8sTopicWatcher(topicOperator, Future.succeededFuture());
    w.eventReceived(ADDED, kafkaTopic);
    mockKafka.assertEmpty(context);
    mockTopicStore.assertEmpty(context);
    async.flag();
}
 
Example #26
Source File: KafkaAssemblyOperatorMockTest.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
@ParameterizedTest
@MethodSource("data")
public void testReconcileUpdatesKafkaPersistentVolumes(Params params, VertxTestContext context) {
    init(params);
    assumeTrue(kafkaStorage instanceof PersistentClaimStorage, "Parameterized Test only runs for Params with Kafka Persistent storage");

    String originalStorageClass = Storage.storageClass(kafkaStorage);

    Checkpoint async = context.checkpoint();
    initialReconcile(context)
        .onComplete(context.succeeding(v -> context.verify(() -> {
            assertStorageClass(context, KafkaCluster.kafkaClusterName(CLUSTER_NAME), originalStorageClass);

            // Try to update the storage class
            String changedClass = originalStorageClass + "2";

            Kafka changedClusterCm = new KafkaBuilder(cluster)
                    .editSpec()
                        .editKafka()
                            .withNewPersistentClaimStorage()
                                .withStorageClass(changedClass)
                                .withSize("123")
                            .endPersistentClaimStorage()
                        .endKafka()
                    .endSpec()
                    .build();
            kafkaAssembly(NAMESPACE, CLUSTER_NAME).patch(changedClusterCm);

            LOGGER.info("Updating with changed storage class");
        })))
        .compose(v -> operator.reconcile(new Reconciliation("test-trigger", Kafka.RESOURCE_KIND, NAMESPACE, CLUSTER_NAME)))
        .onComplete(context.succeeding(v -> context.verify(() -> {
            // Check the storage class was not changed
            assertStorageClass(context, KafkaCluster.kafkaClusterName(CLUSTER_NAME), originalStorageClass);
            async.flag();
        })));
}
 
Example #27
Source File: AbstractResourceOperatorTest.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
@Test
public void testReconcileDeleteThrowsWhenDeletionThrows(VertxTestContext context) {
    RuntimeException ex = new RuntimeException("Testing this exception is handled correctly");
    Deletable mockDeletable = mock(Deletable.class);
    when(mockDeletable.delete()).thenThrow(ex);

    EditReplacePatchDeletable mockERPD = mock(EditReplacePatchDeletable.class);
    when(mockERPD.withGracePeriod(anyLong())).thenReturn(mockDeletable);

    T resource = resource();
    Resource mockResource = mock(resourceType());
    when(mockResource.get()).thenReturn(resource);
    when(mockResource.cascading(eq(true))).thenReturn(mockERPD);

    NonNamespaceOperation mockNameable = mock(NonNamespaceOperation.class);
    when(mockNameable.withName(matches(RESOURCE_NAME))).thenReturn(mockResource);

    MixedOperation mockCms = mock(MixedOperation.class);
    when(mockCms.inNamespace(matches(NAMESPACE))).thenReturn(mockNameable);

    C mockClient = mock(clientType());
    mocker(mockClient, mockCms);

    AbstractResourceOperator<C, T, L, D, R> op = createResourceOperations(vertx, mockClient);

    Checkpoint async = context.checkpoint();
    op.reconcile(resource.getMetadata().getNamespace(), resource.getMetadata().getName(), null)
        .onComplete(context.failing(e -> context.verify(() -> {
            assertThat(e, is(ex));
            async.flag();
        })));
}
 
Example #28
Source File: AbstractCustomResourceOperatorIT.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
@Test
public void testUpdateStatus(VertxTestContext context) {
    Checkpoint async = context.checkpoint();
    String namespace = getNamespace();

    CrdOperator<C, T, L, D> op = operator();

    log.info("Getting Kubernetes version");
    PlatformFeaturesAvailability.create(vertx, client)
            .onComplete(context.succeeding(pfa -> context.verify(() -> {
                assertThat("Kubernetes version : " + pfa.getKubernetesVersion() + " is too old",
                        pfa.getKubernetesVersion().compareTo(KubernetesVersion.V1_11), CoreMatchers.is(not(lessThan(0))));
            })))

            .compose(pfa -> {
                log.info("Creating resource");
                return op.reconcile(namespace, RESOURCE_NAME, getResource());
            })
            .onComplete(context.succeeding())
            .compose(rrCreated -> {
                T newStatus = getResourceWithNewReadyStatus(rrCreated.resource());

                log.info("Updating resource status");
                return op.updateStatusAsync(newStatus);
            })
            .onComplete(context.succeeding())

            .compose(rrModified -> op.getAsync(namespace, RESOURCE_NAME))
            .onComplete(context.succeeding(modifiedCustomResource -> context.verify(() -> {
                assertReady(context, modifiedCustomResource);
            })))

            .compose(rrModified -> {
                log.info("Deleting resource");
                return op.reconcile(namespace, RESOURCE_NAME, null);
            })
            .onComplete(context.succeeding(rrDeleted ->  async.flag()));
}
 
Example #29
Source File: TenantJmsIT.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Creates an HTTP client for managing the fixture of test cases
 * and creates a {@link TenantClient} for invoking operations of the
 * Tenant API.
 *
 * @param ctx The vert.x test context.
 */
@BeforeAll
public static void prepareDeviceRegistry(final VertxTestContext ctx) {

    helper = new IntegrationTestSupport(vertx);
    helper.initRegistryClient();

    final Checkpoint connections = ctx.checkpoint(2);

    final ClientConfigProperties allTenantConfig = IntegrationTestSupport.getDeviceRegistryProperties(
            IntegrationTestSupport.TENANT_ADMIN_USER, IntegrationTestSupport.TENANT_ADMIN_PWD);

    JmsBasedHonoConnection.newConnection(allTenantConfig).connect()
    .map(con -> {
        allTenantConnection = con;
        return con;
    })
    .compose(con -> JmsBasedTenantClient.create(con, allTenantConfig))
    .onComplete(ctx.succeeding(client -> {
        allTenantClient = client;
        connections.flag();
    }));

    final ClientConfigProperties defaultTenantConfig = IntegrationTestSupport.getDeviceRegistryProperties(
            IntegrationTestSupport.HONO_USER, IntegrationTestSupport.HONO_PWD);

    JmsBasedHonoConnection.newConnection(defaultTenantConfig).connect()
    .map(con -> {
        defaultTenantConnection = con;
        return con;
    })
    .compose(con -> JmsBasedTenantClient.create(con, defaultTenantConfig))
    .onComplete(ctx.succeeding(client -> {
        defaultTenantClient = client;
        connections.flag();
    }));
}
 
Example #30
Source File: KafkaRebalanceAssemblyOperatorTest.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
/**
 * Tests the transition from New to to ProposalReady skipping the hard goals check
 *
 * 1. A new rebalance resource is created with some specified not hard goals but with flag to skip the check; it is in the New state
 * 2. The operator requests a rebalance proposal to Cruise Control REST API
 * 3. The rebalance proposal is ready on the first call
 * 4. The rebalance resource moves to ProposalReady state
 */
@Test
public void testNewToProposalReadySkipHardGoalsRebalance(VertxTestContext context) throws IOException, URISyntaxException {

    // Setup the rebalance endpoint with the number of pending calls before a response is received.
    MockCruiseControl.setupCCRebalanceResponse(ccServer, 0);

    KafkaRebalanceSpec kafkaRebalanceSpec = new KafkaRebalanceSpecBuilder()
            .withGoals("DiskCapacityGoal", "CpuCapacityGoal")
            .withSkipHardGoalCheck(true)
            .build();

    KafkaRebalance kr =
            createKafkaRebalance(CLUSTER_NAMESPACE, CLUSTER_NAME, RESOURCE_NAME, kafkaRebalanceSpec);

    Crds.kafkaRebalanceOperation(kubernetesClient).inNamespace(CLUSTER_NAMESPACE).create(kr);

    when(mockKafkaOps.getAsync(CLUSTER_NAMESPACE, CLUSTER_NAME)).thenReturn(Future.succeededFuture(kafka));
    mockRebalanceOperator(mockRebalanceOps, CLUSTER_NAMESPACE, RESOURCE_NAME, kubernetesClient);

    Checkpoint checkpoint = context.checkpoint();
    kcrao.reconcileRebalance(
            new Reconciliation("test-trigger", KafkaRebalance.RESOURCE_KIND, CLUSTER_NAMESPACE, RESOURCE_NAME),
            kr).onComplete(context.succeeding(v -> {
                // the resource moved from New directly to ProposalReady (no pending calls in the Mock server)
                assertState(context, kubernetesClient, CLUSTER_NAMESPACE, RESOURCE_NAME, KafkaRebalanceAssemblyOperator.State.ProposalReady);
                checkpoint.flag();
            }));
}