Java Code Examples for io.vertx.ext.unit.TestContext#async()

The following examples show how to use io.vertx.ext.unit.TestContext#async() . 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: TcpEventBusBridgeTest.java    From vertx-tcp-eventbus-bridge with Apache License 2.0 6 votes vote down vote up
@Test
public void testSendMessageWithReplyBacktrack(TestContext context) {
  // Send a request and get a response
  NetClient client = vertx.createNetClient();
  final Async async = context.async();

  client.connect(7000, "localhost", context.asyncAssertSuccess(socket -> {

    final FrameParser parser = new FrameParser(parse -> {
      context.assertTrue(parse.succeeded());
      JsonObject frame = parse.result();
      context.assertNotEquals("err", frame.getString("type"));
      context.assertEquals(true, frame.getBoolean("send"));
      context.assertEquals("Hello vert.x", frame.getJsonObject("body").getString("value"));
      client.close();
      async.complete();
    });

    socket.handler(parser);

    FrameHelper.sendFrame("send", "hello", "#backtrack", new JsonObject().put("value", "vert.x"), socket);
  }));
}
 
Example 2
Source File: ApiTest.java    From redpipe with Apache License 2.0 6 votes vote down vote up
@Test
public void checkTemplateWithTemplateExtension(TestContext context) {
	Async async = context.async();

	webClient
	.get("/indexWithTemplateExtension")
	.as(BodyCodec.string())
	.rxSend()
	.map(r -> {
		System.err.println("body: "+r.body());
		context.assertEquals(200, r.statusCode());
		context.assertEquals("<html>\n" + 
				" <head>\n" + 
				"  <title>my title</title>\n" + 
				" </head>\n" + 
				" <body>my message</body>\n" + 
				"</html>", r.body());
		return r;
	})
	.doOnError(x -> context.fail(x))
	.subscribe(response -> {
		async.complete();
	});
}
 
Example 3
Source File: VertxCompletableFutureTest.java    From vertx-completable-future with Apache License 2.0 6 votes vote down vote up
@Test
public void testRunAfterBothAsync(TestContext tc) {
  Async async = tc.async();

  VertxCompletableFuture<Integer> future2 = new VertxCompletableFuture<>(vertx);
  future2.complete(1);

  vertx.runOnContext(v -> {
    String thread = Thread.currentThread().getName();

    VertxCompletableFuture<Integer> future1 = new VertxCompletableFuture<>(vertx);
    future1.complete(42);

    future1.runAfterBoth(future2, () -> {
      tc.assertEquals(thread, Thread.currentThread().getName());
      async.complete();
    });
  });

}
 
Example 4
Source File: SpringConfigServerStoreTest.java    From vertx-config with Apache License 2.0 6 votes vote down vote up
@Test
public void testWithWrongServerConfiguration(TestContext tc) {
  Async async = tc.async();
  retriever = ConfigRetriever.create(vertx,
      new ConfigRetrieverOptions().addStore(
          new ConfigStoreOptions()
              .setType("spring-config-server")
              .setConfig(new JsonObject()
                  .put("url", "http://not-valid.de")
                  .put("timeout", 10000))));


  retriever.getConfig(json -> {
    assertThat(json.succeeded()).isFalse();
    async.complete();
  });
}
 
Example 5
Source File: SimpleQueryDataTypeCodecTestBase.java    From vertx-sql-client with Apache License 2.0 6 votes vote down vote up
protected void testDecodeGenericArray(TestContext ctx,
                                      String arrayData,
                                      String columnName,
                                      ColumnChecker checker) {
  Async async = ctx.async();
  PgConnection.connect(vertx, options, ctx.asyncAssertSuccess(conn -> {
    conn.query("SET TIME ZONE 'UTC'").execute(
      ctx.asyncAssertSuccess(res -> {
        conn.query("SELECT " + arrayData + " \"" + columnName + "\"").execute(ctx.asyncAssertSuccess(result -> {
          ctx.assertEquals(1, result.size());
          Row row = result.iterator().next();
          checker.forRow(row);
          async.complete();
        }));
      }));
  }));
}
 
