Java Code Examples for io.vertx.ext.unit.Async#awaitSuccess()

The following examples show how to use io.vertx.ext.unit.Async#awaitSuccess() . 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: CustomMicrometerMetricsITest.java    From vertx-micrometer-metrics with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldPublishQuantilesWithProvidedRegistry(TestContext context) throws Exception {
  PrometheusMeterRegistry registry = new PrometheusMeterRegistry(PrometheusConfig.DEFAULT);
  vertx = Vertx.vertx(new VertxOptions()
    .setMetricsOptions(new MicrometerMetricsOptions()
      .setPrometheusOptions(new VertxPrometheusOptions().setEnabled(true)
        .setPublishQuantiles(true)
        .setStartEmbeddedServer(true)
        .setEmbeddedServerOptions(new HttpServerOptions().setPort(9090)))
      .setMicrometerRegistry(registry)
      .setEnabled(true)));

  Async async = context.async();
  // Dummy connection to trigger some metrics
  PrometheusTestHelper.tryConnect(vertx, context, 9090, "localhost", "/metrics", r1 -> {
    // Delay to make "sure" metrics are populated
    vertx.setTimer(500, l -> {
      assertThat(registry.scrape()).contains("vertx_http_client_responseTime_seconds_bucket{code=\"200\"");
      async.complete();
    });
  });
  async.awaitSuccess(10000);
}
 
Example 2
Source File: PostgresClientIT.java    From raml-module-builder with Apache License 2.0 6 votes vote down vote up
@Test
public void streamGetWithFilterZeroHits(TestContext context) throws IOException, FieldException {
  AtomicInteger objectCount = new AtomicInteger();
  Async async = context.async();

  final String tableDefiniton = "id UUID PRIMARY KEY , jsonb JSONB NOT NULL, distinct_test_field TEXT";

  createTableWithPoLines(context, MOCK_POLINES_TABLE, tableDefiniton);
  CQLWrapper wrapper = new CQLWrapper(new CQL2PgJSON("jsonb"), "edition=Millenium edition");
  postgresClient.streamGet(MOCK_POLINES_TABLE, Object.class, "jsonb", wrapper, false, null,
    context.asyncAssertSuccess(sr -> {
      context.assertEquals(0, sr.resultInto().getTotalRecords());
      sr.handler(streamHandler -> objectCount.incrementAndGet());
      sr.endHandler(x -> {
        context.assertEquals(0, objectCount.get());
        async.complete();
      });
    }));
  async.awaitSuccess();
}
 
Example 3
Source File: HystrixDashboardProxyEurekaTest.java    From standalone-hystrix-dashboard with MIT License 6 votes vote down vote up
@Test
public void testShouldFailOnOfflineEureka(TestContext testContext) throws Exception {
  final String proxyUrl = DASHBOARD_EUREKA_PROXY_URL + "http://localhost:54321/eureka/v2/apps";
  final Async proxyRequest = testContext.async();

  httpClient.getNow(proxyUrl, resp -> {
    testContext.assertTrue(resp.statusCode() == HttpResponseStatus.INTERNAL_SERVER_ERROR.code());

    resp.bodyHandler(bodyBuffer -> {
      final String body = bodyBuffer.toString(StandardCharsets.UTF_8);
      log.info("Response Body: {}", body);
      testContext.assertTrue(body.contains("Connection refused"));
      proxyRequest.complete();
    });
  });

  proxyRequest.awaitSuccess(5000L);
}
 
Example 4
Source File: ShellTest.java    From vertx-shell with Apache License 2.0 6 votes vote down vote up
@Test
public void testSuspendProcess(TestContext context) throws Exception {
  TestTtyConnection conn = new TestTtyConnection(vertx);
  ShellImpl shell = createShell(conn);
  shell.init().readline();
  Async done = context.async();
  Async latch2 = context.async();
  commands.add(CommandBuilder.command("foo").processHandler(process -> {
    Job job = shell.jobController().getJob(1);
    process.suspendHandler(v -> {
      context.assertEquals(ExecStatus.STOPPED, job.status());
      context.assertNull(shell.jobController().foregroundJob());
      done.complete();
    });
    latch2.complete();
  }));
  conn.read("foo\r");
  latch2.awaitSuccess(10000);
  conn.sendEvent(TtyEvent.SUSP);
}
 
