Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
translate ▾

Modern-Apps.git / build-logic / shared-test / java / com / vayunmathur / testsupport / DeterministicAwait.kt

DeterministicAwait.kt184 lines · 8.7 KiBRaw
1package com.vayunmathur.testsupport
2
3import android.os.Looper
4import androidx.compose.ui.test.junit4.ComposeContentTestRule
5import kotlin.time.Duration.Companion.seconds
6import kotlinx.coroutines.flow.Flow
7import kotlinx.coroutines.flow.first
8import kotlinx.coroutines.runBlocking
9import org.robolectric.Shadows
10
11/**
12 * Shared deterministic waits for JVM/Robolectric tests.
13 *
14 * This is the repo's one shared test-await helper. It lives in
15 * `build-logic/shared-test/java`, which both convention plugins
16 * (`common-conventions-app` and `common-conventions-library`) add to every
17 * module's unit-test source set — the same mechanism that already shares
18 * `build-logic/shared-test-resources/robolectric.properties`. There is no
19 * shared test-util Gradle module in this repo, and none is invented here.
20 *
21 * Every wait below is a wait *on a signal*, never on a wall clock:
22 * - [awaitValue] suspends until a [Flow] emits a value matching a predicate
23 * (a StateFlow terminal state, a Room/DataStore flow, a completion flow).
24 * - [awaitWithMainIdle] pumps Robolectric's paused main looper until a
25 * terminal condition holds. Idling the looper is what lets a coroutine
26 * resumed on Main actually run; sleeping would only bet on load.
27 * - [awaitSemantics] is a Compose semantics wait on a terminal node state,
28 * pumping the looper *and* the composition's test scheduler on every
29 * check for the same reason (see its doc).
30 * - [pumpUntil] is the step-bounded pumped wait the per-class copies used
31 * for ViewModel/DataStore terminal states, now shared verbatim.
32 *
33 * None of these sleep, burn CPU, or read `System.currentTimeMillis`.
34 */
35
36/** Runs every task currently queued on Robolectric's paused main looper. */
37fun idleMainLooper() {
38 // At @BeforeClass time (before the Robolectric sandbox installs its
39 // main looper) there is nothing to idle yet; class-level error drains
40 // call this from there, so a missing looper is a no-op, not a crash.
41 val looper = Looper.getMainLooper() ?: return
42 Shadows.shadowOf(looper).idle()
43}
44
45/**
46 * Suspends until [this] flow emits a value matching [predicate], and returns
47 * that value. For a [kotlinx.coroutines.flow.StateFlow] this is a wait for a
48 * terminal state: the caller is resumed by the emission itself, not by a poll.
49 */
50suspend fun <T> Flow<T>.awaitValue(predicate: (T) -> Boolean): T = first(predicate)
51
52/**
53 * Blocking form of [awaitValue] for plain (non-coroutine) JUnit tests.
54 * Safe when the flow's producers run on IO/Default dispatchers or on an
55 * unconfined Main dispatcher; do not use it for a value whose only producer
56 * is queued on Robolectric's paused main looper — use [awaitWithMainIdle].
57 */
58fun <T> awaitValueBlocking(flow: Flow<T>, predicate: (T) -> Boolean): T =
59 runBlocking { flow.awaitValue(predicate) }
60
61/**
62 * Idles the main looper until [condition] holds, then returns.
63 *
64 * Step-counted as a failure bound only: each step is a full looper idle,
65 * which is the work that makes progress possible, and the thread parks
66 * briefly between steps so IO/Default producers on other threads can run.
67 * (A bare yield is not enough in the Robolectric sandbox: a tight
68 * idle+yield loop kept the test thread runnable and an IO search behind
69 * it never landed in 10,000 steps, while parking let it finish in ~10.)
70 * This replaces `Thread.sleep` + `System.currentTimeMillis` deadline loops,
71 * which under Robolectric measured a substituted clock and gave up before
72 * real IO had landed.
73 */
74fun awaitWithMainIdle(description: String, maxSteps: Int = 10_000, condition: () -> Boolean) {
75 var step = 0
76 while (step++ < maxSteps) {
77 idleMainLooper()
78 if (condition()) return
79 java.util.concurrent.locks.LockSupport.parkNanos(1_000_000)
80 }
81 // One last idle + check so the failure reports the settled state.
82 idleMainLooper()
83 check(condition()) { "timed out (step-bounded, no wall clock): $description after $maxSteps looper idles" }
84}
85
86/**
87 * Compose semantics wait on a terminal state: [ComposeContentTestRule.waitUntil]
88 * re-checks [condition] after every idle, and each check first pumps the
89 * main looper so a parse/load resumed on Main can land and compose.
90 * The timeout is the framework's failure bound, not the mechanism.
91 *
92 * The pump has three parts, and all are needed. Idling Robolectric's paused
93 * looper runs work posted to the Android main thread. But the composition's
94 * own coroutines — the recomposer and its [androidx.compose.runtime.LaunchedEffect]s
95 * — live on the Compose test environment's scheduler (the one behind
96 * [androidx.compose.ui.test.MainTestClock]), and `waitUntil` only *advances
97 * that scheduler's frame clock* between checks; it never *runs* the tasks
98 * queued on the scheduler. A state write landing from an IO thread therefore
99 * invalidated the tree (the scaffold title flipped to the parsed subject)
100 * while the recomposition that would compose the new branch sat queued past
101 * the whole 15s wait, and a debounced autosave's timer sat in the
102 * scheduler's future. So each check also (a) runs the scheduler's due tasks
103 * and (b) steps its virtual clock forward a bounded window, executing the
104 * timers and delayed resumes queued there. Stepping virtual time is the
105 * mechanism, not a timing bet: it runs the actual queued work.
106 */
107fun ComposeContentTestRule.awaitSemantics(description: String, condition: () -> Boolean) {
108 waitUntil(15_000) {
109 idleMainLooper()
110 mainClock.scheduler.runCurrent()
111 mainClock.scheduler.advanceTimeBy(SCHEDULER_ADVANCE_SECONDS.seconds)
112 idleMainLooper()
113 condition()
114 }
115 idleMainLooper()
116 // Bounded settle, never advanceUntilIdle(): a composition can host an
117 // infinitely self-rescheduling scheduler task (a focused text field's
118 // cursor blink, an infinite animation), and advancing until idle then
119 // never returns — the test JVM spins at 100% CPU and its whole
120 // forkEvery batch (and the Gradle task) never completes. Stepping the
121 // same bounded window as the wait above runs every timer that could
122 // still be queued without betting on the scheduler ever going idle.
123 mainClock.scheduler.advanceTimeBy(SCHEDULER_ADVANCE_SECONDS.seconds)
124 idleMainLooper()
125 check(condition()) { "terminal semantics state not reached: $description" }
126}
127
128/**
129 * Virtual seconds [awaitSemantics] steps the composition scheduler per
130 * check: past an 800ms debounce or a sharing timeout (5s), far short of any
131 * point where virtual time itself becomes the thing being tested.
132 */
133private const val SCHEDULER_ADVANCE_SECONDS = 60
134
135/**
136 * Step-bounded pumped wait on a terminal [condition]: every step pumps
137 * the paused main looper (running the ViewModel/DataStore work queued
138 * there, including delayed tasks), then parks briefly so
139 * Dispatchers.IO/Default producers get a CPU slice on a contended box.
140 * The bound is pumping steps, never wall-clock seconds that CI contention
141 * can burn before any work runs. This is the shared form of the identical
142 * `pumpUntil` copies that used to live in individual test classes.
143 *
144 * With `stepMs > 0` each step also advances the looper's clock by that
145 * many milliseconds, running delayed work due in that window; classes
146 * whose delayed work must not be driven early pass `stepMs = 0`, which
147 * idles without advancing the clock. Pump first, then check: work that is
148 * already queued still needs that one pump to settle before the condition
149 * behind it can hold.
150 */
151fun pumpUntil(description: String, stepMs: Long = 200L, condition: () -> Boolean) {
152 var steps = 0
153 while (true) {
154 // Pump first, then check: the loops this replaces always idled at
155 // least once before judging the condition, and a condition that is
156 // already true at entry can still need that one pump for the work
157 // behind it to settle.
158 val looper = Looper.getMainLooper()
159 if (looper != null) {
160 val shadow = Shadows.shadowOf(looper)
161 if (stepMs > 0L) {
162 shadow.idleFor(stepMs, java.util.concurrent.TimeUnit.MILLISECONDS)
163 } else {
164 shadow.idle()
165 }
166 }
167 if (condition()) break
168 java.util.concurrent.locks.LockSupport.parkNanos(
169 java.util.concurrent.TimeUnit.MILLISECONDS.toNanos(PUMP_PARK_MS),
170 )
171 if (++steps >= MAX_PUMP_STEPS) {
172 throw AssertionError(
173 "timed out waiting for: $description",
174 AssertionError("timed out (step-bounded): $description after $MAX_PUMP_STEPS pumps"),
175 )
176 }
177 }
178}
179
180/** Park between [pumpUntil] steps so IO/Default producers get a CPU slice. */
181private const val PUMP_PARK_MS = 50L
182
183/** Step bound for [pumpUntil]: steps are looper pumps, never wall-clock time. */
184private const val MAX_PUMP_STEPS = 6_000