Example 6
Source File: OkapiClientTest.java    From okapi with Apache License 2.0 6 votes vote down vote up
@Test
public void testHttpClientLegacy5(TestContext context) {
  Async async = context.async();
  StringBuilder b = new StringBuilder();

  context.assertTrue(server != null);
  HttpClient client = vertx.createHttpClient();
  HttpClientRequest requestAbs = HttpClientLegacy.get(client,
    PORT, LOCALHOST, URL + "/test1", res -> {
      b.append("response");
      async.complete();
    });
  requestAbs.exceptionHandler(res -> {
    b.append("exception");
    async.complete();
  });
  requestAbs.end();
  async.await();
  context.assertEquals("response", b.toString());
}
 
Example 7
Source File: DateTimeTypesExtendedCodecTest.java    From vertx-sql-client with Apache License 2.0 6 votes vote down vote up
private <T> void testDecodeDataTimeGeneric(TestContext ctx,
                                           String dataType,
                                           String columnName,
                                           ColumnChecker checker,
                                           T expected) {
  Async async = ctx.async();
  PgConnection.connect(vertx, options, ctx.asyncAssertSuccess(conn -> {
    conn.prepare("SELECT $1 :: " + dataType + " \"" + columnName + "\"",
      ctx.asyncAssertSuccess(p -> {
        p.query().execute(Tuple.tuple().addValue(expected), ctx.asyncAssertSuccess(result -> {
          ctx.assertEquals(1, result.size());
          ctx.assertEquals(1, result.rowCount());
          Row row = result.iterator().next();
          checker.forRow(row);
          async.complete();
        }));
      }));
  }));
}
 
Example 8
Source File: AppTest.java    From redpipe with Apache License 2.0 5 votes vote down vote up
@After
public void after(TestContext context) {
    Async async = context.async();
    webClient.close();
    server.close().subscribe(() -> async.complete(),
    		x -> {
    			context.fail(x); 
    			async.complete();
    		});
}
 
Example 9
Source File: VolumeV1HugeTest.java    From sfs with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 300000)
public void testHugeReadStream(TestContext context) {
    SfsVertx sfsVertx = new SfsVertxImpl(rule.vertx(), backgroundPool, ioPool);
    final VolumeV1 sfsDataV1 = new VolumeV1(path);
    final int repeat = 5000000;

    Async async = context.async();
    sequence(context, sfsVertx, sfsDataV1, repeat)
            .flatMap(aVoid -> sequence(context, sfsVertx, sfsDataV1, repeat)).repeat(5)
            .subscribe(new TestSubscriber(context, async));
}
 
Example 10
Source File: SchemaMakerIT.java    From raml-module-builder with Apache License 2.0 5 votes vote down vote up
private int selectInteger(TestContext context, String sql) {
  AtomicInteger i = new AtomicInteger();

  Async async = context.async();
  PostgresClient postgresClient = PostgresClient.getInstance(vertx, tenant);
  postgresClient.selectSingle(sql, context.asyncAssertSuccess(result -> {
    i.set(result.getInteger(0));
    async.complete();
  }));

  async.awaitSuccess(5000);
  return i.get();
}
 
Example 11
Source File: ViewsTest.java    From nubes with Apache License 2.0 5 votes vote down vote up
@Test
public void testDynamicViewName(TestContext context) {
  Dog dog = TestVerticle.dogService.someDog();
  Async async = context.async();
  client().getNow("/views/dynamic?name=" + dog.getName() + "&breed=" + dog.getBreed(), response -> {
    context.assertEquals(200, response.statusCode());
    response.bodyHandler(buffer -> {
      String result = buffer.toString("UTF-8");
      context.assertEquals("Hello! I'm a dog and my name is " + dog.getName(), result);
      async.complete();
    });
  });
}
 
Example 12
Source File: RedisClusterTest.java    From vertx-redis-client with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 10_000)
public void testGet(TestContext should) {
  final Async test = should.async();
  final String key = makeKey();
  final String nonExistentKey = "---";


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

      final RedisConnection cluster = onCreate.result();

      cluster.exceptionHandler(should::fail);

      cluster.send(cmd(GET).arg(nonExistentKey), get1 -> {
        should.assertTrue(get1.succeeded());
        should.assertNull(get1.result());

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

          cluster.send(cmd(GET).arg(key), get2 -> {
            should.assertTrue(get2.succeeded());
            should.assertEquals("Hello", get2.result().toString());
            test.complete();
          });
        });
      });
    });
}
 
