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

The following examples show how to use io.vertx.ext.unit.TestContext#assertTrue() . 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: PgUtilIT.java    From raml-module-builder with Apache License 2.0 6 votes vote down vote up
/**
 * Assert that response has the httpStatus and its result is a User with expected username and uuid.
 * uuid=null accepts any uuid. Returns the uuid of the User in response.
 */
private String assertStatusAndUser(TestContext testContext, AsyncResult<Response> result,
    int httpStatus, String username, String uuid) {

  testContext.assertTrue(result.succeeded(), "succeeded()");
  Response response = result.result();
  testContext.assertEquals(httpStatus, response.getStatus(), "status of entity=" + response.getEntity());
  if (response.getEntity() == null) {
    testContext.fail("Expected response with a User instance but it was null");
    return null;
  }
  if (! (response.getEntity() instanceof User)) {
    testContext.fail("Expected response with a User instance but type was "
        + response.getEntity().getClass().getName());
    return null;
  }
  User user = (User) response.getEntity();
  testContext.assertEquals(username, user.getUsername(), "getUsername()");
  if (uuid != null) {
    testContext.assertEquals(uuid, user.getId(), "User::getId()");
  }
  return user.getId();
}
 
Example 2
Source File: ShellCloseTest.java    From vertx-shell with Apache License 2.0 6 votes vote down vote up
@Test
public void testSessionExpires(TestContext context) throws Exception {
  Async ended = context.async();
  registry.add(CommandBuilder.command("cmd").processHandler(process -> {
    process.endHandler(v -> {
      ended.complete();
    });
  }));
  startShellServer(context, 100, 100);
  long now = System.currentTimeMillis();
  TestTtyConnection conn = termServer.openConnection();
  conn.read("cmd\r");
  ended.awaitSuccess(20000);
  context.assertTrue(conn.isClosed());
  long elapsed = System.currentTimeMillis() - now;
  context.assertTrue(elapsed < 1000);
}
 
Example 3
Source File: MultilineParserTest.java    From vertx-mail-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testLastLine(TestContext testContext) {
  MultilineParser multilineParser = new MultilineParser(b -> logger.debug(b.toString()));
  testContext.assertTrue(multilineParser.isFinalLine(Buffer.buffer("250 welcome OK")));
  testContext.assertFalse(multilineParser.isFinalLine(Buffer.buffer("250-welcome OK")));

  testContext.assertTrue(multilineParser.isFinalLine(Buffer.buffer("250-welcome OK\r\n250 2.1.0 OK")));
  testContext.assertTrue(multilineParser.isFinalLine(Buffer.buffer("250 welcome OK\n250 2.1.0 OK")));

  testContext.assertFalse(multilineParser.isFinalLine(Buffer.buffer("250-welcome OK\n250-2.1.0 OK")));
  testContext.assertFalse(multilineParser.isFinalLine(Buffer.buffer("250-welcome OK\r\n250-2.1.0 OK")));

  testContext.assertTrue(multilineParser.isFinalLine(Buffer.buffer("250-welcome OK\n250-2.1.0 OK\n250 2.1.1 OK")));
  testContext.assertTrue(multilineParser.isFinalLine(Buffer.buffer("250-welcome OK\r\n250-2.1.0 OK\r\n250 2.1.1 OK")));

}
 