Example 5
Source File: ConsumerTestBase.java    From vertx-kafka-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testBatchHandler(TestContext ctx) throws Exception {
  String topicName = "testBatchHandler";
  String consumerId = topicName;
  Async batch1 = ctx.async();
  AtomicInteger index = new AtomicInteger();
  int numMessages = 500;
  kafkaCluster.useTo().produceStrings(numMessages, batch1::complete, () ->
    new ProducerRecord<>(topicName, 0, "key-" + index.get(), "value-" + index.getAndIncrement()));
  batch1.awaitSuccess(10000);
  Properties config = kafkaCluster.useTo().getConsumerProperties(consumerId, consumerId, OffsetResetStrategy.EARLIEST);
  config.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
  config.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
  Context context = vertx.getOrCreateContext();
  consumer = createConsumer(context, config);
  Async batchHandler = ctx.async();
  consumer.batchHandler(records -> {
    ctx.assertEquals(numMessages, records.count());
    batchHandler.complete();
  });
  consumer.exceptionHandler(ctx::fail);
  consumer.handler(rec -> {});
  consumer.subscribe(Collections.singleton(topicName));
}
 
Example 6
Source File: TenantAPIIT.java    From raml-module-builder with Apache License 2.0 6 votes vote down vote up
public void tenantDelete(TestContext context) {
  Async async = context.async();
  vertx.runOnContext(run -> {
    TenantAPI tenantAPI = new TenantAPI();
    try {
      tenantAPI.deleteTenant(okapiHeaders, h -> {
        tenantAPI.tenantExists(Vertx.currentContext(), tenantId, onSuccess(context, bool -> {
          context.assertFalse(bool, "tenant exists during delete");
          async.complete();
        }));
      }, Vertx.currentContext());
    } catch (Exception e) {
      context.fail(e);
    }
  });
  async.awaitSuccess();
}
 
Example 7
Source File: ProtonClientTest.java    From vertx-proton with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 20000)
public void testDefaultAnonymousSenderSpecifiesLinkTarget(TestContext context) throws Exception {
  server.close();
  Async async = context.async();

  ProtonServer protonServer = null;
  try {
    protonServer = createServer(
        (serverConnection) -> processConnectionAnonymousSenderSpecifiesLinkTarget(context, async, serverConnection));

    ProtonClient client = ProtonClient.create(vertx);
    client.connect("localhost", protonServer.actualPort(), res -> {
      context.assertTrue(res.succeeded());

      ProtonConnection connection = res.result();
      connection.openHandler(x -> {
        LOG.trace("Client connection opened");

        ProtonSender sender = connection.createSender(null);
        // Can optionally add an openHandler or sendQueueDrainHandler
        // to await remote sender open completing or credit to send being
        // granted. But here we will just buffer the send immediately.
        sender.open();
        sender.send(message("ignored", "content"));
      }).open();
    });

    async.awaitSuccess();
  } finally {
    if (protonServer != null) {
      protonServer.close();
    }
  }
}
 
