Improve test reliability by eliminating fixed-duration Thread.sleeps

Description

Tests which use Thread.sleep to wait for some asynchronous process to complete are liable to flicker due to inconsistent running times. It is usually preferable to test some explicit condition repeatedly, timing out if it is not met within a reasonable time period - the test will then be able to continue immediately as soon as the condition is met, and can have a more generous timeout allowance since we will not usually be waiting that long.

The eventually method provides a convenient common way for tests to do this, and should be used where appropriate:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 inline fun <R> eventually( duration: Duration = Duration.ofSeconds(5), waitBetween: Duration = Duration.ofMillis(100), waitBefore: Duration = waitBetween, test: () -> R): R { val end = System.nanoTime() + duration.toNanos() var times = 0 var lastFailure: AssertionError? = null if (!waitBefore.isZero) Thread.sleep(waitBefore.toMillis()) while (System.nanoTime() < end) { try { return test() } catch (e: AssertionError) { if (!waitBetween.isZero) Thread.sleep(waitBetween.toMillis()) lastFailure = e } times++ } throw AssertionError("Test failed with \"${lastFailure?.message}\" after $duration; attempted $times times") }

https://r3-cev.atlassian.net/browse/ENT-3362 extends this work to include tests that are only defined for Corda Enterprise.

Status

Assignee

Dominic.Fox@r3.com

Reporter

Dominic.Fox@r3.com

Labels

None

Priority

Medium

Fix versions

Ported to...

None

Feature Team

Performance and Platform Sustainability

Severity

Medium

Affects versions

Corda 4.3
Configure