io.vertx.ext.unit.junit.Repeat Java Examples

The following examples show how to use io.vertx.ext.unit.junit.Repeat. 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: CircuitBreakerImplTest.java    From vertx-circuit-breaker with Apache License 2.0 6 votes vote down vote up
@Test
@Repeat(5)
public void testWithUserFutureOk() {
  breaker = CircuitBreaker.create("test", vertx, new CircuitBreakerOptions());
  assertThat(breaker.state()).isEqualTo(CircuitBreakerState.CLOSED);

  AtomicBoolean operationCalled = new AtomicBoolean();
  AtomicReference<String> completionCalled = new AtomicReference<>();

  Promise<String> userFuture = Promise.promise();
  userFuture.future().onComplete(ar ->
    completionCalled.set(ar.result()));

  breaker.executeAndReport(userFuture, fut -> {
    operationCalled.set(true);
    fut.complete("hello");
  });

  await().until(operationCalled::get);
  await().until(() ->  completionCalled.get().equalsIgnoreCase("hello"));
}
 
Example #2
Source File: CircuitBreakerImplTest.java    From vertx-circuit-breaker with Apache License 2.0 6 votes vote down vote up
@Test
@Repeat(5)
public void testOk() {
  breaker = CircuitBreaker.create("test", vertx, new CircuitBreakerOptions());
  assertThat(breaker.state()).isEqualTo(CircuitBreakerState.CLOSED);

  AtomicBoolean operationCalled = new AtomicBoolean();
  AtomicReference<String> completionCalled = new AtomicReference<>();
  breaker.<String>execute(fut -> {
    operationCalled.set(true);
    fut.complete("hello");
  }).onComplete(ar -> completionCalled.set(ar.result()));

  await().until(operationCalled::get);
  await().until(() -> completionCalled.get().equalsIgnoreCase("hello"));
}
 
Example #3
Source File: CircuitBreakerMetricsTest.java    From vertx-circuit-breaker with Apache License 2.0 6 votes vote down vote up
@Test
@Repeat(100)
public void testEviction(TestContext tc) {
  breaker = CircuitBreaker.create("some-circuit-breaker", vertx,
    new CircuitBreakerOptions().setMetricsRollingWindow(10));
  Async async = tc.async();


  int count = 1000;

  List<Future> list = new ArrayList<>();
  for (int i = 0; i < count; i++) {
    list.add(breaker.execute(commandThatWorks()));
  }

  CompositeFuture.all(list)
    .onComplete(ar -> {
      assertThat(ar).succeeded();
      assertThat(metrics().getInteger("totalOperationCount")).isEqualTo(1000);
      assertThat(metrics().getInteger("rollingOperationCount")).isLessThanOrEqualTo(1000);
      async.complete();
    });
}
 
Example #4
Source File: JUnitTest.java    From vertx-unit with Apache License 2.0 5 votes vote down vote up
@Test
@Repeat(3)
public void testMethod(TestContext context) {
  events.add("test" + testCount);
  Async async = context.async();
  new Thread((() -> {
    try {
      Thread.sleep(250);
    } catch (InterruptedException ignore) {
    } finally {
      events.add("complete" + testCount++);
      async.complete();
    }
  })).start();
}
 
Example #5
Source File: StompClientImplTest.java    From vertx-stomp with Apache License 2.0 5 votes vote down vote up
@Test
@Repeat(10)
public void testRejectedConnectionWithExceptionHandler() throws InterruptedException {
  AtomicBoolean done = new AtomicBoolean();
  vertx.createNetServer()
    .connectHandler(NetSocket::close)
    .listen(61614, ar -> done.set(true));

  await().untilAtomic(done, is(true));


  CountDownLatch latch = new CountDownLatch(1);
  AtomicReference<StompClientConnection> reference = new AtomicReference<>();
  AtomicReference<Throwable> failure = new AtomicReference<>();

  StompClientOptions options = new StompClientOptions().setPort(61614);
  options.setConnectTimeout(1000);

  StompClient client = StompClient.create(vertx, options).exceptionHandler(failure::set);

  AtomicBoolean failed = new AtomicBoolean();
  client.connect(ar -> {
    if (ar.failed()) {
      failed.set(true);
      reference.set(null);
    } else {
      reference.set(ar.result());
    }
    latch.countDown();
  });

  latch.await(1, TimeUnit.MINUTES);
  assertNull(reference.get());
  assertTrue(failed.get());
  // Not called as the error happen during the connection process.
  assertThat(failure.get()).isNull();
}
 