Example 8
Source File: ProtonServerImplTest.java    From vertx-proton with Apache License 2.0 5 votes vote down vote up
private void doTestAsyncServerAuthenticatorTestImpl(TestContext context, boolean passAuthentication) {
  Async connectAsync = context.async();
  AtomicBoolean connectedServer = new AtomicBoolean();

  final long delay = 750;
  TestAsyncAuthenticator testAsyncAuthenticator = new TestAsyncAuthenticator(delay, passAuthentication);
  TestAsyncAuthenticatorFactory authenticatorFactory = new TestAsyncAuthenticatorFactory(testAsyncAuthenticator);

  ProtonServer.create(vertx).saslAuthenticatorFactory(authenticatorFactory).connectHandler(protonConnection -> {
    connectedServer.set(true);
  }).listen(server -> {
    final long startTime = System.currentTimeMillis();
    ProtonClient.create(vertx).connect("localhost", server.result().actualPort(), GOOD_USER, PASSWD, conResult -> {
      // Verify the process took expected time from auth delay.
      long actual = System.currentTimeMillis() - startTime;
      context.assertTrue(actual >= delay, "Connect completed before expected time delay elapsed! " + actual);

      if (passAuthentication) {
        context.assertTrue(conResult.succeeded(), "Expected connect to succeed");
        conResult.result().disconnect();
      } else {
        context.assertFalse(conResult.succeeded(), "Expected connect to fail");
      }

      connectAsync.complete();
    });
  });

  connectAsync.awaitSuccess();

  if(passAuthentication) {
    context.assertTrue(connectedServer.get(), "Server handler should have been called");
  } else {
    context.assertFalse(connectedServer.get(), "Server handler should not have been called");
  }

  context.assertEquals(1, authenticatorFactory.getCreateCount(), "unexpected authenticator creation count");
}
 
Example 9
Source File: PgUtilIT.java    From raml-module-builder with Apache License 2.0 5 votes vote down vote up
/**
 * Post a new user, expect the httpStatus, and a returned User with matching username
 * and matching uuid if uuid was not null.
 * @param uuid  optional
 * @return uuid returned by the POST
 */
private String post(TestContext testContext, String username, String uuid, int httpStatus) {
  Async async = testContext.async();
  String [] returnedUuid = new String [1];
  PgUtil.post("users", new User().withUsername(username).withId(uuid),
      okapiHeaders, vertx.getOrCreateContext(), ResponseImpl.class, result -> {
        returnedUuid[0] = assertStatusAndUser(testContext, result, httpStatus, username, uuid);
        async.complete();
      });
  async.awaitSuccess();
  return returnedUuid[0];
}
 
Example 10
Source File: ShellServerPromptTest.java    From vertx-shell with Apache License 2.0 5 votes vote down vote up
@Test
public void testPrompt(TestContext context) {
  commands = new TestCommands(vertx);
  ShellServer server =  ShellServer.create(vertx, new ShellServerOptions()
    .setWelcomeMessage("")
    .setSessionTimeout(100)
    .setReaperInterval(100));
  server.shellHandler(shell -> shell.setPrompt(s -> "FOOPROMPT"));
  TestTermServer termServer = new TestTermServer(vertx);
  server.registerTermServer(termServer);
  server.
    registerCommandResolver(CommandResolver.baseCommands(vertx)).
    registerCommandResolver(commands).
    listen(context.asyncAssertSuccess());

  TestTtyConnection conn = termServer.openConnection();

  Async async = context.async();
  commands.add(CommandBuilder.command("foo").processHandler(process -> {
    context.assertEquals(null, conn.checkWritten("FOOPROMPTfoo\n"));
    process.stdinHandler(cp -> {
      context.fail();
    });
    process.endHandler(v -> {
        async.complete();
      }
    );
    process.end();

  }));
  conn.read("foo\r");
  async.awaitSuccess(5000);
}
 
Example 11
Source File: PostgresClientIT.java    From raml-module-builder with Apache License 2.0 5 votes vote down vote up
private void fillA(TestContext context, PostgresClient client, String tenant, int i) {
  Async async = context.async();
  String schema = PostgresClient.convertToPsqlStandard(tenant);
  execute(context, "INSERT INTO "  + schema + ".a (i) VALUES (" + i + ") ON CONFLICT DO NOTHING;");
  client.select("SELECT i FROM " + schema + ".a", context.asyncAssertSuccess(get -> {
    context.assertEquals(i, get.iterator().next().getInteger(0));
    async.complete();
  }));
  async.awaitSuccess(5000);
}
 
