Java Code Examples for io.vertx.test.core.TestUtils#randomAlphaString()

The following examples show how to use io.vertx.test.core.TestUtils#randomAlphaString() . 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: SockJSWriteTest.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
@Test
public void testXHRStreamingFailure() throws Exception {
  String expected = TestUtils.randomAlphaString(64);
  socketHandler = () -> socket -> {
    socket.endHandler(v -> {
      socket.write(Buffer.buffer(expected), onFailure(err -> {
        testComplete();
      }));
    });
  };
  startServers();
  client.post("/test/400/8ne8e94a/xhr_streaming", Buffer.buffer(), onSuccess(resp -> {
    resp.request().connection().close();
  }));
  await();
}
 
Example 2
Source File: CredentialListParserTest.java    From vertx-mongo-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testSimpleAuthWithSource() {
  JsonObject config = new JsonObject();
  String username = TestUtils.randomAlphaString(8);
  String password = TestUtils.randomAlphaString(20);
  String authSource = TestUtils.randomAlphaString(10);
  config.put("username", username);
  config.put("password", password);
  config.put("authSource", authSource);

  List<MongoCredential> credentials = new CredentialListParser(config).credentials();
  assertEquals(1, credentials.size());
  MongoCredential credential = credentials.get(0);
  assertEquals(username, credential.getUserName());
  assertArrayEquals(password.toCharArray(), credential.getPassword());
  assertEquals(authSource, credential.getSource());
}
 
Example 3
Source File: CredentialListParserTest.java    From vertx-mongo-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testAuth_SCRAM_SHA_1() {
  JsonObject config = new JsonObject();
  String username = TestUtils.randomAlphaString(8);
  String password = TestUtils.randomAlphaString(20);
  String authSource = TestUtils.randomAlphaString(10);
  config.put("username", username);
  config.put("password", password);
  config.put("authSource", authSource);
  config.put("authMechanism", "SCRAM-SHA-1");

  List<MongoCredential> credentials = new CredentialListParser(config).credentials();
  assertEquals(1, credentials.size());
  MongoCredential credential = credentials.get(0);
  assertEquals(username, credential.getUserName());
  assertArrayEquals(password.toCharArray(), credential.getPassword());
  assertEquals(authSource, credential.getSource());

  assertEquals(AuthenticationMechanism.SCRAM_SHA_1, credential.getAuthenticationMechanism());
}
 
Example 4
Source File: SockJSWriteTest.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
@Test
public void testEventSource() throws Exception {
  waitFor(2);
  String expected = TestUtils.randomAlphaString(64);
  socketHandler = () -> socket -> {
    socket.write(Buffer.buffer(expected), onSuccess(v -> {
      complete();
    }));
  };
  startServers();
  client.get("/test/400/8ne8e94a/eventsource", onSuccess(resp -> {
    resp.handler(buffer -> {
      if (buffer.toString().equals("data: a[\"" + expected + "\"]\r\n\r\n")) {
        complete();
      }
    });
  }));
  await();
}
 
Example 5
Source File: EventbusBridgeTest.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
@Test
public void testPermittedOptionsJson() {
  String address = TestUtils.randomAlphaString(10);
  String addressRegex = TestUtils.randomAlphaString(10);
  String requiredAuthority = TestUtils.randomAlphaString(10);
  JsonObject match = new JsonObject().put(TestUtils.randomAlphaString(10), TestUtils.randomAlphaString(10));
  JsonObject json = new JsonObject().
    put("address", address).
    put("addressRegex", addressRegex).
    put("requiredAuthority", requiredAuthority).
    put("match", match);
  PermittedOptions options = new PermittedOptions(json);
  assertEquals(address, options.getAddress());
  assertEquals(addressRegex, options.getAddressRegex());
  assertEquals(requiredAuthority, options.getRequiredAuthority());
  assertEquals(match, options.getMatch());
}
 
Example 6
Source File: SockJSWriteTest.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
@Test
public void testEventSourceFailure() throws Exception {
  String expected = TestUtils.randomAlphaString(64);
  socketHandler = () -> socket -> {
    socket.endHandler(v -> {
      socket.write(Buffer.buffer(expected), onFailure(err -> {
        testComplete();
      }));
    });
  };
  startServers();
  client.get("/test/400/8ne8e94a/eventsource", onSuccess(resp -> {
    resp.request().connection().close();
  }));
  await();
}
 