Example #6
Source File: StompClientImplTest.java    From vertx-stomp with Apache License 2.0 5 votes vote down vote up
@Test
@Repeat(10)
public void testRejectedConnection() throws InterruptedException {
  AtomicBoolean done = new AtomicBoolean();

  vertx.createNetServer()
    .connectHandler(NetSocket::close)
    .listen(61614, ar -> done.set(true));

  await().untilAtomic(done, is(true));
  CountDownLatch latch = new CountDownLatch(1);
  AtomicBoolean failed = new AtomicBoolean();
  AtomicReference<StompClientConnection> reference = new AtomicReference<>();

  StompClientOptions options = new StompClientOptions().setPort(61614);
  options.setConnectTimeout(1000);
  StompClient client = StompClient.create(vertx, options);
  client.connect(ar -> {
    if (ar.failed()) {
      failed.set(true);
      reference.set(null);
    } else {
      reference.set(ar.result());
    }
    latch.countDown();
  });

  latch.await(10, TimeUnit.SECONDS);
  assertNull(reference.get());
  assertTrue(failed.get());
}
 
Example #7
Source File: CircuitBreakerMetricsTest.java    From vertx-circuit-breaker with Apache License 2.0 5 votes vote down vote up
@Test
@Repeat(10)
public void testLatencyComputation(TestContext tc) {
  breaker = CircuitBreaker.create("some-circuit-breaker", vertx);
  Async async = tc.async();


  int count = 1000;

  // Future chain
  Future<Void> fut = breaker.execute(commandThatWorks());
  for (int i = 1; i < count; i++) {
    Future<Void> newFut = breaker.execute(commandThatWorks());
    fut = fut.compose(v -> newFut); // Chain futures
  }

  fut
    .onComplete(ar -> {
      assertThat(ar).succeeded();
      assertThat(metrics())
        .contains("name", "some-circuit-breaker")
        .contains("state", CircuitBreakerState.CLOSED.name())
        .contains("failures", 0)
        .contains("totalErrorCount", 0)
        .contains("totalSuccessCount", count)
        .contains("totalTimeoutCount", 0)
        .contains("totalExceptionCount", 0)
        .contains("totalFailureCount", 0)
        .contains("totalOperationCount", count)
        .contains("totalSuccessPercentage", 100)
        .contains("totalErrorPercentage", 0);
      assertThat(metrics().getInteger("totalLatencyMean")).isNotZero();
      async.complete();
    });
}
 
Example #8
Source File: CircuitBreakerMetricsTest.java    From vertx-circuit-breaker with Apache License 2.0 5 votes vote down vote up
@Test
@Repeat(10)
public void testWithTimeoutCommands(TestContext tc) {
  breaker = CircuitBreaker.create("some-circuit-breaker", vertx, new CircuitBreakerOptions().setTimeout(100));
  Async async = tc.async();

  Future<Void> command1 = breaker.execute(commandThatFails());
  Future<Void> command2 = breaker.execute(commandThatWorks());
  Future<Void> command3 = breaker.execute(commandThatWorks());
  Future<Void> command4 = breaker.execute(commandThatFails());
  Future<Void> command5 = breaker.execute(commandThatTimeout(100));

  CompositeFuture.join(command1, command2, command3, command4, command5)
    .onComplete(ar -> {
      assertThat(metrics())
        .contains("name", "some-circuit-breaker")
        .contains("state", CircuitBreakerState.CLOSED.name())
        .contains("totalErrorCount", 3) // Failure + Timeout + Exception
        .contains("totalSuccessCount", 2)
        .contains("totalTimeoutCount", 1)
        .contains("totalExceptionCount", 0)
        .contains("totalFailureCount", 2)
        .contains("totalOperationCount", 5)
        .contains("totalSuccessPercentage", (2.0 / 5 * 100))
        .contains("totalErrorPercentage", (3.0 / 5 * 100));
      async.complete();
    });
}
 