Example 12
Source File: CommandProcessTest.java    From vertx-shell with Apache License 2.0 5 votes vote down vote up
@Test
public void testRunTerminatedProcess(TestContext context) {
  CommandBuilder builder = CommandBuilder.command("hello");
  Async terminatedLatch = context.async();
  builder.processHandler(CommandProcess::end);
  Process process = builder.build(vertx).createProcess().setSession(Session.create()).setTty(Pty.create().slave());
  process.terminatedHandler(exitCode -> terminatedLatch.complete());
  process.run();
  terminatedLatch.awaitSuccess(10000);
  try {
    process.run();
    context.fail();
  } catch (IllegalStateException ignore) {
  }
}
 
Example 13
Source File: ForeignKeyPerformanceIT.java    From raml-module-builder with Apache License 2.0 5 votes vote down vote up
static private void runSQL(TestContext context, String inputSql) {
  Async async = context.async();
  PostgresClient client = PostgresClient.getInstance(vertx);
  String sql = inputSql;
  if (! sql.endsWith(";\n")) {
    sql += ";\n";
  }
  client.runSQLFile(sql, true, reply -> async.complete());
  async.awaitSuccess(5000);
}
 
Example 14
Source File: ProtonServerImplTest.java    From vertx-proton with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 20000)
public void testAuthenticatorCreatedPerConnection(TestContext context) {
  Async connectedAsync = context.async();
  Async connectedAsync2 = context.async();
  AtomicInteger port = new AtomicInteger(-1);

  final TestPlainAuthenticatorFactory authenticatorFactory = new TestPlainAuthenticatorFactory();

  ProtonServer.create(vertx).saslAuthenticatorFactory(authenticatorFactory).connectHandler(protonConnection -> {
    // Verify the expected auth detail was recorded in the connection attachments, just using a String here.
    String authValue = protonConnection.attachments().get(AUTH_KEY, String.class);
    context.assertEquals(AUTH_VALUE, authValue);
  }).listen(server -> {
    port.set(server.result().actualPort());
    ProtonClient.create(vertx).connect("localhost", port.intValue(), GOOD_USER, PASSWD,
        protonConnectionAsyncResult -> {
          context.assertTrue(protonConnectionAsyncResult.succeeded());
          protonConnectionAsyncResult.result().disconnect();
          connectedAsync.complete();
        });
  });

  connectedAsync.awaitSuccess();

  context.assertEquals(1, authenticatorFactory.getCreateCount(), "unexpected authenticator count");

  ProtonClient.create(vertx).connect("localhost", port.intValue(), GOOD_USER, PASSWD, protonConnectionAsyncResult -> {
    context.assertTrue(protonConnectionAsyncResult.succeeded());
    protonConnectionAsyncResult.result().disconnect();
    connectedAsync2.complete();
  });

  connectedAsync2.awaitSuccess();

  context.assertEquals(2, authenticatorFactory.getCreateCount(), "unexpected authenticator count");
}
 
Example 15
Source File: CommandRegistryTest.java    From vertx-shell with Apache License 2.0 5 votes vote down vote up
@Test
public void testUndeployInVerticleContext(TestContext context) {
  CommandRegistry registry = CommandRegistry.getShared(vertx);
  Async async = context.async();
  AtomicReference<String> ref = new AtomicReference<>();
  vertx.deployVerticle(new AbstractVerticle() {
    @Override
    public void start(Promise<Void> startPromise) throws Exception {
      CommandBuilder command = CommandBuilder.command("hello");
      command.processHandler(process -> {
      });
      registry.registerCommand(command.build(vertx), ar -> {
        if (ar.succeeded()) {
          startPromise.complete();
        } else {
          startPromise.fail(ar.cause());
        }
      });
    }
  }, context.asyncAssertSuccess(id -> {
    ref.set(id);
    async.complete();
  }));
  async.awaitSuccess(5000);
  vertx.undeploy(ref.get(), context.asyncAssertSuccess(v -> {
    context.assertEquals(Collections.emptyList(), registry.commands());
  }));
}
 