Example 13
Source File: RedisPooledTest.java    From vertx-redis-client with Apache License 2.0 5 votes vote down vote up
@Test
public void simpleSelectTest(TestContext should) {
  final Async test = should.async();

  Redis.createClient(rule.vertx(), "redis://localhost:7006/0")
    .send(Request.cmd(Command.PING), send -> {
      should.assertTrue(send.succeeded());
      should.assertNotNull(send.result());

      should.assertEquals("PONG", send.result().toString());
      test.complete();
    });
}
 
Example 14
Source File: VertxCompletableFutureTest.java    From vertx-completable-future with Apache License 2.0 5 votes vote down vote up
@Test
public void testAcceptFailurePropagation(TestContext tc) {
  Async async0 = tc.async();
  Async async1 = tc.async();
  Async async2 = tc.async();
  CompletableFuture<Integer> failure1 = new VertxCompletableFuture<>(vertx);
  CompletableFuture<Integer> failure2 = new VertxCompletableFuture<>(vertx);

  failure1.thenAccept(i -> tc.fail("Should not be called"))
    .whenComplete((res, err) -> {
      tc.assertEquals(err.getClass(), CompletionException.class);
      tc.assertTrue(err.getMessage().contains("A"));
      async0.complete();
    });

  failure1.thenAcceptBoth(failure2, (a, b) -> tc.fail("Should not be called"))
    .whenComplete((res, err) -> {
      tc.assertEquals(err.getClass(), CompletionException.class);
      tc.assertTrue(err.getMessage().contains("A"));
      async2.complete();
    });

  failure1.acceptEither(failure2, i -> tc.fail("Should not be called"))
    .whenComplete((res, err) -> {
      tc.assertEquals(err.getClass(), CompletionException.class);
      tc.assertTrue(err.getMessage().contains("B"));
      async1.complete();
    });

  failure2.completeExceptionally(new RuntimeException("B"));
  failure1.completeExceptionally(new RuntimeException("A"));
}
 
Example 15
Source File: DepResolutionTest.java    From okapi with Apache License 2.0 5 votes vote down vote up
@Test
public void testInstallMinorLeafOptional2(TestContext context) {
  Async async = context.async();

  Map<String, ModuleDescriptor> modsAvailable = new HashMap<>();
  modsAvailable.put(mdA100.getId(), mdA100);
  modsAvailable.put(mdA110.getId(), mdA110);
  modsAvailable.put(mdD100.getId(), mdD100);
  modsAvailable.put(mdD110.getId(), mdD110);

  Map<String, ModuleDescriptor> modsEnabled = new HashMap<>();
  modsEnabled.put(mdA100.getId(), mdA100);
  modsEnabled.put(mdD100.getId(), mdD100);

  List<TenantModuleDescriptor> tml = new LinkedList<>();
  TenantModuleDescriptor tm = new TenantModuleDescriptor();
  tm.setAction(TenantModuleDescriptor.Action.enable);
  tm.setId(mdD110.getId());
  tml.add(tm);

  DepResolution.installSimulate(modsAvailable, modsEnabled, tml, res -> {
    context.assertTrue(res.succeeded());
    logger.debug("tml result = " + Json.encodePrettily(tml));
    context.assertEquals(2, tml.size());
    context.assertEquals("moduleA-1.1.0", tml.get(0).getId());
    context.assertEquals("moduleA-1.0.0", tml.get(0).getFrom());
    context.assertEquals("enable", tml.get(0).getAction().name());
    context.assertEquals("moduleD-1.1.0", tml.get(1).getId());
    context.assertEquals("moduleD-1.0.0", tml.get(1).getFrom());
    context.assertEquals("enable", tml.get(1).getAction().name());
    async.complete();
  });
}
 
Example 16
Source File: SMTPConnectionPoolTest.java    From vertx-mail-client with Apache License 2.0 5 votes vote down vote up
@Test
public final void testAlreadyClosedgetConnection(TestContext testContext) {
  SMTPConnectionPool pool = new SMTPConnectionPool(vertx, config);
  pool.close();
  Async async = testContext.async();
  pool.getConnection("hostname", result -> {
    if (result.succeeded()) {
      testContext.fail("getConnection() should fail");
    } else {
      log.info(result.cause());
      async.complete();
    }
  });
}
 