Example #9
Source File: CircuitBreakerMetricsTest.java    From vertx-circuit-breaker with Apache License 2.0 5 votes vote down vote up
@Test
@Repeat(10)
public void testWithCrashingCommands(TestContext tc) {
  breaker = CircuitBreaker.create("some-circuit-breaker", vertx);
  Async async = tc.async();

  Future<Void> command1 = breaker.execute(commandThatFails());
  Future<Void> command2 = breaker.execute(commandThatWorks());
  Future<Void> command3 = breaker.execute(commandThatWorks());
  Future<Void> command4 = breaker.execute(commandThatFails());
  Future<Void> command5 = breaker.execute(commandThatCrashes());

  CompositeFuture.join(command1, command2, command3, command4, command5)
    .onComplete(ar -> {
      assertThat(metrics())
        .contains("name", "some-circuit-breaker")
        .contains("state", CircuitBreakerState.CLOSED.name())
        .contains("totalErrorCount", 3) // Failure + Timeout + Exception
        .contains("totalSuccessCount", 2)
        .contains("totalTimeoutCount", 0)
        .contains("totalExceptionCount", 1)
        .contains("totalFailureCount", 2)
        .contains("totalOperationCount", 5)
        .contains("totalSuccessPercentage", (2.0 / 5 * 100))
        .contains("totalErrorPercentage", (3.0 / 5 * 100));
      async.complete();
    });
}
 
Example #10
Source File: CircuitBreakerMetricsTest.java    From vertx-circuit-breaker with Apache License 2.0 5 votes vote down vote up
@Test
@Repeat(10)
public void testWithFailedCommands(TestContext tc) {
  breaker = CircuitBreaker.create("some-circuit-breaker", vertx);
  Async async = tc.async();

  Future<Void> command1 = breaker.execute(commandThatFails());
  Future<Void> command2 = breaker.execute(commandThatWorks());
  Future<Void> command3 = breaker.execute(commandThatWorks());
  Future<Void> command4 = breaker.execute(commandThatFails());

  CompositeFuture.join(command1, command2, command3, command4)
    .onComplete(ar -> {
      assertThat(metrics())
        .contains("name", "some-circuit-breaker")
        .contains("state", CircuitBreakerState.CLOSED.name())
        .contains("totalErrorCount", 2) // Failure + Timeout + Exception
        .contains("totalSuccessCount", 2)
        .contains("totalTimeoutCount", 0)
        .contains("totalExceptionCount", 0)
        .contains("totalFailureCount", 2)
        .contains("totalOperationCount", 4)
        .contains("totalSuccessPercentage", 50)
        .contains("totalErrorPercentage", 50);
      async.complete();
    });
}
 
Example #11
Source File: CircuitBreakerMetricsTest.java    From vertx-circuit-breaker with Apache License 2.0 5 votes vote down vote up
@Test
@Repeat(10)
public void testWithSuccessfulCommands(TestContext tc) {
  breaker = CircuitBreaker.create("some-circuit-breaker", vertx);
  Async async = tc.async();


  Future<Void> command1 = breaker.execute(commandThatWorks());
  Future<Void> command2 = breaker.execute(commandThatWorks());
  Future<Void> command3 = breaker.execute(commandThatWorks());

  CompositeFuture.all(command1, command2, command3)
    .onComplete(ar -> {
      assertThat(ar).succeeded();
      assertThat(metrics())
        .contains("name", "some-circuit-breaker")
        .contains("state", CircuitBreakerState.CLOSED.name())
        .contains("failures", 0)
        .contains("totalErrorCount", 0)
        .contains("totalSuccessCount", 3)
        .contains("totalTimeoutCount", 0)
        .contains("totalExceptionCount", 0)
        .contains("totalFailureCount", 0)
        .contains("totalOperationCount", 3)
        .contains("totalSuccessPercentage", 100)
        .contains("totalErrorPercentage", 0);

      async.complete();
    });
}
 