Example 16
Source File: ExceptionTest.java    From GDH with MIT License 4 votes vote down vote up
@Test
public void testVerticleDownRetriesAsync(TestContext context) throws InterruptedException, ExecutionException {
    int amount = 2;
    PrimaryVertex pv = new PrimaryVertex();
    GDHVertex[] verticles = new GDHVertex[amount];
    Configuration[] confs = new Configuration[amount];

    for (int i = 0; i < amount; i++) {
        verticles[i] = new GDHVertex();
        confs[i] = new Configuration();
        String port = amount + "08" + i;
        confs[i].setIP(localhost).setPort(port).setLogLevel(Level.DEBUG).setExchangeTimeoutMillis(60000);
        verticles[i].setConfiguration(confs[i]);
    }
    List<GDHVertex> list = new ArrayList<>(Arrays.asList(verticles));

    Group g = new Group(confs[0], list.stream().map(y -> y.getNode()).collect(Collectors.toList()));
    verticles[0].addGroup(g);

    Async async = context.async();
    for (int i = 0; i < amount - 1; i++)
        pv.run(verticles[i], res -> {
            if (res.succeeded()) {
                async.countDown();
            } else {
                res.cause().printStackTrace();
                return;
            }
        });
    async.awaitSuccess();

    Async async3 = context.async();
    verticles[0].exchange(g.getGroupId(), res -> {
        Assert.assertTrue(res.failed());
        Assert.assertTrue(res.cause().getMessage().contains(Constants.EXCEPTIONRETRIESEXCEEDED));
        async3.complete();
    });
    async3.awaitSuccess();

    Async async2 = context.async();
    for (int i = 0; i < amount - 1; i++)
        pv.kill(verticles[i], res -> {
            if (res.succeeded()) {
                async2.countDown();
            }
        });
    async2.awaitSuccess();
}
 
Example 17
Source File: VertxPoolMetricsTest.java    From vertx-micrometer-metrics with Apache License 2.0 4 votes vote down vote up
@Test
public void shouldReportNamedPoolMetrics(TestContext context) throws InterruptedException {
  int maxPoolSize = 8;
  int taskCount = maxPoolSize * 3;
  int sleepMillis = 30;

  vertx = Vertx.vertx(new VertxOptions().setMetricsOptions(new MicrometerMetricsOptions()
    .setPrometheusOptions(new VertxPrometheusOptions().setEnabled(true))
    .addLabels(Label.POOL_NAME)
    .setEnabled(true)))
    .exceptionHandler(context.exceptionHandler());

  // Setup executor
  WorkerExecutor workerExecutor = vertx.createSharedWorkerExecutor("test-worker", maxPoolSize);
  Async ready = context.async(taskCount);
  for (int i = 0; i < taskCount; i++) {
    workerExecutor.executeBlocking(future -> {
      try {
        Thread.sleep(sleepMillis);
      } catch (InterruptedException e) {
        throw new RuntimeException(e);
      }
      future.complete();
    }, false, context.asyncAssertSuccess(v -> {
      ready.countDown();
    }));
  }
  ready.awaitSuccess();
  RegistryInspector.waitForValue(
    vertx,
    context,
    "vertx.pool.completed[pool_name=test-worker,pool_type=worker]$COUNT",
    value -> value.intValue() == taskCount);

  List<RegistryInspector.Datapoint> datapoints = listDatapoints(startsWith("vertx.pool"));
  assertThat(datapoints).hasSize(10).contains(
    dp("vertx.pool.queue.size[pool_name=test-worker,pool_type=worker]$VALUE", 0),
    dp("vertx.pool.inUse[pool_name=test-worker,pool_type=worker]$VALUE", 0),
    dp("vertx.pool.ratio[pool_name=test-worker,pool_type=worker]$VALUE", 0),
    dp("vertx.pool.completed[pool_name=test-worker,pool_type=worker]$COUNT", taskCount),
    dp("vertx.pool.queue.delay[pool_name=test-worker,pool_type=worker]$COUNT", taskCount),
    dp("vertx.pool.usage[pool_name=test-worker,pool_type=worker]$COUNT", taskCount));

  assertThat(datapoints)
    .usingFieldByFieldElementComparator()
    .usingComparatorForElementFieldsWithType(new DoubleComparator(0.1), Double.class)
    .contains(dp("vertx.pool.usage[pool_name=test-worker,pool_type=worker]$MAX", sleepMillis / 1000d));

  class GreaterOrEqualsComparator implements Comparator<Double> {
    @Override
    public int compare(Double o1, Double o2) {
      return o1 < o2 ? -1 : 0;
    }
  }

  assertThat(datapoints)
    .usingFieldByFieldElementComparator()
    .usingComparatorForElementFieldsWithType(new GreaterOrEqualsComparator(), Double.class)
    .contains(
      dp("vertx.pool.usage[pool_name=test-worker,pool_type=worker]$TOTAL_TIME", taskCount * sleepMillis / 1000d));
}
 