Example 7
Source File: CredentialListParserTest.java    From vertx-mongo-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testAuth_SCRAM_SHA_256() {
  JsonObject config = new JsonObject();
  String username = TestUtils.randomAlphaString(8);
  String password = TestUtils.randomAlphaString(20);
  String authSource = TestUtils.randomAlphaString(10);
  config.put("username", username);
  config.put("password", password);
  config.put("authSource", authSource);
  config.put("authMechanism", "SCRAM-SHA-256");

  List<MongoCredential> credentials = new CredentialListParser(config).credentials();
  assertEquals(1, credentials.size());
  MongoCredential credential = credentials.get(0);
  assertEquals(username, credential.getUserName());
  assertArrayEquals(password.toCharArray(), credential.getPassword());
  assertEquals(authSource, credential.getSource());

  assertEquals(AuthenticationMechanism.SCRAM_SHA_256, credential.getAuthenticationMechanism());
}
 
Example 8
Source File: OptionsTest.java    From vertx-unit with Apache License 2.0 6 votes vote down vote up
@org.junit.Test
public void testCopyOptions() {
  TestOptions options = new TestOptions();
  long timeout = TestUtils.randomLong();
  Boolean useEventLoop = randomBoolean();
  String to = TestUtils.randomAlphaString(10);
  String at = TestUtils.randomAlphaString(10);
  String format = TestUtils.randomAlphaString(10);
  ReportOptions reporter = new ReportOptions().setTo(to).setFormat(format);
  options.setUseEventLoop(useEventLoop).setTimeout(timeout).addReporter(reporter);
  TestOptions copy = new TestOptions(options);
  options.setTimeout(TestUtils.randomLong());
  options.setUseEventLoop(randomBoolean());
  reporter.setTo(TestUtils.randomAlphaString(10));
  reporter.setFormat(TestUtils.randomAlphaString(10));
  options.getReporters().clear();
  assertEquals(timeout, copy.getTimeout());
  assertEquals(useEventLoop, copy.isUseEventLoop());
  assertEquals(1, copy.getReporters().size());
  assertEquals(to, copy.getReporters().get(0).getTo());
  assertEquals(format, copy.getReporters().get(0).getFormat());
}
 
Example 9
Source File: SockJSWriteTest.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
@Test
public void testXHRPollingShutdown() throws Exception {
  // Take 5 seconds which is the hearbeat timeout
  waitFor(3);
  String expected = TestUtils.randomAlphaString(64);
  socketHandler = () -> socket -> {
    socket.write(Buffer.buffer(expected), onFailure(err -> {
      complete();
    }));
    socket.endHandler(v -> {
      socket.write(Buffer.buffer(expected), onFailure(err -> {
        complete();
      }));
    });
  };
  startServers();
  client.post("/test/400/8ne8e94a/xhr", Buffer.buffer(), onSuccess(resp -> {
    assertEquals(200, resp.statusCode());
    complete();
  }));
  await();
}
 
Example 10
Source File: CredentialListParserTest.java    From vertx-mongo-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testSimpleAuth() {
  JsonObject config = new JsonObject().put("db_name", "my-datasource");
  String username = TestUtils.randomAlphaString(8);
  String password = TestUtils.randomAlphaString(20);
  config.put("username", username);
  config.put("password", password);


  List<MongoCredential> credentials = new CredentialListParser(config).credentials();
  assertEquals(1, credentials.size());
  MongoCredential credential = credentials.get(0);
  assertEquals(username, credential.getUserName());
  assertArrayEquals(password.toCharArray(), credential.getPassword());
  // default source should be the database name - see https://github.com/vert-x3/vertx-mongo-client/issues/46.
  assertEquals("my-datasource", credential.getSource());
}
 
Example 11
Source File: SockJSWriteTest.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
@Test
public void testRaw() throws Exception {
  waitFor(2);
  String expected = TestUtils.randomAlphaString(64);
  socketHandler = () -> socket -> {
    socket.write(Buffer.buffer(expected), onSuccess(v -> {
      complete();
    }));
  };
  startServers();
  client.webSocket("/test/websocket", onSuccess(ws -> {
    ws.handler(buffer -> {
      if (buffer.toString().equals(expected)) {
        complete();
      }
    });
  }));
  await();
}
 