Example #12
Source File: CircuitBreakerImplTest.java    From vertx-circuit-breaker with Apache License 2.0 5 votes vote down vote up
@Test
@Repeat(5)
public void testResetAttemptThatFails() {
  AtomicBoolean called = new AtomicBoolean(false);
  CircuitBreakerOptions options = new CircuitBreakerOptions()
    .setResetTimeout(100)
    .setFallbackOnFailure(true);
  breaker = CircuitBreaker.create("test", vertx, options)
    .fallback(v -> {
      called.set(true);
      return "fallback";
    });
  await().until(() -> breaker.state() == CircuitBreakerState.CLOSED);
  assertThat(breaker.state()).isEqualTo(CircuitBreakerState.CLOSED);

  for (int i = 0; i < options.getMaxFailures(); i++) {
    breaker.execute(v -> {
      throw new RuntimeException("oh no, but this is expected");
    });
  }
  await().until(() -> breaker.state() == CircuitBreakerState.OPEN || breaker.state() == CircuitBreakerState.HALF_OPEN);
  assertThat(called.get()).isEqualTo(true);

  await().until(() -> breaker.state() == CircuitBreakerState.HALF_OPEN);
  called.set(false);

  AtomicReference<String> result = new AtomicReference<>();
  breaker.<String>execute(v -> {
    throw new RuntimeException("oh no, but this is expected");
  }).onComplete(ar -> result.set(ar.result()));

  await().until(called::get);
  await().until(() -> breaker.state() == CircuitBreakerState.OPEN || breaker.state() == CircuitBreakerState.HALF_OPEN);
  assertThat(result.get()).isEqualTo("fallback");
}
 
Example #13
Source File: CircuitBreakerImplTest.java    From vertx-circuit-breaker with Apache License 2.0 5 votes vote down vote up
@Test
@Repeat(5)
public void testResetAttempt() {
  AtomicBoolean called = new AtomicBoolean(false);
  CircuitBreakerOptions options = new CircuitBreakerOptions().setResetTimeout(100);
  breaker = CircuitBreaker.create("test", vertx, options)
    .fallback(v -> {
      called.set(true);
      return "fallback";
    });
  assertThat(breaker.state()).isEqualTo(CircuitBreakerState.CLOSED);

  for (int i = 0; i < options.getMaxFailures(); i++) {
    breaker.execute(v -> {
      throw new RuntimeException("oh no, but this is expected");
    });
  }
  await().until(() -> breaker.state() == CircuitBreakerState.OPEN  || breaker.state() == CircuitBreakerState.HALF_OPEN);
  assertThat(called.get()).isEqualTo(false);

  await().until(() -> breaker.state() == CircuitBreakerState.HALF_OPEN);

  AtomicBoolean spy = new AtomicBoolean();
  breaker.execute(v -> {
    spy.set(true);
    v.complete();
  });
  assertThat(spy.get()).isEqualTo(true);
  assertThat(called.get()).isEqualTo(false);
  await().until(() -> breaker.state() == CircuitBreakerState.CLOSED);
  assertThat(breaker.state()).isEqualTo(CircuitBreakerState.CLOSED);
}
 
Example #14
Source File: CircuitBreakerImplTest.java    From vertx-circuit-breaker with Apache License 2.0 5 votes vote down vote up
@Test
@Repeat(5)
public void testExceptionOnSynchronousCode() {
  AtomicBoolean called = new AtomicBoolean(false);
  CircuitBreakerOptions options = new CircuitBreakerOptions()
    .setFallbackOnFailure(false)
    .setResetTimeout(-1);
  breaker = CircuitBreaker.create("test", vertx, options)
    .fallback(t -> {
      called.set(true);
      return "fallback";
    });
  assertThat(breaker.state()).isEqualTo(CircuitBreakerState.CLOSED);

  for (int i = 0; i < options.getMaxFailures(); i++) {
    breaker.execute(v -> {
      throw new RuntimeException("oh no, but this is expected");
    });
  }
  await().until(() -> breaker.state() == CircuitBreakerState.OPEN  ||
    breaker.state() == CircuitBreakerState.HALF_OPEN);
  assertThat(called.get()).isEqualTo(false);

  AtomicBoolean spy = new AtomicBoolean();
  breaker.execute(v -> spy.set(true));
  assertThat(spy.get()).isEqualTo(false);
  assertThat(called.get()).isEqualTo(true);
}
 