Example 4
Source File: MailWithDKIMSignTest.java    From vertx-mail-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testMailSimpleSimpleAttachment(TestContext testContext) {
  this.testContext = testContext;
  Buffer img = vertx.fileSystem().readFileBlocking("logo-white-big.png");
  testContext.assertTrue(img.length() > 0);
  MailAttachment attachment = MailAttachment.create().setName("logo-white-big.png").setData(img);
  MailMessage message = exampleMessage().setText(TEXT_BODY).setAttachment(attachment);

  DKIMSignOptions dkimOps = new DKIMSignOptions(dkimOptionsBase)
    .setHeaderCanonAlgo(CanonicalizationAlgorithm.SIMPLE).setBodyCanonAlgo(CanonicalizationAlgorithm.SIMPLE);
  testSuccess(dkimMailClient(dkimOps), message, () -> {
    final MimeMultipart multiPart = (MimeMultipart)wiser.getMessages().get(0).getMimeMessage().getContent();
    testContext.assertEquals(2, multiPart.getCount());
    testContext.assertEquals(TEXT_BODY, conv2nl(inputStreamToString(multiPart.getBodyPart(0).getInputStream())));
    testContext.assertTrue(Arrays.equals(img.getBytes(), inputStreamToBytes(multiPart.getBodyPart(1).getInputStream())));
    testDKIMSign(dkimOps, testContext);
  });
}
 
Example 5
Source File: MqttServerSubscribeTest.java    From vertx-mqtt with Apache License 2.0 6 votes vote down vote up
private void subscribe(TestContext context, String topic, int expectedQos) {

    this.async = context.async();

    try {
      MemoryPersistence persistence = new MemoryPersistence();
      MqttClient client = new MqttClient(String.format("tcp://%s:%d", MQTT_SERVER_HOST, MQTT_SERVER_PORT), "12345", persistence);
      client.connect();

      String[] topics = new String[]{topic};
      int[] qos = new int[]{expectedQos};
      // after calling subscribe, the qos is replaced with granted QoS that should be the same
      client.subscribe(topics, qos);

      this.async.await();

      context.assertTrue(qos[0] == expectedQos);

    } catch (MqttException e) {

      context.assertTrue(!topic.equals(MQTT_TOPIC_FAILURE) ? false : true);
      e.printStackTrace();
    }
  }
 
Example 6
Source File: OkapiClientTest.java    From okapi with Apache License 2.0 6 votes vote down vote up
@Test
public void testHttpClientLegacy1(TestContext context) {
  Async async = context.async();
  StringBuilder b = new StringBuilder();

  context.assertTrue(server != null);
  HttpClient client = vertx.createHttpClient();
  HttpClientRequest requestAbs = HttpClientLegacy.requestAbs(client,
    HttpMethod.GET, URL + "/test1", res -> {
    b.append("response");
    context.assertEquals(200, res.statusCode());
    async.complete();
  });
  requestAbs.exceptionHandler(res -> {
    b.append("exception");
    async.complete();
  });
  requestAbs.end();
  async.await();
  context.assertEquals("response", b.toString());
}
 
Example 7
Source File: VaultClientWithCertTest.java    From vertx-config with Apache License 2.0 6 votes vote down vote up
public static Handler<AsyncResult<Auth>> getLoginTestHandler(SlimVaultClient client, TestContext tc) {
  Async async = tc.async();
  String rw_path = "secret/app/hello-" + UUID.randomUUID().toString();
  String value = "world " + UUID.randomUUID().toString();
  return ar -> {
    tc.assertTrue(ar.succeeded());
    String token = ar.result().getToken();
    tc.assertNotNull(token);

    client.setToken(token);

    // Try to write and read some secrets - using the "user" policy
    client.write(rw_path, new JsonObject().put("value", value), x -> {
      if (x.failed()) {
        x.cause().printStackTrace();
      }
      tc.assertTrue(x.succeeded());
      client.read(rw_path, y -> {
        tc.assertTrue(y.succeeded());
        tc.assertEquals(value, y.result().getData().getString("value"));
        async.complete();
      });
    });
  };
}
 
