Java Code Examples for io.vertx.ext.unit.Async

The following examples show how to use io.vertx.ext.unit.Async. These examples are extracted from open source projects. 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 Project: vertx-auth   Source File: ChainAuthTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void matchAllTest(TestContext should) {
  final Async test = should.async();
  ChainAuth auth = ChainAuth.all();

  auth.add((authInfo, res) -> {
    // always OK
    res.handle(Future.succeededFuture(createUser(new JsonObject().put("provider", 1))));
  });

  auth.add((authInfo, res) -> {
    // always OK
    res.handle(Future.succeededFuture(createUser(new JsonObject().put("provider", 2))));
  });

  auth.authenticate(new JsonObject(), res -> {
    if (res.succeeded()) {
      should.assertEquals(2, res.result().principal().getInteger("provider").intValue());
      test.complete();
    } else {
      should.fail();
    }
  });
}
 
Example 2
Source Project: sfs   Source File: VolumeV1Test.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testSingleDeleteRealloc(TestContext context) {

    SfsVertx sfsVertx = new SfsVertxImpl(rule.vertx(), backgroundPool, ioPool);

    final Buffer expectedBuffer = Buffer.buffer("HELLO");
    final VolumeV1 sfsDataV1 = new VolumeV1(path);

    long inThePast = System.currentTimeMillis() - VolumeV1.MAX_GC_AGE - 1;

    Calendar cal = Calendar.getInstance();
    cal.setTimeInMillis(inThePast);

    Async async = context.async();
    sfsDataV1.open(sfsVertx)
            .flatMap(new PutFile<Void>(context, sfsVertx, sfsDataV1, expectedBuffer, 0L))
            .flatMap(new GetFile(context, sfsVertx, sfsDataV1, expectedBuffer))
            .flatMap(new DeleteFile(context, sfsVertx, sfsDataV1))
            .flatMap(new SetUpdateDateTime(sfsVertx, sfsDataV1, inThePast))
            .flatMap(new Reclaim(sfsVertx, sfsDataV1))
            .flatMap(new PutFile<Long>(context, sfsVertx, sfsDataV1, expectedBuffer, 0L))
            .map(new ToVoid<Long>())
            .flatMap(new Stop(sfsVertx, sfsDataV1))
            .subscribe(new TestSubscriber(context, async));
}
 
Example 3
Source Project: gushici   Source File: ApiVerticleTest.java    License: GNU General Public License v3.0 6 votes vote down vote up
private <T> void testUrl(TestContext context, String uri,
                         Function<HttpResponse<Buffer>, T> converter,
                         Consumer<T> assertCode) {
    Async async = context.async();
    webClient.get(uri).send(res -> {
        if (res.succeeded()) {
            T result = converter.apply(res.result());
            context.verify(v -> {
                assertCode.accept(result);
                async.complete();
            });
        } else {
            context.fail(res.cause());
        }
    });
}
 
Example 4
private void request(NetClient client, TestContext ctx) {
  for (int i = 0; i < SENT_COUNT; i++) {
    Async async = ctx.async();
    client.connect(9194, "localhost", res -> {
      if (res.failed()) {
        async.complete();
        ctx.fail(res.cause());
        return;
      }
      NetSocket socket = res.result().exceptionHandler(t -> {
        async.complete();
        ctx.fail(t);
      });
      socket.handler(buf -> socket.close());
      socket.write(CLIENT_REQUEST);
      socket.closeHandler(v -> async.complete());
    });
    async.await();
  }
}
 
Example 5
Source Project: weld-vertx   Source File: AsyncReferenceTest.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("serial")
@Test
public void testAsyncReferenceNormalScoped(TestContext context) throws InterruptedException {
    NormalScopedBlockingFoo.reset();
    Async async = context.async();
    AtomicBoolean created = new AtomicBoolean(false);

    weld.select(new TypeLiteral<AsyncReference<NormalScopedBlockingFoo>>() {
    }).get().thenAccept((foo) -> {
        context.assertTrue(NormalScopedBlockingFoo.created.get());
        context.assertEquals("Foo", foo.getMessage());
        created.set(true);
        async.complete();
    });
    assertFalse(created.get());
    NormalScopedBlockingFoo.complete("Foo");
    Awaitility.await().atMost(Timeouts.DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS).until(() -> created.get());
}
 