Example #15
Source File: CircuitBreakerImplTest.java    From vertx-circuit-breaker with Apache License 2.0 5 votes vote down vote up
@Test
@Repeat(5)
public void testHalfOpen() {
  AtomicBoolean thrown = new AtomicBoolean(false);
  Context ctx = vertx.getOrCreateContext()
    .exceptionHandler(ex -> // intercept exceptions
      thrown.set(true));

  breaker = CircuitBreaker.create("test", vertx, new CircuitBreakerOptions()
    .setResetTimeout(200)
    .setMaxFailures(1));

  Handler<Promise<Void>> fail = p -> p.fail("fail");
  Handler<Promise<Void>> success = p -> p.complete();

  ctx.runOnContext(v -> {
    breaker.execute(fail);
    breaker.execute(fail);
  });

  await().until(() -> breaker.state() == CircuitBreakerState.HALF_OPEN);

  ctx.runOnContext(v -> {
    breaker.execute(fail);
  });

  await().until(() -> breaker.state() == CircuitBreakerState.HALF_OPEN);

  ctx.runOnContext(v -> {
    breaker.execute(success);
  });

  await().until(() -> breaker.state() == CircuitBreakerState.CLOSED);

  assertThat(thrown.get()).isFalse();
}
 
Example #16
Source File: CircuitBreakerImplTest.java    From vertx-circuit-breaker with Apache License 2.0 4 votes vote down vote up
@Test
@Repeat(10)
public void testResetAttemptThatFailsOnTimeout() {
  AtomicBoolean called = new AtomicBoolean(false);
  AtomicBoolean hasBeenOpened = new AtomicBoolean(false);
  CircuitBreakerOptions options = new CircuitBreakerOptions()
    .setResetTimeout(100)
    .setTimeout(10)
    .setFallbackOnFailure(true);
  breaker = CircuitBreaker.create("test", vertx, options)
    .fallback(v -> {
      called.set(true);
      return "fallback";
    })
    .openHandler(v -> hasBeenOpened.set(true));
  assertThat(breaker.state()).isEqualTo(CircuitBreakerState.CLOSED);

  for (int i = 0; i < options.getMaxFailures(); i++) {
    breaker.execute(future -> {
      // Do nothing with the future, this is a very bad thing.
    });
  }
  await().untilAtomic(hasBeenOpened, is(true));
  assertThat(called.get()).isEqualTo(true);
  await().until(() -> breaker.state() == CircuitBreakerState.HALF_OPEN);
  hasBeenOpened.set(false);
  called.set(false);

  breaker.execute(future -> {
    // Do nothing with the future, this is a very bad thing.
  });
  // Failed again, open circuit
  await().until(() -> breaker.state() == CircuitBreakerState.OPEN || breaker.state() == CircuitBreakerState.HALF_OPEN);
  await().untilAtomic(called, is(true));
  await().untilAtomic(hasBeenOpened, is(true));

  hasBeenOpened.set(false);
  called.set(false);

  breaker.execute(future -> {
    // Do nothing with the future, this is a very bad thing.
  });
  // Failed again, open circuit
  await().until(() -> breaker.state() == CircuitBreakerState.OPEN || breaker.state() == CircuitBreakerState.HALF_OPEN);
  await().untilAtomic(called, is(true));
  await().untilAtomic(hasBeenOpened, is(true));

  hasBeenOpened.set(false);
  called.set(false);

  hasBeenOpened.set(false);
  called.set(false);

  await().until(() -> breaker.state() == CircuitBreakerState.CLOSED  || breaker.state() == CircuitBreakerState.HALF_OPEN);

  // If HO - need to get next request executed and wait until we are closed
  breaker.execute(Promise::complete);
  await().until(() -> {
    if (breaker.state() == CircuitBreakerState.CLOSED) {
      return true;
    } else {
      breaker.execute(Promise::complete);
      return false;
    }
  });
  called.set(false);
  for (int i = 0; i < options.getMaxFailures(); i++) {
    breaker.execute(f -> f.complete(null));
  }

  await().until(() -> breaker.state() == CircuitBreakerState.CLOSED);
  await().untilAtomic(hasBeenOpened, is(false));
}
 
