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

The following examples show how to use io.vertx.ext.unit.Async#complete() . 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: TestContextImpl.java    From vertx-unit with Apache License 2.0 6 votes vote down vote up
@Override
public <T> Handler<AsyncResult<T>> asyncAssertSuccess(Handler<T> resultHandler) {
  Async async = async();
  return ar -> {
    if (ar.succeeded()) {
      T result = ar.result();
      try {
        resultHandler.handle(result);
        async.complete();
      } catch (Throwable e) {
        failed(e);
      }
    } else {
      failed(ar.cause());
    }
  };
}
 
Example 2
Source File: KafkaProducerServiceIntegrationTest.java    From vertx-kafka-service with Apache License 2.0 6 votes vote down vote up
public void shouldReceiveMessage(TestContext testContext, Async async) throws Exception {
    final StringKafkaMessage stringKafkaMessage = new StringKafkaMessage("foobar", "bar");
    final KafkaProducerService kafkaProducerService = KafkaProducerService.createProxy(vertx, ADDRESS);
    kafkaProducerService.sendString(stringKafkaMessage, (Handler<AsyncResult<Void>>) message -> {
        if (message.failed()) {
            testContext.fail();
        }
    });

    wait.until(new RunnableAssert("shouldReceiveMessage") {
        @Override
        public void run() throws Exception {
            assertThat(messagesReceived.contains("foobar"), is(true));
        }
    });
    async.complete();
}
 
Example 3
Source File: ProcessModuleHandleTest.java    From okapi with Apache License 2.0 6 votes vote down vote up
@Test
public void testCmdlineStartFails(TestContext context) {
  final Async async = context.async();
  // Cannot rely on sh and kill on Windows
  String os = System.getProperty("os.name").toLowerCase();
  if (os.contains("win")) {
    async.complete();
    return;
  }
  LaunchDescriptor desc = new LaunchDescriptor();
  // start fails (no such file or directory)
  desc.setCmdlineStart("gyf %p");
  desc.setCmdlineStop("gyf");
  ModuleHandle mh = createModuleHandle(desc, 0);

  mh.start(res -> {
    context.assertTrue(res.failed());
    async.complete();
  });

}
 
Example 4
Source File: TcpEventBusBridgeTest.java    From vertx-tcp-eventbus-bridge with Apache License 2.0 6 votes vote down vote up
@Test
public void testSendPing(TestContext context) {
  NetClient client = vertx.createNetClient();
  final Async async = context.async();
  // MESSAGE for ping
  final FrameParser parser = new FrameParser(parse -> {
    context.assertTrue(parse.succeeded());
    JsonObject frame = parse.result();
    context.assertEquals("pong", frame.getString("type"));
    client.close();
    async.complete();
  });
  client.connect(7000, "localhost", context.asyncAssertSuccess(socket -> {
  socket.handler(parser);
    FrameHelper.sendFrame("register", "echo", null, socket);
    FrameHelper.sendFrame("ping", socket);
  }));
}
 
Example 5
Source File: ProcessModuleHandleTest.java    From okapi with Apache License 2.0 6 votes vote down vote up
@Test
public void testBadCmdlineStop(TestContext context) {
  final Async async = context.async();
  // Cannot rely on sh and kill on Windows
  String os = System.getProperty("os.name").toLowerCase();
  if (os.contains("win")) {
    async.complete();
    return;
  }
  LaunchDescriptor desc = new LaunchDescriptor();
  // start works (we don't check port) but stop fails
  desc.setCmdlineStart("echo %p; sleep 1 &");
  desc.setCmdlineStop("gyf");
  ModuleHandle mh = createModuleHandle(desc, 0);

  mh.start(res1 -> {
    context.assertTrue(res1.succeeded());
    mh.stop(res2 -> {
      context.assertTrue(res2.failed());
      async.complete();
    });
  });
}
 
Example 6
Source File: PgUtilIT.java    From raml-module-builder with Apache License 2.0 6 votes vote down vote up
/**
 * Return a handler that, when invoked, asserts that the AsyncResult succeeded, the Response has httpStatus,
 * and the toString() of the entity of Response contains the snippet.
 */
private Handler<AsyncResult<Response>> asyncAssertSuccess(TestContext testContext, int httpStatus, String snippet) {
  Async async = testContext.async();
  return handler -> {
    testContext.assertTrue(handler.succeeded(), "handler.succeeded()");
    Response response = handler.result();
    String entity = "null";
    if (response.getEntity() != null) {
      entity = response.getEntity().toString();
    }
    if (httpStatus != response.getStatus() || ! entity.contains(snippet)) {
      testContext.fail("Expected " + httpStatus + " and entity containing " + snippet + "\n"
          + "but got " + response.getStatus() + " with entity=" + entity);
    }
    async.complete();
  };
}
 