Example 8
Source File: ProtonClientTest.java    From vertx-proton with Apache License 2.0 5 votes vote down vote up
@Override
public void validate(TestContext context, Map<Symbol, Object> props) {
  context.assertNotNull(props, "no properties map provided");

  context.assertTrue(props.containsKey(ProtonMetaDataSupportImpl.PRODUCT_KEY), "product not present");
  context.assertNotNull(props.get(ProtonMetaDataSupportImpl.VERSION_KEY), "unexpected product");
  context.assertEquals(expectedProduct, props.get(ProtonMetaDataSupportImpl.PRODUCT_KEY), "unexpected product");

  context.assertTrue(props.containsKey(ProtonMetaDataSupportImpl.VERSION_KEY), "version not present");
  context.assertNotNull(props.get(ProtonMetaDataSupportImpl.VERSION_KEY), "unexpected version");
  context.assertEquals(expectedVersion, props.get(ProtonMetaDataSupportImpl.VERSION_KEY), "unexpected version");
}
 
Example 9
Source File: OkapiClientTest.java    From okapi with Apache License 2.0 5 votes vote down vote up
@Test
public void testClosed2(TestContext context) {
  Async async = context.async();

  context.assertTrue(server != null);
  server.close(res -> {
    OkapiClient cli = new OkapiClient(URL, vertx, null);
    cli.setClosedRetry(90);
    cli.get("/test1", res2 -> {
      context.assertTrue(res2.failed());
      context.assertEquals(ErrorType.INTERNAL, res2.getType());
      async.complete();
    });
  });
}
 
Example 10
Source File: OkapiClientTest.java    From okapi with Apache License 2.0 5 votes vote down vote up
@Test
public void testClosed1(TestContext context) {
  Async async = context.async();

  context.assertTrue(server != null);
  server.close(res -> {
    OkapiClient cli = new OkapiClient(URL, vertx, null);
    cli.setClosedRetry(0);
    cli.get("/test1", res2 -> {
      context.assertTrue(res2.failed());
      context.assertEquals(ErrorType.INTERNAL, res2.getType());
      async.complete();
    });
  });
}
 
Example 11
Source File: SessionAwareWebClientTest.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
@Test
public void testCookieStoreIsFluent(TestContext context) {
  CookieStore store = CookieStore.build();
  Cookie cookie = new DefaultCookie("a", "a");
  context.assertTrue(store == store.put(cookie));
  context.assertTrue(store == store.remove(cookie));
}
 
Example 12
Source File: MailWithDKIMSignTest.java    From vertx-mail-client with Apache License 2.0 5 votes vote down vote up
@Test
public void testMailRelaxedRelaxedHtmlWithAttachmentStream(TestContext testContext) {
  System.setProperty("vertx.mail.attachment.cache.file", "true");
  this.testContext = testContext;
  Buffer img = vertx.fileSystem().readFileBlocking("logo-white-big.png");
  ReadStream<Buffer> stream = vertx.fileSystem().openBlocking("logo-white-big.png", new OpenOptions());
  testContext.assertTrue(img.length() > 0);
  MailAttachment attachment = MailAttachment.create().setName("logo-white-big.png").setSize(img.length()).setStream(stream);
  MailAttachment inLineAttachment = MailAttachment.create().setName("logo-inline").setData(img);
  MailMessage message = exampleMessage()
    .setText(TEXT_BODY)
    .setHtml(HTML_BODY)
    .setInlineAttachment(inLineAttachment)
    .setAttachment(attachment);

  DKIMSignOptions dkimOps = new DKIMSignOptions(dkimOptionsBase)
    .setHeaderCanonAlgo(CanonicalizationAlgorithm.RELAXED).setBodyCanonAlgo(CanonicalizationAlgorithm.RELAXED);
  testSuccess(dkimMailClient(dkimOps), message, () -> {

    // 1. alternative multi part
    //    1.1: text part
    //    1.2: html multi part with inline attachment
    //       1.2.1: html body part
    //       1.2.2: inline attachment
    // 2. attachment part
    final MimeMultipart multiPart = (MimeMultipart)wiser.getMessages().get(0).getMimeMessage().getContent();
    testContext.assertEquals(2, multiPart.getCount());
    MimeMultipart alternative = (MimeMultipart)multiPart.getBodyPart(0).getContent();
    testContext.assertEquals(2, alternative.getCount());
    testContext.assertEquals(TEXT_BODY, conv2nl(inputStreamToString(alternative.getBodyPart(0).getInputStream())));
    MimeMultipart htmlPart = (MimeMultipart)alternative.getBodyPart(1).getContent();
    testContext.assertEquals(2, htmlPart.getCount());
    testContext.assertEquals(HTML_BODY, conv2nl(inputStreamToString(htmlPart.getBodyPart(0).getInputStream())));
    testContext.assertTrue(Arrays.equals(img.getBytes(), inputStreamToBytes(htmlPart.getBodyPart(1).getInputStream())));

    testContext.assertTrue(Arrays.equals(img.getBytes(), inputStreamToBytes(multiPart.getBodyPart(1).getInputStream())));

    testDKIMSign(dkimOps, testContext);
  });
}
 