Example 12
Source File: SockJSWriteTest.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
@Test
public void testXHRPollingClose() throws Exception {
  // Take 5 seconds which is the hearbeat timeout
  waitFor(3);
  String expected = TestUtils.randomAlphaString(64);
  socketHandler = () -> socket -> {
    socket.write(Buffer.buffer(expected), onFailure(err -> {
      complete();
    }));
    socket.endHandler(v -> {
      socket.write(Buffer.buffer(expected), onFailure(err -> {
        complete();
      }));
    });
    socket.close();
  };
  startServers();
  client.post("/test/400/8ne8e94a/xhr", Buffer.buffer(), onSuccess(resp -> {
    assertEquals(200, resp.statusCode());
    complete();
  }));
  await();
}
 
Example 13
Source File: MongoClientTestBase.java    From vertx-mongo-client with Apache License 2.0 5 votes vote down vote up
@Test
public void testMongoClientUpdateResultUnacknowledge() throws Exception {
  String collection = randomCollection();
  String upsertedId = TestUtils.randomAlphaString(20);
  mongoClient.insert(collection, createDoc(), onSuccess(id -> {
    mongoClient.updateCollectionWithOptions(collection, new JsonObject().put("_id", upsertedId), new JsonObject().put("$set", new JsonObject().put("foo", "fooed")),
      new UpdateOptions().setWriteOption(UNACKNOWLEDGED),onSuccess(res -> {
        assertNull(res);
        testComplete();
      }));
  }));
  await();
}
 
Example 14
Source File: SockJSHandlerTest.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
@Test
public void testSplitLargeReplySockJs() throws InterruptedException {
  String serverPath = "/large-reply-sockjs";

  String largeMessage = TestUtils.randomAlphaString(65536 * 2);
  Buffer largeReplyBuffer = Buffer.buffer(largeMessage);

  setupSockJsServer(serverPath, (sock, requestBuffer) -> {
    sock.write(largeReplyBuffer);
    sock.close();
  });

  List<Buffer> receivedMessages = new ArrayList<>();
  WebSocket openedWebSocket = setupSockJsClient(serverPath, receivedMessages);

  String messageToSend = "[\"hello\"]";
  openedWebSocket.writeFrame(WebSocketFrame.textFrame(messageToSend, true));

  await(5, TimeUnit.SECONDS);

  int receivedReplyCount = receivedMessages.size();
  assertTrue("Should have received > 2 reply frame, actually received " + receivedReplyCount, receivedReplyCount > 2);

  Buffer expectedReplyBuffer = Buffer.buffer("a[\"").appendBuffer(largeReplyBuffer).appendBuffer(Buffer.buffer("\"]"));
  Buffer clientReplyBuffer = combineReplies(receivedMessages.subList(0, receivedMessages.size() - 1));
  assertEquals(String.format("Combined reply on client (length %s) should equal message from server (%s)",
    clientReplyBuffer.length(), expectedReplyBuffer.length()),
    expectedReplyBuffer, clientReplyBuffer);

  Buffer finalMessage = receivedMessages.get(receivedMessages.size() - 1);
  assertEquals("Final message should have been a close", SOCKJS_CLOSE_REPLY, finalMessage);
}
 
Example 15
Source File: MetricsTest.java    From vertx-dropwizard-metrics with Apache License 2.0 5 votes vote down vote up
@Test
public void testNamedHttpClientMetrics() throws Exception {
  String name = TestUtils.randomAlphaString(10);
  HttpClient client = vertx.createHttpClient(new HttpClientOptions().setMetricsName(name));
  HttpServer server = vertx.createHttpServer(new HttpServerOptions().setHost("localhost").setPort(8080)).requestHandler(req -> {
    req.response().end();
  }).listen(ar -> {
    assertTrue(ar.succeeded());
    client.get(8080, "localhost", "/file", ar1 -> {
      if (ar1.succeeded()) {
        HttpClientResponse resp = ar1.result();
        resp.bodyHandler(buff -> {
          testComplete();
        });
      }
    });
  });

  await();

  String baseName = "vertx.http.clients." + name;
  JsonObject metrics = metricsService.getMetricsSnapshot(baseName);
  assertTrue(metrics.size() > 0);
  assertCount(metrics.getJsonObject(baseName + ".bytes-read"), 0L);

  cleanup(client);

  assertWaitUntil(() -> metricsService.getMetricsSnapshot(baseName).size() == 0);

  cleanup(server);
}
 
Example 16
Source File: MetricsTest.java    From vertx-dropwizard-metrics with Apache License 2.0 5 votes vote down vote up
@Test
public void testHttpClientMetricsName() throws Exception {
  String name = TestUtils.randomAlphaString(10);
  HttpClient namedClient = vertx.createHttpClient(new HttpClientOptions().setMetricsName(name));
  assertEquals(AbstractMetrics.unwrap(namedClient).baseName(), "vertx.http.clients." + name);
  cleanup(namedClient);

  HttpClient unnamedClient = vertx.createHttpClient();
  assertEquals(AbstractMetrics.unwrap(unnamedClient).baseName(), "vertx.http.clients");
  cleanup(unnamedClient);
}
 
Example 17
Source File: JunitXmlReporterTest.java    From vertx-unit with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testReportAfterFailure() throws Exception {
  String testSuiteName = TestUtils.randomAlphaString(10);
  String testCaseName1 = TestUtils.randomAlphaString(10);
  TestSuiteImpl suite = (TestSuiteImpl) TestSuite.create(testSuiteName).
      test(testCaseName1, context -> {
      }).
      after(context -> {
        context.fail("the_after_failure");
      });
  JunitXmlFormatter reporter = new JunitXmlFormatter(this::reportTo);
  suite.runner().setReporter(new TestCompletionImpl(reporter)).run();
  latch.await(10, TimeUnit.SECONDS);
  Element testsuiteElt = doc.getDocumentElement();
  assertEquals("testsuite", testsuiteElt.getTagName());
  assertNotNull(testsuiteElt.getAttribute("time"));
  assertEquals("2", testsuiteElt.getAttribute("tests"));
  assertEquals("1", testsuiteElt.getAttribute("errors"));
  assertEquals("0", testsuiteElt.getAttribute("skipped"));
  assertEquals(testSuiteName, testsuiteElt.getAttribute("name"));
  NodeList testCases = testsuiteElt.getElementsByTagName("testcase");
  assertEquals(2, testCases.getLength());
  Element testCase1Elt = (Element) testCases.item(0);
  assertEquals(testCaseName1, testCase1Elt.getAttribute("name"));
  assertNotNull(testCase1Elt.getAttribute("time"));
  assertEquals(0, testCase1Elt.getElementsByTagName("failure").getLength());
  Element testCase2Elt = (Element) testCases.item(1);
  assertEquals(testSuiteName, testCase2Elt.getAttribute("name"));
  assertNotNull(testCase2Elt.getAttribute("time"));
  assertEquals(1, testCase2Elt.getElementsByTagName("failure").getLength());
  Element testCase2FailureElt = (Element) testCase2Elt.getElementsByTagName("failure").item(0);
  assertEquals("AssertionError", testCase2FailureElt.getAttribute("type"));
  assertEquals("the_after_failure", testCase2FailureElt.getAttribute("message"));
  testComplete();
}
 
Example 18
Source File: SockJSWriteTest.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
@Test
public void testWebSocketFailure() throws Exception {
  String expected = TestUtils.randomAlphaString(64);
  socketHandler = () -> socket -> {
    socket.endHandler(v -> {
      socket.write(Buffer.buffer(expected), onFailure(err -> {
        testComplete();
      }));
    });
  };
  startServers();
  client.webSocket("/test/400/8ne8e94a/websocket", onSuccess(WebSocketBase::close));
  await();
}
 
Example 19
Source File: MongoTestBase.java    From vertx-mongo-client with Apache License 2.0 4 votes vote down vote up
protected String randomCollection() {
  return "ext-mongo" + TestUtils.randomAlphaString(20);
}
 