Example 7
Source File: TestContextImpl.java    From vertx-unit with Apache License 2.0 6 votes vote down vote up
@Override
public <T> Handler<AsyncResult<T>> asyncAssertFailure(Handler<Throwable> causeHandler) {
  Async async = async();
  return ar -> {
    if (ar.failed()) {
      Throwable result = ar.cause();
      try {
        causeHandler.handle(result);
        async.complete();
      } catch (Throwable e) {
        failed(e);
      }
    } else {
      reportAssertionError("Was expecting a failure instead of of success");
    }
  };
}
 
Example 8
Source File: TestContextImpl.java    From vertx-unit with Apache License 2.0 5 votes vote down vote up
public void run(Throwable failed, long timeout, Handler<TestContext> test, Handler<Throwable> eh) {
  CountDownLatch latch = new CountDownLatch(1);
  synchronized (this) {
    if (running) {
      throw new IllegalStateException("Already running");
    }
    running = true;
    completionLatch = latch;
    completionResult = null;
    completionHandler = err -> {
      if (failed != null) {
        eh.handle(failed);
      } else {
        eh.handle(err);
      }
    };
  }
  if (timeout > 0) {
    Runnable cancel = () -> {
      try {
        if (latch.await(timeout, TimeUnit.MILLISECONDS)) {
          return;
        }
        tryFail(new TimeoutException());
      } catch (InterruptedException e) {
        Thread.currentThread().interrupt(); // Should fail as interrupted ?
      }
    };
    Thread timeoutThread = new Thread(cancel);
    timeoutThread.setName("vert.x-unit-timeout-thread-" + threadCount.incrementAndGet());
    timeoutThread.start();
  }
  Async async = async(1, false);
  try {
    test.handle(TestContextImpl.this);
    async.complete();
  } catch (Throwable t) {
    tryFail(t);
  }
}
 
Example 9
Source File: PgUtilIT.java    From raml-module-builder with Apache License 2.0 5 votes vote down vote up
/**
 * Return a handler that, when invoked, asserts that the AsyncResult failed, and the message of the
 * cause of the failure contains the snippet.
 */
private Handler<AsyncResult<Response>> asyncAssertFail(TestContext testContext, String snippet) {
  Async async = testContext.async();
  return handler -> {
    testContext.assertTrue(handler.failed(), "handler.failed()");
    String message = handler.cause().getMessage();
    testContext.assertTrue(message.contains(snippet),
        "'" + snippet + "' expected in error message: " + message);
    async.complete();
  };
}
 
Example 10
Source File: SSHServerTest.java    From vertx-shell with Apache License 2.0 5 votes vote down vote up
@Test
public void testType(TestContext context) throws Exception {
  Async async = context.async();
  termHandler = term -> {
    context.assertEquals("vt100", term.type());
    async.complete();
  };
  startShell();
  Session session = createSession("paulo", "secret", false);
  session.connect();
  Channel channel = session.openChannel("shell");
  channel.connect();
}
 
Example 11
Source File: TestBase.java    From okapi with Apache License 2.0 5 votes vote down vote up
/**
 * Like context.asyncAssertSuccess() but for ExtendedAsyncResult;
 */
protected Handler<ExtendedAsyncResult<Void>> asyncAssertSuccess(TestContext context) {
  Async async = context.async();
  return handler -> {
    if (handler.failed()) {
      context.fail(handler.cause());
    }
    async.complete();
  };
}
 
Example 12
Source File: PetStoreTest.java    From vertx-swagger with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 2000)
public void testSwaggerManager(TestContext context) {
    Async async = context.async(2);
    SwaggerManager instance = SwaggerManager.getInstance();
    context.assertNotNull(instance.getSwagger());
    context.assertEquals("Swagger Petstore", instance.getSwagger().getInfo().getTitle());
    async.complete();
}
 
Example 13
Source File: ShellCloseTest.java    From vertx-shell with Apache License 2.0 5 votes vote down vote up
@Test
public void testCloseWhileEnding(TestContext context) throws Exception {
  Async processStarted = context.async();
  Async processEnding = context.async();
  Async processEnd = context.async();
  Async closed = context.async();
  AtomicReference<Runnable> end = new AtomicReference<>();
  registry.add(CommandBuilder.command("cmd").processHandler(process -> {
    process.endHandler(v -> {
      processEnding.complete();
      processEnd.awaitSuccess(20000);
    });
    Context ctx = process.vertx().getOrCreateContext();
    end.set(() -> {
      ctx.runOnContext(v -> {
        process.end();
      });
    });
    processStarted.complete();
  }));
  startShellServer(context, 30000, 100);
  TestTtyConnection conn = termServer.openConnection();
  conn.read("cmd\r");
  processStarted.awaitSuccess(20000);
  end.get().run();
  processEnding.awaitSuccess(20000);
  shellServer.close(context.asyncAssertSuccess(v -> {
      closed.complete();
    }
  ));
  processEnd.complete();
}
 
