import kotlin.test.* import kotlinx.coroutines.* import kotlinx.coroutines.test.* class T4Test { class Boom(val n: Int) : RuntimeException("boom $n") @Test fun returnsFirstSuccessWithoutWaiting() = runTest { var calls = 0 assertEquals("ok", retry(3, 100, 1000) { calls++; "ok" }) assertEquals(1, calls); assertEquals(0L, currentTime) } @Test fun attemptNumbersStartAtOne() = runTest { val seen = mutableListOf() retry(4, 10, 100) { a -> seen += a; if (a < 3) throw Boom(a) else a } assertEquals(listOf(1, 2, 3), seen) } @Test fun exponentialDelaysWithCap() = runTest { val times = mutableListOf() assertFailsWith { retry(5, 100, 500) { a -> times += currentTime; throw Boom(a) } } assertEquals(listOf(0L, 100L, 300L, 700L, 1200L), times) } @Test fun customFactor() = runTest { val times = mutableListOf() assertFailsWith { retry(4, 10, 10_000, factor = 3.0) { a -> times += currentTime; throw Boom(a) } } assertEquals(listOf(0L, 10L, 40L, 130L), times) } @Test fun noWaitAfterLastAttempt() = runTest { assertFailsWith { retry(2, 100, 100) { a -> throw Boom(a) } } assertEquals(100L, currentTime) } @Test fun lastExceptionWithSuppressedInOrder() = runTest { val e = assertFailsWith { retry(3, 1, 1) { a -> throw Boom(a) } } assertEquals(3, e.n) assertEquals(listOf(1, 2), e.suppressed.map { (it as Boom).n }) } @Test fun shouldRetryFalseRethrowsImmediately() = runTest { var calls = 0 val e = assertFailsWith { retry(5, 100, 100, shouldRetry = { it !is IllegalStateException }) { calls++; throw IllegalStateException("no") } } assertEquals(1, calls); assertEquals(0L, currentTime); assertEquals(0, e.suppressed.size) } @Test fun cancellationFromBlockNotRetried() = runTest { var calls = 0 assertFailsWith { retry(5, 100, 100) { calls++; throw CancellationException("stop") } } assertEquals(1, calls) } @Test fun cancellingCallerStopsWaiting() = runTest { var calls = 0 val job = launch { retry(5, 1_000, 1_000) { calls++; throw Boom(calls) } } advanceTimeBy(500); job.cancel(); job.join() advanceUntilIdle() assertEquals(1, calls); assertTrue(job.isCancelled) } @Test fun timeoutCancellationNotRetried() = runTest { var calls = 0 assertFailsWith { retry(5, 10, 10) { calls++; withTimeout(50) { delay(100) } } } assertEquals(1, calls) } @Test fun largeValuesDoNotOverflow() = runTest { val times = mutableListOf() assertFailsWith { retry(100, 1000, 60_000, factor = 10.0) { a -> times += currentTime; throw Boom(a) } } val waits = times.zipWithNext { x, y -> y - x } assertEquals(listOf(1000L, 10_000L) + List(97) { 60_000L }, waits) } @Test fun validatesArguments() = runTest { assertFailsWith { retry(0, 1, 1) { 1 } } assertFailsWith { retry(1, -1, 1) { 1 } } assertFailsWith { retry(1, 10, 5) { 1 } } assertFailsWith { retry(1, 1, 1, factor = 0.5) { 1 } } } @Test fun singleAttemptNoWait() = runTest { assertFailsWith { retry(1, 100, 100) { throw Boom(1) } } assertEquals(0L, currentTime) } }