Example #17
Source File: ZookeeperBridgeTest.java    From vertx-service-discovery with Apache License 2.0 4 votes vote down vote up
@Test
@Repeat(10)
public void testServiceArrivalWithSameName(TestContext tc) throws Exception {
  Async async = tc.async();

  UriSpec uriSpec = new UriSpec("{scheme}://foo.com:{port}");
  ServiceInstance<String> instance1 = ServiceInstance.<String>builder()
    .name("foo-service")
    .payload(new JsonObject().put("foo", "bar").encodePrettily())
    .port(8080)
    .uriSpec(uriSpec)
    .build();

  ServiceInstance<String> instance2 = ServiceInstance.<String>builder()
    .name("foo-service")
    .payload(new JsonObject().put("foo", "bar2").encodePrettily())
    .port(8081)
    .uriSpec(uriSpec)
    .build();

  discovery.registerService(instance1);

  sd.registerServiceImporter(
    new ZookeeperServiceImporter(),
    new JsonObject().put("connection", zkTestServer.getConnectString()),
    v -> {
      tc.assertTrue(v.succeeded());

      waitUntil(() -> serviceLookup(sd, 1), list -> {
        tc.assertTrue(list.succeeded());
        tc.assertEquals(list.result().get(0).getName(), "foo-service");
        vertx.executeBlocking(future -> {
          try {
            this.discovery.registerService(instance2);
            future.complete();
          } catch (Exception e) {
            future.fail(e);
          }
        }, ar -> {
          tc.assertTrue(ar.succeeded());
          waitUntil(() -> serviceLookup(sd, 2), lookup -> {
            tc.assertTrue(lookup.succeeded());
            tc.assertEquals(lookup.result().get(0).getName(), "foo-service");
            tc.assertEquals(lookup.result().get(1).getName(), "foo-service");
            async.complete();
          });
        });
      });
    });
}
 
Example #18
Source File: VertxCompletableFutureTest.java    From vertx-completable-future with Apache License 2.0 4 votes vote down vote up
@Test
@Repeat(50)
public void testAcceptEitherAsyncWithExecutor(TestContext tc) {
  // Success and success
  Async async1 = tc.async();
  Async async11 = tc.async();
  // Failure and Success
  Async async2 = tc.async();
  // Success and Failure
  Async async3 = tc.async();

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

  VertxCompletableFuture<Integer> success2 = new VertxCompletableFuture<>(vertx);
  vertx.setTimer(100, l -> success2.complete(42));


  VertxCompletableFuture<Integer> failure = new VertxCompletableFuture<>(vertx);
  failure.completeExceptionally(new RuntimeException("My bad"));

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

    success.acceptEitherAsync(
      success2,
      i -> {
        tc.assertNotEquals(thread, Thread.currentThread().getName());
        tc.assertEquals(i, 1);
        async1.complete();
      }, executor
    );

    success2.acceptEitherAsync(
      success,
      i -> {
        tc.assertNotEquals(thread, Thread.currentThread().getName());
        tc.assertEquals(i, 1);
        async11.complete();
      },
      executor
    );

    failure.acceptEitherAsync(
      success,
      i -> tc.fail("Should not be called"),
      executor
    ).whenComplete((res, err) -> {
      tc.assertNotNull(err);
      tc.assertNull(res);
      // We can't enforce the thread used here - it's non-deterministic.
      async2.complete();
    });

    success.acceptEitherAsync(
      failure,
      i -> {
        tc.assertNotEquals(thread, Thread.currentThread().getName());
        tc.assertEquals(i, 1);
        async3.complete();
      },
      executor
    );
  });

}
 