Example 18
Source File: ProtonSubscriberIntTest.java    From vertx-proton with Apache License 2.0 4 votes vote down vote up
@Test(timeout = 20000)
public void testConfigureProducerLinkName(TestContext context) throws Exception {
  server.close();

  final Async serverLinkOpenAsync = context.async();
  final Async serverReceivedMessageAsync = context.async();
  final Async serverLinkCloseAsync = context.async();

  final String linkName = "testConfigureProducerLinkName";

  ProtonServer protonServer = null;
  try {
    protonServer = createServer((serverConnection) -> {
      serverConnection.openHandler(result -> {
        serverConnection.open();
      });

      serverConnection.sessionOpenHandler(session -> session.open());

      serverConnection.receiverOpenHandler(serverReceiver -> {
        LOG.trace("Server receiver opened");

        // Verify the link details used were as expected
        context.assertEquals(linkName, serverReceiver.getName(), "unexpected link name");

        serverReceiver.handler((delivery, msg) -> {
          // We got the message that was sent, complete the test
          if (LOG.isTraceEnabled()) {
            LOG.trace("Server got msg: " + getMessageBody(context, msg));
          }
          validateMessage(context, 1, "1", msg);
          serverReceivedMessageAsync.complete();
        });

        serverReceiver.closeHandler(x -> {
          serverReceiver.close();
          serverLinkCloseAsync.complete();
        });

        // Set the local terminus details [naively]
        serverReceiver.setTarget(serverReceiver.getRemoteTarget().copy());

        serverReceiver.open();

        serverLinkOpenAsync.complete();
      });
    });

    // ===== Client Handling =====

    ProtonClient client = ProtonClient.create(vertx);
    client.connect("localhost", protonServer.actualPort(), res -> {
      context.assertTrue(res.succeeded());

      ProtonConnection connection = res.result();
      connection.open();

      // Create subscriber with given link name
      ProtonSubscriberOptions options = new ProtonSubscriberOptions().setLinkName(linkName);

      ProtonSubscriber<Tracker> subscriber = ProtonStreams.createTrackerProducer(connection,"myAddress", options);

      Tracker envelope = Tracker.create(message("1"));
      Publisher<Tracker> producer = Flowable.just(envelope);
      producer.subscribe(subscriber);
    });

    serverLinkOpenAsync.awaitSuccess();
    serverReceivedMessageAsync.awaitSuccess();
    serverLinkCloseAsync.awaitSuccess();
  } finally {
    if (protonServer != null) {
      protonServer.close();
    }
  }
}
 