Example 17
Source File: ConsumerTestBase.java    From vertx-kafka-client with Apache License 2.0 5 votes vote down vote up
@Test
public void testConsumeWithPoll(TestContext ctx) {
  final String topicName = "testConsumeWithPoll";
  final String consumerId = topicName;
  Async batch = ctx.async();
  int numMessages = 1000;
  kafkaCluster.useTo().produceStrings(numMessages, batch::complete, () ->
    new ProducerRecord<>(topicName, "value")
  );
  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);
  KafkaConsumer<String, String> consumer = KafkaConsumer.create(vertx, config);
  Async done = ctx.async();
  AtomicInteger count = new AtomicInteger(numMessages);

  consumer.subscribe(Collections.singleton(topicName), subscribeResult -> {

    if (subscribeResult.succeeded()) {

      vertx.setPeriodic(1000, t -> {
        consumer.poll(Duration.ofMillis(100), pollResult -> {
          if (pollResult.succeeded()) {
            if (count.updateAndGet(o -> count.get() - pollResult.result().size()) == 0) {
              vertx.cancelTimer(t);
              done.complete();
            }
          } else {
            ctx.fail();
          }
        });
      });

    } else {
      ctx.fail();
    }
  });
}
 
Example 18
Source File: NumericTypesExtendedCodecTest.java    From vertx-sql-client with Apache License 2.0 5 votes vote down vote up
@Test
public void testEncodeSerial8(TestContext ctx) {
  Async async = ctx.async();
  PgConnection.connect(vertx, options, ctx.asyncAssertSuccess(conn -> {
    conn.prepare("UPDATE \"NumericDataType\" SET \"BigSerial\" = $1 WHERE \"id\" = $2 RETURNING \"BigSerial\"",
      ctx.asyncAssertSuccess(p -> {
        p.query().execute(Tuple.tuple()
            .addLong(Long.MIN_VALUE)
            .addInteger(2)
          , ctx.asyncAssertSuccess(result -> {
            ctx.assertEquals(1, result.size());
            ctx.assertEquals(1, result.rowCount());
            Row row = result.iterator().next();
            ColumnChecker.checkColumn(0, "BigSerial")
              .returns(Tuple::getValue, Row::getValue, Long.MIN_VALUE)
              .returns(Tuple::getShort, Row::getShort, (short) 0)
              .returns(Tuple::getInteger, Row::getInteger, 0)
              .returns(Tuple::getLong, Row::getLong, Long.MIN_VALUE)
              .returns(Tuple::getFloat, Row::getFloat, -9.223372E18f)
              .returns(Tuple::getDouble, Row::getDouble, -9.223372036854776E18d)
              .returns(Tuple::getBigDecimal, Row::getBigDecimal, new BigDecimal(Long.MIN_VALUE))
              .returns(Numeric.class, Numeric.create(Long.MIN_VALUE))
              .forRow(row);
            async.complete();
          }));
      }));
  }));
}
 