Example 14
Source File: JsonRxPetStoreTest.java    From vertx-swagger with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 2000)
public void testSwaggerManager(TestContext context) {
    Async async = context.async(2);
    SwaggerManager instance = SwaggerManager.getInstance();
    context.assertNotNull(instance.getSwagger());
    context.assertEquals("Swagger Petstore", instance.getSwagger().getInfo().getTitle());
    async.complete();
}
 
Example 15
Source File: RxPetStoreTest.java    From vertx-swagger with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 2000)
public void testSwaggerManager(TestContext context) {
    Async async = context.async(2);
    SwaggerManager instance = SwaggerManager.getInstance();
    context.assertNotNull(instance.getSwagger());
    context.assertEquals("Swagger Petstore", instance.getSwagger().getInfo().getTitle());
    async.complete();
}
 
Example 16
Source File: RabbitMQConsumptionStreamingTest.java    From vertx-rabbitmq-client with Apache License 2.0 5 votes vote down vote up
@Test
public void pauseAndResumeShouldWork(TestContext ctx) throws Exception {
  int count = 1;
  Set<String> messages = createMessages(count);
  String q = setupQueue(ctx, messages);

  Async paused = ctx.async();
  Async resumed = ctx.async();
  Async messageReceived = ctx.async();

  client.basicConsumer(q, new QueueOptions(), ctx.asyncAssertSuccess(consumer -> {
    consumer.pause();
    consumer.handler(msg -> {
      ctx.assertNotNull(msg);
      // if not resumed, test should fail
      if (resumed.count() == 1) {
        ctx.fail();
      } else {
        messageReceived.complete();
      }
    });
    paused.complete();
    // wait for resume command
    resumed.await();
    consumer.resume();
  }));

  paused.awaitSuccess(15000);

  // wait some time to ensure that handler will not receive any messages when it is paused
  Thread.sleep(1000);
  resumed.complete();
}
 
Example 17
Source File: ManagedServiceDiscoveryTest.java    From vertx-graphql-service-discovery with Apache License 2.0 5 votes vote down vote up
@Test
public void should_Invoke_Close_Action_When_Closing_Managed_Discovery(TestContext context) {
    Async async = context.async();
    AtomicInteger check = new AtomicInteger(1);

    final Action<Void> closeAction = () -> {
        assertEquals(0, check.decrementAndGet());
        async.complete();
        return null;
    };
    ServiceDiscovery discovery = ManagedServiceDiscovery.of(
            ServiceDiscovery.create(vertx, new ServiceDiscoveryOptions().setName("discovery2")), closeAction);
    discovery.close();
}
 
Example 18
Source File: PostgresClientIT.java    From raml-module-builder with Apache License 2.0 5 votes vote down vote up
/**
 * Similar to context.asyncAssertSuccess(resultHandler) but the type of the resultHandler
 * is {@code Handler<AsyncResult<SQLConnection>>} and not {@code Handler<SQLConnection>}.
 * Usage: {@code postgresClient.startTx(asyncAssertTx(context, trans ->}
 */
private static Handler<AsyncResult<SQLConnection>> asyncAssertTx(
    TestContext context, Handler<AsyncResult<SQLConnection>> resultHandler) {

  Async async = context.async();
  return trans -> {
    if (trans.failed()) {
      context.fail(trans.cause());
    }
    resultHandler.handle(trans);
    async.complete();
  };
}
 
Example 19
Source File: ConsumerTestBase.java    From vertx-kafka-client with Apache License 2.0 4 votes vote down vote up
@Test
public void testAssignThenSetHandler(TestContext ctx) throws Exception {
  String topicName = "testAssignThenSetHandler";
  String consumerId = topicName;
  kafkaCluster.createTopic(topicName, 1, 1);
  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);
  int numMessages = 1;
  Async finished = ctx.async(numMessages + 2);
  kafkaCluster.useTo().produceStrings(numMessages, finished::countDown,
    () -> new ProducerRecord<>(topicName, 0, "key", "value"));
  Context context = vertx.getOrCreateContext();
  consumer = createConsumer(context, config);

  Async assigned = ctx.async();
  Async handler = ctx.async();

  consumer.batchHandler(records -> {
    ctx.assertTrue(handler.isCompleted() && assigned.isCompleted());
    finished.countDown();
  });

  TopicPartition partition = new TopicPartition(topicName, 0);

  consumer.assign(Collections.singleton(partition), asyncResult -> {

    if (asyncResult.succeeded()) {

      assigned.complete();

    } else {
      ctx.fail();
    }

  });

  consumer.handler(record -> {
    ctx.assertTrue(handler.isCompleted() && assigned.isCompleted());
    finished.countDown();
  });
  handler.complete();

}
 
Example 20
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();
}