Example 19
Source File: PostgresClientIT.java    From raml-module-builder with Apache License 2.0 4 votes vote down vote up
@Test
public void executeTransParam(TestContext context) {
  Async asyncTotal = context.async();

  Async async1 = context.async();
  JsonArray ids = new JsonArray().add(randomUuid()).add(randomUuid());
  postgresClient = insertXAndSingleQuotePojo(context, ids);
  postgresClient.startTx(trans -> {
    assertSuccess(context, trans);
    postgresClient.execute(trans, "DELETE FROM tenant_raml_module_builder.foo WHERE id=$1",
        Tuple.of(UUID.fromString(ids.getString(1))), res -> {
      assertSuccess(context, res);
      postgresClient.rollbackTx(trans, rollback -> {
        assertSuccess(context, rollback);
        async1.complete();
      });
    });
  });
  async1.awaitSuccess(5000);

  Async async2 = context.async();
  postgresClient.startTx(trans -> {
    assertSuccess(context, trans);
    postgresClient.execute(trans, "DELETE FROM tenant_raml_module_builder.foo WHERE id=$1",
        Tuple.of(UUID.fromString(ids.getString(0))), res -> {
      assertSuccess(context, res);
      postgresClient.endTx(trans, end -> {
        assertSuccess(context, end);
        async2.complete();
      });
    });
  });
  async2.awaitSuccess(5000);

  Async async3 = context.async();
  postgresClient.getById(FOO, ids, res -> {
    assertSuccess(context, res);
    context.assertEquals(1, res.result().size());
    async3.complete();
  });
  async3.awaitSuccess(5000);

  asyncTotal.complete();
}
 
Example 20
Source File: ConsumerTestBase.java    From vertx-kafka-client with Apache License 2.0 4 votes vote down vote up
public void testBeginningEndOffset(TestContext ctx, boolean beginningOffset) throws Exception {
  String topicName = "testBeginningEndOffset_" + (beginningOffset ? "beginning" : "end");
  String consumerId = topicName;
  Async batch = ctx.async();
  AtomicInteger index = new AtomicInteger();
  int numMessages = 1000;
  kafkaCluster.useTo().produceStrings(numMessages, batch::complete, () ->
    new ProducerRecord<>(topicName, 0, "key-" + index.get(), "value-" + index.getAndIncrement()));
  batch.awaitSuccess(20000);

  Properties config = kafkaCluster.useTo().getConsumerProperties(consumerId, consumerId, OffsetResetStrategy.EARLIEST);
  config.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
  config.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);

  Context context = vertx.getOrCreateContext();
  consumer = createConsumer(context, config);

  consumer.exceptionHandler(ctx::fail);

  Set<TopicPartition> topicPartitions = new HashSet<>();
  TopicPartition topicPartition = new TopicPartition(topicName, 0);
  topicPartitions.add(topicPartition);

  // Test contains two sub-tests
  Async done = ctx.async(2);
  consumer.handler(handler -> {
    // nothing to do in this test
  });

  consumer.subscribe(Collections.singleton(topicName), ctx.asyncAssertSuccess(subscribeRes -> {
      if (beginningOffset) {
        consumer.beginningOffsets(topicPartitions, beginningOffsetResult -> {
          ctx.assertTrue(beginningOffsetResult.succeeded());
          // expect one result
          ctx.assertEquals(1, beginningOffsetResult.result().size());
          // beginning offset must be 0
          ctx.assertEquals(0L, beginningOffsetResult.result().get(topicPartition));
          done.countDown();
        });
        consumer.beginningOffsets(topicPartition, beginningOffsetResult -> {
          ctx.assertTrue(beginningOffsetResult.succeeded());
          // beginning offset must be 0
          ctx.assertEquals(0L, beginningOffsetResult.result());
          done.countDown();
        });
      }
      // Tests for endOffset
      else {
        consumer.endOffsets(topicPartitions, endOffsetResult -> {
          ctx.assertTrue(endOffsetResult.succeeded());
          ctx.assertEquals(1, endOffsetResult.result().size());
          // endOffset must be equal to the number of ingested messages
          ctx.assertEquals((long) numMessages, endOffsetResult.result().get(topicPartition));
          done.countDown();
        });

        consumer.endOffsets(topicPartition, endOffsetResult -> {
          ctx.assertTrue(endOffsetResult.succeeded());
          // endOffset must be equal to the number of ingested messages
          ctx.assertEquals((long) numMessages, endOffsetResult.result());
          done.countDown();
        });
      }
    }
  ));
}