Example 13
Source File: ShellTest.java    From vertx-shell with Apache License 2.0 5 votes vote down vote up
@Test
public void testEndInBackground(TestContext context) throws Exception {
  Async fooRunning = context.async();
  Async fooSusp = context.async();
  Async fooResumed = context.async();
  Async endLatch = context.async();
  AtomicReference<CommandProcess> cmdProcess = new AtomicReference<>();
  AtomicReference<Context> cmdContext = new AtomicReference<>();
  commands.add(
      CommandBuilder.command("foo").processHandler(process -> {
        cmdProcess.set(process);
        cmdContext.set(Vertx.currentContext());
        process.suspendHandler(v -> fooSusp.complete());
        process.resumeHandler(v -> fooResumed.complete());
        process.endHandler(v -> {
          endLatch.complete();
        });
        fooRunning.complete();
      }));
  TestTtyConnection conn = new TestTtyConnection(vertx);
  ShellImpl shell = createShell(conn);
  shell.init().readline();
  conn.read("foo\r");
  fooRunning.awaitSuccess(2000);
  conn.sendEvent(TtyEvent.SUSP);
  fooSusp.awaitSuccess(2000);
  conn.read("bg\r");
  fooResumed.awaitSuccess(2000);
  cmdContext.get().runOnContext(v -> {
    cmdProcess.get().end();
  });
  long now = System.currentTimeMillis();
  while (shell.jobController().jobs().size() > 0) {
    context.assertTrue(System.currentTimeMillis() - now < 2000);
    Thread.sleep(1);
  }
  conn.read("exit\r");
  conn.getCloseLatch().await(2, TimeUnit.SECONDS);
}
 
Example 14
Source File: MqttServerBadClientTest.java    From vertx-mqtt with Apache License 2.0 5 votes vote down vote up
@Test
public void noConnectTest(TestContext context) throws Exception {

  EventLoopGroup group = new NioEventLoopGroup();
  try {

    Bootstrap bootstrap = new Bootstrap();
    bootstrap
      .group(group)
      .channel(NioSocketChannel.class)
      .handler(new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(SocketChannel ch) throws Exception {

          ChannelPipeline pipeline = ch.pipeline();
          pipeline.addLast("mqttEncoder", MqttEncoder.INSTANCE);
        }
      });

    // Start the client.
    ChannelFuture f = bootstrap.connect(MQTT_SERVER_HOST, MQTT_SERVER_PORT).sync();

    f.channel().writeAndFlush(createPublishMessage());

    // Wait until the connection is closed.
    f.channel().closeFuture().sync();

    context.assertTrue(true);

  } finally {
    // Shut down the event loop to terminate all threads.
    group.shutdownGracefully();
  }
}
 
