com.ubertob.pesticide.core.Eventually.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of pesticide-core Show documentation
Show all versions of pesticide-core Show documentation
A Library To Write Domain-Driven Tests
package com.ubertob.pesticide.core
import java.time.Clock
import java.time.Duration
//Note expectation should be an operation that takes less then the within duration
inline fun eventually(within: Duration, expectation: () -> T): T {
val intervals: Iterator = fibonacci().iterator()
val chrono = Chrono()
while (true) {
try {
return expectation()
} catch (t: Throwable) {
if (chrono.hasTimedOut(within))
throw t
}
Thread.sleep(intervals.next())
}
}
fun fibonacci(): Sequence = generateSequence(1L to 1L, { it.second to (it.second + it.first) }).map { it.first }
data class Chrono(val startedMillis: Long = System.currentTimeMillis(), val clock: Clock = Clock.systemUTC()) {
fun elapsedMillis(): Long = clock.millis() - startedMillis
fun isWithin(duration: Duration): Boolean = elapsedMillis() <= duration.toMillis()
fun hasTimedOut(duration: Duration): Boolean = !isWithin(duration)
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy