Modern Apps git

← Modern-Apps.git

flashcards: deflake view-model and pages tests (169 tests)

Commit
e404a0b16fdd6053dcde4f87886afa1c22439cc5
Author
Vayun Mathur <[email protected]>
When
2026-11-15 03:14 UTC (21 days ago)
Parents
a474323
The flashcards suite was genuinely flaky under load: in a loaded
reproduction (--max-workers=64 on a busy host) 5 of 6 runs failed,
each time in different tests, while isolated runs passed. The races
all had the same shape - a test awaited a partial effect and then
asserted the full effect:

- noteTypes is a combine of three separate Room flows (types,
  fields, templates), and saveNoteType writes those tables in turn,
  so the flow emits intermediate snapshots with a type present but
  its fields/templates still empty. Tests that waited only for the
  type row then read fields == [] (expected [Q,A] was []), and
  saveNote, which reads its template config from noteTypes.value,
  generated zero cards against the not-yet-loaded templates
  (expected 1 was 0). Setup in both test classes now waits for the
  complete built-in configuration, and the note-type tests wait for
  the created type's full fields/templates via a new awaitNoteType
  helper before asserting or saving notes against it.
- saveNote upserts the note row before regenerating its cards in
  the same IO coroutine, and CSV import inserts notes one by one,
  so awaiting the first note and asserting its cards (or the import
  count) raced the rest of the write. saveBasicNote now also waits
  for the note's generated card, and the reversed/cloze, card-
  regeneration, review-log, leech-suspension and CSV tests wait for
  the exact card/log/count condition they then assert.
- The empty-deck CSV export test awaited file existence, which can
  observe the just-created empty file before the writer finishes;
  it now waits for the finished content (or the share emission).
- FlashcardsPagesTest.noteTypePagesBind used onNodeWithText("Basic"),
  which throws when two semantics nodes match while the list is
  settling; it now waits for the row and clicks the first match
  (the Basic type, first in the list) explicitly.

No assertions were removed or weakened and no sleeps were added:
every change is a bounded wait-for-condition on the exact value
asserted afterwards.

Verified: before the fix, 1/6 loaded runs passed (rotating
failures in noteTypeSaveDeleteAndBuiltInGuard,
noteTypeEditRegeneratesCardsAndDeleteTypeRemovesNotes,
regeneratingCardsDeletesRemovedCardsReviewLogs,
csvImportAndExportAndApkgExport and others) and 6/6 isolated runs
passed. After the fix: 10 consecutive green
:flashcards:testDevUnitTest runs with --no-build-cache, 7 isolated
at --max-workers=32 and 3 under load at --max-workers=64 on a busy
host (169 tests).

Diff