Example #19
Source File: VertxCompletableFutureTest.java    From vertx-completable-future with Apache License 2.0 4 votes vote down vote up
@Test
@Repeat(50)
public void testApplyEitherAsyncWithExecutor(TestContext tc) {
  // Success and success
  Async async1 = tc.async();
  Async async11 = tc.async();
  // Failure and Success
  Async async2 = tc.async();
  // Success and Failure
  Async async3 = tc.async();

  VertxCompletableFuture<Integer> success = new VertxCompletableFuture<>(vertx);
  vertx.setTimer(500, l -> success.complete(1));

  VertxCompletableFuture<Integer> success2 = new VertxCompletableFuture<>(vertx);
  vertx.setTimer(1500, l -> success2.complete(42));

  VertxCompletableFuture<Integer> failure = new VertxCompletableFuture<>(vertx);
  failure.completeExceptionally(new RuntimeException("My bad"));

  VertxCompletableFuture<Integer> failure2 = new VertxCompletableFuture<>(vertx);
  vertx.setTimer(1500, l -> failure.completeExceptionally(new RuntimeException("My bad")));

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

    success.applyToEitherAsync(
      success2,
      i -> {
        tc.assertNotEquals(thread, Thread.currentThread().getName());
        tc.assertEquals(i, 1);
        return i + 1;
      },
      executor
    ).whenComplete((res, err) -> {
      tc.assertNotNull(res);
      tc.assertNull(err);
      tc.assertEquals(res, 2);
      async1.complete();
    });

    success2.applyToEitherAsync(
      success,
      i -> {
        tc.assertNotEquals(thread, Thread.currentThread().getName());
        tc.assertEquals(i, 1);
        return i + 5;
      },
      executor
    ).whenComplete((res, err) -> {
      tc.assertNotNull(res);
      tc.assertNull(err);
      tc.assertEquals(res, 6);
      async11.complete();
    });

    failure
      .applyToEitherAsync(
      success2,
      i -> {
        tc.fail("should not be called");
        return "not the right result";
      },
      executor
    )
      .whenComplete((res, err) -> {
        tc.assertNotNull(err);
        tc.assertNull(res);
        // We can't enforce the thread used here.
        async2.complete();
      });

    success.applyToEitherAsync(
      failure2,
      i -> {
        tc.assertNotEquals(thread, Thread.currentThread().getName());
        tc.assertEquals(i, 1);
        return i * 2;
      },
      executor
    ).whenComplete((res, err) -> {
      tc.assertNotNull(res);
      tc.assertNull(err);
      tc.assertNotEquals(thread, Thread.currentThread().getName());
      tc.assertEquals(res, 2);
      async3.complete();
    });
  });

}
 
Example #20
Source File: RepeatingTest.java    From vertx-unit with Apache License 2.0 4 votes vote down vote up
@Repeat(1000)
@Test
public void testSomething(TestContext context) {
  // This will be executed 1000 times
}
 
Example #21
Source File: CircuitBreakerImplTest.java    From vertx-circuit-breaker with Apache License 2.0 4 votes vote down vote up
@Test
@Repeat(5)
public void testOpenAndCloseHandler() {
  AtomicInteger spyOpen = new AtomicInteger();
  AtomicInteger spyClosed = new AtomicInteger();

  AtomicReference<Throwable> lastException = new AtomicReference<>();

  breaker = CircuitBreaker.create("name", vertx, new CircuitBreakerOptions().setResetTimeout(-1))
    .openHandler((v) -> spyOpen.incrementAndGet())
    .closeHandler((v) -> spyClosed.incrementAndGet());

  assertThat(spyOpen.get()).isEqualTo(0);
  assertThat(spyClosed.get()).isEqualTo(0);

  // First failure
  breaker.execute(v -> {
    throw new RuntimeException("oh no, but this is expected");
  })
    .onComplete(ar -> lastException.set(ar.cause()));

  assertThat(spyOpen.get()).isEqualTo(0);
  assertThat(spyClosed.get()).isEqualTo(0);
  await().until(() -> breaker.state() == CircuitBreakerState.CLOSED);
  assertThat(lastException.get()).isNotNull();
  lastException.set(null);

  for (int i = 1; i < CircuitBreakerOptions.DEFAULT_MAX_FAILURES; i++) {
    breaker.execute(v -> {
      throw new RuntimeException("oh no, but this is expected");
    })
      .onComplete(ar -> lastException.set(ar.cause()));
  }
  await().until(() -> breaker.state() == CircuitBreakerState.OPEN || breaker.state() == CircuitBreakerState.HALF_OPEN);
  assertThat(spyOpen.get()).isEqualTo(1);
  assertThat(lastException.get()).isNotNull();

  ((CircuitBreakerImpl) breaker).reset(true);
  assertThat(breaker.state()).isEqualTo(CircuitBreakerState.CLOSED);
  assertThat(spyOpen.get()).isEqualTo(1);
  assertThat(spyClosed.get()).isEqualTo(1);
}