clock: kill sleep-polls, and the receiver NPE that made tests flaky
- Commit
a249024b03204cc7a11ecb6d082c50d6927ded73- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-21 21:33 UTC (14 days ago)
- Parents
42e8d3a
Clock had the repo's densest hand-rolled Thread.sleep poll helpers. All replaced with shared DeterministicAwait terminal signals (flow tuples, semantics, looper pumps) - the drain family now pumps before draining so late DB errors are consumed by the right test. The sweep found the flake's root in production: five clock receivers called pendingResult.finish() unconditionally, but goAsync() is null when onReceive is invoked directly, so an NPE escaped onto an IO thread and was attributed to whichever test was running. Receivers now safe-call finish (the established repo pattern). The shared idleMainLooper also went null-safe pre-sandbox. Verified: full clock suite 256 tests green twice, second run forced clean with no build cache.
Diff
build-logic/shared-test/java/com/vayunmathur/testsupport/DeterministicAwait.kt
diff --git a/build-logic/shared-test/java/com/vayunmathur/testsupport/DeterministicAwait.kt b/build-logic/shared-test/java/com/vayunmathur/testsupport/DeterministicAwait.ktindex 4cd1798aab..a83e106515 100644--- a/build-logic/shared-test/java/com/vayunmathur/testsupport/DeterministicAwait.kt+++ b/build-logic/shared-test/java/com/vayunmathur/testsupport/DeterministicAwait.kt@@ -33,7 +33,11 @@ import org.robolectric.Shadows /** Runs every task currently queued on Robolectric's paused main looper. */ fun idleMainLooper() {- Shadows.shadowOf(Looper.getMainLooper()).idle()+ // At @BeforeClass time (before the Robolectric sandbox installs its+ // main looper) there is nothing to idle yet; class-level error drains+ // call this from there, so a missing looper is a no-op, not a crash.+ val looper = Looper.getMainLooper() ?: return+ Shadows.shadowOf(looper).idle() } /**
clock/src/main/java/com/vayunmathur/clock/platform/AlarmReceiver.kt
diff --git a/clock/src/main/java/com/vayunmathur/clock/platform/AlarmReceiver.kt b/clock/src/main/java/com/vayunmathur/clock/platform/AlarmReceiver.ktindex 4b3b631eb5..087f3ca748 100644--- a/clock/src/main/java/com/vayunmathur/clock/platform/AlarmReceiver.kt+++ b/clock/src/main/java/com/vayunmathur/clock/platform/AlarmReceiver.kt@@ -164,7 +164,7 @@ class AlarmReceiver : BroadcastReceiver() { } catch (e: Exception) { Log.error(TAG, "Alarm $alarmId: could not reschedule", e) } finally {- pendingResult.finish()+ pendingResult?.finish() } } }
clock/src/main/java/com/vayunmathur/clock/platform/BootReceiver.kt
diff --git a/clock/src/main/java/com/vayunmathur/clock/platform/BootReceiver.kt b/clock/src/main/java/com/vayunmathur/clock/platform/BootReceiver.ktindex 56852e9413..58061d0cc2 100644--- a/clock/src/main/java/com/vayunmathur/clock/platform/BootReceiver.kt+++ b/clock/src/main/java/com/vayunmathur/clock/platform/BootReceiver.kt@@ -54,7 +54,7 @@ class BootReceiver : BroadcastReceiver() { // alarm survives the reboot. Log.error(TAG, "${intent.action}: could not reschedule alarms", e) } finally {- pendingResult.finish()+ pendingResult?.finish() } } }
clock/src/main/java/com/vayunmathur/clock/platform/StopwatchActionReceiver.kt
diff --git a/clock/src/main/java/com/vayunmathur/clock/platform/StopwatchActionReceiver.kt b/clock/src/main/java/com/vayunmathur/clock/platform/StopwatchActionReceiver.ktindex 8fa46c25f2..2a1137a9d4 100644--- a/clock/src/main/java/com/vayunmathur/clock/platform/StopwatchActionReceiver.kt+++ b/clock/src/main/java/com/vayunmathur/clock/platform/StopwatchActionReceiver.kt@@ -76,7 +76,7 @@ class StopwatchActionReceiver : BroadcastReceiver() { } } catch (_: Exception) { } finally {- pendingResult.finish()+ pendingResult?.finish() } } }
clock/src/main/java/com/vayunmathur/clock/platform/TimerActionReceiver.kt
diff --git a/clock/src/main/java/com/vayunmathur/clock/platform/TimerActionReceiver.kt b/clock/src/main/java/com/vayunmathur/clock/platform/TimerActionReceiver.ktindex 23630930ea..f5bd5397ec 100644--- a/clock/src/main/java/com/vayunmathur/clock/platform/TimerActionReceiver.kt+++ b/clock/src/main/java/com/vayunmathur/clock/platform/TimerActionReceiver.kt@@ -33,7 +33,7 @@ class TimerActionReceiver : BroadcastReceiver() { } catch (e: Exception) { Log.error(TAG, "Timer $timerId: action $action failed", e) } finally {- pendingResult.finish()+ pendingResult?.finish() } } }
clock/src/main/java/com/vayunmathur/clock/platform/TimerReciever.kt
diff --git a/clock/src/main/java/com/vayunmathur/clock/platform/TimerReciever.kt b/clock/src/main/java/com/vayunmathur/clock/platform/TimerReciever.ktindex 1f14e0f66c..e3e16f6667 100644--- a/clock/src/main/java/com/vayunmathur/clock/platform/TimerReciever.kt+++ b/clock/src/main/java/com/vayunmathur/clock/platform/TimerReciever.kt@@ -86,7 +86,7 @@ class TimerReceiver : BroadcastReceiver() { } catch (e: Exception) { Log.error(TAG, "could not complete timer $id", e) } finally {- pendingResult.finish()+ pendingResult?.finish() } } }
clock/src/test/java/com/vayunmathur/clock/MainActivityDeepTest.kt
diff --git a/clock/src/test/java/com/vayunmathur/clock/MainActivityDeepTest.kt b/clock/src/test/java/com/vayunmathur/clock/MainActivityDeepTest.ktindex 4b88a2b3e1..99d8e99d0b 100644--- a/clock/src/test/java/com/vayunmathur/clock/MainActivityDeepTest.kt+++ b/clock/src/test/java/com/vayunmathur/clock/MainActivityDeepTest.kt@@ -1,13 +1,11 @@ package com.vayunmathur.clock import android.content.Intent-import android.os.Looper+import com.vayunmathur.testsupport.awaitWithMainIdle import org.junit.Before import org.junit.runner.RunWith import org.robolectric.Robolectric import org.robolectric.RobolectricTestRunner-import org.robolectric.Shadows.shadowOf-import java.util.concurrent.TimeUnit import kotlin.test.Test import kotlin.test.assertFalse @@ -18,12 +16,9 @@ class MainActivityDeepTest { @Test fun mainActivityComposesContentOnResume() { val controller = Robolectric.buildActivity(MainActivity::class.java, Intent(Intent.ACTION_MAIN)) val activity = controller.setup().get()- // Drive frames so the permission gate / navigation content actually composes.- repeat(10) {- shadowOf(Looper.getMainLooper()).idle()- shadowOf(Looper.getMainLooper()).idleFor(100, TimeUnit.MILLISECONDS)- Thread.sleep(20)- }+ // Pump the main looper until the permission gate / navigation content+ // has composed and the activity is settled (not finishing).+ awaitWithMainIdle("main activity composed") { !activity.isFinishing } assertFalse(activity.isFinishing) controller.pause().stop().destroy() }
clock/src/test/java/com/vayunmathur/clock/platform/AlarmActivityDeepTest.kt
diff --git a/clock/src/test/java/com/vayunmathur/clock/platform/AlarmActivityDeepTest.kt b/clock/src/test/java/com/vayunmathur/clock/platform/AlarmActivityDeepTest.ktindex 179ac3b82c..8814f3c604 100644--- a/clock/src/test/java/com/vayunmathur/clock/platform/AlarmActivityDeepTest.kt+++ b/clock/src/test/java/com/vayunmathur/clock/platform/AlarmActivityDeepTest.kt@@ -1,16 +1,14 @@ package com.vayunmathur.clock.platform import android.content.Intent-import android.os.Looper import androidx.test.core.app.ApplicationProvider import android.content.Context import com.vayunmathur.clock.FakeAndroidKeyStore+import com.vayunmathur.testsupport.awaitWithMainIdle import org.junit.Before import org.junit.runner.RunWith import org.robolectric.Robolectric import org.robolectric.RobolectricTestRunner-import org.robolectric.Shadows.shadowOf-import java.util.concurrent.TimeUnit import kotlin.test.Test import kotlin.test.assertTrue @@ -21,18 +19,10 @@ class AlarmActivityDeepTest { private val ctx: Context get() = ApplicationProvider.getApplicationContext() - private fun pump() {- repeat(10) {- shadowOf(Looper.getMainLooper()).idle()- shadowOf(Looper.getMainLooper()).idleFor(50, TimeUnit.MILLISECONDS)- Thread.sleep(20)- }- }- @Test fun ringingScreenComposesAndLoadFailureFinishes() { val intent = Intent(ctx, AlarmActivity::class.java).apply { putExtra("ALARM_ID", 31415L) } val controller = Robolectric.buildActivity(AlarmActivity::class.java, intent).create().start().resume()- pump()+ awaitWithMainIdle("load failure finishes activity", maxSteps = 100_000) { controller.get().isFinishing } // The DB is SQLCipher-backed and unavailable on the host JVM, so the load // fails and the activity finishes rather than ringing forever. assertTrue(controller.get().isFinishing)@@ -44,7 +34,7 @@ class AlarmActivityDeepTest { val controller = Robolectric.buildActivity(AlarmActivity::class.java, intent).create().start().resume() val activity = controller.get() controller.newIntent(Intent(ctx, AlarmActivity::class.java).apply { putExtra("ALARM_ID", 2L) })- pump()+ awaitWithMainIdle("reloaded load failure finishes activity", maxSteps = 100_000) { activity.isFinishing } assertTrue(activity.isFinishing) controller.destroy() }
clock/src/test/java/com/vayunmathur/clock/platform/ClockViewModelTest.kt
diff --git a/clock/src/test/java/com/vayunmathur/clock/platform/ClockViewModelTest.kt b/clock/src/test/java/com/vayunmathur/clock/platform/ClockViewModelTest.ktindex 31e6eee8d8..749a380889 100644--- a/clock/src/test/java/com/vayunmathur/clock/platform/ClockViewModelTest.kt+++ b/clock/src/test/java/com/vayunmathur/clock/platform/ClockViewModelTest.kt@@ -2,7 +2,6 @@ package com.vayunmathur.clock.platform import android.app.Application import android.content.Intent-import android.os.Looper import android.provider.AlarmClock import androidx.test.core.app.ApplicationProvider import android.content.Context@@ -11,7 +10,6 @@ import com.vayunmathur.clock.data.Alarm import com.vayunmathur.clock.data.ClockRepository import com.vayunmathur.clock.data.Timer import com.vayunmathur.library.util.DataStoreUtils-import java.util.concurrent.TimeUnit import kotlinx.coroutines.flow.first import kotlinx.coroutines.runBlocking import kotlinx.datetime.LocalTime@@ -19,7 +17,9 @@ import org.junit.runner.RunWith import com.vayunmathur.clock.FakeAndroidKeyStore import org.junit.Before import org.robolectric.RobolectricTestRunner-import org.robolectric.Shadows.shadowOf+import com.vayunmathur.testsupport.awaitWithMainIdle+import com.vayunmathur.testsupport.awaitValueBlocking+import kotlinx.coroutines.flow.combine import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFalse@@ -42,17 +42,6 @@ class ClockViewModelTest { private fun vm() = ClockViewModel(app, ClockRepository.get(app)) - private fun await(desc: String, cond: () -> Boolean) {- val deadline = System.currentTimeMillis() + 10_000- while (System.currentTimeMillis() < deadline) {- shadowOf(Looper.getMainLooper()).idle()- shadowOf(Looper.getMainLooper()).idleFor(50, TimeUnit.MILLISECONDS)- if (cond()) return- Thread.sleep(25)- }- throw AssertionError("timed out: $desc")- }- private fun timer(name: String) = Timer( isRunning = false, name = name, remainingStartTime = Clock.System.now(), remainingLength = 3.minutes, totalLength = 3.minutes,@@ -147,12 +136,15 @@ class ClockViewModelTest { // (not just the in-memory state) so the external writes below cannot // interleave with the reset's still-landing edits. val ds = DataStoreUtils.getInstance(app)- await("store settled after reset") {- !ds.getBoolean(StopwatchActionReceiver.KEY_STOPWATCH_RUNNING, true) &&- (ds.getLong(StopwatchActionReceiver.KEY_STOPWATCH_TOTAL) ?: -1L) == 0L &&- (ds.getString(StopwatchActionReceiver.KEY_STOPWATCH_LAPS) ?: "x").isEmpty()- }- await("vm settled after reset") { !vm.stopwatchRunning.value && vm.lapTimes.value.isEmpty() }+ // Terminal persisted tuple after reset (separate DataStore edits).+ awaitValueBlocking(+ combine(+ ds.booleanFlow(StopwatchActionReceiver.KEY_STOPWATCH_RUNNING, true),+ ds.longFlow(StopwatchActionReceiver.KEY_STOPWATCH_TOTAL, -1L),+ ds.stringFlow(StopwatchActionReceiver.KEY_STOPWATCH_LAPS),+ ) { running, total, laps -> !running && total == 0L && laps.isEmpty() },+ ) { it }+ awaitWithMainIdle("vm settled after reset") { !vm.stopwatchRunning.value && vm.lapTimes.value.isEmpty() } // Simulate StopwatchActionReceiver acting on the notification while // this ViewModel (and its activity) stays alive. runBlocking {@@ -161,19 +153,19 @@ class ClockViewModelTest { ds.setString(StopwatchActionReceiver.KEY_STOPWATCH_LAPS, "1000,2000") ds.setBoolean(StopwatchActionReceiver.KEY_STOPWATCH_RUNNING, true) }- await("vm observes external start") { vm.stopwatchRunning.value && vm.lapTimes.value.size == 2 }+ awaitWithMainIdle("vm observes external start") { vm.stopwatchRunning.value && vm.lapTimes.value.size == 2 } runBlocking { ds.setBoolean(StopwatchActionReceiver.KEY_STOPWATCH_RUNNING, false) ds.setLong(StopwatchActionReceiver.KEY_STOPWATCH_TOTAL, 0L) ds.setString(StopwatchActionReceiver.KEY_STOPWATCH_LAPS, "") }- await("vm observes external stop") { !vm.stopwatchRunning.value && vm.lapTimes.value.isEmpty() }+ awaitWithMainIdle("vm observes external stop") { !vm.stopwatchRunning.value && vm.lapTimes.value.isEmpty() } } @Test fun citiesLoadFromAssets() { val vm = vm()- await("cities loaded") { vm.cities.value != null }+ awaitValueBlocking(vm.cities) { it != null } assertTrue(vm.cities.value!!.isNotEmpty()) }
clock/src/test/java/com/vayunmathur/clock/platform/ClockViewModelWriteTest.kt
diff --git a/clock/src/test/java/com/vayunmathur/clock/platform/ClockViewModelWriteTest.kt b/clock/src/test/java/com/vayunmathur/clock/platform/ClockViewModelWriteTest.ktindex fb044f4e56..bf97e7f1a9 100644--- a/clock/src/test/java/com/vayunmathur/clock/platform/ClockViewModelWriteTest.kt+++ b/clock/src/test/java/com/vayunmathur/clock/platform/ClockViewModelWriteTest.kt@@ -13,6 +13,7 @@ import kotlinx.datetime.LocalTime import org.junit.Before import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner+import com.vayunmathur.testsupport.awaitWithMainIdle import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertNull@@ -40,16 +41,17 @@ class ClockViewModelWriteTest { * error is expected, so it cannot fail an unrelated later test. */ private fun drainUncaughtDbErrors() {- Thread.sleep(400) // Background DB coroutines can take a while to reach the failing open; // drain repeatedly so a late one cannot leak into the next compose test.+ // Between attempts, pump the main looper (step-bounded, no wall sleep)+ // so IO producers get scheduled and their error can land in the store. repeat(8) {+ run { var pumped = 0; awaitWithMainIdle("pump background work", maxSteps = 25_000) { ++pumped >= 25_000 } } try { kotlinx.coroutines.test.runTest { } } catch (e: IllegalStateException) { if (e.javaClass.simpleName != "UncaughtExceptionsBeforeTest") throw e }- Thread.sleep(400) } } @@ -66,7 +68,7 @@ class ClockViewModelWriteTest { vm.delete(alarm) // Give the IO coroutines a chance to run into the (host-unavailable) database; // the calls above must already have returned normally.- Thread.sleep(300)+ run { var pumped = 0; awaitWithMainIdle("pump background work", maxSteps = 5_000) { ++pumped >= 400 } } drainUncaughtDbErrors() assertEquals("gym", alarm.name) assertEquals(LocalTime(7, 0), alarm.time)
clock/src/test/java/com/vayunmathur/clock/platform/ReceiverRestoreTest.kt
diff --git a/clock/src/test/java/com/vayunmathur/clock/platform/ReceiverRestoreTest.kt b/clock/src/test/java/com/vayunmathur/clock/platform/ReceiverRestoreTest.ktindex e8cb9e9499..e239affceb 100644--- a/clock/src/test/java/com/vayunmathur/clock/platform/ReceiverRestoreTest.kt+++ b/clock/src/test/java/com/vayunmathur/clock/platform/ReceiverRestoreTest.kt@@ -16,6 +16,7 @@ import org.junit.After import org.junit.Before import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner+import com.vayunmathur.testsupport.awaitWithMainIdle import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFalse@@ -77,14 +78,6 @@ class ReceiverRestoreTest { } } - private fun await(desc: String, cond: () -> Boolean) {- val deadline = System.currentTimeMillis() + 8_000- while (System.currentTimeMillis() < deadline) {- if (runCatching { cond() }.getOrDefault(false)) return- Thread.sleep(25)- }- throw AssertionError("timed out: $desc")- } private fun timer(name: String, running: Boolean, remaining: Duration, startedAgo: Duration = 0.seconds) = Timer(@@ -102,10 +95,7 @@ class ReceiverRestoreTest { BootReceiver().onReceive(ctx, Intent(Intent.ACTION_BOOT_COMPLETED)) - await("expired timer completed on boot") {- val expired = runBlocking { repo.getTimer(expiredId) }- !expired.isRunning && expired.remainingLength == Duration.ZERO- }+ awaitWithMainIdle("expired timer completed on boot") { runCatching { val expired = runBlocking { repo.getTimer(expiredId) }; !expired.isRunning && expired.remainingLength == Duration.ZERO }.getOrDefault(false) } val future = runBlocking { repo.getTimer(futureId) } assertTrue(future.isRunning, "a timer still in the future must stay running after boot") val paused = runBlocking { repo.getTimer(pausedId) }@@ -125,7 +115,7 @@ class ReceiverRestoreTest { BootReceiver().onReceive(ctx, Intent(Intent.ACTION_TIME_CHANGED)) - await("spent snooze cleared") { runBlocking { repo.getAlarm(spentId) }.snoozedUntil == null }+ awaitWithMainIdle("spent snooze cleared") { runCatching { runBlocking { repo.getAlarm(spentId) }.snoozedUntil == null }.getOrDefault(false) } // (Persisted instants keep second precision, so compare by range.) val kept = runBlocking { repo.getAlarm(futureId) }.snoozedUntil assertTrue(@@ -140,7 +130,7 @@ class ReceiverRestoreTest { TimerActionReceiver().onReceive(ctx, Intent(action).apply { putExtra("timer_id", id) }) fire(TimerActionReceiver.ACTION_PAUSE)- await("pause persisted") { !runBlocking { repo.getTimer(id) }.isRunning }+ awaitWithMainIdle("pause persisted") { runCatching { !runBlocking { repo.getTimer(id) }.isRunning }.getOrDefault(false) } val paused = runBlocking { repo.getTimer(id) } assertTrue( paused.remainingLength in 3.minutes..5.minutes,@@ -148,16 +138,13 @@ class ReceiverRestoreTest { ) fire(TimerActionReceiver.ACTION_RESUME)- await("resume persisted") { runBlocking { repo.getTimer(id) }.isRunning }+ awaitWithMainIdle("resume persisted") { runCatching { runBlocking { repo.getTimer(id) }.isRunning }.getOrDefault(false) } fire(TimerActionReceiver.ACTION_RESET)- await("reset persisted") {- val t = runBlocking { repo.getTimer(id) }- !t.isRunning && t.remainingLength == t.totalLength- }+ awaitWithMainIdle("reset persisted") { runCatching { val t = runBlocking { repo.getTimer(id) }; !t.isRunning && t.remainingLength == t.totalLength }.getOrDefault(false) } fire(TimerActionReceiver.ACTION_CANCEL)- await("cancel persisted") { runBlocking { repo.getAllTimers() }.none { it.id == id } }+ awaitWithMainIdle("cancel persisted") { runCatching { runBlocking { repo.getAllTimers() }.none { it.id == id } }.getOrDefault(false) } } @Test fun timerActionOnPausedTimerKeepsItsBankedRemaining() {@@ -166,7 +153,7 @@ class ReceiverRestoreTest { ctx, Intent(TimerActionReceiver.ACTION_PAUSE).apply { putExtra("timer_id", id) }, )- await("banked pause settled") { runBlocking { repo.getTimer(id) }.remainingLength == 90.seconds }+ awaitWithMainIdle("banked pause settled") { runCatching { runBlocking { repo.getTimer(id) }.remainingLength == 90.seconds }.getOrDefault(false) } assertFalse(runBlocking { repo.getTimer(id) }.isRunning) } }
clock/src/test/java/com/vayunmathur/clock/platform/ReceiversAndNotificationsTest.kt
diff --git a/clock/src/test/java/com/vayunmathur/clock/platform/ReceiversAndNotificationsTest.kt b/clock/src/test/java/com/vayunmathur/clock/platform/ReceiversAndNotificationsTest.ktindex 7ac10d5cff..85e1abe12b 100644--- a/clock/src/test/java/com/vayunmathur/clock/platform/ReceiversAndNotificationsTest.kt+++ b/clock/src/test/java/com/vayunmathur/clock/platform/ReceiversAndNotificationsTest.kt@@ -14,6 +14,9 @@ import org.junit.Before import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.Shadows.shadowOf+import com.vayunmathur.testsupport.awaitWithMainIdle+import com.vayunmathur.testsupport.awaitValueBlocking+import kotlinx.coroutines.flow.combine import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertNotNull@@ -36,12 +39,12 @@ class ReceiversAndNotificationsTest { */ @org.junit.AfterClass @JvmStatic fun drainStoredDbErrors() { repeat(8) {+ run { var pumped = 0; awaitWithMainIdle("pump background work", maxSteps = 25_000) { ++pumped >= 25_000 } } try { kotlinx.coroutines.test.runTest { } } catch (e: IllegalStateException) { if (e.javaClass.simpleName != "UncaughtExceptionsBeforeTest") throw e }- Thread.sleep(400) } } }@@ -49,14 +52,6 @@ class ReceiversAndNotificationsTest { private val ctx: Context get() = ApplicationProvider.getApplicationContext() private val nm: NotificationManager get() = ctx.getSystemService(NotificationManager::class.java) - private fun await(desc: String, cond: () -> Boolean) {- val deadline = System.currentTimeMillis() + 5000- while (System.currentTimeMillis() < deadline) {- if (cond()) return- Thread.sleep(25)- }- throw AssertionError("timed out: $desc")- } @Test fun channelsAreCreated() {@@ -159,7 +154,7 @@ class ReceiversAndNotificationsTest { putExtra("timer_name", "pasta") } TimerReceiver().onReceive(ctx, intent)- await("finished notification") { shadowOf(nm).getNotification(77L.hashCode()) != null }+ awaitWithMainIdle("finished notification", maxSteps = 100_000) { shadowOf(nm).getNotification(77L.hashCode()) != null } } @Test@@ -168,7 +163,7 @@ class ReceiversAndNotificationsTest { // An action for a timer that cannot be loaded fails soft inside the receiver coroutine. val intent = Intent(TimerActionReceiver.ACTION_PAUSE).apply { putExtra("timer_id", 999L) } TimerActionReceiver().onReceive(ctx, intent)- Thread.sleep(200)+ run { var pumped = 0; awaitWithMainIdle("pump background work", maxSteps = 5_000) { ++pumped >= 400 } } } @Test@@ -179,19 +174,24 @@ class ReceiversAndNotificationsTest { ds.setString(StopwatchActionReceiver.KEY_STOPWATCH_LAPS, "") StopwatchActionReceiver().onReceive(ctx, Intent(StopwatchActionReceiver.ACTION_TOGGLE))- await("running") { ds.getBoolean(StopwatchActionReceiver.KEY_STOPWATCH_RUNNING, false) }+ awaitValueBlocking(ds.booleanFlow(StopwatchActionReceiver.KEY_STOPWATCH_RUNNING, false)) { it } StopwatchActionReceiver().onReceive(ctx, Intent(StopwatchActionReceiver.ACTION_LAP))- await("lap recorded") { (ds.getString(StopwatchActionReceiver.KEY_STOPWATCH_LAPS) ?: "").isNotEmpty() }+ awaitValueBlocking(ds.stringFlow(StopwatchActionReceiver.KEY_STOPWATCH_LAPS)) { it.isNotEmpty() } StopwatchActionReceiver().onReceive(ctx, Intent(StopwatchActionReceiver.ACTION_STOP))- await("stopped") {- !ds.getBoolean(StopwatchActionReceiver.KEY_STOPWATCH_RUNNING, true) &&- (ds.getLong(StopwatchActionReceiver.KEY_STOPWATCH_TOTAL) ?: -1L) == 0L- }+ // Terminal persisted tuple for STOP: stopped flag, zeroed total and+ // cleared laps all landed (they are separate DataStore edits).+ awaitValueBlocking(+ combine(+ ds.booleanFlow(StopwatchActionReceiver.KEY_STOPWATCH_RUNNING, true),+ ds.longFlow(StopwatchActionReceiver.KEY_STOPWATCH_TOTAL, -1L),+ ds.stringFlow(StopwatchActionReceiver.KEY_STOPWATCH_LAPS),+ ) { running, total, laps -> !running && total == 0L && laps.isEmpty() },+ ) { it } // Lap while stopped is ignored. StopwatchActionReceiver().onReceive(ctx, Intent(StopwatchActionReceiver.ACTION_LAP))- Thread.sleep(200)+ run { var pumped = 0; awaitWithMainIdle("pump background work", maxSteps = 5_000) { ++pumped >= 400 } } assertEquals("", ds.getString(StopwatchActionReceiver.KEY_STOPWATCH_LAPS)) } @@ -203,7 +203,7 @@ class ReceiversAndNotificationsTest { @Test fun bootReceiverRunsForBootCompleted() { BootReceiver().onReceive(ctx, Intent(Intent.ACTION_BOOT_COMPLETED))- Thread.sleep(200)+ run { var pumped = 0; awaitWithMainIdle("pump background work", maxSteps = 5_000) { ++pumped >= 400 } } } @Test@@ -214,6 +214,6 @@ class ReceiversAndNotificationsTest { // path at all instead of falling through the when unmatched. BootReceiver().onReceive(ctx, Intent(Intent.ACTION_TIMEZONE_CHANGED)) BootReceiver().onReceive(ctx, Intent(Intent.ACTION_TIME_CHANGED))- Thread.sleep(200)+ run { var pumped = 0; awaitWithMainIdle("pump background work", maxSteps = 5_000) { ++pumped >= 400 } } } }
clock/src/test/java/com/vayunmathur/clock/platform/ReceiversDeepTest.kt
diff --git a/clock/src/test/java/com/vayunmathur/clock/platform/ReceiversDeepTest.kt b/clock/src/test/java/com/vayunmathur/clock/platform/ReceiversDeepTest.ktindex 8ba2aec990..cab3fc65a7 100644--- a/clock/src/test/java/com/vayunmathur/clock/platform/ReceiversDeepTest.kt+++ b/clock/src/test/java/com/vayunmathur/clock/platform/ReceiversDeepTest.kt@@ -11,6 +11,9 @@ import org.junit.Before import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.Shadows.shadowOf+import com.vayunmathur.testsupport.awaitWithMainIdle+import com.vayunmathur.testsupport.awaitValueBlocking+import kotlinx.coroutines.flow.combine import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertNotNull@@ -25,27 +28,17 @@ class ReceiversDeepTest { private val ctx: Context get() = ApplicationProvider.getApplicationContext() private val nm: NotificationManager get() = ctx.getSystemService(NotificationManager::class.java) - private fun await(desc: String, cond: () -> Boolean) {- val deadline = System.currentTimeMillis() + 5_000- while (System.currentTimeMillis() < deadline) {- if (cond()) return- Thread.sleep(25)- }- throw AssertionError("timed out: $desc")- }- /** Consume the stored SQLCipher background error so later runTest tests stay clean. */ private fun drain() {- Thread.sleep(1_000) // Background DB coroutines can take a while to reach the failing open; // drain repeatedly so a late one cannot leak into the next compose test. repeat(8) {+ run { var pumped = 0; awaitWithMainIdle("pump background work", maxSteps = 25_000) { ++pumped >= 25_000 } } try { kotlinx.coroutines.test.runTest { } } catch (e: IllegalStateException) { if (e.javaClass.simpleName != "UncaughtExceptionsBeforeTest") throw e }- Thread.sleep(400) } } @@ -73,7 +66,7 @@ class ReceiversDeepTest { createNotificationChannels(ctx) val intent = Intent().apply { putExtra("timer_id", 66L) } TimerReceiver().onReceive(ctx, intent)- await("finished notification") { shadowOf(nm).getNotification(66L.hashCode()) != null }+ awaitWithMainIdle("finished notification", maxSteps = 100_000) { shadowOf(nm).getNotification(66L.hashCode()) != null } val posted = shadowOf(nm).getNotification(66L.hashCode()) assertNotNull(posted) drain()@@ -110,10 +103,9 @@ class ReceiversDeepTest { ds.setString(StopwatchActionReceiver.KEY_STOPWATCH_LAPS, "") StopwatchActionReceiver().onReceive(ctx, Intent(StopwatchActionReceiver.ACTION_TOGGLE))- await("running") { ds.getBoolean(StopwatchActionReceiver.KEY_STOPWATCH_RUNNING, false) }- Thread.sleep(150)+ awaitValueBlocking(ds.booleanFlow(StopwatchActionReceiver.KEY_STOPWATCH_RUNNING, false)) { it } // Robolectric's monotonic clock is tied to its paused scheduler and- // does not advance over Thread.sleep, so backdate the stored+ // does not advance on its own, so backdate the stored // monotonic anchor to simulate 200ms of real elapsed time. ds.setLong( StopwatchActionReceiver.KEY_STOPWATCH_START_MONO,@@ -121,14 +113,16 @@ class ReceiversDeepTest { ) // Toggling again pauses and banks the elapsed total. StopwatchActionReceiver().onReceive(ctx, Intent(StopwatchActionReceiver.ACTION_TOGGLE))- await("paused with banked total") {- !ds.getBoolean(StopwatchActionReceiver.KEY_STOPWATCH_RUNNING, true) &&- (ds.getLong(StopwatchActionReceiver.KEY_STOPWATCH_TOTAL) ?: 0L) > 0L- }+ awaitValueBlocking(+ combine(+ ds.booleanFlow(StopwatchActionReceiver.KEY_STOPWATCH_RUNNING, true),+ ds.longFlow(StopwatchActionReceiver.KEY_STOPWATCH_TOTAL, 0L),+ ) { running, total -> !running && total > 0L },+ ) { it } // Lap while paused is ignored, and an unknown action changes nothing. StopwatchActionReceiver().onReceive(ctx, Intent(StopwatchActionReceiver.ACTION_LAP)) StopwatchActionReceiver().onReceive(ctx, Intent("com.vayunmathur.clock.STOPWATCH_UNKNOWN"))- Thread.sleep(200)+ run { var pumped = 0; awaitWithMainIdle("pump background work", maxSteps = 5_000) { ++pumped >= 400 } } assertEquals("", ds.getString(StopwatchActionReceiver.KEY_STOPWATCH_LAPS)) assertTrue((ds.getLong(StopwatchActionReceiver.KEY_STOPWATCH_TOTAL) ?: 0L) > 0L) // Clean up shared stopwatch state.
clock/src/test/java/com/vayunmathur/clock/platform/SchedulerAndReceiverDeepTest.kt
diff --git a/clock/src/test/java/com/vayunmathur/clock/platform/SchedulerAndReceiverDeepTest.kt b/clock/src/test/java/com/vayunmathur/clock/platform/SchedulerAndReceiverDeepTest.ktindex a0c5db23ce..5e8b31002c 100644--- a/clock/src/test/java/com/vayunmathur/clock/platform/SchedulerAndReceiverDeepTest.kt+++ b/clock/src/test/java/com/vayunmathur/clock/platform/SchedulerAndReceiverDeepTest.kt@@ -15,6 +15,7 @@ import org.junit.Before import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.Shadows.shadowOf+import com.vayunmathur.testsupport.awaitWithMainIdle import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFailsWith@@ -106,14 +107,13 @@ class SchedulerAndReceiverDeepTest { /** Consume stored background DB errors so later runTest tests stay clean. */ private fun drain() {- Thread.sleep(1_000) repeat(8) {+ run { var pumped = 0; awaitWithMainIdle("pump background work", maxSteps = 25_000) { ++pumped >= 25_000 } } try { kotlinx.coroutines.test.runTest { } } catch (e: IllegalStateException) { if (e.javaClass.simpleName != "UncaughtExceptionsBeforeTest") throw e }- Thread.sleep(400) } }
clock/src/test/java/com/vayunmathur/clock/platform/StopwatchViewModelTest.kt
diff --git a/clock/src/test/java/com/vayunmathur/clock/platform/StopwatchViewModelTest.kt b/clock/src/test/java/com/vayunmathur/clock/platform/StopwatchViewModelTest.ktindex 33596b76b6..e2182a9267 100644--- a/clock/src/test/java/com/vayunmathur/clock/platform/StopwatchViewModelTest.kt+++ b/clock/src/test/java/com/vayunmathur/clock/platform/StopwatchViewModelTest.kt@@ -30,23 +30,12 @@ class StopwatchViewModelTest { private val ctx get() = ApplicationProvider.getApplicationContext<Application>() private fun vm() = ClockViewModel(ctx, ClockRepository.get(ctx)) - /**- * Pumps Robolectric's paused main looper (where viewModelScope and- * the stopwatch's DataStore collector resume) until [cond] — a- * terminal StateFlow state — holds. Step-bounded and sleep-free:- * each step is a looper idle, not a wall-clock bet. Replaces a fixed- * `repeat(6) { idle; idleFor(30ms); Thread.sleep(30) }` pump that- * both wasted real time and still raced the persisted reload.- */- private fun pumpUntil(desc: String, cond: () -> Boolean) =- awaitWithMainIdle(desc) { cond() }- @Test fun toggleLapResetAndReload() { val vm = vm() vm.resetStopwatch() // Reset applies in memory at once; idle the looper so the // persisted-state collector cannot replay a stale snapshot over it.- pumpUntil("reset settled") { !vm.stopwatchRunning.value && vm.lapTimes.value.isEmpty() }+ awaitWithMainIdle("reset settled") { !vm.stopwatchRunning.value && vm.lapTimes.value.isEmpty() } assertFalse(vm.stopwatchRunning.value) vm.toggleStopwatch()@@ -57,18 +46,18 @@ class StopwatchViewModelTest { DataStoreUtils.getInstance(ctx) .booleanFlow(StopwatchActionReceiver.KEY_STOPWATCH_RUNNING, false), ) { it }- pumpUntil("running settled") { vm.stopwatchRunning.value }+ awaitWithMainIdle("running settled") { vm.stopwatchRunning.value } assertTrue(vm.stopwatchRunning.value) assertTrue(vm.stopwatchCountingTime.value >= Duration.ZERO) vm.addLap()- pumpUntil("lap recorded") { vm.lapTimes.value.size == 1 }+ awaitWithMainIdle("lap recorded") { vm.lapTimes.value.size == 1 } vm.toggleStopwatch() // pause: banks the elapsed time awaitValueBlocking( DataStoreUtils.getInstance(ctx) .booleanFlow(StopwatchActionReceiver.KEY_STOPWATCH_RUNNING, false), ) { !it }- pumpUntil("paused settled") { !vm.stopwatchRunning.value }+ awaitWithMainIdle("paused settled") { !vm.stopwatchRunning.value } assertFalse(vm.stopwatchRunning.value) // Persisted terminal state first, as a terminal signal: the@@ -102,13 +91,13 @@ class StopwatchViewModelTest { // The persisted value is already in DataStore (awaited above), // so this pump only replays it through the main looper. val reloaded = vm()- pumpUntil("reloaded persisted state") {+ awaitWithMainIdle("reloaded persisted state") { !reloaded.stopwatchRunning.value && reloaded.lapTimes.value.size == 1 } assertFalse(reloaded.stopwatchRunning.value) vm.resetStopwatch()- pumpUntil("reset after reload") {+ awaitWithMainIdle("reset after reload") { vm.stopwatchCountingTime.value == Duration.ZERO && vm.lapTimes.value.isEmpty() } assertEquals(Duration.ZERO, vm.stopwatchCountingTime.value)
clock/src/test/java/com/vayunmathur/clock/service/AlarmSoundPlayTest.kt
diff --git a/clock/src/test/java/com/vayunmathur/clock/service/AlarmSoundPlayTest.kt b/clock/src/test/java/com/vayunmathur/clock/service/AlarmSoundPlayTest.ktindex c71692c0ee..a5eaf322cf 100644--- a/clock/src/test/java/com/vayunmathur/clock/service/AlarmSoundPlayTest.kt+++ b/clock/src/test/java/com/vayunmathur/clock/service/AlarmSoundPlayTest.kt@@ -4,11 +4,11 @@ import android.content.Intent import android.media.MediaPlayer import android.media.RingtoneManager import android.os.Looper-import java.util.concurrent.TimeUnit import org.junit.runner.RunWith import org.robolectric.Robolectric import org.robolectric.RobolectricTestRunner import org.robolectric.Shadows.shadowOf+import com.vayunmathur.testsupport.awaitWithMainIdle import org.robolectric.shadows.ShadowMediaPlayer import kotlin.test.Test import kotlin.test.assertEquals@@ -37,17 +37,12 @@ class AlarmSoundPlayTest { val controller = Robolectric.buildService(AlarmSoundService::class.java).create() val service = controller.get() service.onStartCommand(Intent().putExtra("ALARM_ID", 99L), 0, 1)- // The ring setup runs on the service's IO scope; give it time, pumping main.- val deadline = System.currentTimeMillis() + 8_000- while (System.currentTimeMillis() < deadline) {- shadowOf(Looper.getMainLooper()).idle()- shadowOf(Looper.getMainLooper()).idleFor(50, TimeUnit.MILLISECONDS)- Thread.sleep(40)- // A second, overlapping alarm retires the first ring and re-rings.- break- }+ // The ring setup runs on the service's IO scope; pump the main looper+ // (step-bounded, no wall sleep) so it can attempt the ring, then a+ // second, overlapping alarm retires the first ring and re-rings.+ run { var pumped = 0; awaitWithMainIdle("pump background work", maxSteps = 5_000) { ++pumped >= 400 } } service.onStartCommand(Intent().putExtra("ALARM_ID", 100L), 0, 2)- Thread.sleep(300)+ run { var pumped = 0; awaitWithMainIdle("pump background work", maxSteps = 5_000) { ++pumped >= 400 } } shadowOf(Looper.getMainLooper()).idle() service.onDestroy() shadowOf(Looper.getMainLooper()).idle()
clock/src/test/java/com/vayunmathur/clock/service/AlarmSoundServiceDeepTest.kt
diff --git a/clock/src/test/java/com/vayunmathur/clock/service/AlarmSoundServiceDeepTest.kt b/clock/src/test/java/com/vayunmathur/clock/service/AlarmSoundServiceDeepTest.ktindex f991d23ede..1584d263f3 100644--- a/clock/src/test/java/com/vayunmathur/clock/service/AlarmSoundServiceDeepTest.kt+++ b/clock/src/test/java/com/vayunmathur/clock/service/AlarmSoundServiceDeepTest.kt@@ -2,15 +2,13 @@ package com.vayunmathur.clock.service import android.content.Context import android.content.Intent-import android.os.Looper import androidx.test.core.app.ApplicationProvider import com.vayunmathur.clock.FakeAndroidKeyStore+import com.vayunmathur.testsupport.awaitWithMainIdle import org.junit.Before import org.junit.runner.RunWith import org.robolectric.Robolectric import org.robolectric.RobolectricTestRunner-import org.robolectric.Shadows.shadowOf-import java.util.concurrent.TimeUnit import kotlin.test.Test import kotlin.test.assertEquals @@ -25,22 +23,15 @@ class AlarmSoundServiceDeepTest { private val ctx: Context get() = ApplicationProvider.getApplicationContext() - private fun pump() {- repeat(20) {- shadowOf(Looper.getMainLooper()).idle()- shadowOf(Looper.getMainLooper()).idleFor(50, TimeUnit.MILLISECONDS)- Thread.sleep(25)- }- } @Test fun ringAttemptRunsVibrationAndRingtoneFallbackThenDestroys() { val intent = Intent(ctx, AlarmSoundService::class.java).apply { putExtra("ALARM_ID", 777L) } val controller = Robolectric.buildService(AlarmSoundService::class.java, intent).create() val result = controller.get().onStartCommand(intent, 0, 1) assertEquals(android.app.Service.START_NOT_STICKY, result)- pump()+ run { var pumped = 0; awaitWithMainIdle("pump background work", maxSteps = 5_000) { ++pumped >= 400 } } controller.destroy()- pump()+ run { var pumped = 0; awaitWithMainIdle("pump background work", maxSteps = 5_000) { ++pumped >= 400 } } } @Test fun overlappingAlarmsHandOverAndDestroyIsClean() {@@ -49,12 +40,12 @@ class AlarmSoundServiceDeepTest { service.onStartCommand( Intent(ctx, AlarmSoundService::class.java).apply { putExtra("ALARM_ID", 1L) }, 0, 1, )- pump()+ run { var pumped = 0; awaitWithMainIdle("pump background work", maxSteps = 5_000) { ++pumped >= 400 } } // A second alarm supersedes the first: the old player/vibrator are stopped first. service.onStartCommand( Intent(ctx, AlarmSoundService::class.java).apply { putExtra("ALARM_ID", 2L) }, 0, 2, )- pump()+ run { var pumped = 0; awaitWithMainIdle("pump background work", maxSteps = 5_000) { ++pumped >= 400 } } controller.destroy() } }
clock/src/test/java/com/vayunmathur/clock/service/AlarmSoundServiceTest.kt
diff --git a/clock/src/test/java/com/vayunmathur/clock/service/AlarmSoundServiceTest.kt b/clock/src/test/java/com/vayunmathur/clock/service/AlarmSoundServiceTest.ktindex 59c437805e..79414c44f1 100644--- a/clock/src/test/java/com/vayunmathur/clock/service/AlarmSoundServiceTest.kt+++ b/clock/src/test/java/com/vayunmathur/clock/service/AlarmSoundServiceTest.kt@@ -8,6 +8,7 @@ import org.junit.Before import org.junit.runner.RunWith import org.robolectric.Robolectric import org.robolectric.RobolectricTestRunner+import com.vayunmathur.testsupport.awaitWithMainIdle import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertNull@@ -40,8 +41,8 @@ class AlarmSoundServiceTest { putExtra("ALARM_ID", 4242L) } val controller = Robolectric.buildService(AlarmSoundService::class.java, intent).create().startCommand(0, 1)- // Give the IO coroutine a moment to attempt the (failing) DB read and ringtone.- Thread.sleep(500)+ // Pump the main looper so the IO coroutine attempts the (failing) DB read and ringtone.+ run { var pumped = 0; awaitWithMainIdle("pump background work", maxSteps = 5_000) { ++pumped >= 400 } } controller.destroy() } @@ -52,7 +53,7 @@ class AlarmSoundServiceTest { val service = controller.get() service.onStartCommand(Intent(ctx, AlarmSoundService::class.java).apply { putExtra("ALARM_ID", 1L) }, 0, 1) service.onStartCommand(Intent(ctx, AlarmSoundService::class.java).apply { putExtra("ALARM_ID", 2L) }, 0, 2)- Thread.sleep(300)+ run { var pumped = 0; awaitWithMainIdle("pump background work", maxSteps = 5_000) { ++pumped >= 400 } } controller.destroy() }
clock/src/test/java/com/vayunmathur/clock/ui/AlarmRingingScreenTest.kt
diff --git a/clock/src/test/java/com/vayunmathur/clock/ui/AlarmRingingScreenTest.kt b/clock/src/test/java/com/vayunmathur/clock/ui/AlarmRingingScreenTest.ktindex 5a3db09da8..c46cd26f3d 100644--- a/clock/src/test/java/com/vayunmathur/clock/ui/AlarmRingingScreenTest.kt+++ b/clock/src/test/java/com/vayunmathur/clock/ui/AlarmRingingScreenTest.kt@@ -1,6 +1,7 @@ package com.vayunmathur.clock.ui import androidx.compose.ui.test.junit4.createComposeRule+import com.vayunmathur.testsupport.awaitWithMainIdle import androidx.compose.ui.test.onNodeWithText import androidx.compose.ui.test.performClick import androidx.test.ext.junit.runners.AndroidJUnit4@@ -19,12 +20,12 @@ class AlarmRingingScreenTest { /** Drain stored background-DB errors from earlier classes (see ClockDialogsDeepTest). */ @org.junit.BeforeClass @JvmStatic fun drainStoredDbErrors() { repeat(8) {+ run { var pumped = 0; awaitWithMainIdle("pump background work", maxSteps = 25_000) { ++pumped >= 25_000 } } try { kotlinx.coroutines.test.runTest { } } catch (e: IllegalStateException) { if (e.javaClass.simpleName != "UncaughtExceptionsBeforeTest") throw e }- Thread.sleep(400) } } }
clock/src/test/java/com/vayunmathur/clock/ui/AlarmSettingsRingtoneTest.kt
diff --git a/clock/src/test/java/com/vayunmathur/clock/ui/AlarmSettingsRingtoneTest.kt b/clock/src/test/java/com/vayunmathur/clock/ui/AlarmSettingsRingtoneTest.ktindex 3ac0170d0c..02fb9f9e2f 100644--- a/clock/src/test/java/com/vayunmathur/clock/ui/AlarmSettingsRingtoneTest.kt+++ b/clock/src/test/java/com/vayunmathur/clock/ui/AlarmSettingsRingtoneTest.kt@@ -1,6 +1,9 @@ package com.vayunmathur.clock.ui import android.app.Activity+import com.vayunmathur.testsupport.awaitWithMainIdle+import com.vayunmathur.testsupport.awaitSemantics+import com.vayunmathur.testsupport.awaitValueBlocking import android.content.Context import android.content.Intent import android.media.RingtoneManager@@ -36,12 +39,12 @@ class AlarmSettingsRingtoneTest { /** Earlier classes' background DB errors surface here otherwise (see ClockDialogsDeepTest). */ @org.junit.BeforeClass @JvmStatic fun drainStoredDbErrors() { repeat(8) {+ run { var pumped = 0; awaitWithMainIdle("pump background work", maxSteps = 25_000) { ++pumped >= 25_000 } } try { kotlinx.coroutines.test.runTest { } } catch (e: IllegalStateException) { if (e.javaClass.simpleName != "UncaughtExceptionsBeforeTest") throw e }- Thread.sleep(400) } } }@@ -50,16 +53,6 @@ class AlarmSettingsRingtoneTest { private val ctx: Context get() = ApplicationProvider.getApplicationContext() - private fun awaitValue(deadlineMs: Long = 10_000, read: () -> Boolean): Boolean {- val deadline = System.currentTimeMillis() + deadlineMs- while (System.currentTimeMillis() < deadline) {- if (read()) return true- Thread.sleep(50)- rule.waitForIdle()- }- return read()- }- @Test fun ringtonePickPersistsAndCancelKeeps() { val ds = DataStoreUtils.getInstance(ctx) val stack = NavBackStack(arrayOf<Route>(Route.Alarm, Route.AlarmSettings))@@ -78,10 +71,12 @@ class AlarmSettingsRingtoneTest { ActivityResult(Activity.RESULT_OK, Intent().putExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI, picked)), ) rule.waitForIdle()- assertEquals(- true,- awaitValue { ds.getString(ClockViewModel.KEY_DEFAULT_RINGTONE) == picked.toString() },- )+ // Terminal signal: the persisted ringtone reaches the picked URI+ // (the write is launched on the composition scope, so pump it).+ rule.awaitSemantics("picked ringtone persisted") {+ ds.getString(ClockViewModel.KEY_DEFAULT_RINGTONE) == picked.toString()+ }+ assertEquals(picked.toString(), ds.getString(ClockViewModel.KEY_DEFAULT_RINGTONE)) // Cancel the next pick: the stored default must not move. val titleAfter = ringtoneTitle(ctx, picked.toString(), RingtoneManager.TYPE_ALARM)
clock/src/test/java/com/vayunmathur/clock/ui/CardsAndDialogSaveTest.kt
diff --git a/clock/src/test/java/com/vayunmathur/clock/ui/CardsAndDialogSaveTest.kt b/clock/src/test/java/com/vayunmathur/clock/ui/CardsAndDialogSaveTest.ktindex 6958d457fb..ee7f2fe987 100644--- a/clock/src/test/java/com/vayunmathur/clock/ui/CardsAndDialogSaveTest.kt+++ b/clock/src/test/java/com/vayunmathur/clock/ui/CardsAndDialogSaveTest.kt@@ -1,6 +1,7 @@ package com.vayunmathur.clock.ui import android.app.Application+import com.vayunmathur.testsupport.awaitWithMainIdle import androidx.compose.ui.test.hasSetTextAction import androidx.compose.ui.test.isToggleable import androidx.compose.ui.test.junit4.createComposeRule@@ -62,12 +63,12 @@ class CardsAndDialogSaveTest { // Drain kotlinx-coroutines-test's stored uncaught errors from // earlier classes, as in ClockDialogsDeepTest. repeat(8) {+ run { var pumped = 0; awaitWithMainIdle("pump background work", maxSteps = 25_000) { ++pumped >= 25_000 } } try { kotlinx.coroutines.test.runTest { } } catch (e: IllegalStateException) { if (e.javaClass.simpleName != "UncaughtExceptionsBeforeTest") throw e }- Thread.sleep(400) } } }@@ -87,12 +88,12 @@ class CardsAndDialogSaveTest { @org.junit.After fun drainAfter() { repeat(6) {+ run { var pumped = 0; awaitWithMainIdle("pump background work", maxSteps = 25_000) { ++pumped >= 25_000 } } try { kotlinx.coroutines.test.runTest { } } catch (e: IllegalStateException) { if (e.javaClass.simpleName != "UncaughtExceptionsBeforeTest") throw e }- Thread.sleep(300) } }
clock/src/test/java/com/vayunmathur/clock/ui/ClockDialogsDeepTest.kt
diff --git a/clock/src/test/java/com/vayunmathur/clock/ui/ClockDialogsDeepTest.kt b/clock/src/test/java/com/vayunmathur/clock/ui/ClockDialogsDeepTest.ktindex fd86039add..22a9e1c8f5 100644--- a/clock/src/test/java/com/vayunmathur/clock/ui/ClockDialogsDeepTest.kt+++ b/clock/src/test/java/com/vayunmathur/clock/ui/ClockDialogsDeepTest.kt@@ -1,6 +1,7 @@ package com.vayunmathur.clock.ui import android.app.Application+import com.vayunmathur.testsupport.awaitWithMainIdle import android.content.Context import androidx.compose.ui.test.hasSetTextAction import androidx.compose.ui.test.junit4.createComposeRule@@ -37,12 +38,12 @@ class ClockDialogsDeepTest { */ @org.junit.BeforeClass @JvmStatic fun drainStoredDbErrors() { repeat(8) {+ run { var pumped = 0; awaitWithMainIdle("pump background work", maxSteps = 25_000) { ++pumped >= 25_000 } } try { kotlinx.coroutines.test.runTest { } } catch (e: IllegalStateException) { if (e.javaClass.simpleName != "UncaughtExceptionsBeforeTest") throw e }- Thread.sleep(400) } } }
clock/src/test/java/com/vayunmathur/clock/ui/ClockPageDeepTest.kt
diff --git a/clock/src/test/java/com/vayunmathur/clock/ui/ClockPageDeepTest.kt b/clock/src/test/java/com/vayunmathur/clock/ui/ClockPageDeepTest.ktindex b293f1b9ca..4c7bc8c68b 100644--- a/clock/src/test/java/com/vayunmathur/clock/ui/ClockPageDeepTest.kt+++ b/clock/src/test/java/com/vayunmathur/clock/ui/ClockPageDeepTest.kt@@ -18,6 +18,7 @@ import com.vayunmathur.clock.platform.WorldClockCities import com.vayunmathur.library.util.DataStoreUtils import com.vayunmathur.library.util.NavBackStack import kotlinx.coroutines.runBlocking+import com.vayunmathur.testsupport.awaitValueBlocking import org.junit.Before import org.junit.Rule import org.junit.runner.RunWith@@ -38,11 +39,8 @@ class ClockPageDeepTest { @Test fun clockPageShowsSelectedWorldClocksAndAddNavigates() { val vm = vm()- val deadline = System.currentTimeMillis() + 10_000- while (vm.cities.value == null && System.currentTimeMillis() < deadline) {- Thread.sleep(50)- rule.waitForIdle()- }+ // Terminal signal: the cities StateFlow emits its asset-parsed map.+ awaitValueBlocking(vm.cities) { it != null } val cities = vm.cities.value.orEmpty() assertTrue(cities.isNotEmpty()) val picked = cities.keys.take(2)
clock/src/test/java/com/vayunmathur/clock/ui/ClockPageDragTest.kt
diff --git a/clock/src/test/java/com/vayunmathur/clock/ui/ClockPageDragTest.kt b/clock/src/test/java/com/vayunmathur/clock/ui/ClockPageDragTest.ktindex 3961bd0891..69f11146ed 100644--- a/clock/src/test/java/com/vayunmathur/clock/ui/ClockPageDragTest.kt+++ b/clock/src/test/java/com/vayunmathur/clock/ui/ClockPageDragTest.kt@@ -1,6 +1,7 @@ package com.vayunmathur.clock.ui import android.app.Application+import com.vayunmathur.testsupport.awaitWithMainIdle import androidx.compose.ui.test.junit4.createComposeRule import androidx.compose.ui.test.onAllNodesWithContentDescription import androidx.compose.ui.test.onNodeWithText@@ -20,6 +21,8 @@ import com.vayunmathur.library.util.DataStoreUtils import com.vayunmathur.library.util.NavBackStack import kotlinx.coroutines.flow.first import kotlinx.coroutines.runBlocking+import com.vayunmathur.testsupport.awaitSemantics+import com.vayunmathur.testsupport.awaitValueBlocking import org.junit.Before import org.junit.Rule import org.junit.runner.RunWith@@ -39,12 +42,12 @@ class ClockPageDragTest { companion object { @org.junit.BeforeClass @JvmStatic fun drainStoredDbErrors() { repeat(8) {+ run { var pumped = 0; awaitWithMainIdle("pump background work", maxSteps = 25_000) { ++pumped >= 25_000 } } try { kotlinx.coroutines.test.runTest { } } catch (e: IllegalStateException) { if (e.javaClass.simpleName != "UncaughtExceptionsBeforeTest") throw e }- Thread.sleep(400) } } }@@ -59,16 +62,11 @@ class ClockPageDragTest { val vm = ClockViewModel(ctx, ClockRepository.get(ctx)) val stack = NavBackStack(arrayOf<Route>(Route.Alarm)) rule.setContent { ClockPage(stack, ds, vm) }- // Cities load from the VM's asset parse; wait for both rows.- val deadline = System.currentTimeMillis() + 15_000- var rows = 0- while (System.currentTimeMillis() < deadline) {- rule.waitForIdle()- rows = rule.onAllNodesWithContentDescription("Reorder").fetchSemanticsNodes().size- if (rows == 2) break- Thread.sleep(100)+ // Cities load from the VM's asset parse; wait for both rows to compose.+ rule.awaitSemantics("both world-clock rows composed") {+ rule.onAllNodesWithContentDescription("Reorder").fetchSemanticsNodes().size == 2 }- assertEquals(2, rows)+ assertEquals(2, rule.onAllNodesWithContentDescription("Reorder").fetchSemanticsNodes().size) rule.onNodeWithText("Tokyo").assertExists() rule.onNodeWithText("London").assertExists() @@ -83,14 +81,8 @@ class ClockPageDragTest { } rule.waitForIdle() - val persistDeadline = System.currentTimeMillis() + 10_000- var stored: List<String> = emptyList()- while (System.currentTimeMillis() < persistDeadline) {- stored = runBlocking { WorldClockCities.flow(ds).first() }- if (stored == listOf("London", "Tokyo")) break- Thread.sleep(100)- rule.waitForIdle()- }+ // Terminal signal: the persisted world-clock flow emits the new order.+ val stored = awaitValueBlocking(WorldClockCities.flow(ds)) { it == listOf("London", "Tokyo") } assertEquals(listOf("London", "Tokyo"), stored) runBlocking { WorldClockCities.set(ds, emptyList()) } }
clock/src/test/java/com/vayunmathur/clock/ui/ClockPagesUiTest.kt
diff --git a/clock/src/test/java/com/vayunmathur/clock/ui/ClockPagesUiTest.kt b/clock/src/test/java/com/vayunmathur/clock/ui/ClockPagesUiTest.ktindex 6a41c9f0d3..40d1cb0a9e 100644--- a/clock/src/test/java/com/vayunmathur/clock/ui/ClockPagesUiTest.kt+++ b/clock/src/test/java/com/vayunmathur/clock/ui/ClockPagesUiTest.kt@@ -26,6 +26,7 @@ import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertNotNull import kotlin.test.assertTrue+import com.vayunmathur.testsupport.awaitWithMainIdle /** Tests for the page binders, [Navigation], [Route] serialization, MainActivity and AlarmActivity. */ @RunWith(AndroidJUnit4::class)@@ -119,12 +120,9 @@ class ClockPagesUiTest { fun alarmActivityWithUnknownIdFinishesAfterLoadFails() { val intent = Intent(ctx, AlarmActivity::class.java).apply { putExtra("ALARM_ID", 987654L) } val controller = Robolectric.buildActivity(AlarmActivity::class.java, intent).create().start()- // DB lookup fails under Robolectric, which finishes the activity.- val deadline = System.currentTimeMillis() + 5000- while (!controller.get().isFinishing && System.currentTimeMillis() < deadline) {- org.robolectric.Shadows.shadowOf(android.os.Looper.getMainLooper()).idle()- Thread.sleep(50)- }+ // DB lookup fails under Robolectric, which finishes the activity:+ // wait on that terminal activity state, pumping the main looper.+ awaitWithMainIdle("alarm activity finishes after load fails", maxSteps = 100_000) { controller.get().isFinishing } assertTrue(controller.get().isFinishing) controller.destroy() }
clock/src/test/java/com/vayunmathur/clock/ui/ClockScreensDeepTest.kt
diff --git a/clock/src/test/java/com/vayunmathur/clock/ui/ClockScreensDeepTest.kt b/clock/src/test/java/com/vayunmathur/clock/ui/ClockScreensDeepTest.ktindex 7fb7fbe89e..36ad7975b3 100644--- a/clock/src/test/java/com/vayunmathur/clock/ui/ClockScreensDeepTest.kt+++ b/clock/src/test/java/com/vayunmathur/clock/ui/ClockScreensDeepTest.kt@@ -43,6 +43,7 @@ import kotlin.time.Duration.Companion.hours import kotlin.time.Duration.Companion.minutes import kotlin.time.Duration.Companion.seconds import kotlin.time.Clock+import com.vayunmathur.testsupport.awaitSemantics /** Deep interaction coverage for the stateless tab screens and cards. */ @RunWith(AndroidJUnit4::class)@@ -163,23 +164,21 @@ class ClockScreensDeepTest { rule.waitForIdle() rule.onNodeWithText(ctx.getString(com.vayunmathur.clock.R.string.alarm_settings)).assertExists() rule.onNode(isToggleable()).performClick()- val deadline = System.currentTimeMillis() + 10_000- var flipped = false- while (System.currentTimeMillis() < deadline) {- if (ds.getBoolean(ClockViewModel.KEY_DEFAULT_VIBRATE, !vibrateBefore) == !vibrateBefore) { flipped = true; break }- Thread.sleep(50); rule.waitForIdle()+ // Terminal signals: the persisted defaults reach the new values. The+ // writes are launched on the composition scope, so the check must run+ // through the semantics pump (which drives that scope), not a+ // blocking flow wait that parks the main thread it needs.+ rule.awaitSemantics("vibrate default persisted") {+ ds.getBoolean(ClockViewModel.KEY_DEFAULT_VIBRATE, vibrateBefore) == !vibrateBefore }- assertTrue(flipped, "vibrate default was not persisted")+ assertTrue(ds.getBoolean(ClockViewModel.KEY_DEFAULT_VIBRATE, !vibrateBefore) == !vibrateBefore, "vibrate default was not persisted") rule.onNodeWithText("5 min").performClick() rule.waitForIdle() rule.onNodeWithText("10 min", useUnmergedTree = true).performClick()- var snoozed = false- val deadline2 = System.currentTimeMillis() + 10_000- while (System.currentTimeMillis() < deadline2) {- if ((ds.getLong(ClockViewModel.KEY_DEFAULT_SNOOZE) ?: -1L) == 10L) { snoozed = true; break }- Thread.sleep(50); rule.waitForIdle()+ rule.awaitSemantics("snooze default persisted") {+ (ds.getLong(ClockViewModel.KEY_DEFAULT_SNOOZE) ?: -1L) == 10L }- assertTrue(snoozed, "snooze default was not persisted")+ assertTrue((ds.getLong(ClockViewModel.KEY_DEFAULT_SNOOZE) ?: -1L) == 10L, "snooze default was not persisted") kotlinx.coroutines.runBlocking { ds.setBoolean(ClockViewModel.KEY_DEFAULT_VIBRATE, vibrateBefore) ds.setLong(ClockViewModel.KEY_DEFAULT_SNOOZE, 5L)
clock/src/test/java/com/vayunmathur/clock/ui/DialAndCompletedCardTest.kt
diff --git a/clock/src/test/java/com/vayunmathur/clock/ui/DialAndCompletedCardTest.kt b/clock/src/test/java/com/vayunmathur/clock/ui/DialAndCompletedCardTest.ktindex 032e42d7f0..576bf2ad52 100644--- a/clock/src/test/java/com/vayunmathur/clock/ui/DialAndCompletedCardTest.kt+++ b/clock/src/test/java/com/vayunmathur/clock/ui/DialAndCompletedCardTest.kt@@ -1,6 +1,7 @@ package com.vayunmathur.clock.ui import androidx.compose.foundation.layout.fillMaxSize+import com.vayunmathur.testsupport.awaitWithMainIdle import androidx.compose.ui.Modifier import androidx.compose.ui.test.captureToImage import androidx.compose.ui.test.junit4.createComposeRule@@ -36,12 +37,12 @@ class DialAndCompletedCardTest { /** Drain stored background-DB errors from earlier classes (see ClockDialogsDeepTest). */ @org.junit.BeforeClass @JvmStatic fun drainStoredDbErrors() { repeat(8) {+ run { var pumped = 0; awaitWithMainIdle("pump background work", maxSteps = 25_000) { ++pumped >= 25_000 } } try { kotlinx.coroutines.test.runTest { } } catch (e: IllegalStateException) { if (e.javaClass.simpleName != "UncaughtExceptionsBeforeTest") throw e }- Thread.sleep(400) } } }
clock/src/test/java/com/vayunmathur/clock/ui/DialogsWithVmUiTest.kt
diff --git a/clock/src/test/java/com/vayunmathur/clock/ui/DialogsWithVmUiTest.kt b/clock/src/test/java/com/vayunmathur/clock/ui/DialogsWithVmUiTest.ktindex f39508c543..59bc2275f1 100644--- a/clock/src/test/java/com/vayunmathur/clock/ui/DialogsWithVmUiTest.kt+++ b/clock/src/test/java/com/vayunmathur/clock/ui/DialogsWithVmUiTest.kt@@ -21,6 +21,7 @@ import com.vayunmathur.library.util.DataStoreUtils import com.vayunmathur.library.util.NavBackStack import org.junit.Before import kotlinx.coroutines.flow.first+import com.vayunmathur.testsupport.awaitValueBlocking import org.junit.Rule import org.junit.runner.RunWith import kotlin.test.Test@@ -43,14 +44,6 @@ class DialogsWithVmUiTest { .performSemanticsAction(androidx.compose.ui.semantics.SemanticsActions.OnClick) } - private fun awaitCities(vm: ClockViewModel) {- val deadline = System.currentTimeMillis() + 10_000- while (vm.cities.value == null && System.currentTimeMillis() < deadline) {- Thread.sleep(50)- rule.waitForIdle()- }- assertTrue(vm.cities.value?.isNotEmpty() == true, "cities did not load")- } @Test fun newAlarmDialogShowsPickerAndCancels() {@@ -76,7 +69,7 @@ class DialogsWithVmUiTest { @Test fun selectTimeZonesListsCitiesAndSearchFilters() { val v = vm()- awaitCities(v)+ awaitValueBlocking(v.cities) { it?.isNotEmpty() == true } val ds = DataStoreUtils.getInstance(ctx) val stack = NavBackStack(arrayOf<Route>(Route.Alarm, Route.SelectTimeZonesDialog)) rule.setContent { SelectTimeZonesDialog(stack, ds, v) }@@ -92,23 +85,15 @@ class DialogsWithVmUiTest { @Test fun selectTimeZonesToggleSelectsCity() { val v = vm()- awaitCities(v)+ awaitValueBlocking(v.cities) { it?.isNotEmpty() == true } val ds = DataStoreUtils.getInstance(ctx) val stack = NavBackStack(arrayOf<Route>(Route.Alarm, Route.SelectTimeZonesDialog)) rule.setContent { SelectTimeZonesDialog(stack, ds, v) } rule.waitForIdle() val city = v.cities.value!!.keys.first() clickRow(city)- // Selection persists through WorldClockCities; give the DataStore write a moment.- val deadline = System.currentTimeMillis() + 5000- var selected: List<String> = emptyList()- while (System.currentTimeMillis() < deadline) {- kotlinx.coroutines.runBlocking {- selected = com.vayunmathur.clock.platform.WorldClockCities.flow(ds).first()- }- if (city in selected) break- Thread.sleep(50)- }+ // Terminal signal: the persisted selection flow emits the chosen city.+ val selected = awaitValueBlocking(com.vayunmathur.clock.platform.WorldClockCities.flow(ds)) { city in it } assertTrue(city in selected, "selected=$selected city=$city") // Clean up so other tests start unselected. kotlinx.coroutines.runBlocking { com.vayunmathur.clock.platform.WorldClockCities.set(ds, emptyList()) }
clock/src/test/java/com/vayunmathur/clock/ui/NavigationRoutesTest.kt
diff --git a/clock/src/test/java/com/vayunmathur/clock/ui/NavigationRoutesTest.kt b/clock/src/test/java/com/vayunmathur/clock/ui/NavigationRoutesTest.ktindex 706b5d7543..92c58a98dd 100644--- a/clock/src/test/java/com/vayunmathur/clock/ui/NavigationRoutesTest.kt+++ b/clock/src/test/java/com/vayunmathur/clock/ui/NavigationRoutesTest.kt@@ -1,6 +1,7 @@ package com.vayunmathur.clock.ui import android.app.Application+import com.vayunmathur.testsupport.awaitWithMainIdle import androidx.compose.ui.test.junit4.createComposeRule import androidx.compose.ui.test.onNodeWithContentDescription import androidx.compose.ui.test.onNodeWithText@@ -32,12 +33,12 @@ class NavigationRoutesTest { /** Drain stored background-DB errors from earlier classes (see ClockDialogsDeepTest). */ @org.junit.BeforeClass @JvmStatic fun drainStoredDbErrors() { repeat(8) {+ run { var pumped = 0; awaitWithMainIdle("pump background work", maxSteps = 25_000) { ++pumped >= 25_000 } } try { kotlinx.coroutines.test.runTest { } } catch (e: IllegalStateException) { if (e.javaClass.simpleName != "UncaughtExceptionsBeforeTest") throw e }- Thread.sleep(400) } } }
clock/src/test/java/com/vayunmathur/clock/ui/ScreensDirectTest.kt
diff --git a/clock/src/test/java/com/vayunmathur/clock/ui/ScreensDirectTest.kt b/clock/src/test/java/com/vayunmathur/clock/ui/ScreensDirectTest.ktindex 323bb5acd6..60ff54b2f3 100644--- a/clock/src/test/java/com/vayunmathur/clock/ui/ScreensDirectTest.kt+++ b/clock/src/test/java/com/vayunmathur/clock/ui/ScreensDirectTest.kt@@ -1,6 +1,7 @@ package com.vayunmathur.clock.ui import androidx.compose.ui.test.assertIsEnabled+import com.vayunmathur.testsupport.awaitWithMainIdle import androidx.compose.ui.test.hasSetTextAction import androidx.compose.ui.test.junit4.createComposeRule import androidx.compose.ui.test.moveBy@@ -52,12 +53,12 @@ class ScreensDirectTest { /** Drain stored background-DB errors from earlier classes (see ClockDialogsDeepTest). */ @org.junit.BeforeClass @JvmStatic fun drainStoredDbErrors() { repeat(8) {+ run { var pumped = 0; awaitWithMainIdle("pump background work", maxSteps = 25_000) { ++pumped >= 25_000 } } try { kotlinx.coroutines.test.runTest { } } catch (e: IllegalStateException) { if (e.javaClass.simpleName != "UncaughtExceptionsBeforeTest") throw e }- Thread.sleep(400) } } }