flashcards/src/test/java/com/vayunmathur/flashcards/ui/FlashcardsPagesTest.kt
diff --git a/flashcards/src/test/java/com/vayunmathur/flashcards/ui/FlashcardsPagesTest.kt b/flashcards/src/test/java/com/vayunmathur/flashcards/ui/FlashcardsPagesTest.ktindex 1c0bc15b32..5361a81964 100644--- a/flashcards/src/test/java/com/vayunmathur/flashcards/ui/FlashcardsPagesTest.kt+++ b/flashcards/src/test/java/com/vayunmathur/flashcards/ui/FlashcardsPagesTest.kt@@ -6,6 +6,7 @@ import androidx.compose.ui.test.assertIsDisplayed import androidx.compose.ui.test.junit4.createComposeRule import androidx.compose.ui.test.onNodeWithContentDescription import androidx.compose.ui.test.onAllNodesWithContentDescription+import androidx.compose.ui.test.onAllNodesWithText import androidx.compose.ui.test.onNodeWithText import androidx.compose.ui.test.performClick import androidx.compose.ui.test.performScrollTo@@ -74,7 +75,18 @@ class FlashcardsPagesTest {         scope.launch { vm.notes.collect {} }         scope.launch { vm.settings.collect {} }         scope.launch { vm.deckPresets.collect {} }-        await("built-ins") { vm.noteTypes.value.size >= 3 }+        // As in FlashcardsViewModelTest: wait for the complete built-in+        // configuration, not just the type rows (fields/templates load in+        // later combine emissions).+        await("built-ins fully loaded") {+            val byId = vm.noteTypes.value.associateBy { it.noteType.id }+            byId[1L]?.fields?.map { it.name } == listOf("Front", "Back") &&+                byId[1L]?.templates?.size == 1 &&+                byId[2L]?.fields?.size == 2 &&+                byId[2L]?.templates?.size == 2 &&+                byId[3L]?.fields?.size == 2 &&+                byId[3L]?.templates?.size == 1+        }         // The settings combine only emits once the mapNotNull flows have values.         vm.setReminderEnabledImpl(false)         vm.setAutoPlayImpl(false)@@ -157,8 +169,16 @@ class FlashcardsPagesTest {     fun noteTypePagesBind() {         val stack = NavBackStack<Route>(arrayOf(Route.Main))         rule.setContent { DynamicTheme { NoteTypeListPage(stack, vm) } }-        rule.onNodeWithText("Basic").assertIsDisplayed()-        rule.onNodeWithText("Basic").performClick()+        // "Basic" can match two semantics nodes while the list is still+        // settling (the built-in row plus its substring sibling row in the+        // unmerged tree), so onNodeWithText throws on the ambiguity.+        // Address the first matching row explicitly: it is the Basic type+        // (id 1, first in the list), which is the row this test opens.+        await("basic row composed") {+            rule.onAllNodesWithText("Basic").fetchSemanticsNodes().isNotEmpty()+        }+        rule.onAllNodesWithText("Basic")[0].assertIsDisplayed()+        rule.onAllNodesWithText("Basic")[0].performClick()         assertEquals(Route.NoteTypeEdit(1L), stack.last())     } 
flashcards/src/test/java/com/vayunmathur/flashcards/util/FlashcardsViewModelTest.kt
diff --git a/flashcards/src/test/java/com/vayunmathur/flashcards/util/FlashcardsViewModelTest.kt b/flashcards/src/test/java/com/vayunmathur/flashcards/util/FlashcardsViewModelTest.ktindex 5886055b89..28519f740d 100644--- a/flashcards/src/test/java/com/vayunmathur/flashcards/util/FlashcardsViewModelTest.kt+++ b/flashcards/src/test/java/com/vayunmathur/flashcards/util/FlashcardsViewModelTest.kt@@ -71,7 +71,27 @@ class FlashcardsViewModelTest {         scope.launch { vm.notes.collect {} }         scope.launch { vm.settings.collect {} }         scope.launch { vm.deckPresets.collect {} }-        await("built-in note types") { vm.noteTypes.value.size >= 3 }+        // The combine over the three Room flows (types/fields/templates)+        // emits intermediate snapshots while seeding writes each table in+        // turn: a type can be visible with no fields or templates yet.+        // Wait for the complete built-in configuration, not just the rows.+        await("built-in note types fully loaded") {+            val byId = vm.noteTypes.value.associateBy { it.noteType.id }+            byId[1L]?.fields?.map { it.name } == listOf("Front", "Back") &&+                byId[1L]?.templates?.size == 1 &&+                byId[2L]?.fields?.map { it.name } == listOf("Front", "Back") &&+                byId[2L]?.templates?.size == 2 &&+                byId[3L]?.fields?.size == 2 &&+                byId[3L]?.templates?.size == 1+        }+    }++    /** Awaits a custom note type's complete config (fields + templates), not just its row. */+    private fun awaitNoteType(name: String, fields: List<String>, templates: Int) {+        await("note type $name fully loaded") {+            vm.noteTypes.value.firstOrNull { it.noteType.name == name }+                ?.let { it.fields.map { f -> f.name } == fields && it.templates.size == templates } == true+        }     }      private fun await(label: String, condition: () -> Boolean) {@@ -93,7 +113,11 @@ class FlashcardsViewModelTest {     private fun saveBasicNote(deckId: Long, front: String, back: String, tags: String = ""): Note {         vm.saveNoteImpl(0, FlashcardsViewModel.BASIC_NOTE_TYPE_ID, deckId, listOf(front, back), tags)         await("note $front") { runBlocking { repo.getAllNotesImpl().any { it.sortField == front } } }-        return runBlocking { repo.getAllNotesImpl().first { it.sortField == front && it.deckId == deckId } }+        val note = runBlocking { repo.getAllNotesImpl().first { it.sortField == front && it.deckId == deckId } }+        // The note row is upserted before its cards are regenerated in the+        // same IO coroutine, so the note can be visible with no cards yet.+        await("cards for $front") { runBlocking { repo.getCardsByNoteImpl(note.id) }.isNotEmpty() }+        return note     }      @Test@@ -167,10 +191,12 @@ class FlashcardsViewModelTest {         vm.saveNoteImpl(0, 2L, deck.id, listOf("FrontMulti", "BackMulti"), "")         await("reversed note") { runBlocking { repo.getAllNotesImpl().any { it.sortField == "FrontMulti" } } }         val note = runBlocking { repo.getAllNotesImpl().first { it.sortField == "FrontMulti" } }+        await("reversed cards") { runBlocking { repo.getCardsByNoteImpl(note.id) }.size == 2 }         assertEquals(2, runBlocking { repo.getCardsByNoteImpl(note.id) }.size)         vm.saveNoteImpl(0, 3L, deck.id, listOf("The {{c1::capital}} of {{c2::France}}", "extra"), "")         await("cloze note") { runBlocking { repo.getAllNotesImpl().any { it.sortField.startsWith("The {{c1") } } }         val cloze = runBlocking { repo.getAllNotesImpl().first { it.sortField.startsWith("The {{c1") } }+        await("cloze cards") { runBlocking { repo.getCardsByNoteImpl(cloze.id) }.size == 2 }         assertEquals(setOf(0, 1), runBlocking { repo.getCardsByNoteImpl(cloze.id) }.map { it.templateOrd }.toSet())     } @@ -249,7 +275,9 @@ class FlashcardsViewModelTest {     @Test     fun noteTypeSaveDeleteAndBuiltInGuard() {         vm.saveNoteTypeImpl(0, "VmCustomType", ".c{}", 0, listOf("Q", "A"), listOf(TemplateDraft("Only", "{{Q}}", "{{A}}")))-        await("note type created") { vm.noteTypes.value.any { it.noteType.name == "VmCustomType" } }+        // The type row is written before its fields/templates, and the+        // combine emits that intermediate snapshot (fields == []).+        awaitNoteType("VmCustomType", listOf("Q", "A"), templates = 1)         val created = vm.noteTypes.value.first { it.noteType.name == "VmCustomType" }         assertEquals(listOf("Q", "A"), created.fields.map { it.name })         // Built-in types cannot be deleted.@@ -335,6 +363,9 @@ class FlashcardsViewModelTest {         await("card graded in db") {             runBlocking { repo.getAllCardsImpl().first { it.id == cardId }.reps > 0 }         }+        await("review log written") {+            runBlocking { repo.getReviewLogsByDeckOrderedImpl(deck.id) }.size == 1+        }         assertEquals(1, runBlocking { repo.getReviewLogsByDeckOrderedImpl(deck.id) }.size)         assertTrue(vm.review.value.canUndo)         vm.undoReviewImpl()@@ -386,6 +417,7 @@ class FlashcardsViewModelTest {             runBlocking { repo.getAllNotesImpl().any { it.sortField == "RegenFront" } }         }         val note = runBlocking { repo.getAllNotesImpl().first { it.sortField == "RegenFront" } }+        await("regen cards generated") { runBlocking { repo.getCardsByNoteImpl(note.id) }.size == 2 }         val cards = runBlocking { repo.getCardsByNoteImpl(note.id) }         assertEquals(2, cards.size)         runBlocking {@@ -457,7 +489,10 @@ class FlashcardsViewModelTest {         val csv = File(app.cacheDir, "import_vm.csv")         csv.writeText("front,back\nCsvFront,CsvBack\nSecond,Row\n")         vm.importCsvImpl(deck.id, Uri.fromFile(csv))-        await("csv imported") { runBlocking { repo.getAllNotesImpl().any { it.sortField == "CsvFront" && it.deckId == deck.id } } }+        // The first imported note is visible before the second is written.+        await("csv imported") {+            runBlocking { repo.getAllNotesImpl().count { it.deckId == deck.id } } == 2+        }         assertEquals(2, runBlocking { repo.getAllNotesImpl().count { it.deckId == deck.id } })         // Importing an empty csv is a no-op.         val empty = File(app.cacheDir, "empty_vm.csv"); empty.writeText("front,back\n")@@ -504,11 +539,15 @@ class FlashcardsViewModelTest {     fun noteTypeEditRegeneratesCardsAndDeleteTypeRemovesNotes() {         val deck = uniqueDeck("TypeRegenDeck")         vm.saveNoteTypeImpl(0, "RegenType", "", 0, listOf("Q", "A"), listOf(TemplateDraft("Only", "{{Q}}", "{{A}}")))-        await("regen type created") { vm.noteTypes.value.any { it.noteType.name == "RegenType" } }+        // saveNote reads its template config from noteTypes.value: saving+        // against the intermediate snapshot (type present, templates not+        // yet loaded) would generate zero cards for the note.+        awaitNoteType("RegenType", listOf("Q", "A"), templates = 1)         val type = vm.noteTypes.value.first { it.noteType.name == "RegenType" }         vm.saveNoteImpl(0, type.noteType.id, deck.id, listOf("RegenQ", "RegenA"), "")         await("regen note") { runBlocking { repo.getAllNotesImpl().any { it.sortField == "RegenQ" } } }         val note = runBlocking { repo.getAllNotesImpl().first { it.sortField == "RegenQ" } }+        await("regen note card") { runBlocking { repo.getCardsByNoteImpl(note.id) }.size == 1 }         assertEquals(1, runBlocking { repo.getCardsByNoteImpl(note.id) }.size)         // Adding a second template regenerates a second card for the existing note.         vm.saveNoteTypeImpl(@@ -570,6 +609,10 @@ class FlashcardsViewModelTest {         await("leech tagged") {             runBlocking { repo.getNoteImpl(note.id)?.tags?.contains(FlashcardsViewModel.LEECH_TAG) == true }         }+        await("leech card suspended") {+            runBlocking { repo.getCardsByNoteImpl(note.id) }+                .let { it.isNotEmpty() && it.all { c -> c.suspended == 1 } }+        }         assertTrue(runBlocking { repo.getCardsByNoteImpl(note.id) }.all { it.suspended == 1 })     } @@ -585,8 +628,14 @@ class FlashcardsViewModelTest {         val shares = mutableListOf<Uri>()         scope.launch { vm.shareRequests.collect { shares.add(it) } }         vm.exportCsvImpl(deck.id)-        await("empty deck csv shared") {-            shares.isNotEmpty() || File(app.cacheDir, "shared_decks/EmptyCsvDeck.csv").exists()+        // Await the finished content, not mere existence: the writer+        // creates the file before writing it, and the share collector+        // launched above can miss the emission entirely if it subscribes+        // after the export completes.+        await("empty deck csv written") {+            shares.isNotEmpty() ||+                runCatching { File(app.cacheDir, "shared_decks/EmptyCsvDeck.csv").readText() }+                    .getOrNull() == "front,back\n"         }         assertEquals("front,back\n", File(app.cacheDir, "shared_decks/EmptyCsvDeck.csv").readText())         vm.exportCsvImpl(987654L)