Example 6
@Test
public void executeQueryShouldReturnExceptionIfCircuitIsHalfOpenedAndQueryFails(TestContext context) {
    // given
    givenExecuteQueryReturning(singletonList(
            Future.failedFuture(new RuntimeException("exception1"))));

    // when
    final Async async = context.async();
    jdbcClient.executeQuery("query", emptyList(), identity(), timeout) // 1 call
            .recover(ignored -> jdbcClient.executeQuery("query", emptyList(), identity(), timeout)) // 2 call
            .setHandler(ignored -> vertx.setTimer(201L, id -> async.complete()));
    async.await();

    final Future<?> future = jdbcClient.executeQuery("query", emptyList(), identity(), timeout); // 3 call

    // then
    future.setHandler(context.asyncAssertFailure(exception -> {
        assertThat(exception).isInstanceOf(RuntimeException.class).hasMessage("exception1");

        verify(wrappedJdbcClient, times(2))
                .executeQuery(any(), any(), any(), any()); // invoked only on 1 & 3 calls
    }));
}
 
Example 7
@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 8
@Test
public void testTimestamp(TestContext ctx) {
  Async async = ctx.async();
  PgConnection.connect(vertx, options, ctx.asyncAssertSuccess(conn -> {
    conn
      .query("SELECT '2017-05-14 19:35:58.237666'::TIMESTAMP \"LocalDateTime\"").execute(ctx.asyncAssertSuccess(result -> {
        LocalDateTime ldt = LocalDateTime.parse("2017-05-14T19:35:58.237666");
        ctx.assertEquals(1, result.size());
        Row row = result.iterator().next();
        ColumnChecker.checkColumn(0, "LocalDateTime")
          .returns(Tuple::getValue, Row::getValue, ldt)
          .returns(Tuple::getLocalTime, Row::getLocalTime, ldt.toLocalTime())
          .returns(Tuple::getLocalDate, Row::getLocalDate, ldt.toLocalDate())
          .returns(Tuple::getLocalDateTime, Row::getLocalDateTime, ldt)
          .returns(Tuple::getTemporal, Row::getTemporal, ldt)
          .forRow(row);
        async.complete();
      }));
  }));
}
 
Example 9
@Test
public void testHandle(TestContext tc) {
  Async async1 = tc.async();
  Async async2 = tc.async();

  VertxCompletableFuture<Integer> failure = new VertxCompletableFuture<>(vertx);
  VertxCompletableFuture<Integer> success = new VertxCompletableFuture<>(vertx);

  failure.handle((r, t) -> 43).thenAccept(i -> {
    tc.assertEquals(i, 43);
    async1.complete();
  });

  success.handle((r, t) -> r).thenAccept(i -> {
    tc.assertEquals(i, 42);
    async2.complete();
  });

  success.complete(42);
  failure.completeExceptionally(new RuntimeException("my bad"));

}
 
Example 10
Source Project: vertx-mqtt   Source File: MqttClientIdTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void afterConnectClientId(TestContext context) {

  Async async = context.async();

  MqttClientOptions options = new MqttClientOptions();
  options.setClientId("myClient");
  MqttClient client = MqttClient.create(Vertx.vertx(), options);

  client.connect(TestUtil.BROKER_PORT, TestUtil.BROKER_ADDRESS, c -> {

    assertTrue(c.succeeded());
    assertThat(client.clientId(), notNullValue());
    assertFalse(client.clientId().isEmpty());
    assertEquals(client.clientId(), "myClient");

    log.info("Client connected with requested client id = " + client.clientId());

    async.countDown();
  });
  async.await();
}
 
Example 11
@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 12
Source Project: vertx-swagger   Source File: BodyParameterExtractorTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testOkAddArrayBodyWithXML(TestContext context) {
    Async async = context.async();
    String bodyReqXml = "<BodyType><id>1</id><name>body 1</name></BodyType><BodyType><id>2</id><name>body 2</name></BodyType>";
    HttpClientRequest req = httpClient.post(TEST_PORT, TEST_HOST, "/body/array");
    req.handler(response -> {
        context.assertEquals(response.statusCode(), 200);
        response.bodyHandler(body -> {
            context.assertEquals(bodyReqXml, body.toString());
            async.complete();
        });

    })
    .putHeader(HttpHeaders.CONTENT_TYPE, "application/xml")
    .end(bodyReqXml);
}
 