Example 15
Source File: DeployVerticleTest.java    From vertx-shell with Apache License 2.0 5 votes vote down vote up
@Test
public void testDeployWithOptionsAsJsonConfig(TestContext context) {
  String cmd =
    "verticle-deploy io.vertx.ext.shell.command.base.DeployVerticleTest$SomeVerticle '{\"config\":{\"ok\":true}}'";
  String result = testDeployCmd(context, cmd);
  context.assertNotNull(ctx.get());
  context.assertEquals(result, "Deployed " + ctx.get().deploymentID());
  context.assertEquals(1, ctx.get().getInstanceCount());
  context.assertNotNull(ctx.get().config());
  context.assertTrue(ctx.get().config().containsKey("ok"));
  context.assertEquals(true, ctx.get().config().getBoolean("ok"));
}
 
Example 16
Source File: ShellCloseTest.java    From vertx-shell with Apache License 2.0 5 votes vote down vote up
@Test
public void testLastAccessed(TestContext context) throws Exception {
  startShellServer(context, 100, 100);
  TestTtyConnection conn = termServer.openConnection();
  for (int i = 0; i < 100; i++) {
    conn.read("" + i);
    Thread.sleep(10);
    context.assertFalse(conn.isClosed());
  }
  context.assertTrue(conn.getCloseLatch().await(2, TimeUnit.SECONDS));
}
 
Example 17
Source File: MqttServerDisconnectTest.java    From vertx-mqtt with Apache License 2.0 5 votes vote down vote up
@Test
public void disconnect(TestContext context) {

  try {
    MemoryPersistence persistence = new MemoryPersistence();
    MqttClient client = new MqttClient(String.format("tcp://%s:%d", MQTT_SERVER_HOST, MQTT_SERVER_PORT), "12345", persistence);
    client.connect();
    client.disconnect();
    context.assertTrue(true);
  } catch (MqttException e) {
    context.assertTrue(false);
    e.printStackTrace();
  }
}
 
Example 18
Source File: MailWithDKIMSignTest.java    From vertx-mail-client with Apache License 2.0 5 votes vote down vote up
@Test
public void testMailRelaxedRelaxedHtmlWithAttachment(TestContext testContext) {
  this.testContext = testContext;
  Buffer img = vertx.fileSystem().readFileBlocking("logo-white-big.png");
  testContext.assertTrue(img.length() > 0);
  MailAttachment attachment = MailAttachment.create().setName("logo-white-big.png").setData(img);
  MailAttachment inLineAttachment = MailAttachment.create().setName("logo-inline").setData(img);
  MailMessage message = exampleMessage()
    .setText(TEXT_BODY)
    .setHtml(HTML_BODY)
    .setInlineAttachment(inLineAttachment)
    .setAttachment(attachment);

  DKIMSignOptions dkimOps = new DKIMSignOptions(dkimOptionsBase)
    .setHeaderCanonAlgo(CanonicalizationAlgorithm.RELAXED).setBodyCanonAlgo(CanonicalizationAlgorithm.RELAXED);
  testSuccess(dkimMailClient(dkimOps), message, () -> {

    // 1. alternative multi part
    //    1.1: text part
    //    1.2: html multi part with inline attachment
    //       1.2.1: html body part
    //       1.2.2: inline attachment
    // 2. attachment part
    final MimeMultipart multiPart = (MimeMultipart)wiser.getMessages().get(0).getMimeMessage().getContent();
    testContext.assertEquals(2, multiPart.getCount());
    MimeMultipart alternative = (MimeMultipart)multiPart.getBodyPart(0).getContent();
    testContext.assertEquals(2, alternative.getCount());
    testContext.assertEquals(TEXT_BODY, conv2nl(inputStreamToString(alternative.getBodyPart(0).getInputStream())));
    MimeMultipart htmlPart = (MimeMultipart)alternative.getBodyPart(1).getContent();
    testContext.assertEquals(2, htmlPart.getCount());
    testContext.assertEquals(HTML_BODY, conv2nl(inputStreamToString(htmlPart.getBodyPart(0).getInputStream())));
    testContext.assertTrue(Arrays.equals(img.getBytes(), inputStreamToBytes(htmlPart.getBodyPart(1).getInputStream())));

    testContext.assertTrue(Arrays.equals(img.getBytes(), inputStreamToBytes(multiPart.getBodyPart(1).getInputStream())));

    testDKIMSign(dkimOps, testContext);
  });
}
 
Example 19
Source File: MySQLQueryTest.java    From vertx-sql-client with Apache License 2.0 4 votes vote down vote up
@Test
public void testLocalInfileRequestInPackets(TestContext ctx) {
  FileSystem fileSystem = vertx.fileSystem();
  Buffer fileData = Buffer.buffer();
  for (int i = 0; i < 200000; i++) {
    fileData.appendString("Fluffy,Harold,cat,f,1993-02-04,NULL")
      .appendString("\n")
      .appendString("Bowser,Diane,dog,m,1979-08-31,1995-07-29")
      .appendString("\n")
      .appendString("Whistler,Gwen,bird,NULL,1997-12-09,NULL")
      .appendString("\n");
  }
  ctx.assertTrue(fileData.length() > 0xFFFFFF);
  fileSystem.createTempFile(null, null, ctx.asyncAssertSuccess(filename -> {
    fileSystem.writeFile(filename, fileData, ctx.asyncAssertSuccess(write -> {
      MySQLConnection.connect(vertx, options, ctx.asyncAssertSuccess(conn -> {
        conn.query("TRUNCATE TABLE localinfile").execute(ctx.asyncAssertSuccess(cleanup -> {
          conn.query("LOAD DATA LOCAL INFILE '" + filename + "' INTO TABLE localinfile FIELDS TERMINATED BY ',' ENCLOSED BY '\"' LINES TERMINATED BY '\\n';").execute(ctx.asyncAssertSuccess(v -> {
            conn.query("SELECT * FROM localinfile").execute(ctx.asyncAssertSuccess(rowSet -> {
              ctx.assertEquals(600000, rowSet.size());
              RowIterator<Row> iterator = rowSet.iterator();
              for (int i = 0; i < 200000; i++) {
                Row row1 = iterator.next();
                ctx.assertEquals("Fluffy", row1.getValue(0));
                ctx.assertEquals("Harold", row1.getValue(1));
                ctx.assertEquals("cat", row1.getValue(2));
                ctx.assertEquals("f", row1.getValue(3));
                ctx.assertEquals(LocalDate.of(1993, 2, 4), row1.getValue(4));
                ctx.assertEquals(null, row1.getValue(5));
                Row row2 = iterator.next();
                ctx.assertEquals("Bowser", row2.getValue(0));
                ctx.assertEquals("Diane", row2.getValue(1));
                ctx.assertEquals("dog", row2.getValue(2));
                ctx.assertEquals("m", row2.getValue(3));
                ctx.assertEquals(LocalDate.of(1979, 8, 31), row2.getValue(4));
                ctx.assertEquals(LocalDate.of(1995, 7, 29), row2.getValue(5));
                Row row3 = iterator.next();
                ctx.assertEquals("Whistler", row3.getValue(0));
                ctx.assertEquals("Gwen", row3.getValue(1));
                ctx.assertEquals("bird", row3.getValue(2));
                ctx.assertEquals(null, row3.getValue(3));
                ctx.assertEquals(LocalDate.of(1997, 12, 9), row3.getValue(4));
                ctx.assertEquals(null, row3.getValue(5));
              }
              conn.close();
            }));
          }));
        }));
      }));
    }));
  }));
}
 
Example 20
Source File: StompServerImplTest.java    From vertx-stomp with Apache License 2.0 4 votes vote down vote up
private void ensureListening(TestContext context, AsyncResult<StompServer> ar) {
  context.assertTrue(ar.succeeded());
  context.assertNotNull(ar.result());
  context.assertTrue(ar.result().isListening());
}