Modern Apps git

← Modern-Apps.git

tests: kill the wedges behind the 45m appstore timeout and 8 flakes

Commit
ab55bced1529708c73aac17271f71e2209739666
Author
Vayun Mathur <[email protected]>
When
2026-11-22 21:11 UTC (13 days ago)
Parents
56a2254
Appstore's Native companion timed out with zero failures:
classes wedge for their full 300s pump budget when
ViewModel init's purgeDisabled deletes their seeded rows
(DetailAndBrowseOpsTest, TvDetailWrapperAndActionsTest -
both reproduced locally at ~301s burns) or when tests wait
on real catalogue syncs (PhoneSyncSourcesTest). All three
now use the hermetic pattern (settled init, persisted
enabled sources, failing download overrides); companion
186/186 in 3m15s. CI's extra contention (shared 8-thread
box, 256 cpu-shares) turns each wedge into task death.

Same round: uniflix's TV grid class was the only sibling
never planting a database (shared-JVM stale DB - 5
failures; now hermetic in-memory fixture); contacts seeded
a DataStore set fire-and-forget then migrated (now the
suspending seed); nonogram's pump advanced the looper
clock per-step, retriggering session-cancel generations
(now idle-first like the file's own awaitFlow); health's
recipe rename awaited the loaded text but not the editable
field itself (order-proof await of the single editable
node; the exact CI stack reproduced pre-fix) plus a
same-genus meal-search sleep-poll.

Verified: each class x3 and full module suites green
under taskset 5 CPUs. No assertions weakened.

Diff

appstore/src/test/java/com/vayunmathur/appstore/tv/TvDetailWrapperAndActionsTest.kt
diff --git a/appstore/src/test/java/com/vayunmathur/appstore/tv/TvDetailWrapperAndActionsTest.kt b/appstore/src/test/java/com/vayunmathur/appstore/tv/TvDetailWrapperAndActionsTest.ktindex acb435b62d..dac4f35ec4 100644--- a/appstore/src/test/java/com/vayunmathur/appstore/tv/TvDetailWrapperAndActionsTest.kt+++ b/appstore/src/test/java/com/vayunmathur/appstore/tv/TvDetailWrapperAndActionsTest.kt@@ -46,6 +46,26 @@ class TvDetailWrapperAndActionsTest {     @BeforeTest     fun setUp() {         app = ApplicationProvider.getApplicationContext()+        // Hermetic offline + purge-proof (the TvHomeBranchesTest+        // pattern): persist FDROID as enabled before the ViewModel+        // exists, so init's purgeDisabled keeps F-Droid rows instead of+        // deleting the seeded one whenever its launch wins the race+        // against a test's seed (the "startup settled" signal below can+        // be satisfied by the package-index collector's loadHome before+        // init's own purge has run — observed as a 300s wedge where+        // loadDetail shelled the package via Play). The failing+        // download override keeps init's first-sync offline; cleared in+        // tearDown so loopback-download classes keep real behaviour.+        com.vayunmathur.appstore.data.FDroidRepository.downloadOverride = { url, _ ->+            throw java.io.IOException("offline test double for $url")+        }+        kotlinx.coroutines.runBlocking {+            val settings = com.vayunmathur.appstore.data.SettingsRepository(+                app, kotlinx.coroutines.CoroutineScope(kotlinx.coroutines.Dispatchers.IO),+            )+            settings.setSourceEnabled(AppSource.FDROID, true)+            settings.setSourceEnabled(AppSource.MODERN_APPS, true)+        }         db = Room.inMemoryDatabaseBuilder(app, AppDatabase::class.java)             .setDriver(BundledSQLiteDriver())             .allowMainThreadQueries()@@ -55,6 +75,11 @@ class TvDetailWrapperAndActionsTest {         vm = TvStoreViewModel(app, db)     } +    @kotlin.test.AfterTest+    fun tearDown() {+        com.vayunmathur.appstore.data.FDroidRepository.downloadOverride = null+    }+     private fun await(description: String, condition: () -> Boolean) {         try {             pumpUntil(description, condition)
appstore/src/test/java/com/vayunmathur/appstore/util/DetailAndBrowseOpsTest.kt
diff --git a/appstore/src/test/java/com/vayunmathur/appstore/util/DetailAndBrowseOpsTest.kt b/appstore/src/test/java/com/vayunmathur/appstore/util/DetailAndBrowseOpsTest.ktindex 3765b75c16..04d99248c0 100644--- a/appstore/src/test/java/com/vayunmathur/appstore/util/DetailAndBrowseOpsTest.kt+++ b/appstore/src/test/java/com/vayunmathur/appstore/util/DetailAndBrowseOpsTest.kt@@ -43,35 +43,56 @@ class DetailAndBrowseOpsTest {             .setDriver(BundledSQLiteDriver())             .allowMainThreadQueries()             .build()-        runBlocking {-            db.cachedAppDao().upsertAll(-                listOf(-                    UnifiedApp(-                        packageName = "com.example.cached",-                        source = AppSource.FDROID,-                        name = "Cached Name",-                        versionCode = 9L,-                        categories = listOf("Games"),-                        repoUrl = DefaultRepos.FDROID.url,-                    ).toEntity(),-                    UnifiedApp(-                        packageName = "com.example.zmodern",-                        source = AppSource.MODERN_APPS,-                        name = "Zulu Modern",-                        repoUrl = DefaultRepos.MODERN_APPS.url,-                    ).toEntity(),-                    UnifiedApp(-                        packageName = "com.example.amodern",-                        source = AppSource.MODERN_APPS,-                        name = "Alpha Modern",-                        repoUrl = DefaultRepos.MODERN_APPS.url,-                    ).toEntity(),-                ),-            )-        }+        seedCatalogue()         vm = AppStoreViewModel(app, db)     } +    private fun seedCatalogue() = runBlocking {+        db.cachedAppDao().upsertAll(+            listOf(+                UnifiedApp(+                    packageName = "com.example.cached",+                    source = AppSource.FDROID,+                    name = "Cached Name",+                    versionCode = 9L,+                    categories = listOf("Games"),+                    repoUrl = DefaultRepos.FDROID.url,+                ).toEntity(),+                UnifiedApp(+                    packageName = "com.example.zmodern",+                    source = AppSource.MODERN_APPS,+                    name = "Zulu Modern",+                    repoUrl = DefaultRepos.MODERN_APPS.url,+                ).toEntity(),+                UnifiedApp(+                    packageName = "com.example.amodern",+                    source = AppSource.MODERN_APPS,+                    name = "Alpha Modern",+                    repoUrl = DefaultRepos.MODERN_APPS.url,+                ).toEntity(),+            ),+        )+    }++    /**+     * Settle-then-reseed (the LoadHomeTest arrangement): ViewModel init+     * purges every disabled source's cached rows — F-Droid is not in+     * DEFAULT_ENABLED, so the seeded "Cached Name" row is deleted+     * whenever init's purge lands before a test's query, and the pumped+     * awaits below then burn their whole 6,000-step budget on a+     * condition that can never become true again (observed: "category+     * browse" wedged for 300s in a contended companion run). The+     * modern-recent section is init's terminal home signal (only its+     * loadHome can produce it here); re-seeding afterwards restores+     * the row init legitimately purged, and no second purge runs.+     */+    private fun settleInit() {+        await("init home") {+            vm.home.value.sections.any { it.id == "modern-recent" }+        }+        seedCatalogue()+    }+     private fun await(description: String, condition: () -> Boolean) {         try {             pumpUntil(description, condition)@@ -117,6 +138,7 @@ class DetailAndBrowseOpsTest {      @Test     fun `loadDetail by package resolves the catalogue row`() {+        settleInit()         // Even a package Play also lists: the catalogue row an install         // would use wins over any shell listing.         vm.loadDetail("com.example.cached")@@ -135,6 +157,7 @@ class DetailAndBrowseOpsTest {      @Test     fun `loading a second package replaces the first detail`() {+        settleInit()         // The route-argument contract in one test: the entry for package B         // must never render package A's listing, not even briefly from a         // stale flow — loadDetail drops the old app synchronously.@@ -151,6 +174,7 @@ class DetailAndBrowseOpsTest {      @Test     fun `browse expands an offline section to its full sorted catalogue`() {+        settleInit()         vm.loadBrowse("modern-recent")         await("browse loaded") { vm.browse.value.apps.size == 2 && !vm.browse.value.isLoading }         assertEquals("modern-recent", vm.browse.value.sectionId)@@ -163,6 +187,7 @@ class DetailAndBrowseOpsTest {      @Test     fun `browse by category and by play cluster fallback`() {+        settleInit()         // A category's name lives only in the home row's title: browse the         // category home is currently showing.         vm.selectCategory("Games")
appstore/src/test/java/com/vayunmathur/appstore/util/PhoneSyncSourcesTest.kt
diff --git a/appstore/src/test/java/com/vayunmathur/appstore/util/PhoneSyncSourcesTest.kt b/appstore/src/test/java/com/vayunmathur/appstore/util/PhoneSyncSourcesTest.ktindex bdeaae3ded..3b7372f371 100644--- a/appstore/src/test/java/com/vayunmathur/appstore/util/PhoneSyncSourcesTest.kt+++ b/appstore/src/test/java/com/vayunmathur/appstore/util/PhoneSyncSourcesTest.kt@@ -27,6 +27,21 @@ class PhoneSyncSourcesTest {      @BeforeTest     fun setUp() {+        // Hermetic offline (the TvHomeBranchesTest pattern): this test+        // waits for the init sync and then a refresh sync to settle.+        // Without a failing download override both syncs fetch the real+        // F-Droid/Modern/Proprietary/Izzy indices (multi-MB downloads ++        // full-catalogue parse/upserts), so the class's duration is+        // whatever the host's egress + CPU contention make it — seconds+        // on an idle dev box, unbounded (30s connect / 120s read+        // timeouts per file, per source, per sync) on a throttled CI+        // container. The assertions below only need the sync lifecycle+        // (flag rises/falls, status clears), which a failed sync+        // exercises identically. Cleared in tearDown so loopback-download+        // classes in the same JVM keep real behaviour.+        com.vayunmathur.appstore.data.FDroidRepository.downloadOverride = { url, _ ->+            throw java.io.IOException("offline test double for $url")+        }         val app = ApplicationProvider.getApplicationContext<Application>()         val db = Room.inMemoryDatabaseBuilder(app, AppDatabase::class.java)             .setDriver(BundledSQLiteDriver())@@ -35,6 +50,11 @@ class PhoneSyncSourcesTest {         vm = AppStoreViewModel(app, db)     } +    @kotlin.test.AfterTest+    fun tearDown() {+        com.vayunmathur.appstore.data.FDroidRepository.downloadOverride = null+    }+     @Test     fun `refresh syncs and settles`() {         // Let the init work finish first so refresh is the only sync.
contacts/src/test/java/com/vayunmathur/contacts/util/MigrationBranchesW5Test.kt
diff --git a/contacts/src/test/java/com/vayunmathur/contacts/util/MigrationBranchesW5Test.kt b/contacts/src/test/java/com/vayunmathur/contacts/util/MigrationBranchesW5Test.ktindex 7d2c81abdc..4b1fd6a0e4 100644--- a/contacts/src/test/java/com/vayunmathur/contacts/util/MigrationBranchesW5Test.kt+++ b/contacts/src/test/java/com/vayunmathur/contacts/util/MigrationBranchesW5Test.kt@@ -90,16 +90,18 @@ class MigrationBranchesW5Test {     fun hiddenKeysOfEveryShapeMigrateOrKeep() {         val vm = ContactViewModel(app)         ioBlocking {-            vm.dataStore.addStringToSet("hidden_accounts", "com.google|Raw Name")-            vm.dataStore.addStringToSet("hidden_accounts", "no-pipe-entry")-            vm.dataStore.addStringToSet("hidden_accounts", encodeHiddenAccountKey("com.google", "Clean Name"))-            vm.dataStore.addStringToSet("hidden_accounts", "|")-            val deadline = System.nanoTime() + 15_000_000_000L-            while (!vm.dataStore.getStringSetAwait("hidden_accounts").contains("no-pipe-entry") &&-                System.nanoTime() < deadline-            ) {-                Thread.sleep(25)-            }+            // Suspending adds, not addStringToSet: that API is+            // fire-and-forget (scope.launch), so under CPU contention+            // the later seeds may not have landed when the migration+            // reads the set — the "no seeded key should be lost"+            // assertion then measures scheduler timing, not migration+            // behaviour (CI run fd5ebb27d: only the first two seeds+            // were visible). addStringToSetIfAbsent returns only once+            // its edit is committed, so every seed is present below.+            vm.dataStore.addStringToSetIfAbsent("hidden_accounts", "com.google|Raw Name")+            vm.dataStore.addStringToSetIfAbsent("hidden_accounts", "no-pipe-entry")+            vm.dataStore.addStringToSetIfAbsent("hidden_accounts", encodeHiddenAccountKey("com.google", "Clean Name"))+            vm.dataStore.addStringToSetIfAbsent("hidden_accounts", "|")             vm.migrateHiddenAccountKeys()             val hidden = vm.dataStore.getStringSetAwait("hidden_accounts")             assertTrue(hidden.contains("no-pipe-entry"), "pipe-less keys are kept, hidden=$hidden")
games/nonogram/src/test/java/com/vayunmathur/games/nonogram/platform/NonogramViewModelTest.kt
diff --git a/games/nonogram/src/test/java/com/vayunmathur/games/nonogram/platform/NonogramViewModelTest.kt b/games/nonogram/src/test/java/com/vayunmathur/games/nonogram/platform/NonogramViewModelTest.ktindex 16360cae4d..a7ca95f6c4 100644--- a/games/nonogram/src/test/java/com/vayunmathur/games/nonogram/platform/NonogramViewModelTest.kt+++ b/games/nonogram/src/test/java/com/vayunmathur/games/nonogram/platform/NonogramViewModelTest.kt@@ -105,8 +105,24 @@ class NonogramViewModelTest {             // idled at least once before judging the condition, and a             // condition that is already true at entry can still need             // that one pump for the work behind it to settle.-            Shadows.shadowOf(Looper.getMainLooper())-                .idleFor(PUMP_STEP_MS, java.util.concurrent.TimeUnit.MILLISECONDS)+            //+            // Idle WITHOUT advancing the looper clock on most steps.+            // Advancing it every step is what awaitFlow (below) proved+            // keeps retriggering the session combine while a generation+            // runs on Dispatchers.Default: each clock-advanced idle lets+            // a delayed re-emission land, collectLatest cancels the+            // in-flight generation, and under CI CPU contention the+            // replacement never finishes either — generating=true+            // forever (fd5ebb27d: rapidMovesAllPersistInOrder burned+            // both 6,000-step budgets, ~603s, with every worker idle+            // between cancellations). Delayed posts still get their+            // chance: the clock advances every 20th step, as in+            // awaitFlow.+            Shadows.shadowOf(Looper.getMainLooper()).idle()+            if (steps % 20 == 19) {+                Shadows.shadowOf(Looper.getMainLooper())+                    .idleFor(PUMP_STEP_MS, java.util.concurrent.TimeUnit.MILLISECONDS)+            }             if (condition()) break             java.util.concurrent.locks.LockSupport.parkNanos(                 java.util.concurrent.TimeUnit.MILLISECONDS.toNanos(PARK_MS),
health/src/test/java/com/vayunmathur/health/ui/MealAndPickerSearchTest.kt
diff --git a/health/src/test/java/com/vayunmathur/health/ui/MealAndPickerSearchTest.kt b/health/src/test/java/com/vayunmathur/health/ui/MealAndPickerSearchTest.ktindex 126bf9b05a..3e1a57049a 100644--- a/health/src/test/java/com/vayunmathur/health/ui/MealAndPickerSearchTest.kt+++ b/health/src/test/java/com/vayunmathur/health/ui/MealAndPickerSearchTest.kt@@ -27,6 +27,7 @@ import kotlin.test.BeforeTest import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertTrue+import kotlinx.coroutines.async import kotlinx.coroutines.flow.first import kotlinx.coroutines.runBlocking import org.junit.Rule@@ -75,12 +76,23 @@ class MealAndPickerSearchTest {         rule.onNodeWithText("Save").performClick()         rule.waitForIdle()         assertTrue(dismissed)-        var logged = false-        repeat(100) {-            if (repo.getRecordsFlow(RecordType.Nutrition).first().any { it.metadata == "MealFlow Stew" }) { logged = true; return@repeat }-            Thread.sleep(10)+        // Wait on the terminal Room emission while pumping the main+        // looper: logMeal runs on viewModelScope (Main), so its insert+        // segment only executes when the paused Robolectric looper is+        // idled — the previous Thread.sleep poll never pumped it and+        // burned its 1s wall-clock budget in a batched (forkEvery = 20)+        // JVM before the IO hop landed. Collecting on IO + pumped idle+        // is the NonogramViewModelTest blocking pattern.+        val loggedJob = kotlinx.coroutines.CoroutineScope(kotlinx.coroutines.Dispatchers.IO)+            .async {+                repo.getRecordsFlow(RecordType.Nutrition)+                    .first { rows -> rows.any { it.metadata == "MealFlow Stew" } }+                true+            }+        runCatching {+            com.vayunmathur.testsupport.awaitWithMainIdle("meal logged to Room") { loggedJob.isCompleted }         }-        assertTrue(logged, "meal was logged to Room")+        assertTrue(loggedJob.isCompleted && loggedJob.await(), "meal was logged to Room")     }      @Test
health/src/test/java/com/vayunmathur/health/ui/RecipeEditorFlowTest.kt
diff --git a/health/src/test/java/com/vayunmathur/health/ui/RecipeEditorFlowTest.kt b/health/src/test/java/com/vayunmathur/health/ui/RecipeEditorFlowTest.ktindex 49748ea4a4..3e666dc1ac 100644--- a/health/src/test/java/com/vayunmathur/health/ui/RecipeEditorFlowTest.kt+++ b/health/src/test/java/com/vayunmathur/health/ui/RecipeEditorFlowTest.kt@@ -80,8 +80,25 @@ class RecipeEditorFlowTest {             rule.onAllNodesWithText("Flow Rice", substring = true).fetchSemanticsNodes().isNotEmpty()         }         rule.onNodeWithText("Flow Rice", substring = true).assertIsDisplayed()-        // Rename through the name field (loaded name is the field value).-        rule.onNodeWithText("Flow Bowl").performTextInput("Flow Bowl v2")+        // The ingredient text and the name field do not publish together:+        // "Flow Rice" is a plain Text set in the same recomposition that+        // assigns the loaded name, but the text field's editable semantics+        // sync from its internal state on a later scheduler pass. In a+        // batched (forkEvery = 20) JVM that pass can still be queued when+        // the ingredient appears, and performTextInput by the loaded+        // value then finds no editable 'Flow Bowl' node (full-suite-only+        // failure; the class alone is fast enough to hide it). Waiting+        // for the value's semantics proved equally racy, so address the+        // field itself: it is the screen's only editable node, and the+        // rename is order-proof — if the load lands after the input, its+        // `if (recipeName.isBlank())` guard keeps the typed name. The+        // renamed-value await below still verifies the rename landed.+        rule.awaitSemantics("recipe name field editable") {+            rule.onAllNodes(androidx.compose.ui.test.hasSetTextAction())+                .fetchSemanticsNodes().isNotEmpty()+        }+        // Rename through the name field.+        rule.onNode(androidx.compose.ui.test.hasSetTextAction()).performTextInput("Flow Bowl v2")         // The text input lands through the paused main looper; a single         // waitForIdle can return before it applies under load, leaving Save         // to race the rename. Wait until the renamed value itself is the
uniflix/src/test/java/com/vayunmathur/uniflix/ui/tv/TvGridAndListCoverageTest.kt
diff --git a/uniflix/src/test/java/com/vayunmathur/uniflix/ui/tv/TvGridAndListCoverageTest.kt b/uniflix/src/test/java/com/vayunmathur/uniflix/ui/tv/TvGridAndListCoverageTest.ktindex d7ad11d3df..cd24582d03 100644--- a/uniflix/src/test/java/com/vayunmathur/uniflix/ui/tv/TvGridAndListCoverageTest.kt+++ b/uniflix/src/test/java/com/vayunmathur/uniflix/ui/tv/TvGridAndListCoverageTest.kt@@ -1,23 +1,54 @@ package com.vayunmathur.uniflix.ui.tv  import androidx.compose.ui.test.junit4.createComposeRule+import androidx.room3.Room+import androidx.test.core.app.ApplicationProvider import com.vayunmathur.library.ui.DynamicTheme import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.uniflix.data.UniflixDatabase+import com.vayunmathur.uniflix.data.UniflixRepository import com.vayunmathur.uniflix.data.uniflixTransport+import com.vayunmathur.uniflix.platform.FakeAndroidKeyStore import kotlin.test.AfterTest+import kotlin.test.BeforeTest import kotlin.test.Test import kotlin.test.assertEquals+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.ExperimentalCoroutinesApi+import kotlinx.coroutines.test.UnconfinedTestDispatcher+import kotlinx.coroutines.test.setMain import org.junit.Rule import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner  /** TvGridPage kinds + TvMyListTab in their offline/empty states. */+@OptIn(ExperimentalCoroutinesApi::class) @RunWith(RobolectricTestRunner::class) class TvGridAndListCoverageTest {      @get:Rule     val composeRule = createComposeRule() +    @BeforeTest+    fun setUp() {+        // Hermetic DB (the sibling TV-test pattern): TvGridPage/TvMyListTab+        // compose HomeViewModel/ListsViewModel, which collect the+        // repository's Room flows. Without a planted in-memory DB the+        // repository builds the real SQLCipher file DB — which needs the+        // AndroidKeyStore on a host JVM — and in a shared test JVM it+        // instead inherits whatever stale/closed in-memory instance a+        // previous class planted in the process-wide registry, whose+        // flows then fail with "no such table". Plant a fresh in-memory+        // DB and rebind the repository singleton for every test.+        FakeAndroidKeyStore.install()+        Dispatchers.setMain(UnconfinedTestDispatcher())+        val context = ApplicationProvider.getApplicationContext<android.content.Context>()+        val db = Room.inMemoryDatabaseBuilder(context, UniflixDatabase::class.java)+            .allowMainThreadQueries().build()+        com.vayunmathur.library.util.databases[UniflixDatabase::class] = db+        UniflixRepository.resetInstanceForTest()+    }+     @AfterTest fun tearDown() { uniflixTransport = null }      @Test fun gridPageContinueWatchingEmpty() {