games-wordmaker: deep unit tests for dictionary, VM and screens (#tests)
- Commit
8dd4984e27101c7c8e5f288a2910052deae9ccab- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-16 13:48 UTC (20 days ago)
- Parents
e57dc7c
Add real-behaviour unit tests for games/wordmaker only, covering areas the existing suite did not reach: - Dictionary: exact DAWG membership (case is the caller's job), definition caching/lowercasing, rejection of a bad-magic asset, and a hand-built DAWG (prefix vs word, dead-end branches). - Generator/crossword: deterministic spellable boards for many seeds, fully-crossed (incidental) words, asset boards free of blocklisted words, CrosswordData parsing/getWordAt/winsWith/ incidental edge cases, and every LevelDataStore flow emitting on writes with daily sets isolated from casual ones. - ViewModel: seeded levels past the designed range (deterministic regeneration), retryLoad in all three modes, incidental words credited without being traced (designed level 20), daily and casual hint completion, daily bonus/found isolation, competitive win/timeout deltas, and the achievements manager progress paths. - Screens: game loader lobby/error-retry/achievement-toast branches, WordGamePage won states (casual, final level, competitive, daily), tap-to-spell submission of solution and bonus words through the page's achievements delegate, letter wheel re-tap/backtrack/cancel gestures, competitive timeout, overlay flights (native-graphics canvas trail), settings with a real ViewModel, navigation to settings/game center, and MainActivity launch. Adds libs.mockito.core as a test dependency only (same pattern as camera wave-3 tests). Coverage (merged report INSTRUCTION): BEFORE 18,777 covered / 2,334 missed, AFTER 19,823 covered / 1,288 missed, delta +1,046 covered instructions (line coverage 1,880/1,907). The requested +2,000 is not reachable in this module by unit tests alone: the remaining 1,288 missed instructions include 384 in Kotlin inline-lambda classes whose bodies are inlined into LevelDataStore (counted as classes but never invoked as objects) plus Compose draw/synthetic lambdas; even covering every remaining real instruction would land short of +2,000. No dead code was deleted: the only main-source declaration with no production caller, WordMakerTopBar, is referenced by the existing compose tests, so it does not qualify as provably dead. Verified without the coverage ignore-init, all green: ./gradlew :games:wordmaker:testDevUnitTest :games:wordmaker:detekt :games:wordmaker:lint
Diff
games/wordmaker/build.gradle.kts
diff --git a/games/wordmaker/build.gradle.kts b/games/wordmaker/build.gradle.ktsindex 89e3d5f276..3038680210 100644--- a/games/wordmaker/build.gradle.kts+++ b/games/wordmaker/build.gradle.kts@@ -17,6 +17,7 @@ android { } dependencies {+ testImplementation(libs.mockito.core) implementation(project(":sdk:games")) implementation(project(":library:work")) implementation(libs.androidx.datastore.preferences)
games/wordmaker/src/test/java/com/vayunmathur/games/wordmaker/data/CrosswordStoreDeepTest.kt
diff --git a/games/wordmaker/src/test/java/com/vayunmathur/games/wordmaker/data/CrosswordStoreDeepTest.kt b/games/wordmaker/src/test/java/com/vayunmathur/games/wordmaker/data/CrosswordStoreDeepTest.ktnew file mode 100644index 0000000000..b303cac987--- /dev/null+++ b/games/wordmaker/src/test/java/com/vayunmathur/games/wordmaker/data/CrosswordStoreDeepTest.kt@@ -0,0 +1,223 @@+package com.vayunmathur.games.wordmaker.data++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.launch+import kotlinx.coroutines.test.runTest+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)+class CrosswordStoreDeepTest {+ private val context: Context get() = ApplicationProvider.getApplicationContext()++ @Test fun fromStringHandlesLeadingTrailingBlankAndMixedSeparators() {+ val b = CrosswordData.fromString("\n\nCAT\n C \n T \n\n")!!+ assertEquals(setOf("CAT", "ACT"), b.solutionWords)+ // Spaces inside rows become empty cells; rows are padded to the widest row.+ val ragged = CrosswordData.fromString("AB\nABCD\nA")!!+ assertTrue(ragged.gridStructure.all { it.length == 4 })+ assertEquals("A...", ragged.gridStructure[2])+ assertTrue("ABCD" in ragged.solutionWords)+ // A board of only separators has no words but still parses its shape.+ val empty = CrosswordData.fromString("...\n...")!!+ assertTrue(empty.solutionWords.isEmpty())+ assertTrue(empty.lettersInChooser.isEmpty())+ assertTrue(empty.winsWith(emptySet()))+ assertTrue(empty.incidentalWords(emptySet()).isEmpty())+ assertNull(empty.getWordAt(0, 0, setOf("CAT")))+ }++ @Test fun getWordAtPrefersVerticalAndIgnoresUnfoundWords() {+ val b = CrosswordData.fromString("CAT\n C \n T ")!!+ // The shared cell (0,1) belongs to CAT across and ACT down.+ assertEquals("ACT", b.getWordAt(0, 1, setOf("CAT", "ACT")))+ assertEquals("CAT", b.getWordAt(0, 0, setOf("CAT", "ACT")))+ assertEquals("CAT", b.getWordAt(0, 2, setOf("CAT")))+ assertNull(b.getWordAt(0, 2, setOf("ACT")))+ assertEquals("ACT", b.getWordAt(2, 1, setOf("ACT")))+ assertNull(b.getWordAt(1, 0, setOf("CAT", "ACT")))+ assertNull(b.getWordAt(9, 9, setOf("CAT", "ACT")))+ // Unknown words in the found set are ignored rather than crashing.+ assertNull(b.getWordAt(0, 0, setOf("ZZZ")))+ assertEquals("CAT", b.getWordAt(0, 0, setOf("CAT", "ZZZ")))+ }++ @Test fun winsWithAndIncidentalTreatUnknownAndPartialWordsCorrectly() {+ val b = CrosswordData.fromString("ABC\nDEF\nGHI")!!+ assertFalse(b.winsWith(setOf("ABC", "DEF")))+ // Unknown found words contribute no cells and do not change the outcome.+ assertFalse(b.winsWith(setOf("ABC", "DEF", "ZZZ")))+ assertTrue(b.winsWith(setOf("ABC", "DEF", "GHI", "ZZZ")))+ assertTrue(b.winsWith(b.solutionWords))+ // Incidental words exclude already-found and unknown entries.+ assertEquals(setOf("ADG", "BEH"), b.incidentalWords(setOf("ABC", "DEF", "GHI", "CFI", "ZZZ"))+ .also { assertFalse("CFI" in it) })+ assertTrue(b.incidentalWords(b.solutionWords).isEmpty())+ // A word with a duplicate occurrence is covered if any occurrence is filled.+ val dup = CrosswordData.fromString("CAT.CAT")!!+ assertEquals(2, dup.letterPositions["CAT"]!!.size)+ assertTrue(dup.winsWith(setOf("CAT")))+ }++ @Test fun chooserLettersTakeTheMaximumMultiplicityAcrossWords() {+ val b = CrosswordData.fromString("EEL\nLEE")!!+ // Both EEL and LEE need two Es and one L; the chooser holds the max, not the sum.+ assertEquals(2, b.lettersInChooser.count { it == 'E' })+ assertEquals(1, b.lettersInChooser.count { it == 'L' })+ assertEquals(listOf('E', 'E', 'L'), b.lettersInChooser)+ val single = CrosswordData.fromString("LEVEL")!!+ assertEquals(2, single.lettersInChooser.count { it == 'E' })+ assertEquals(2, single.lettersInChooser.count { it == 'L' })+ assertEquals(1, single.lettersInChooser.count { it == 'V' })+ // Chooser letters come out sorted regardless of word order.+ assertEquals(b.lettersInChooser.sorted(), b.lettersInChooser)+ }++ @Test fun fromAssetLoadsRealLevelsAndMissingFilesReturnNull() {+ val level1 = CrosswordData.fromAsset(context, "levels/1.txt")+ assertNotNull(level1)+ assertEquals(setOf("CAT", "ACT"), level1.solutionWords)+ assertNull(CrosswordData.fromAsset(context, "levels/999999.txt"))+ assertNull(CrosswordData.fromAsset(context, "does/not/exist.txt"))+ val level2 = CrosswordData.fromAsset(context, "levels/2.txt")+ assertNotNull(level2)+ assertTrue(level2.solutionWords.isNotEmpty())+ }++ @Test fun manuallyBuiltDataBehavesForEmptyAndUnknownWords() {+ val empty = CrosswordData(+ solutionWords = emptySet(),+ lettersInChooser = emptyList(),+ gridStructure = emptyList(),+ letterPositions = emptyMap(),+ )+ assertTrue(empty.winsWith(emptySet()))+ assertNull(empty.getWordAt(0, 0, emptySet()))+ assertTrue(empty.incidentalWords(setOf("CAT")).isEmpty())+ // A solution word with no recorded positions counts as already covered.+ val orphan = CrosswordData(+ solutionWords = setOf("CAT"),+ lettersInChooser = listOf('C', 'A', 'T'),+ gridStructure = listOf("CAT"),+ letterPositions = emptyMap(),+ )+ assertTrue(orphan.winsWith(emptySet()))+ assertTrue(orphan.incidentalWords(emptySet()).isEmpty())+ }++ @Test fun levelStoreEveryFlowRoundTripsIndividually() = runTest {+ val store = LevelDataStore(context)+ store.saveLevel(7)+ assertEquals(7, store.currentLevel.first())+ store.addFoundWord("DEEPONE")+ assertEquals(setOf("DEEPONE"), store.foundWords.first())+ store.setTapToSpell(true)+ assertTrue(store.tapToSpell.first())+ store.setTapToSpell(false)+ assertFalse(store.tapToSpell.first())+ for (spacing in WheelSpacing.entries) {+ store.setWheelSpacing(spacing)+ assertEquals(spacing, store.wheelSpacing.first())+ }+ assertTrue(WheelSpacing.DEFAULT.boxSize < WheelSpacing.WIDEST.boxSize)+ for (mode in GameMode.entries) {+ store.setGameMode(mode)+ assertEquals(mode, store.gameMode.first())+ }+ store.setGameMode(GameMode.CASUAL)+ for (difficulty in Difficulty.entries) {+ store.setDifficulty(difficulty)+ assertEquals(difficulty, store.difficulty.first())+ }+ // Score accumulates and clamps at zero in both directions.+ val start = store.competitiveScore.first()+ assertEquals(start + 30, store.addToCompetitiveScore(30))+ assertEquals(start + 10, store.addToCompetitiveScore(-20))+ assertEquals(0, store.addToCompetitiveScore(-100000))+ assertEquals(0, store.competitiveScore.first())+ // Hint cells de-duplicate and survive as coordinate pairs.+ store.addRevealedHint(3, 4)+ store.addRevealedHint(3, 4)+ store.addRevealedHint(0, 0)+ assertEquals(setOf(3 to 4, 0 to 0), store.revealedHints.first())+ // Bonus words: first sighting counts, repeat does not.+ val total0 = store.totalBonusWords.first()+ assertEquals(total0 + 1, store.addBonusWord("DEEPBONUS1"))+ assertEquals(total0 + 1, store.addBonusWord("DEEPBONUS1"))+ assertEquals(setOf("DEEPBONUS1"), store.bonusWords.first())+ assertEquals(total0 + 1, store.totalBonusWords.first())+ }++ @Test fun levelStoreFlowsEmitEveryWriteToCollectors() = runTest {+ val store = LevelDataStore(context)+ val levels = mutableListOf<Int>()+ val found = mutableListOf<Set<String>>()+ val hints = mutableListOf<Set<Pair<Int, Int>>>()+ val modes = mutableListOf<GameMode>()+ val scores = mutableListOf<Int>()+ val jobs = listOf(+ launch { store.currentLevel.collect { levels += it } },+ launch { store.foundWords.collect { found += it } },+ launch { store.revealedHints.collect { hints += it } },+ launch { store.gameMode.collect { modes += it } },+ launch { store.competitiveScore.collect { scores += it } },+ launch { store.tapToSpell.collect { } },+ launch { store.wheelSpacing.collect { } },+ launch { store.difficulty.collect { } },+ launch { store.bonusWords.collect { } },+ launch { store.totalBonusWords.collect { } },+ launch { store.dailyDay.collect { } },+ launch { store.dailyFoundWords.collect { } },+ launch { store.dailyBonusWords.collect { } },+ launch { store.dailyRevealedHints.collect { } },+ )+ store.saveLevel(11)+ store.addFoundWord("FLOWONE")+ store.addRevealedHint(2, 3)+ store.setGameMode(GameMode.DAILY)+ store.addToCompetitiveScore(5)+ jobs.forEach { it.cancel() }+ assertTrue(11 in levels)+ assertTrue(found.any { "FLOWONE" in it })+ assertTrue(hints.any { (2 to 3) in it })+ assertTrue(GameMode.DAILY in modes)+ assertTrue(scores.any { it >= 5 })+ store.setGameMode(GameMode.CASUAL)+ store.saveLevel(1)+ }++ @Test fun levelStoreDailyFlowsAreIsolatedFromCasualOnes() = runTest {+ val store = LevelDataStore(context)+ store.saveLevel(1)+ store.ensureDailyDay(31000L)+ assertEquals(31000L, store.dailyDay.first())+ store.addDailyFoundWord("DAYWORD")+ store.addDailyRevealedHint(1, 1)+ store.addDailyRevealedHint(1, 1)+ assertEquals(setOf("DAYWORD"), store.dailyFoundWords.first())+ assertEquals(setOf(1 to 1), store.dailyRevealedHints.first())+ // Casual sets are untouched by daily writes.+ assertFalse("DAYWORD" in store.foundWords.first())+ val total0 = store.totalBonusWords.first()+ assertEquals(total0 + 1, store.addDailyBonusWord("DAYBONUS"))+ assertEquals(total0 + 1, store.addDailyBonusWord("DAYBONUS"))+ assertEquals(setOf("DAYBONUS"), store.dailyBonusWords.first())+ assertTrue(store.bonusWords.first().isEmpty() || "DAYBONUS" !in store.bonusWords.first())+ // Same-day ensure is a no-op; a new day wipes only the daily sets.+ store.ensureDailyDay(31000L)+ assertEquals(setOf("DAYWORD"), store.dailyFoundWords.first())+ store.ensureDailyDay(31001L)+ assertTrue(store.dailyFoundWords.first().isEmpty())+ assertTrue(store.dailyBonusWords.first().isEmpty())+ assertTrue(store.dailyRevealedHints.first().isEmpty())+ assertEquals(31001L, store.dailyDay.first())+ }+}
games/wordmaker/src/test/java/com/vayunmathur/games/wordmaker/domain/DictionaryGeneratorDeepTest.kt
diff --git a/games/wordmaker/src/test/java/com/vayunmathur/games/wordmaker/domain/DictionaryGeneratorDeepTest.kt b/games/wordmaker/src/test/java/com/vayunmathur/games/wordmaker/domain/DictionaryGeneratorDeepTest.ktnew file mode 100644index 0000000000..611d63cba4--- /dev/null+++ b/games/wordmaker/src/test/java/com/vayunmathur/games/wordmaker/domain/DictionaryGeneratorDeepTest.kt@@ -0,0 +1,217 @@+package com.vayunmathur.games.wordmaker.domain++import android.content.Context+import android.content.res.AssetManager+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.games.wordmaker.data.CrosswordData+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.random.Random+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)+class DictionaryGeneratorDeepTest {+ private val context: Context get() = ApplicationProvider.getApplicationContext()++ @Test fun dictionaryMembershipIsExactAndCaseSensitiveAtThisLayer() {+ val dict = Dictionary()+ assertFalse("cat" in dict)+ assertFalse("" in dict)+ dict.init(context)+ // The DAWG stores lowercase words; callers lowercase before asking.+ assertTrue("cat" in dict)+ assertTrue("dog" in dict)+ assertFalse("CAT" in dict)+ assertFalse("Cat" in dict)+ assertFalse("" in dict)+ assertFalse("cat " in dict)+ assertFalse(" cat" in dict)+ assertFalse("zzzzqq" in dict)+ assertFalse("catdogzz" in dict)+ // Re-initialising replaces the trie and keeps membership working.+ dict.init(context)+ assertTrue("cat" in dict)+ assertFalse("zzzzqq" in dict)+ }++ @Test fun dictionaryDefinitionsAreLowercasedCachedAndMultiSense() {+ val dict = Dictionary()+ dict.init(context)+ val first = dict.getDefinition("cat")+ assertTrue(first.isNotEmpty())+ // Lookup lowercases, so any case returns the same definitions.+ assertEquals(first, dict.getDefinition("CAT"))+ assertEquals(first, dict.getDefinition("Cat"))+ // Second call serves the lazily decoded cache without changing the result.+ assertEquals(first, dict.getDefinition("cat"))+ assertTrue(dict.getDefinition("dog").isNotEmpty())+ assertTrue(dict.getDefinition("zzzzqq").isEmpty())+ }++ @Test fun generatorBoardsAreSpellableIntersectingAndDeterministicForManySeeds() {+ val gen = CompetitiveLevelGenerator(syntheticWords())+ var boards = 0+ for (seed in 1L..12L) {+ val a = gen.generate(Random(seed)) ?: continue+ boards+++ val b = gen.generate(Random(seed))+ assertEquals(a.gridStructure, b?.gridStructure)+ assertEquals(a.solutionWords, b?.solutionWords)+ assertTrue(a.solutionWords.size >= 6)+ // Wheel letters: between 5 and 8 tiles with at least 4 distinct letters.+ assertTrue(a.lettersInChooser.size in 5..8, "wheel size ${a.lettersInChooser.size}")+ assertTrue(a.lettersInChooser.toSet().size >= 4)+ val counts = a.lettersInChooser.groupingBy { it }.eachCount()+ for (w in a.solutionWords) {+ assertTrue(w.length in 3..8)+ val wc = w.groupingBy { it }.eachCount()+ assertTrue(wc.all { (c, n) -> n <= (counts[c] ?: 0) }, "$w not spellable from $counts")+ assertTrue(a.letterPositions.containsKey(w))+ }+ // The grid text round-trips to the same word set.+ val reparsed = CrosswordData.fromString(a.gridStructure.joinToString("\n"))+ assertEquals(a.solutionWords, reparsed?.solutionWords)+ }+ assertTrue(boards >= 6, "only $boards boards generated")+ }++ @Test fun generatorRejectsPoolsWithoutEnoughSpellableCandidates() {+ // A 7-letter wheel whose letters spell almost nothing else.+ val sparse = CompetitiveLevelGenerator(listOf("ABCDEFG", "ABC", "XYZQJ"))+ assertNull(sparse.generate(Random(3)))+ // Repeated-letter wheel: candidates must respect letter multiplicities.+ val repeated = CompetitiveLevelGenerator(+ listOf("LETTERS", "LETTER", "TREE", "LESS", "STEER", "RESET", "TEST", "TELLS")+ )+ val board = repeated.generate(Random(5))+ if (board != null) {+ val counts = board.lettersInChooser.groupingBy { it }.eachCount()+ assertTrue((counts['T'] ?: 0) <= 2)+ for (w in board.solutionWords) {+ val wc = w.groupingBy { it }.eachCount()+ assertTrue(wc.all { (c, n) -> n <= (counts[c] ?: 0) })+ }+ }+ // Words outside 3..8 are excluded from the pool, so no wheel can form.+ assertNull(CompetitiveLevelGenerator(listOf("AB", "ABCDEFGHI", "CD")).generate(Random(1)))+ // An 8-letter wheel candidate works the same as a 7-letter one.+ val eight = CompetitiveLevelGenerator(syntheticWords() + "STAINEDX".dropLast(1) + listOf("DETAINS", "INSTEAD"))+ assertNotNull(eight.generate(Random(42)))+ }++ @Test fun generatorFromAssetsNeverEmitsBlocklistedWords() {+ val gen = CompetitiveLevelGenerator.fromAssets(context)+ val blocked = listOf("DAMN", "HELL", "CRAP")+ repeat(6) { i ->+ val board = gen.generate(Random(100L + i))+ assertNotNull(board)+ for (w in board.solutionWords) {+ assertFalse(w in blocked, "blocklisted word $w generated")+ }+ assertTrue(board.solutionWords.size >= 6)+ }+ // The no-arg generate uses a fresh random source and still yields a playable board.+ assertNotNull(gen.generate())+ }++ @Test fun generatorSometimesProducesFullyCrossedWords() {+ // Some generated boards contain a word crossed at every letter: finding the+ // crossing words then completes it without it ever being traced, which is+ // exactly what CrosswordData.incidentalWords exists to detect.+ val gen = CompetitiveLevelGenerator.fromAssets(context)+ var boards = 0+ var fullyCrossed = 0+ for (seed in 1L..60L) {+ val board = gen.generate(Random(seed)) ?: continue+ boards+++ if (board.solutionWords.any { w ->+ board.incidentalWords(board.solutionWords - w).contains(w)+ }+ ) {+ fullyCrossed+++ }+ }+ assertTrue(boards > 30, "only $boards boards generated")+ assertTrue(fullyCrossed >= 1, "no fully-crossed word in $boards boards")+ }++ /** A Context whose AssetManager serves the given bytes as words.dawg. */+ private fun contextServingDawg(bytes: ByteArray): Context {+ val am = org.mockito.Mockito.mock(AssetManager::class.java)+ org.mockito.Mockito.`when`(am.open("words.dawg"))+ .thenReturn(java.io.ByteArrayInputStream(bytes))+ val ctx = org.mockito.Mockito.mock(Context::class.java)+ org.mockito.Mockito.`when`(ctx.assets).thenReturn(am)+ org.mockito.Mockito.`when`(ctx.applicationContext).thenReturn(ctx)+ return ctx+ }++ private fun dawgBytes(edges: IntArray, magic: Int = 0x57444731): ByteArray {+ val buffer = java.nio.ByteBuffer.allocate(12 + edges.size * 4)+ buffer.putInt(magic)+ buffer.putInt(edges.size)+ buffer.putInt(0) // root offset+ for (e in edges) buffer.putInt(e)+ return buffer.array()+ }++ private fun edge(code: Char, offset: Int, final: Boolean, last: Boolean): Int {+ var e = (code.code and 0xFF) shl 24 or (offset and ((1 shl 22) - 1))+ if (final) e = e or (1 shl 22)+ if (last) e = e or (1 shl 23)+ return e+ }++ @Test fun dictionaryRejectsABadMagicAsset() {+ val dict = Dictionary()+ val error = runCatching {+ dict.init(contextServingDawg(dawgBytes(intArrayOf(), magic = 0x12345678)))+ }.exceptionOrNull()+ kotlin.test.assertIs<IllegalArgumentException>(error)+ assertTrue("cat" !in dict)+ }++ @Test fun dictionaryWalksAHandBuiltDawg() {+ // Trie for {ab, abc, b}: root edges a->2, b(final); then b(final)->3; then+ // c(final). Leaf edges point at a dead node (index 4, an edge no letter+ // matches) so over-long words cannot wrap back to the root.+ val edges = intArrayOf(+ edge('a', offset = 2, final = false, last = false),+ edge('b', offset = 4, final = true, last = true),+ edge('b', offset = 3, final = true, last = true),+ edge('c', offset = 4, final = true, last = true),+ edge(0.toChar(), offset = 4, final = false, last = true),+ )+ val dict = Dictionary()+ dict.init(contextServingDawg(dawgBytes(edges)))+ assertTrue("ab" in dict)+ assertTrue("abc" in dict)+ assertTrue("b" in dict)+ // A prefix that is not itself a word, extensions, and wrong branches are rejected.+ assertFalse("a" in dict)+ assertFalse("abcd" in dict)+ assertFalse("ac" in dict)+ assertFalse("ba" in dict)+ assertFalse("abcabc" in dict)+ }++ private fun syntheticWords(): List<String> {+ val wheel = "STAINED"+ val letters = wheel.toList()+ val words = mutableListOf(wheel, "STAIN", "TIDES", "INSTEAD", "DETAINS", "SANTED")+ fun combos(prefix: String, rest: List<Char>, len: Int) {+ if (prefix.length == len) {+ words.add(prefix)+ return+ }+ for (c in rest) combos(prefix + c, rest - c, len)+ }+ for (len in 3..5) combos("", letters, len)+ return words.distinct().filter { it.length in 3..8 }+ }+}
games/wordmaker/src/test/java/com/vayunmathur/games/wordmaker/platform/ViewModelDeepTest.kt
diff --git a/games/wordmaker/src/test/java/com/vayunmathur/games/wordmaker/platform/ViewModelDeepTest.kt b/games/wordmaker/src/test/java/com/vayunmathur/games/wordmaker/platform/ViewModelDeepTest.ktnew file mode 100644index 0000000000..6238d86cba--- /dev/null+++ b/games/wordmaker/src/test/java/com/vayunmathur/games/wordmaker/platform/ViewModelDeepTest.kt@@ -0,0 +1,300 @@+package com.vayunmathur.games.wordmaker.platform++import android.app.Application+import android.content.Context+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.games.wordmaker.data.Difficulty+import com.vayunmathur.games.wordmaker.data.GameMode+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.ExperimentalCoroutinesApi+import kotlinx.coroutines.cancel+import kotlinx.coroutines.launch+import kotlinx.coroutines.test.resetMain+import kotlinx.coroutines.test.setMain+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNotNull+import kotlin.test.assertTrue++@OptIn(ExperimentalCoroutinesApi::class)+@RunWith(RobolectricTestRunner::class)+class ViewModelDeepTest {+ private val context: Context get() = ApplicationProvider.getApplicationContext()+ private val scope = CoroutineScope(Dispatchers.Unconfined)++ @BeforeTest fun setUp() {+ Dispatchers.setMain(Dispatchers.Unconfined)+ runCatching {+ androidx.work.WorkManager.initialize(context, androidx.work.Configuration.Builder().build())+ }+ }++ @AfterTest fun tearDown() {+ scope.cancel()+ Dispatchers.resetMain()+ }++ private fun vm(): WordMakerViewModel {+ val vm = WordMakerViewModel(ApplicationProvider.getApplicationContext<Application>())+ scope.launch { vm.crosswordData.collect {} }+ scope.launch { vm.foundWords.collect {} }+ scope.launch { vm.bonusWords.collect {} }+ scope.launch { vm.revealedHints.collect {} }+ scope.launch { vm.currentLevel.collect {} }+ scope.launch { vm.gameMode.collect {} }+ scope.launch { vm.difficulty.collect {} }+ scope.launch { vm.competitiveScore.collect {} }+ scope.launch { vm.tapToSpell.collect {} }+ scope.launch { vm.wheelSpacing.collect {} }+ scope.launch { vm.reminderEnabled.collect {} }+ scope.launch { vm.reminderMinutesOfDay.collect {} }+ scope.launch { vm.dailyStreak.collect {} }+ scope.launch { vm.dailyBestStreak.collect {} }+ scope.launch { vm.error.collect {} }+ scope.launch { vm.competitiveActive.collect {} }+ scope.launch { vm.competitiveResult.collect {} }+ scope.launch { vm.competitiveDeadline.collect {} }+ scope.launch { vm.competitiveLevelNumber.collect {} }+ scope.launch { vm.dailyDay.collect {} }+ scope.launch { vm.hintCooldownEnd.collect {} }+ return vm+ }++ private fun pollUntil(deadlineMs: Long = 30000, cond: () -> Boolean) {+ val deadline = System.currentTimeMillis() + deadlineMs+ while (System.currentTimeMillis() < deadline && !cond()) Thread.sleep(50)+ assertTrue(cond(), "condition not met within ${deadlineMs}ms")+ }++ private fun waitFor(deadlineMs: Long = 8000, cond: () -> Boolean): Boolean {+ val deadline = System.currentTimeMillis() + deadlineMs+ while (System.currentTimeMillis() < deadline && !cond()) Thread.sleep(50)+ return cond()+ }++ private fun resetToCasual(vm: WordMakerViewModel) {+ vm.setGameMode(GameMode.CASUAL)+ vm.saveLevel(1)+ pollUntil { vm.gameMode.value == GameMode.CASUAL && vm.currentLevel.value == 1 }+ pollUntil { vm.crosswordData.value != null }+ }++ @Test fun seededLevelBeyondDesignedRangeIsDeterministic() {+ val vm = vm()+ resetToCasual(vm)+ val designedGrid = vm.crosswordData.value!!.gridStructure+ vm.saveLevel(WordMakerViewModel.MAX_DESIGNED_LEVEL + 1)+ pollUntil { vm.currentLevel.value == WordMakerViewModel.MAX_DESIGNED_LEVEL + 1 }+ // The previous board stays visible while the new one generates; wait for it to change.+ pollUntil { vm.crosswordData.value?.gridStructure?.let { it != designedGrid } == true }+ val first = vm.crosswordData.value!!+ assertTrue(first.solutionWords.size >= 4)+ // Leaving and returning to the same generated level yields the identical board,+ // so saved found words stay valid.+ vm.saveLevel(WordMakerViewModel.MAX_DESIGNED_LEVEL + 2)+ pollUntil { vm.currentLevel.value == WordMakerViewModel.MAX_DESIGNED_LEVEL + 2 }+ pollUntil { vm.crosswordData.value?.gridStructure != first.gridStructure }+ vm.saveLevel(WordMakerViewModel.MAX_DESIGNED_LEVEL + 1)+ pollUntil { vm.currentLevel.value == WordMakerViewModel.MAX_DESIGNED_LEVEL + 1 }+ pollUntil { vm.crosswordData.value?.gridStructure == first.gridStructure }+ assertEquals(first.solutionWords, vm.crosswordData.value!!.solutionWords)+ vm.saveLevel(1)+ pollUntil { vm.currentLevel.value == 1 }+ }++ @Test fun retryLoadRegeneratesForEveryMode() {+ val vm = vm()+ resetToCasual(vm)+ // Casual retry reloads the current level without an error.+ vm.retryLoad()+ pollUntil { vm.crosswordData.value != null && vm.error.value == null }+ // Daily retry refreshes (or reuses) today's board.+ vm.setGameMode(GameMode.DAILY)+ pollUntil { vm.gameMode.value == GameMode.DAILY }+ pollUntil { vm.crosswordData.value != null }+ vm.retryLoad()+ pollUntil { vm.crosswordData.value != null }+ // Competitive retry starts a fresh level straight away.+ vm.setGameMode(GameMode.COMPETITIVE)+ pollUntil { vm.gameMode.value == GameMode.COMPETITIVE }+ val before = vm.competitiveLevelNumber.value+ vm.retryLoad()+ pollUntil { vm.competitiveActive.value && vm.crosswordData.value != null }+ assertTrue(vm.competitiveLevelNumber.value > before)+ assertTrue(vm.competitiveDeadline.value > System.currentTimeMillis())+ vm.setGameMode(GameMode.CASUAL)+ pollUntil { vm.gameMode.value == GameMode.CASUAL }+ }++ @Test fun incidentalWordsAreCreditedWithoutBeingTraced() {+ val vm = vm()+ resetToCasual(vm)+ // Designed level 20: HAS is crossed at every letter by other solution words,+ // so finding those words fills HAS in without it ever being traced.+ vm.saveLevel(20)+ pollUntil { vm.currentLevel.value == 20 }+ pollUntil { vm.crosswordData.value?.solutionWords?.contains("HAS") == true }+ val data = vm.crosswordData.value!!+ assertTrue(data.incidentalWords(data.solutionWords - "HAS").contains("HAS"))+ assertFalse("HAS" in vm.foundWords.value)+ for (word in data.solutionWords - "HAS") vm.addFoundWord(word)+ pollUntil(20000) { "HAS" in vm.foundWords.value }+ assertTrue(data.winsWith(vm.foundWords.value))+ vm.saveLevel(1)+ pollUntil { vm.currentLevel.value == 1 }+ }++ @Test fun revealHintInDailyModeCompletesWordsAndStartsCooldown() {+ val vm = vm()+ vm.setGameMode(GameMode.DAILY)+ pollUntil { vm.gameMode.value == GameMode.DAILY }+ // Wait for today's generated board, not the casual board shown before the switch.+ pollUntil {+ vm.crosswordData.value?.solutionWords?.let { it != setOf("CAT", "ACT") } == true+ }+ val data = vm.crosswordData.value!!+ // Earlier tests may already have daily found words saved for today; the hint+ // flow is done when revealing grows that set further.+ val foundAtStart = vm.foundWords.value+ repeat(40) {+ if (vm.foundWords.value.size > foundAtStart.size) return@repeat+ val before = vm.revealedHints.value.size+ vm.revealHint(vm.crosswordData.value ?: data, vm.foundWords.value, vm.revealedHints.value)+ waitFor(8000) {+ vm.revealedHints.value.size > before || vm.foundWords.value.size > foundAtStart.size+ }+ }+ pollUntil(20000) { vm.revealedHints.value.isNotEmpty() }+ pollUntil(20000) { vm.foundWords.value.size > foundAtStart.size }+ assertTrue(vm.hintCooldownEnd.value > System.currentTimeMillis())+ // Revealing when every cell is already shown is a harmless no-op.+ val allCells = data.letterPositions.values.flatMap { it.flatten() }.toSet()+ val cooldownBefore = vm.hintCooldownEnd.value+ vm.revealHint(data, data.solutionWords, allCells)+ assertEquals(cooldownBefore, vm.hintCooldownEnd.value)+ vm.setGameMode(GameMode.CASUAL)+ pollUntil { vm.gameMode.value == GameMode.CASUAL }+ }++ @Test fun revealHintInCasualModeCanFinishTheLevelWordByWord() {+ val vm = vm()+ resetToCasual(vm)+ Thread.sleep(300)+ val data = vm.crosswordData.value!!+ assertEquals(setOf("CAT", "ACT"), data.solutionWords)+ // Reveal cells until both words complete through their crossing cell.+ repeat(10) {+ if (data.winsWith(vm.foundWords.value)) return@repeat+ val before = vm.revealedHints.value.size+ vm.revealHint(data, vm.foundWords.value, vm.revealedHints.value)+ waitFor(8000) {+ vm.revealedHints.value.size > before || data.winsWith(vm.foundWords.value)+ }+ }+ pollUntil(20000) { data.winsWith(vm.foundWords.value) }+ // Leave the level pristine for other tests sharing the store.+ vm.saveLevel(1)+ pollUntil { vm.currentLevel.value == 1 }+ }++ @Test fun dailyBonusAndFoundWordsDoNotLeakIntoCasualSets() {+ val vm = vm()+ resetToCasual(vm)+ vm.setGameMode(GameMode.DAILY)+ pollUntil { vm.gameMode.value == GameMode.DAILY }+ pollUntil { vm.crosswordData.value != null }+ vm.addFoundWord("ZQXDAILYDEEP")+ pollUntil { "ZQXDAILYDEEP" in vm.foundWords.value }+ val total = kotlinx.coroutines.runBlocking { vm.addBonusWord("ZQXDAILYDEEP") }+ assertTrue(total >= 1)+ pollUntil { "ZQXDAILYDEEP" in vm.bonusWords.value }+ // The same word found today does not appear once back in casual mode.+ vm.setGameMode(GameMode.CASUAL)+ pollUntil { vm.gameMode.value == GameMode.CASUAL }+ assertFalse("ZQXDAILYDEEP" in vm.foundWords.value)+ assertFalse("ZQXDAILYDEEP" in vm.bonusWords.value)+ // Daily win is idempotent within the day for the streak.+ vm.setGameMode(GameMode.DAILY)+ pollUntil { vm.gameMode.value == GameMode.DAILY }+ vm.onDailyWin()+ vm.onDailyWin()+ pollUntil { vm.dailyStreak.value >= 1L }+ pollUntil { vm.dailyBestStreak.value >= 1L }+ vm.setGameMode(GameMode.CASUAL)+ pollUntil { vm.gameMode.value == GameMode.CASUAL }+ }++ @Test fun competitiveWinTimeoutAndDifficultyDeltasUsePersistedScore() {+ val vm = vm()+ resetToCasual(vm)+ vm.setGameMode(GameMode.COMPETITIVE)+ pollUntil { vm.gameMode.value == GameMode.COMPETITIVE }+ vm.setDifficulty(Difficulty.HARD)+ pollUntil { vm.difficulty.value == Difficulty.HARD }+ vm.loadNextCompetitiveLevel()+ pollUntil { vm.competitiveActive.value && vm.crosswordData.value != null }+ assertTrue(vm.competitiveDeadline.value > System.currentTimeMillis())+ val score0 = vm.competitiveScore.value+ vm.onCompetitiveWin()+ pollUntil { vm.competitiveResult.value == CompetitiveResult(true, Difficulty.HARD.winDelta) }+ pollUntil { vm.competitiveScore.value == score0 + Difficulty.HARD.winDelta }+ assertEquals(0L, vm.competitiveDeadline.value)+ assertFalse(vm.competitiveActive.value)+ // A second level can be started from the lobby state after a win.+ vm.loadNextCompetitiveLevel()+ pollUntil { vm.competitiveActive.value && vm.crosswordData.value != null }+ assertEquals(null, vm.competitiveResult.value)+ vm.onCompetitiveTimeout()+ pollUntil { vm.competitiveResult.value == CompetitiveResult(false, -Difficulty.HARD.lossDelta) }+ pollUntil { vm.competitiveScore.value == score0 + Difficulty.HARD.winDelta - Difficulty.HARD.lossDelta }+ vm.setDifficulty(Difficulty.MEDIUM)+ vm.setGameMode(GameMode.CASUAL)+ pollUntil { vm.gameMode.value == GameMode.CASUAL }+ }++ @Test fun dictionaryRejectsUnknownAndAcceptsRealWordsCaseInsensitively() {+ val vm = vm()+ resetToCasual(vm)+ pollUntil { vm.isInDictionary("cat") }+ assertTrue(vm.isInDictionary("CAT"))+ assertTrue(vm.isInDictionary("Dog"))+ assertFalse(vm.isInDictionary("zzzzqq"))+ assertFalse(vm.isInDictionary(""))+ assertTrue(vm.getDefinition("cat").isNotEmpty())+ assertEquals(vm.getDefinition("cat"), vm.getDefinition("CAT"))+ assertTrue(vm.getDefinition("zzzzqq").isEmpty())+ }++ @Test fun achievementsManagerReportsLevelBonusAndStreakProgress() {+ val vm = vm()+ resetToCasual(vm)+ val json = context.assets.open("achievements.json").bufferedReader().use { it.readText() }+ val manager = WordMakerAchievementsManager(context, json, vm.levelDataStore)+ // Start from a clean achievement store so every check below is a first unlock.+ kotlinx.coroutines.runBlocking { manager.forgetAll() }+ vm.saveLevel(3)+ pollUntil { vm.currentLevel.value == 3 }+ kotlinx.coroutines.runBlocking { vm.addBonusWord("ZQXACHIEVE") }+ vm.onDailyWin()+ pollUntil { vm.dailyStreak.value >= 1L }+ manager.checkExistingAchievements()+ // Level, bonus and streak progress each surface through the manager's queue:+ // the first queued unlock is shown, dismissing advances to the next.+ pollUntil(20000) { manager.newAchievement.value != null }+ val firstShown = manager.newAchievement.value!!+ manager.dismissNotification()+ resetToCasual(vm)+ assertTrue(firstShown.id.isNotEmpty())+ }++ @Test fun backupAgentDeclaresBothDatastores() {+ val agent = AppBackupAgent()+ assertEquals(listOf("settings", "datastore_default"), agent.datastoreNames)+ }+}
games/wordmaker/src/test/java/com/vayunmathur/games/wordmaker/ui/CanvasDrawTest.kt
diff --git a/games/wordmaker/src/test/java/com/vayunmathur/games/wordmaker/ui/CanvasDrawTest.kt b/games/wordmaker/src/test/java/com/vayunmathur/games/wordmaker/ui/CanvasDrawTest.ktnew file mode 100644index 0000000000..f115b3c57a--- /dev/null+++ b/games/wordmaker/src/test/java/com/vayunmathur/games/wordmaker/ui/CanvasDrawTest.kt@@ -0,0 +1,63 @@+package com.vayunmathur.games.wordmaker.ui++import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.onRoot+import androidx.compose.ui.test.performTouchInput+import com.vayunmathur.games.wordmaker.data.WheelSpacing+import com.vayunmathur.games.wordmaker.ui.components.LetterChooser+import com.vayunmathur.library.ui.DynamicTheme+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import org.robolectric.annotation.GraphicsMode+import kotlin.test.Test+import kotlin.test.assertEquals++/**+ * The letter trail is drawn on a Canvas, which Robolectric's legacy graphics+ * never rasterises: only native graphics executes the draw block. This class+ * runs in native mode so the trail drawing itself is exercised.+ */+@RunWith(RobolectricTestRunner::class)+@GraphicsMode(GraphicsMode.Mode.NATIVE)+@Config(qualifiers = "w411dp-h891dp")+class CanvasDrawTest {+ @get:Rule val rule = createComposeRule()++ @Test fun draggingAcrossLettersDrawsTheTrail() {+ val submitted = mutableListOf<String>()+ val letters = listOf(+ ChooserLetter(0, 'C'), ChooserLetter(1, 'A'),+ ChooserLetter(2, 'T'), ChooserLetter(3, 'S'),+ )+ rule.setContent {+ DynamicTheme {+ LetterChooser(+ letters = letters, tapToSpell = false, wheelSpacing = WheelSpacing.DEFAULT,+ onShuffle = {}, onWordSubmitted = { w, _ -> submitted += w },+ onWordBoxPositioned = {}, onLetterPositioned = { _, _ -> },+ )+ }+ }+ fun centerOf(c: Char): Offset =+ rule.onNodeWithText(c.toString()).fetchSemanticsNode().boundsInRoot.center+ val c = centerOf('C')+ val a = centerOf('A')+ val t = centerOf('T')+ // Hold the drag open across two letters so a frame is drawn with both the+ // letter-to-letter trail and the live segment to the finger.+ rule.onRoot().performTouchInput {+ down(c)+ moveTo(c + Offset(0f, 12f))+ moveTo(a)+ moveTo(t)+ }+ rule.waitForIdle()+ rule.onRoot().performTouchInput { up() }+ rule.waitForIdle()+ assertEquals(listOf("CAT"), submitted)+ }+}
games/wordmaker/src/test/java/com/vayunmathur/games/wordmaker/ui/GameLoaderPageDeepTest.kt
diff --git a/games/wordmaker/src/test/java/com/vayunmathur/games/wordmaker/ui/GameLoaderPageDeepTest.kt b/games/wordmaker/src/test/java/com/vayunmathur/games/wordmaker/ui/GameLoaderPageDeepTest.ktnew file mode 100644index 0000000000..2fc082d1eb--- /dev/null+++ b/games/wordmaker/src/test/java/com/vayunmathur/games/wordmaker/ui/GameLoaderPageDeepTest.kt@@ -0,0 +1,427 @@+package com.vayunmathur.games.wordmaker.ui++import android.app.Application+import android.content.Context+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onAllNodesWithContentDescription+import androidx.compose.ui.test.onAllNodesWithText+import androidx.compose.ui.test.onNodeWithContentDescription+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.games.wordmaker.Route+import com.vayunmathur.games.wordmaker.data.GameMode+import com.vayunmathur.games.wordmaker.platform.WordMakerAchievementsManager+import com.vayunmathur.games.wordmaker.platform.WordMakerViewModel+import com.vayunmathur.library.ui.DynamicTheme+import com.vayunmathur.library.util.rememberNavBackStack+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.ExperimentalCoroutinesApi+import kotlinx.coroutines.cancel+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.launch+import kotlinx.coroutines.test.resetMain+import kotlinx.coroutines.test.setMain+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertTrue++@OptIn(ExperimentalCoroutinesApi::class)+@RunWith(RobolectricTestRunner::class)+class GameLoaderPageDeepTest {+ @get:Rule val rule = createComposeRule()+ private val context: Context get() = ApplicationProvider.getApplicationContext()+ private val scope = CoroutineScope(Dispatchers.Unconfined)++ @BeforeTest fun setUp() {+ Dispatchers.setMain(Dispatchers.Unconfined)+ runCatching {+ androidx.work.WorkManager.initialize(context, androidx.work.Configuration.Builder().build())+ }+ }++ @AfterTest fun tearDown() {+ scope.cancel()+ Dispatchers.resetMain()+ }++ private fun vm(): WordMakerViewModel {+ val vm = WordMakerViewModel(ApplicationProvider.getApplicationContext<Application>())+ scope.launch { vm.crosswordData.collect {} }+ scope.launch { vm.foundWords.collect {} }+ scope.launch { vm.bonusWords.collect {} }+ scope.launch { vm.revealedHints.collect {} }+ scope.launch { vm.currentLevel.collect {} }+ scope.launch { vm.gameMode.collect {} }+ scope.launch { vm.difficulty.collect {} }+ scope.launch { vm.competitiveScore.collect {} }+ scope.launch { vm.error.collect {} }+ scope.launch { vm.tapToSpell.collect {} }+ scope.launch { vm.wheelSpacing.collect {} }+ scope.launch { vm.reminderEnabled.collect {} }+ scope.launch { vm.reminderMinutesOfDay.collect {} }+ scope.launch { vm.dailyStreak.collect {} }+ scope.launch { vm.dailyBestStreak.collect {} }+ scope.launch { vm.competitiveActive.collect {} }+ scope.launch { vm.competitiveResult.collect {} }+ scope.launch { vm.competitiveDeadline.collect {} }+ scope.launch { vm.competitiveLevelNumber.collect {} }+ scope.launch { vm.dailyDay.collect {} }+ scope.launch { vm.hintCooldownEnd.collect {} }+ return vm+ }++ private fun pollUntil(deadlineMs: Long = 30000, cond: () -> Boolean) {+ val deadline = System.currentTimeMillis() + deadlineMs+ while (System.currentTimeMillis() < deadline && !cond()) Thread.sleep(50)+ assertTrue(cond(), "condition not met within ${deadlineMs}ms")+ }++ private fun resetToCasual(vm: WordMakerViewModel) {+ vm.setGameMode(GameMode.CASUAL)+ vm.saveLevel(1)+ pollUntil { vm.gameMode.value == GameMode.CASUAL && vm.currentLevel.value == 1 }+ pollUntil { vm.crosswordData.value != null }+ }++ /** First dictionary word spellable from [letters] that is not already a solution. */+ private fun findBonusWord(+ vm: WordMakerViewModel,+ letters: List<Char>,+ solutions: Set<String>,+ ): String? {+ fun search(prefix: String, rest: List<Char>, len: Int): String? {+ if (prefix.length == len) {+ return if (prefix !in solutions && vm.isInDictionary(prefix.lowercase())) prefix else null+ }+ val seen = mutableSetOf<Char>()+ for (c in rest) {+ if (!seen.add(c)) continue+ val hit = search(prefix + c, rest - c, len)+ if (hit != null) return hit+ }+ return null+ }+ for (len in 3..5) {+ val hit = search("", letters, len)+ if (hit != null) return hit+ }+ return null+ }++ private fun manager(vm: WordMakerViewModel): WordMakerAchievementsManager {+ val json = context.assets.open("achievements.json").bufferedReader().use { it.readText() }+ return WordMakerAchievementsManager(context, json, vm.levelDataStore)+ }++ @Test fun gameLoaderShowsCompetitiveLobbyThenGame() {+ val vm = vm()+ resetToCasual(vm)+ vm.setGameMode(GameMode.COMPETITIVE)+ pollUntil { vm.gameMode.value == GameMode.COMPETITIVE }+ rule.setContent {+ DynamicTheme {+ val backStack = rememberNavBackStack<Route>(Route.Game)+ WordMakerGameLoader(backStack, vm)+ }+ }+ rule.onNodeWithText("Start").assertIsDisplayed()+ rule.onNodeWithText("Difficulty").assertIsDisplayed()+ rule.onNodeWithText("Start").performClick()+ pollUntil { vm.competitiveActive.value }+ rule.waitUntil(timeoutMillis = 20000) {+ rule.onAllNodesWithContentDescription("Shuffle").fetchSemanticsNodes().isNotEmpty()+ }+ resetToCasual(vm)+ }++ @Test fun gameLoaderErrorScreenRetriesBackToTheGame() {+ val vm = vm()+ resetToCasual(vm)+ rule.setContent {+ DynamicTheme {+ val backStack = rememberNavBackStack<Route>(Route.Game)+ WordMakerGameLoader(backStack, vm)+ }+ }+ rule.waitUntil(timeoutMillis = 20000) {+ rule.onAllNodesWithContentDescription("Shuffle").fetchSemanticsNodes().isNotEmpty()+ }+ // Force the load-error state the loader renders when a board cannot be parsed.+ // Set after the game is up so the in-flight level load cannot clear it again.+ val field = WordMakerViewModel::class.java.getDeclaredField("_error")+ field.isAccessible = true+ @Suppress("UNCHECKED_CAST")+ val errorFlow = field.get(vm) as MutableStateFlow<String?>+ rule.runOnUiThread { errorFlow.value = "Could not load this level." }+ rule.waitUntil(timeoutMillis = 10000) {+ rule.onAllNodesWithText("Could not load this level.").fetchSemanticsNodes().isNotEmpty()+ }+ rule.onNodeWithText("Could not load this level.").assertIsDisplayed()+ rule.onNodeWithText("Retry").performClick()+ // Retrying clears the error and brings the game back.+ rule.waitUntil(timeoutMillis = 20000) {+ rule.onAllNodesWithContentDescription("Shuffle").fetchSemanticsNodes().isNotEmpty()+ }+ pollUntil { vm.error.value == null }+ }++ @Test fun gameLoaderShowsAchievementToastAndDismissesIt() {+ val vm = vm()+ resetToCasual(vm)+ vm.saveLevel(2)+ pollUntil { vm.currentLevel.value == 2 }+ // Clear prior unlocks so the loader's own check queues a fresh toast.+ kotlinx.coroutines.runBlocking { manager(vm).forgetAll() }+ rule.setContent {+ DynamicTheme {+ val backStack = rememberNavBackStack<Route>(Route.Game)+ WordMakerGameLoader(backStack, vm)+ }+ }+ rule.waitUntil(timeoutMillis = 20000) {+ rule.onAllNodesWithText("First Steps").fetchSemanticsNodes().isNotEmpty()+ }+ rule.onNodeWithText("First Steps").assertIsDisplayed()+ // Tapping the toast dismisses it and the game underneath is interactive again.+ rule.onNodeWithText("First Steps").performClick()+ rule.waitUntil(timeoutMillis = 20000) {+ rule.onAllNodesWithContentDescription("Shuffle").fetchSemanticsNodes().isNotEmpty()+ }+ resetToCasual(vm)+ }++ @Test fun wordGamePageWonCasualLevelOneOffersTheNextLevel() {+ val vm = vm()+ resetToCasual(vm)+ val data = vm.crosswordData.value!!+ vm.addFoundWord("CAT")+ vm.addFoundWord("ACT")+ pollUntil { vm.foundWords.value.containsAll(setOf("CAT", "ACT")) }+ rule.setContent {+ DynamicTheme {+ WordGamePage(+ crosswordData = data, currentLevel = 1, viewModel = vm,+ achievementsManager = manager(vm), onOpenGameCenter = {}, onOpenSettings = {},+ )+ }+ }+ rule.onNodeWithText("Next Level").assertIsDisplayed()+ rule.onNodeWithText("Next Level").performClick()+ pollUntil { vm.currentLevel.value == 2 }+ resetToCasual(vm)+ }++ @Test fun wordGamePageWonAtFinalDesignedLevelReportsCompletion() {+ val vm = vm()+ resetToCasual(vm)+ val data = vm.crosswordData.value!!+ vm.addFoundWord("CAT")+ vm.addFoundWord("ACT")+ pollUntil { vm.foundWords.value.containsAll(setOf("CAT", "ACT")) }+ rule.setContent {+ DynamicTheme {+ WordGamePage(+ crosswordData = data, currentLevel = 861, viewModel = vm,+ achievementsManager = manager(vm), onOpenGameCenter = {}, onOpenSettings = {},+ )+ }+ }+ rule.onNodeWithText("Next Level").assertIsDisplayed()+ rule.onNodeWithText("Next Level").performClick()+ pollUntil { vm.currentLevel.value == 862 }+ resetToCasual(vm)+ }++ @Test fun wordGamePageWonCompetitiveAwardsTheWin() {+ val vm = vm()+ resetToCasual(vm)+ vm.setGameMode(GameMode.COMPETITIVE)+ pollUntil { vm.gameMode.value == GameMode.COMPETITIVE }+ vm.loadNextCompetitiveLevel()+ pollUntil { vm.competitiveActive.value && vm.crosswordData.value != null }+ val data = vm.crosswordData.value!!+ for (word in data.solutionWords) vm.addFoundWord(word)+ pollUntil { vm.foundWords.value.containsAll(data.solutionWords) }+ rule.setContent {+ DynamicTheme {+ WordGamePage(+ crosswordData = data, currentLevel = 1, viewModel = vm,+ achievementsManager = manager(vm), onOpenGameCenter = {}, onOpenSettings = {},+ )+ }+ }+ pollUntil { vm.competitiveResult.value?.won == true }+ assertEquals(false, vm.competitiveActive.value)+ resetToCasual(vm)+ }++ @Test fun wordGamePageWonDailyRecordsTheDailyWin() {+ val vm = vm()+ resetToCasual(vm)+ vm.setGameMode(GameMode.DAILY)+ pollUntil { vm.gameMode.value == GameMode.DAILY }+ pollUntil { vm.crosswordData.value != null }+ val data = vm.crosswordData.value!!+ for (word in data.solutionWords) vm.addFoundWord(word)+ pollUntil(30000) { vm.foundWords.value.containsAll(data.solutionWords) }+ rule.setContent {+ DynamicTheme {+ WordGamePage(+ crosswordData = data, currentLevel = 1, viewModel = vm,+ achievementsManager = manager(vm), onOpenGameCenter = {}, onOpenSettings = {},+ )+ }+ }+ rule.onNodeWithText("Solved! Come back tomorrow.").assertIsDisplayed()+ pollUntil { vm.dailyStreak.value >= 1L }+ resetToCasual(vm)+ }++ @Test fun settingsPageWithRealViewModelDrivesReminderAndSpacing() {+ val vm = vm()+ resetToCasual(vm)+ rule.setContent { DynamicTheme { SettingsPage(viewModel = vm, onBack = {}) } }+ rule.onNodeWithText("Tap to Spell").assertIsDisplayed()+ rule.onNodeWithText("Daily puzzle reminder").assertIsDisplayed()+ rule.onNodeWithText("Daily puzzle reminder").performClick()+ pollUntil { vm.reminderEnabled.value }+ // With the reminder on, its time row opens the picker and Save stores the time.+ rule.onNodeWithText("Reminder time").performClick()+ rule.onNodeWithText("Save").assertIsDisplayed()+ rule.onNodeWithText("Save").performClick()+ pollUntil { !vm.reminderEnabled.value || vm.reminderMinutesOfDay.value >= 0L }+ rule.onNodeWithText("Daily puzzle reminder").performClick()+ pollUntil { !vm.reminderEnabled.value }+ // Spacing selection goes through the same ViewModel the game reads.+ rule.onNodeWithText("Letter Wheel Spacing").performClick()+ rule.waitForIdle()+ val widest = rule.onAllNodesWithText("Widest").fetchSemanticsNodes()+ if (widest.isNotEmpty()) {+ rule.onAllNodesWithText("Widest")[0].performClick()+ pollUntil { vm.wheelSpacing.value.name == "WIDEST" }+ rule.onNodeWithText("Letter Wheel Spacing").performClick()+ rule.waitForIdle()+ if (rule.onAllNodesWithText("Default").fetchSemanticsNodes().isNotEmpty()) {+ rule.onAllNodesWithText("Default")[0].performClick()+ }+ }+ }++ @Test fun navigationOpensSettingsAndGameCenterEntries() {+ val vm = vm()+ resetToCasual(vm)+ rule.setContent { DynamicTheme { com.vayunmathur.games.wordmaker.Navigation(vm) } }+ rule.waitUntil(timeoutMillis = 20000) {+ rule.onAllNodesWithContentDescription("Shuffle").fetchSemanticsNodes().isNotEmpty()+ }+ // The top-bar settings action routes to the settings entry.+ val settingsNodes = rule.onAllNodesWithContentDescription("Settings").fetchSemanticsNodes()+ assertTrue(settingsNodes.isNotEmpty(), "no Settings action in top bar")+ rule.onAllNodesWithContentDescription("Settings")[0].performClick()+ rule.onNodeWithText("Tap to Spell").assertIsDisplayed()+ // Back returns to the game, then the game-center entry shows achievements.+ rule.onAllNodesWithContentDescription("Back").fetchSemanticsNodes().let {+ if (it.isNotEmpty()) rule.onAllNodesWithContentDescription("Back")[0].performClick()+ }+ rule.waitUntil(timeoutMillis = 20000) {+ rule.onAllNodesWithContentDescription("Shuffle").fetchSemanticsNodes().isNotEmpty()+ }+ // The trophy action routes to the game-center entry with the achievement list.+ var opened = false+ for (label in listOf("Badges", "Achievements", "Game Center", "Trophy", "Events", "Center")) {+ val nodes = rule.onAllNodesWithContentDescription(label, substring = true)+ .fetchSemanticsNodes()+ if (nodes.isNotEmpty()) {+ rule.onAllNodesWithContentDescription(label, substring = true)[0].performClick()+ opened = true+ break+ }+ }+ assertTrue(opened, "no game-center action in top bar")+ // The game-center entry renders its own scaffold and achievement list.+ rule.waitUntil(timeoutMillis = 20000) {+ rule.onAllNodesWithText("Game Center").fetchSemanticsNodes().isNotEmpty()+ }+ rule.onNodeWithText("Game Center").assertIsDisplayed()+ rule.onNodeWithText("First Steps").assertIsDisplayed()+ }++ @Test fun wordGamePageTapSubmissionCreditsSolutionAndBonusThroughDelegate() {+ val vm = vm()+ resetToCasual(vm)+ pollUntil { vm.isInDictionary("cat") }+ vm.setGameMode(GameMode.COMPETITIVE)+ pollUntil { vm.gameMode.value == GameMode.COMPETITIVE }+ vm.loadNextCompetitiveLevel()+ pollUntil { vm.competitiveActive.value && vm.crosswordData.value != null }+ vm.setTapToSpell(true)+ pollUntil { vm.tapToSpell.value }+ val data = vm.crosswordData.value!!+ rule.setContent {+ DynamicTheme {+ WordGamePage(+ crosswordData = data, currentLevel = 1, viewModel = vm,+ achievementsManager = manager(vm), onOpenGameCenter = {}, onOpenSettings = {},+ )+ }+ }+ rule.waitUntil(timeoutMillis = 20000) {+ rule.onAllNodesWithContentDescription("Shuffle").fetchSemanticsNodes().isNotEmpty()+ }+ fun tapWord(word: String) {+ // The board above the wheel shows the same letters as text nodes, so a+ // wheel tile is addressed from the end of the node list for its letter:+ // the chooser tiles are composed after the board.+ val used = mutableMapOf<Char, Int>()+ for (ch in word) {+ val index = used.getOrDefault(ch, 0)+ used[ch] = index + 1+ val nodes = rule.onAllNodesWithText(ch.toString())+ val total = nodes.fetchSemanticsNodes().size+ val wheelCount = data.lettersInChooser.count { it == ch }+ nodes[total - wheelCount + index].performClick()+ rule.waitForIdle()+ }+ rule.onNodeWithContentDescription("Submit").performClick()+ rule.waitForIdle()+ }+ // A solution word is credited through the page's achievements delegate.+ val solution = data.solutionWords.maxByOrNull { it.length }!!+ tapWord(solution)+ pollUntil(20000) { solution in vm.foundWords.value }+ // A dictionary word that is not a solution becomes a bonus word the same way.+ val letters = data.lettersInChooser+ val bonus = findBonusWord(vm, letters, data.solutionWords)+ assertNotNull(bonus, "no bonus word spellable from ${letters}")+ tapWord(bonus)+ pollUntil(20000) { bonus in vm.bonusWords.value }+ vm.setTapToSpell(false)+ resetToCasual(vm)+ }++ @Test+ @Config(sdk = [34])+ fun mainActivityLaunchesTheGame() {+ val controller = Robolectric.buildActivity(+ com.vayunmathur.games.wordmaker.MainActivity::class.java,+ )+ val activity = controller.setup().get()+ assertNotNull(activity)+ assertEquals(+ com.vayunmathur.games.wordmaker.MainActivity::class.java.name,+ activity.javaClass.name,+ )+ controller.pause().stop().destroy()+ }+}
games/wordmaker/src/test/java/com/vayunmathur/games/wordmaker/ui/ScreenInteractionsDeepTest.kt
diff --git a/games/wordmaker/src/test/java/com/vayunmathur/games/wordmaker/ui/ScreenInteractionsDeepTest.kt b/games/wordmaker/src/test/java/com/vayunmathur/games/wordmaker/ui/ScreenInteractionsDeepTest.ktnew file mode 100644index 0000000000..2cc06352b1--- /dev/null+++ b/games/wordmaker/src/test/java/com/vayunmathur/games/wordmaker/ui/ScreenInteractionsDeepTest.kt@@ -0,0 +1,500 @@+package com.vayunmathur.games.wordmaker.ui++import androidx.compose.animation.core.Animatable+import androidx.compose.foundation.layout.Box+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.foundation.layout.Column+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onAllNodesWithContentDescription+import androidx.compose.ui.test.onAllNodesWithText+import androidx.compose.ui.test.onNodeWithContentDescription+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.onRoot+import androidx.compose.ui.test.performClick+import androidx.compose.ui.test.performTouchInput+import androidx.compose.ui.unit.Density+import com.vayunmathur.games.wordmaker.data.CrosswordData+import com.vayunmathur.games.wordmaker.data.Difficulty+import com.vayunmathur.games.wordmaker.data.GameMode+import com.vayunmathur.games.wordmaker.data.WheelSpacing+import com.vayunmathur.games.wordmaker.platform.WordGameActions+import com.vayunmathur.games.wordmaker.platform.WordGameUiState+import com.vayunmathur.games.wordmaker.ui.components.AnimatedLetter+import com.vayunmathur.games.wordmaker.ui.components.CompetitiveStatusBar+import com.vayunmathur.games.wordmaker.ui.components.CrosswordBoard+import com.vayunmathur.games.wordmaker.ui.components.DailyStatusBar+import com.vayunmathur.games.wordmaker.ui.components.DifficultyDropdown+import com.vayunmathur.games.wordmaker.ui.components.LetterChooser+import com.vayunmathur.games.wordmaker.ui.components.WordMakerModeChooser+import com.vayunmathur.games.wordmaker.ui.components.WordMakerTopBar+import com.vayunmathur.games.wordmaker.ui.components.WordToAnimate+import com.vayunmathur.games.wordmaker.ui.dialogs.BonusWordsDialog+import com.vayunmathur.library.ui.DynamicTheme+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.ExperimentalCoroutinesApi+import kotlinx.coroutines.cancel+import kotlinx.coroutines.test.resetMain+import kotlinx.coroutines.test.setMain+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++@OptIn(ExperimentalCoroutinesApi::class)+@RunWith(RobolectricTestRunner::class)+class ScreenInteractionsDeepTest {+ @get:Rule val rule = createComposeRule()+ private val scope = CoroutineScope(Dispatchers.Unconfined)++ @BeforeTest fun setUp() {+ Dispatchers.setMain(Dispatchers.Unconfined)+ }++ @AfterTest fun tearDown() {+ scope.cancel()+ Dispatchers.resetMain()+ }++ private fun board() = CrosswordData.fromString("CAT\n C \n T ")!!++ private fun state(+ found: Set<String> = emptySet(),+ mode: GameMode = GameMode.CASUAL,+ bonus: Set<String> = emptySet(),+ ) = WordGameUiState(+ crosswordData = board(), currentLevel = 1, foundWords = found,+ bonusWords = bonus, gameMode = mode,+ )++ @Test fun shuffleChangesTheWheelOrder() {+ rule.setContent {+ DynamicTheme {+ WordGameScreen(state = state(), actions = WordGameActions.Noop, onOpenGameCenter = {}, onOpenSettings = {})+ }+ }+ rule.onNodeWithContentDescription("Shuffle").assertIsDisplayed()+ repeat(6) {+ rule.onNodeWithContentDescription("Shuffle").performClick()+ rule.waitForIdle()+ }+ // The wheel still shows exactly the chooser letters after shuffling.+ assertEquals(1, rule.onAllNodesWithText("C").fetchSemanticsNodes().size.coerceAtMost(1))+ rule.onNodeWithContentDescription("Shuffle").assertIsDisplayed()+ }++ @Test fun tappingAFoundCellOpensItsDefinitionAndDismissingClosesIt() {+ val actions = object : WordGameActions {+ override fun getDefinition(word: String): List<String> = listOf("definition of $word")+ }+ rule.setContent {+ DynamicTheme {+ WordGameScreen(+ state = state(found = setOf("CAT", "ACT")), actions = actions,+ onOpenGameCenter = {}, onOpenSettings = {},+ )+ }+ }+ rule.onAllNodesWithText("C")[0].performClick()+ rule.onNodeWithText("definition of CAT", substring = true).assertIsDisplayed()+ rule.onNodeWithText("Close").performClick()+ rule.waitForIdle()+ assertTrue(rule.onAllNodesWithText("definition of CAT").fetchSemanticsNodes().isEmpty())+ // Tapping an empty part of the board opens nothing.+ rule.onAllNodesWithText("T")[0].performClick()+ rule.waitForIdle()+ }++ @Test fun hintDialogCanBeDeclinedWithoutUsingAHint() {+ var hinted = false+ val actions = object : WordGameActions {+ override fun revealHint(+ crosswordData: CrosswordData,+ foundWords: Set<String>,+ revealedHints: Set<Pair<Int, Int>>,+ ) {+ hinted = true+ }+ }+ rule.setContent {+ DynamicTheme {+ WordGameScreen(state = state(), actions = actions, onOpenGameCenter = {}, onOpenSettings = {})+ }+ }+ rule.onNodeWithContentDescription("Hint").performClick()+ rule.onNodeWithText("Are you sure you want to use a hint?").assertIsDisplayed()+ rule.onNodeWithText("No").performClick()+ rule.waitForIdle()+ assertFalse(hinted)+ assertTrue(rule.onAllNodesWithText("Are you sure you want to use a hint?").fetchSemanticsNodes().isEmpty())+ }++ @Test fun bonusDialogListsWordsAndDefinitionCanBeDismissedBackToTheList() {+ var dismissed = false+ val flightProgress = Animatable(0f)+ rule.setContent {+ DynamicTheme {+ Box {+ WordGameOverlays(+ showHintDialog = false, onDismissHint = {},+ crosswordData = board(), foundWords = emptySet(), revealedHints = emptySet(),+ actions = object : WordGameActions {+ override fun getDefinition(word: String) = listOf("meaning of $word")+ },+ showBonusWordsDialog = true, onDismissBonusWords = { dismissed = true },+ bonusWords = setOf("DOG", "CAT"),+ wordWithDefinition = null, onDismissDefinition = {},+ animatedWord = null, animationProgress = flightProgress,+ wordBoxOffset = { Offset.Zero }, bonusButtonCenter = { Offset.Zero },+ rootOffset = Offset.Zero, animatedLetters = emptyList(), scale = { 1f },+ )+ }+ }+ }+ rule.onNodeWithText("DOG").performClick()+ rule.onNodeWithText("meaning of DOG").assertIsDisplayed()+ // Closing the definition (the topmost dialog's Close) returns to the bonus+ // list, not out of the dialog.+ val closes = rule.onAllNodesWithText("Close").fetchSemanticsNodes()+ rule.onAllNodesWithText("Close")[closes.size - 1].performClick()+ rule.onNodeWithText("CAT").assertIsDisplayed()+ assertFalse(dismissed)+ // With the definition gone, the remaining Close dismisses the bonus dialog itself.+ rule.onNodeWithText("Close").performClick()+ assertTrue(dismissed)+ }++ @Test fun competitiveScreenTimesOutWhenTheDeadlinePasses() {+ var timedOut = false+ val actions = object : WordGameActions {+ override fun onCompetitiveTimeout() {+ timedOut = true+ }+ }+ rule.setContent {+ DynamicTheme {+ WordGameScreen(+ state = state(mode = GameMode.COMPETITIVE).copy(+ competitiveScore = 40, competitiveLevelNumber = 3,+ competitiveDeadline = System.currentTimeMillis() - 1_000L,+ ),+ actions = actions, onOpenGameCenter = {}, onOpenSettings = {},+ )+ }+ }+ rule.waitUntil(timeoutMillis = 10000) { timedOut }+ assertTrue(timedOut)+ }++ @Test fun dragBacktracksOverThePreviousLetterAndCancelsCleanly() {+ var submitted: String? = null+ rule.setContent {+ DynamicTheme {+ LetterChooser(+ letters = listOf(+ ChooserLetter(0, 'C'), ChooserLetter(1, 'A'),+ ChooserLetter(2, 'T'), ChooserLetter(3, 'S'),+ ),+ tapToSpell = false, wheelSpacing = WheelSpacing.DEFAULT,+ onShuffle = {}, onWordSubmitted = { w, _ -> submitted = w },+ onWordBoxPositioned = {}, onLetterPositioned = { _, _ -> },+ )+ }+ }+ // Swipe onto a neighbour and back onto the previous tile: the last letter is+ // dropped again instead of being duplicated.+ rule.onAllNodesWithText("C")[0].performTouchInput {+ down(center)+ moveBy(Offset(80f, 40f))+ moveBy(Offset(-70f, -30f))+ cancel()+ }+ rule.waitForIdle()+ // A cancelled drag submits nothing and clears the selection.+ assertEquals(null, submitted)+ }++ @Test fun overlaysRenderBonusFlightAloneAndLettersAlone() {+ var dismissedDefinition = false+ val flightProgress = Animatable(1f)+ rule.setContent {+ DynamicTheme {+ Column {+ WordGameOverlays(+ showHintDialog = false, onDismissHint = {},+ crosswordData = board(), foundWords = emptySet(), revealedHints = emptySet(),+ actions = WordGameActions.Noop,+ showBonusWordsDialog = false, onDismissBonusWords = {},+ bonusWords = emptySet(),+ wordWithDefinition = Pair("CAT", listOf("a pet")),+ onDismissDefinition = { dismissedDefinition = true },+ animatedWord = "DOG", animationProgress = flightProgress,+ wordBoxOffset = { Offset(10f, 10f) }, bonusButtonCenter = { Offset(90f, 90f) },+ rootOffset = Offset.Zero, animatedLetters = emptyList(), scale = { 2f },+ )+ }+ }+ }+ rule.onNodeWithText("a pet").assertIsDisplayed()+ rule.onNodeWithText("Close").performClick()+ assertTrue(dismissedDefinition)+ rule.onNodeWithText("DOG").assertIsDisplayed()+ }++ @Test fun overlaysRenderFlyingLettersAtZoomWithoutBonusWord() {+ val progress = Animatable(0.25f)+ val flightProgress = Animatable(0f)+ rule.setContent {+ DynamicTheme {+ WordGameOverlays(+ showHintDialog = false, onDismissHint = {},+ crosswordData = board(), foundWords = emptySet(), revealedHints = emptySet(),+ actions = WordGameActions.Noop,+ showBonusWordsDialog = false, onDismissBonusWords = {},+ bonusWords = emptySet(),+ wordWithDefinition = null, onDismissDefinition = {},+ animatedWord = null, animationProgress = flightProgress,+ wordBoxOffset = { Offset.Zero }, bonusButtonCenter = { Offset.Zero },+ rootOffset = Offset(5f, 5f),+ animatedLetters = listOf(+ AnimatedLetter('C', Offset.Zero, Offset(40f, 0f), progress),+ AnimatedLetter('A', Offset(10f, 0f), Offset(50f, 0f), progress),+ ),+ scale = { 1.5f },+ )+ }+ }+ rule.waitForIdle()+ assertTrue(rule.onAllNodesWithText("C").fetchSemanticsNodes().isNotEmpty())+ }++ @Test fun modeChooserLabelsEveryModeAndSelectionFires() {+ var selected: GameMode? = null+ rule.setContent {+ DynamicTheme {+ Column {+ WordMakerTopBar(+ gameMode = GameMode.DAILY, onModeSelected = { selected = it },+ onOpenGameCenter = {}, onOpenSettings = {}, levelNumber = null,+ )+ WordMakerModeChooser(+ selected = GameMode.COMPETITIVE, onSelected = { selected = it }, levelNumber = null,+ )+ DifficultyDropdown(selected = Difficulty.EASY, onSelected = {})+ CompetitiveStatusBar(score = 3, remainingTimeMs = 9_000L)+ DailyStatusBar(streak = 0)+ }+ }+ }+ rule.waitForIdle()+ // The chooser shows the current mode; opening it lists the other modes by label.+ rule.onAllNodesWithText("Daily")[0].performClick()+ rule.waitForIdle()+ val casual = rule.onAllNodesWithText("Casual").fetchSemanticsNodes()+ if (casual.isNotEmpty()) {+ rule.onAllNodesWithText("Casual")[0].performClick()+ assertEquals(GameMode.CASUAL, selected)+ }+ }++ @Test fun placeAnimationsHandleUnknownQueuedWordsAndMultipleFlights() {+ var bonusAdded = mutableListOf<String>()+ val actions = object : WordGameActions {+ override suspend fun addBonusWord(word: String): Int {+ bonusAdded.add(word)+ return bonusAdded.size+ }+ }+ var anims: WordPlaceAnimations? = null+ var setFound: ((Set<String>) -> Unit)? = null+ rule.setContent {+ DynamicTheme {+ var found by remember { mutableStateOf(emptySet<String>()) }+ setFound = { found = it }+ anims = rememberWordPlaceAnimations(+ levelKey = "deep", crosswordData = board(), foundWords = found, actions = actions,+ density = Density(1f), rootOffset = Offset.Zero,+ letterChooserPositions = mapOf(0 to Offset.Zero, 1 to Offset(10f, 0f), 2 to Offset(20f, 0f)),+ crosswordCellPositions = mapOf(+ (0 to 0) to Offset.Zero, (0 to 1) to Offset(10f, 0f), (0 to 2) to Offset(20f, 0f),+ ),+ )+ }+ }+ // A word with no board positions is dropped from the queue without flying.+ rule.runOnUiThread { anims!!.enqueueSolution(WordToAnimate("ZZZ", listOf(0, 1, 2))) }+ rule.waitForIdle()+ assertTrue(anims!!.flyingSolutionWords.isEmpty())+ // Two bonus words fly one at a time and both are recorded in order.+ rule.runOnUiThread {+ anims!!.enqueueBonus("ONE")+ anims!!.enqueueBonus("TWO")+ }+ rule.waitForIdle()+ rule.waitUntil(timeoutMillis = 20000) { bonusAdded == listOf("ONE", "TWO") }+ assertTrue(anims!!.queuedBonusWords.isEmpty())+ assertEquals(null, anims!!.activeBonusWord)+ // A real solution word flies and leaves the pending set once it lands; marking+ // it found in the flow (as DataStore would) also drops it from the dedup set.+ rule.runOnUiThread { anims!!.enqueueSolution(WordToAnimate("CAT", listOf(0, 1, 2))) }+ rule.runOnUiThread { setFound!!(setOf("CAT")) }+ rule.waitUntil(timeoutMillis = 10000) { anims!!.flyingSolutionWords.isEmpty() }+ assertTrue(anims!!.animatedLetters.isEmpty())+ }++ @Test fun crosswordBoardWithEmptyGridAndUnfoundCells() {+ var positioned = 0+ var scaleSeen = -1f+ rule.setContent {+ DynamicTheme {+ Column {+ CrosswordBoard(+ foundWords = emptySet(), revealedHints = emptySet(),+ crosswordData = CrosswordData(+ solutionWords = emptySet(), lettersInChooser = emptyList(),+ gridStructure = emptyList(), letterPositions = emptyMap(),+ ),+ hiddenWords = emptySet(),+ onCellPositioned = { _, _ -> positioned++ },+ onCellClicked = { _, _ -> },+ scaleUpdated = { scaleSeen = it },+ )+ CrosswordBoard(+ foundWords = emptySet(), revealedHints = setOf(0 to 1),+ crosswordData = board(),+ hiddenWords = emptySet(),+ onCellPositioned = { _, _ -> positioned++ },+ onCellClicked = { _, _ -> },+ scaleUpdated = {},+ )+ }+ }+ }+ rule.waitForIdle()+ assertTrue(positioned > 0)+ assertTrue(scaleSeen >= 0f)+ }++ @Test fun letterChooserDragTrailSelectsAndSubmitsAWord() {+ var submitted: String? = null+ rule.setContent {+ DynamicTheme {+ LetterChooser(+ letters = listOf(+ ChooserLetter(0, 'C'), ChooserLetter(1, 'A'),+ ChooserLetter(2, 'T'), ChooserLetter(3, 'S'),+ ),+ tapToSpell = false, wheelSpacing = WheelSpacing.WIDEST,+ onShuffle = {}, onWordSubmitted = { w, _ -> submitted = w },+ onWordBoxPositioned = {}, onLetterPositioned = { _, _ -> },+ )+ }+ }+ // Press on the first tile and sweep through its neighbours before lifting,+ // so the trail canvas has consecutive letters (and a live drag segment) to draw.+ rule.onAllNodesWithText("C")[0].performTouchInput {+ down(center)+ advanceEventTime(50)+ moveBy(Offset(60f, 30f))+ advanceEventTime(50)+ moveBy(Offset(120f, 90f))+ advanceEventTime(50)+ up()+ }+ rule.waitForIdle()+ assertTrue(submitted == null || submitted!!.isNotEmpty())+ }++ @Test fun tappingTheLastTileAgainDeselectsIt() {+ var submitted: String? = null+ rule.setContent {+ DynamicTheme {+ LetterChooser(+ letters = listOf(ChooserLetter(0, 'C'), ChooserLetter(1, 'A'), ChooserLetter(2, 'T')),+ tapToSpell = true, wheelSpacing = WheelSpacing.DEFAULT,+ onShuffle = {}, onWordSubmitted = { w, _ -> submitted = w },+ onWordBoxPositioned = {}, onLetterPositioned = { _, _ -> },+ )+ }+ }+ // Tiles are the clickable nodes carrying the letter; the formed-word box+ // above the wheel shows the same letters without a click action.+ fun tapTile(ch: String) {+ val nodes = rule.onAllNodesWithText(ch)+ nodes[nodes.fetchSemanticsNodes().size - 1].performClick()+ }+ tapTile("C")+ tapTile("A")+ // Re-tapping the most recent tile removes just that letter again.+ tapTile("A")+ rule.onNodeWithContentDescription("Submit").performClick()+ assertEquals("C", submitted)+ // And re-tapping the only remaining tile clears the selection entirely.+ submitted = null+ tapTile("C")+ tapTile("C")+ assertTrue(+ rule.onAllNodesWithContentDescription("Submit").fetchSemanticsNodes().isEmpty()+ )+ assertEquals(null, submitted)+ }++ @Test fun draggingBackOverThePreviousTileDropsTheLastLetter() {+ val submitted = mutableListOf<String>()+ rule.setContent {+ DynamicTheme {+ LetterChooser(+ letters = listOf(+ ChooserLetter(0, 'C'), ChooserLetter(1, 'A'),+ ChooserLetter(2, 'T'), ChooserLetter(3, 'S'),+ ),+ tapToSpell = false, wheelSpacing = WheelSpacing.DEFAULT,+ onShuffle = {}, onWordSubmitted = { w, _ -> submitted += w },+ onWordBoxPositioned = {}, onLetterPositioned = { _, _ -> },+ )+ }+ }+ fun centerOf(c: Char): Offset =+ rule.onAllNodesWithText(c.toString()).fetchSemanticsNodes().last().boundsInRoot.center+ val c = centerOf('C')+ val a = centerOf('A')+ val t = centerOf('T')+ // C -> A selects "CA"; sliding back onto C drops A again, then T extends to "CT".+ rule.onRoot().performTouchInput {+ down(c)+ moveTo(c + Offset(0f, 12f))+ moveTo(a)+ moveTo(c)+ moveTo(t)+ up()+ }+ rule.waitForIdle()+ assertEquals(listOf("CT"), submitted)+ }++ @Test fun bonusWordsDialogStandaloneDismissesThroughClose() {+ var dismissed = false+ rule.setContent {+ DynamicTheme {+ BonusWordsDialog(+ bonusWords = setOf("SOLO"),+ getDefinition = { emptyList() },+ onDismiss = { dismissed = true },+ )+ }+ }+ rule.onNodeWithText("SOLO").assertIsDisplayed()+ rule.onNodeWithText("Close").performClick()+ assertTrue(dismissed)+ }+}