Example 20
Source File: EventBusTest.java    From vertx-unit with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testEventBusReport() throws Exception {
  long now = System.currentTimeMillis();
  String address = TestUtils.randomAlphaString(10);
  String testSuiteName = TestUtils.randomAlphaString(10);
  String testCaseName1 = TestUtils.randomAlphaString(10);
  String testCaseName2 = TestUtils.randomAlphaString(10);
  String testCaseName3 = TestUtils.randomAlphaString(10);
  MessageConsumer<JsonObject> consumer = vertx.eventBus().localConsumer(address);
  Handler<Message<JsonObject>> messageHandler = EventBusCollector.create(vertx, testSuite -> {
    Map<TestCaseReport, TestResult> results = new LinkedHashMap<>();
    testSuite.handler(testCase -> {
      testCase.endHandler(result -> {
        results.put(testCase, result);
      });
    });
    testSuite.endHandler(done -> {
      assertEquals(testSuiteName, testSuite.name());
      assertEquals(3, results.size());
      Iterator<Map.Entry<TestCaseReport, TestResult>> it = results.entrySet().iterator();
      Map.Entry<TestCaseReport, TestResult> entry1 = it.next();
      assertEquals(entry1.getKey().name(), entry1.getValue().name());
      assertEquals(testCaseName1, entry1.getValue().name());
      assertTrue(entry1.getValue().succeeded());
      assertTrue(entry1.getValue().beginTime() >= now);
      assertEquals(10, entry1.getValue().durationTime());
      assertNull(entry1.getValue().failure());
      Map.Entry<TestCaseReport, TestResult> entry2 = it.next();
      assertEquals(entry2.getKey().name(), entry2.getValue().name());
      assertEquals(testCaseName2, entry2.getValue().name());
      assertFalse(entry2.getValue().succeeded());
      assertTrue(entry2.getValue().beginTime() >= now);
      assertEquals(5, entry2.getValue().durationTime());
      assertNotNull(entry2.getValue().failure());
      assertEquals(false, entry2.getValue().failure().isError());
      assertEquals("the_failure_message", entry2.getValue().failure().message());
      assertEquals("the_failure_stackTrace", entry2.getValue().failure().stackTrace());
      assertTrue(entry2.getValue().failure().cause() instanceof IOException);
      Map.Entry<TestCaseReport, TestResult> entry3 = it.next();
      assertEquals(entry3.getKey().name(), entry3.getValue().name());
      assertEquals(testCaseName3, entry3.getValue().name());
      assertFalse(entry3.getValue().succeeded());
      assertTrue(entry3.getValue().beginTime() >= now);
      assertEquals(7, entry3.getValue().durationTime());
      assertNotNull(entry3.getValue().failure());
      assertEquals(false, entry3.getValue().failure().isError());
      assertEquals(null, entry3.getValue().failure().message());
      assertEquals("the_failure_stackTrace", entry3.getValue().failure().stackTrace());
      assertTrue(entry3.getValue().failure().cause() instanceof IOException);
      consumer.unregister();
      testComplete();
    });
  }).asMessageHandler();
  consumer.completionHandler(ar -> {
    assertTrue(ar.succeeded());
    vertx.eventBus().publish(address, new JsonObject().put("type", EventBusCollector.EVENT_TEST_SUITE_BEGIN).put("name", testSuiteName));
    vertx.eventBus().publish(address, new JsonObject().put("type", EventBusCollector.EVENT_TEST_CASE_BEGIN).put("name", testCaseName1));
    vertx.eventBus().publish(address, new JsonObject().put("type", EventBusCollector.EVENT_TEST_CASE_END).put("name", testCaseName1).put("beginTime", System.currentTimeMillis()).put("durationTime", 10L));
    vertx.eventBus().publish(address, new JsonObject().put("type", EventBusCollector.EVENT_TEST_CASE_BEGIN).put("name", testCaseName2));
    vertx.eventBus().publish(address, new JsonObject().put("type", EventBusCollector.EVENT_TEST_CASE_END).put("name", testCaseName2).put("beginTime", System.currentTimeMillis()).put("durationTime", 5L).
        put("failure", new FailureImpl(
            false, "the_failure_message", "the_failure_stackTrace", new IOException()).toJson()));
    vertx.eventBus().publish(address, new JsonObject().put("type", EventBusCollector.EVENT_TEST_CASE_BEGIN).put("name", testCaseName3));
    vertx.eventBus().publish(address, new JsonObject().put("type", EventBusCollector.EVENT_TEST_CASE_END).put("name", testCaseName3).put("beginTime", System.currentTimeMillis()).put("durationTime", 7L).
        put("failure", new FailureImpl(
            false, null, "the_failure_stackTrace", new IOException()).toJson()));
    vertx.eventBus().publish(address, new JsonObject().put("type", EventBusCollector.EVENT_TEST_SUITE_END));
  });
  consumer.handler(messageHandler);
  await();
}