Example 13
Source Project: vertx-web   Source File: FreeMarkerTemplateTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testTemplateHandlerOnFileSystem(TestContext should) {
  final Async test = should.async();
  TemplateEngine engine = FreeMarkerTemplateEngine.create(vertx);

  final JsonObject context = new JsonObject()
    .put("foo", "badger")
    .put("bar", "fox");

  context.put("context", new JsonObject().put("path", "/test-freemarker-template3.ftl"));

  engine.render(context, "src/test/filesystemtemplates/test-freemarker-template3.ftl", render -> {
    should.assertTrue(render.succeeded());
    should.assertEquals("Hello badger and fox\nRequest path is /test-freemarker-template3.ftl\n", render.result().toString());
    test.complete();
  });
  test.await();
}
 
Example 14
@Test
public void executeQueryShouldReportMetricsOnCircuitClosed(TestContext context) {
    // given
    givenExecuteQueryReturning(asList(
            Future.failedFuture(new RuntimeException("exception1")),
            Future.succeededFuture()));

    // when
    final Async async = context.async();
    jdbcClient.executeQuery("query", emptyList(), identity(), timeout) // 1 call
            .recover(ignored -> jdbcClient.executeQuery("query", emptyList(), identity(), timeout)) // 2 call
            .setHandler(ignored -> vertx.setTimer(201L, id -> async.complete()));
    async.await();

    final Future<?> future = jdbcClient.executeQuery("query", emptyList(),
            resultSet -> resultSet.getResults().get(0).getString(0), timeout); // 3 call

    // then
    future.setHandler(context.asyncAssertSuccess(result ->
            verify(metrics).updateDatabaseCircuitBreakerMetric(eq(false))));
}
 
Example 15
@Test
public void testLoadingFromSystemProperties(TestContext context) {
  Async async = context.async();
  store = factory.create(vertx, new JsonObject());
  getJsonConfiguration(vertx, store, ar -> {
    ConfigChecker.check(ar);

    // By default, the configuration is cached, try adding some entries
    System.setProperty("new", "some new value");
    getJsonConfiguration(vertx, store, ar2 -> {
      ConfigChecker.check(ar2);
      assertThat(ar2.result().getString("new")).isNull();
      async.complete();
    });
  });
}
 
Example 16
Source Project: vertx-auth   Source File: ChainAuthTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void singleTestAll(TestContext should) {
  final Async test = should.async();
  ChainAuth auth = ChainAuth.all();

  auth.add((authInfo, res) -> {
    // always OK
    res.handle(Future.succeededFuture(createUser(new JsonObject())));
  });

  auth.authenticate(new JsonObject(), res -> {
    if (res.succeeded()) {
      test.complete();
    } else {
      should.fail();
    }
  });
}
 
Example 17
Source Project: okapi   Source File: ProcessModuleHandleTest.java    License: 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 18
Source Project: vertx-redis-client   Source File: RedisClientTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testSrem(TestContext should) {
  final Async test = should.async();
  final String mykey = makeKey();
  redis.sadd(toList(mykey, "one", "two", "three"), reply0 -> {
    should.assertTrue(reply0.succeeded());
    should.assertEquals(3L, reply0.result().toLong());
    redis.srem(toList(mykey, "one"), reply1 -> {
      should.assertTrue(reply1.succeeded());
      should.assertEquals(1L, reply1.result().toLong());
      redis.srem(toList(mykey, "four"), reply2 -> {
        should.assertTrue(reply2.succeeded());
        should.assertEquals(0L, reply2.result().toLong());
        test.complete();
      });
    });
  });
}
 
Example 19
Source Project: vertx-web   Source File: JsonStreamTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testSimpleStream(TestContext tc) {
  AtomicInteger counter = new AtomicInteger();
  Async async = tc.async();
  JsonParser parser = JsonParser.newParser().objectValueMode()
    .exceptionHandler(tc::fail)
    .handler(event -> {
      JsonObject object = event.objectValue();
      tc.assertEquals(counter.getAndIncrement(), object.getInteger("count"));
      tc.assertEquals("some message", object.getString("data"));
    })
    .endHandler(x -> async.complete());

  client.get("/?separator=nl&count=10").as(BodyCodec.jsonStream(parser)).send(x -> {
    if (x.failed()) {
      tc.fail(x.cause());
    }
  });
}
 
Example 20
Source Project: vertx-redis-client   Source File: RedisClusterTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testDecrBy(TestContext should) {
  final Async test = should.async();
  final String key = makeKey();

  client
    .connect(onCreate -> {
      should.assertTrue(onCreate.succeeded());

      final RedisConnection cluster = onCreate.result();
      cluster.exceptionHandler(should::fail);

      cluster.send(cmd(SET).arg(key).arg(10), set -> {
        should.assertTrue(set.succeeded());

        cluster.send(cmd(DECRBY).arg(key).arg(5), decrBy -> {
          should.assertTrue(decrBy.succeeded());
          should.assertEquals(5L, decrBy.result().toLong());
          test.complete();
        });
      });
    });
}
 
Example 21
Source Project: konduit-serving   Source File: PortsTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testSpecifiedPortWithoutEnvironment(TestContext testContext) {
    int selectedPort = PortUtils.getAvailablePort();  // Making sure it's an available port

    Async async = testContext.async();

    DeployKonduitServing.deployInference(getConfig(testContext, selectedPort),
            handler -> {
                if(handler.succeeded()) {
                    int port = handler.result().getServingConfig().getHttpPort();

                    testContext.assertEquals(port, selectedPort);

                    // Health checking
                    given().port(selectedPort)
                            .get("/healthcheck")
                            .then()
                            .statusCode(204);

                    async.complete();
                } else {
                    testContext.fail(handler.cause());
                }
            });
}
 
Example 22
@Test
public void testEncodeUUID(TestContext ctx) {
  Async async = ctx.async();
  PgConnection.connect(vertx, options, ctx.asyncAssertSuccess(conn -> {
    conn.prepare("UPDATE \"CharacterDataType\" SET \"uuid\" = $1 WHERE \"id\" = $2 RETURNING \"uuid\"",
      ctx.asyncAssertSuccess(p -> {
        UUID uuid = UUID.fromString("92b53cf1-2ad0-49f9-be9d-ca48966e43ee");
        p.query().execute(Tuple.tuple()
          .addUUID(uuid)
          .addInteger(2), ctx.asyncAssertSuccess(result -> {
          ctx.assertEquals(1, result.size());
          ctx.assertEquals(1, result.rowCount());
          Row row = result.iterator().next();
          ColumnChecker.checkColumn(0, "uuid")
            .returns(Tuple::getValue, Row::getValue, uuid)
            .returns(Tuple::getUUID, Row::getUUID, uuid)
            .forRow(row);
          async.complete();
        }));
      }));
  }));
}
 
Example 23
Source Project: vertx-config   Source File: HoconProcessorTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testWithMissingFile(TestContext tc) {
  Async async = tc.async();
  retriever = ConfigRetriever.create(vertx,
      new ConfigRetrieverOptions().addStore(
          new ConfigStoreOptions()
              .setType("file")
              .setFormat("hocon")
              .setConfig(new JsonObject().put("path", "src/test/resources/some-missing-file.conf"))));

  retriever.getConfig(ar -> {
    assertThat(ar.failed()).isTrue();
    assertThat(ar.cause()).isNotNull().isInstanceOf(FileSystemException.class);
    async.complete();
  });
}
 
Example 24
Source Project: okapi   Source File: AuthModuleTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testFilterError(TestContext context) {
  Async async = context.async();

  HashMap<String, String> headers = new HashMap<>();
  headers.put(XOkapiHeaders.URL, URL);
  headers.put(XOkapiHeaders.TENANT, "my-lib");
  headers.put(XOkapiHeaders.FILTER, "pre");
  headers.put("X-filter-pre-error", "true");

  OkapiClient cli = new OkapiClient(URL, vertx, headers);

  cli.get("/normal", res -> {
    context.assertTrue(res.failed());
    context.assertEquals(ErrorType.INTERNAL, res.getType());
    cli.close();
    async.complete();
  });
}
 
Example 25
Source Project: apiman   Source File: LdapQueryTests.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void shouldReturnEmptyForUnmatchedFilter() throws InterruptedException {
    config.setBindDn("uid=admin,ou=system");
    config.setBindPassword("secret");

    connect((connection, context) -> {
        Async async = context.async();
        connection.search("ou=people,o=apiman", "(uid=sushi)", LdapSearchScope.SUBTREE)
        .search(searchResult -> {
            context.assertTrue(searchResult.isSuccess());

            List<ILdapSearchEntry> result = searchResult.getResult();
            context.assertEquals(0, result.size());
            async.complete();
        });
    });
}
 
Example 26
Source Project: raml-module-builder   Source File: TenantLoadingTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testOKIdRaw(TestContext context) {
  Async async = context.async();
  List<Parameter> parameters = new LinkedList<>();
  parameters.add(new Parameter().withKey("loadRef").withValue("true"));
  TenantAttributes tenantAttributes = new TenantAttributes()
    .withModuleTo("mod-1.0.0")
    .withParameters(parameters);
  Map<String, String> headers = new HashMap<String, String>();
  headers.put("X-Okapi-Url-to", "http://localhost:" + Integer.toString(port));
  TenantLoading tl = new TenantLoading().withKey("loadRef").withLead("tenant-load-ref");
  tl.withIdRaw().add("data-w-id", "data/1");
  tl.perform(tenantAttributes, headers, vertx, res -> {
    context.assertTrue(res.succeeded());
    context.assertEquals(1, res.result());
    context.assertTrue(ids.contains("1"));
    async.complete();
  });
}
 
Example 27
@Test
public void callback_path_responds_with_302_when_no_auth_code_param_is_present(final TestContext ctx) {
    final Async async = ctx.async();

    vertx.createHttpClient().get(PORT, HOST, "/oauth/callback", res -> {
        assertEquals(302, res.statusCode());
        final URL redirectUrl = buildUrl(res.headers().get(HttpHeaders.LOCATION));
        assertEquals("accounts.google.com", redirectUrl.getHost());
        final Map<String, String> params = parseQuery(redirectUrl);
        assertEquals("offline", params.get("access_type"));
        assertEquals("force", params.get("approval_prompt"));
        assertEquals(System.getenv("CLIENT_ID"), params.get("client_id"));
        assertEquals(System.getenv("REDIRECT_URL"), params.get("redirect_uri"));
        assertEquals("code", params.get("response_type"));
        async.complete();
    }).putHeader(HttpHeaders.USER_AGENT, "SomeUserAgent/1.0").end();
}
 
Example 28
Source Project: vertx-redis-client   Source File: RedisClusterTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testDecr(TestContext should) {
  final Async test = should.async();
  final String key = makeKey();

  client
    .connect(onCreate -> {
      should.assertTrue(onCreate.succeeded());

      final RedisConnection cluster = onCreate.result();
      cluster.exceptionHandler(should::fail);

      cluster.send(cmd(SET).arg(key).arg(10), set -> {
        should.assertTrue(set.succeeded());

        cluster.send(cmd(DECR).arg(key), decr -> {
          should.assertTrue(decr.succeeded());
          should.assertEquals(9L, decr.result().toLong());
          test.complete();
        });
      });
    });
}
 
Example 29
Source Project: vertx-config   Source File: ConfigMapStoreTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testWithProperties(TestContext tc) {
  Async async = tc.async();
  store = new ConfigMapStore(vertx, config()
    .put("name", "my-config-map").put("key", "my-app-props"));

  store.get(ar -> {
    tc.assertTrue(ar.succeeded());
    Properties properties = new Properties();
    try {
      properties.load(new StringReader(ar.result().toString()));
    } catch (IOException e) {
      tc.fail(e);
    }
    tc.assertEquals(properties.get("foo"), "bar");
    tc.assertEquals(properties.get("port"), "8080");
    tc.assertEquals(properties.get("debug"), "true");
    async.complete();
  });
}
 
Example 30
@Test
public void mailTest(TestContext context) {
  log.info("starting");

  Async async = context.async();

  MailClient mailClient = MailClient.create(vertx, mailConfig());

  MailMessage email = new MailMessage()
    .setFrom("[email protected]")
    .setTo("[email protected]")
    .setSubject("Test email")
    .setText("this is a message");

  mailClient.sendMail(email, result -> {
    log.info("mail finished");
    if (result.succeeded()) {
      log.info(result.result().toString());
      async.complete();
    } else {
      log.warn("got exception", result.cause());
      context.fail(result.cause());
    }
  });
}