Skip to content

Instantly share code, notes, and snippets.

@ttddyy
Created August 3, 2016 04:30
Show Gist options
  • Save ttddyy/467bc181b997bfc281381ed0d4497f7b to your computer and use it in GitHub Desktop.
Save ttddyy/467bc181b997bfc281381ed0d4497f7b to your computer and use it in GitHub Desktop.
test wait for async framework(vmware/xenon)
public class TestContext {
private CountDownLatch latch;
private LocalDateTime expireAt;
private volatile Throwable error;
public TestContext(int count) {
this(count, XenonTestConfig.timeoutStrategy.getTimeout());
}
public TestContext(int count, Duration duration) {
this.latch = new CountDownLatch(count);
this.expireAt = LocalDateTime.now().plus(duration);
}
public void complete() {
this.latch.countDown();
}
public void fail(Throwable e) {
this.error = e;
this.latch.countDown();
}
public void await() {
// throw checked exception as unchecked
ExceptionTestUtils.executeSafely(() -> {
if (this.latch == null) {
throw new IllegalStateException("This context is already used");
}
// keep polling latch every second, allows for easier debugging
while (this.expireAt.isAfter(LocalDateTime.now())) {
if (this.latch.await(1, TimeUnit.SECONDS)) {
break;
}
}
if (this.expireAt.isBefore(LocalDateTime.now())) {
// TODO: include latch count info and maybe stack info into error message
throw new TimeoutException();
}
// prevent this latch from being reused
this.latch = null;
if (this.error != null) {
// TOOD: may include more information into error by error.addSuppressed() or wrapping error
throw this.error;
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment