Stress

object Stress(source)

Concurrency stress tests on real threads. Everything runs on Dispatchers.Default: a thread pool on the JVM and Kotlin/Native, the single event loop on JS and Wasm. The same common test therefore races threads where the platform has them, and interleaves at suspension points where it does not.

Every run is bounded: a fixed number of iterations and a timeout in real time, so a deadlock or a lost wakeup fails the test instead of hanging the build. Call it from runTest. It leaves virtual time for its duration, so endpoints under stress must use the real clock (TimeSource.Monotonic, the default), not testScheduler.timeSource. Uncaught exceptions in StressScope.background still reach the test's exception handler and fail the test.

@Test
fun closeRacesRequests() = runTest {
Stress.run(iterations = 50) {
val client = CoapClient(network.attach(), background)
Stress.race({ client.get(uri) }, { client.close() })
}
}

Properties

Link copied to clipboard
const val DEFAULT_ITERATIONS: Int = 100

Iterations of run unless the test asks for others.

Link copied to clipboard
const val DEFAULT_PARALLELISM: Int = 4

Iterations of run in progress at the same time unless the test asks for another number.

Link copied to clipboard

How long a whole run may take in real time unless the test allows another limit.

Functions

Link copied to clipboard
suspend fun <T> race(vararg actions: suspend () -> T): List<Result<T>>

Starts every action at once on Dispatchers.Default and waits for all of them. The result of each action is in the same position of the returned list, a failure as Result.failure, so a test can check which side of a race won and that the loser failed the way it should.

Link copied to clipboard
suspend fun run(iterations: Int = DEFAULT_ITERATIONS, parallelism: Int = DEFAULT_PARALLELISM, timeout: Duration = DEFAULT_TIMEOUT, body: suspend StressScope.() -> Unit)

Runs body times on Dispatchers.Default, parallelism iterations at a time. Each iteration gets a StressScope with its number and a StressScope.background scope that is cancelled, and joined, when the iteration ends.