Example 19
Source File: SessionAwareWebClientTest.java    From vertx-web with Apache License 2.0 4 votes vote down vote up
@Test
public void testRequestIsPrepared(TestContext context) {
  prepareServer(context, req -> {
    req.response().headers().add("set-cookie", ServerCookieEncoder.STRICT.encode(new DefaultCookie("test", "toast")));
  });

  Consumer<HttpRequest<Buffer>> check = r -> {
    Async async = context.async();
    Cookie c = new DefaultCookie("test", "localhost");
    c.setPath("/");
    client.cookieStore().remove(c);
    r.send(ar -> {
      async.complete();
      validate(context, client.cookieStore().get(false, "localhost", "/"),
          new String[] { "test" }, new String[] { "toast" });
    });
    async.await();
  };

  check.accept(client.delete("/"));
  check.accept(client.delete("localhost", "/"));
  check.accept(client.delete(PORT, "localhost", "/"));
  check.accept(client.deleteAbs("http://localhost/"));
  check.accept(client.get("/"));
  check.accept(client.get("localhost", "/"));
  check.accept(client.get(PORT, "localhost", "/"));
  check.accept(client.getAbs("http://localhost/"));
  check.accept(client.head("/"));
  check.accept(client.head("localhost", "/"));
  check.accept(client.head(PORT, "localhost", "/"));
  check.accept(client.headAbs("http://localhost/"));
  check.accept(client.patch("/"));
  check.accept(client.patch("localhost", "/"));
  check.accept(client.patch(PORT, "localhost", "/"));
  check.accept(client.patchAbs("http://localhost/"));
  check.accept(client.post("/"));
  check.accept(client.post("localhost", "/"));
  check.accept(client.post(PORT, "localhost", "/"));
  check.accept(client.postAbs("http://localhost/"));
  check.accept(client.put("/"));
  check.accept(client.put("localhost", "/"));
  check.accept(client.put(PORT, "localhost", "/"));
  check.accept(client.putAbs("http://localhost/"));
  check.accept(client.request(HttpMethod.GET, new RequestOptions()));
  check.accept(client.request(HttpMethod.GET, "/"));
  check.accept(client.request(HttpMethod.GET, "localhost", "/"));
  check.accept(client.request(HttpMethod.GET, PORT, "localhost", "/"));
  check.accept(client.requestAbs(HttpMethod.GET, "http://localhost/"));
}
 
Example 20
Source File: SchemaRegistrarTest.java    From vertx-graphql-service-discovery with Apache License 2.0 4 votes vote down vote up
@Test
public void should_Manage_Schema_Registration_And_Close_Properly(TestContext context) {
    Async async = context.async();
    context.assertNotNull(schemaRegistrar.getPublisherId());
    schemaRegistrar = SchemaRegistrar.create(vertx, "thePublisherId");
    context.assertEquals("thePublisherId", schemaRegistrar.getPublisherId());

    ServiceDiscovery discovery = schemaRegistrar.getOrCreateDiscovery(options);
    context.assertNotNull(discovery);
    context.assertNotNull(schemaRegistrar.registrations());
    context.assertEquals(0, schemaRegistrar.registrations().size());

    // Fans of nested handlers, take note! ;)
    // Publish 1
    schemaPublisher.publish(options, droidsSchema, rh -> {
        context.assertTrue(rh.succeeded());
        context.assertEquals(1, schemaPublisher.registeredSchemas().size());

        // Publish 2
        schemaPublisher.publish(options, starWarsSchema, rh2 -> {
            context.assertTrue(rh2.succeeded());
            context.assertEquals(2, schemaPublisher.registeredSchemas().size());

            // Re-publish 1. No change, already published
            schemaPublisher.publish(options, droidsSchema, rh3 -> {
                context.assertFalse(rh3.succeeded());
                context.assertEquals(2, schemaPublisher.registeredSchemas().size());

                // Publish 1 to different repository. Creates new registrations 1'
                schemaPublisher.publish(new ServiceDiscoveryOptions(options).setName("theOtherRegistry"),
                        droidsSchema, rh4 -> {
                    context.assertTrue(rh4.succeeded());
                    context.assertEquals(3, schemaPublisher.registeredSchemas().size());

                    // Unpublish 1. Discovery still in use
                    schemaPublisher.unpublish(rh.result(), rh5 -> {
                        context.assertTrue(rh5.succeeded());
                        context.assertEquals(2, schemaPublisher.registeredSchemas().size());
                        context.assertEquals(2, schemaPublisher.managedDiscoveries().size());

                        // Unpublish 2. Discovery now closed
                        schemaPublisher.unpublish(rh2.result(), rh6 -> {
                            assertTrue(rh6.succeeded());
                            assertEquals(1, schemaPublisher.registeredSchemas().size());
                            assertEquals(1, schemaPublisher.managedDiscoveries().size());

                            // Publish 1 again
                            schemaPublisher.publish(options, droidsSchema, rh7 -> {
                                context.assertTrue(rh7.succeeded());
                                assertEquals(2, schemaPublisher.managedDiscoveries().size());

                                schemaPublisher.registrar.close((registration, handler) ->
                                        handler.handle(Future.succeededFuture()), rh8 ->
                                        {
                                            assertEquals(0, schemaPublisher.managedDiscoveries().size());
                                            async.complete();
                                        });
                            });
                        });
                    });
                });
            });
        });
    });
}