games-sudoku: add tests for viewmodel, stats, datastore and UI
- Commit
cba8b8977ab4ce65995079a68feb179185a574b2- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-07 06:17 UTC (29 days ago)
- Parents
75e026c
Coverage (merged INSTRUCTION, games/sudoku): 15.7% (1406/8950) -> 93.0% (8325/8950). New tests (9 files, 59 tests; module total 101, all passing): - platform/SudokuViewModelTest: newGame, select/place/erase/notes, clearCell, hint priority (wrong cell first, then selected, then first blank), undo, restart, giveUp streak break, timer, win recording, answer-mode rejection/lives/game-over, setAnswerMode persistence. - data/SudokuStatsRepositoryTest: per-variant played/won/lost, streak and best-time aggregation, size/total rollups, persistence. - data/SudokuDataStoreTest: answer-mode round-trip across instances. - data/SudokuModelsTest: box geometry, letter symbols, clue targets, GameConfig variant, fresh state, snapshot. - platform/SudokuAchievementsAndMiscTest: achievement back-fill from seeded stats, backup agent file lists, UiState/RejectedDigit, Noop actions, Route serialization. - ui/components/SudokuComponentsTest: grid selection/notes/states for all sizes, number pad digits/notes-mode/disabled completed digit/ rejection/letter keys. - ui/SudokuScreensTest: board loading, actions, give-up dialog dismiss/confirm, win and game-over overlays, display names. - ui/SudokuHomeAndGameScreenTest: home pickers/new-game/continue/ stats cards, GameScreen dealing, Navigation home/board/game-center. - SudokuMainActivityTest: activity launches to home. No production changes. Bugs fixed: none. Verified: gslot ./gradlew :games:sudoku:createMergedCoverageReport, :games:sudoku:testDevUnitTest (101 tests, 0 failures) and :games:sudoku:lint all pass. detekt via ./check is blocked repo-wide: detekt-core 2.0.0-alpha.6 jar is missing from the Maven mirror (lead-inbox note filed). Untestable remainder: none material; remaining misses are the side-by-side board layout branch, grid drawBehind line painting, and DataStore flow inlined copies. (cherry picked from commit 9818cffcabbdcd56a974322e2422b78180e815bc)
Diff
games/sudoku/src/test/java/com/vayunmathur/games/sudoku/SudokuMainActivityTest.kt
diff --git a/games/sudoku/src/test/java/com/vayunmathur/games/sudoku/SudokuMainActivityTest.kt b/games/sudoku/src/test/java/com/vayunmathur/games/sudoku/SudokuMainActivityTest.ktnew file mode 100644index 0000000000..e383ba4ee3--- /dev/null+++ b/games/sudoku/src/test/java/com/vayunmathur/games/sudoku/SudokuMainActivityTest.kt@@ -0,0 +1,20 @@+package com.vayunmathur.games.sudoku++import androidx.compose.ui.test.junit4.createAndroidComposeRule+import androidx.compose.ui.test.onNodeWithText+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.Test++@RunWith(RobolectricTestRunner::class)+class SudokuMainActivityTest {++ @get:Rule val rule = createAndroidComposeRule<MainActivity>()++ @Test+ fun mainActivityLaunchesToHome() {+ rule.onNodeWithText("New Game").assertExists()+ rule.onNodeWithText("Board size").assertExists()+ }+}
games/sudoku/src/test/java/com/vayunmathur/games/sudoku/data/SudokuDataStoreTest.kt
diff --git a/games/sudoku/src/test/java/com/vayunmathur/games/sudoku/data/SudokuDataStoreTest.kt b/games/sudoku/src/test/java/com/vayunmathur/games/sudoku/data/SudokuDataStoreTest.ktnew file mode 100644index 0000000000..f288667b92--- /dev/null+++ b/games/sudoku/src/test/java/com/vayunmathur/games/sudoku/data/SudokuDataStoreTest.kt@@ -0,0 +1,30 @@+package com.vayunmathur.games.sudoku.data++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.Test+import kotlin.test.assertFalse+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)+class SudokuDataStoreTest {++ private val context: Context get() = ApplicationProvider.getApplicationContext()++ @Test+ fun answerModeRoundTrips() = runBlocking {+ val store = SudokuDataStore(context)+ store.setAnswerMode(false)+ assertFalse(store.answerMode.first(), "explicit off must read back off")++ store.setAnswerMode(true)+ assertTrue(SudokuDataStore(context).answerMode.first(), "on must persist across instances")++ store.setAnswerMode(false)+ assertFalse(store.answerMode.first())+ }+}
games/sudoku/src/test/java/com/vayunmathur/games/sudoku/data/SudokuModelsTest.kt
diff --git a/games/sudoku/src/test/java/com/vayunmathur/games/sudoku/data/SudokuModelsTest.kt b/games/sudoku/src/test/java/com/vayunmathur/games/sudoku/data/SudokuModelsTest.ktnew file mode 100644index 0000000000..ed49f8ebc9--- /dev/null+++ b/games/sudoku/src/test/java/com/vayunmathur/games/sudoku/data/SudokuModelsTest.kt@@ -0,0 +1,119 @@+package com.vayunmathur.games.sudoku.data++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++class SudokuModelsTest {++ @Test+ fun boardSizeGeometryAndBoxOf() {+ assertEquals(36, BoardSize.SIX.cellCount)+ assertEquals(81, BoardSize.NINE.cellCount)+ assertEquals(144, BoardSize.TWELVE.cellCount)+ // Corners and box boundaries for the non-square boxes.+ assertEquals(0, BoardSize.SIX.boxOf(0))+ assertEquals(0, BoardSize.SIX.boxOf(2))+ assertEquals(1, BoardSize.SIX.boxOf(3))+ assertEquals(1, BoardSize.SIX.boxOf(5))+ assertEquals(0, BoardSize.SIX.boxOf(6))+ assertEquals(5, BoardSize.SIX.boxOf(35))+ assertEquals(0, BoardSize.NINE.boxOf(0))+ assertEquals(4, BoardSize.NINE.boxOf(40))+ assertEquals(8, BoardSize.NINE.boxOf(80))+ assertEquals(0, BoardSize.TWELVE.boxOf(0))+ assertEquals(2, BoardSize.TWELVE.boxOf(11))+ assertEquals(11, BoardSize.TWELVE.boxOf(143))+ }++ @Test+ fun symbolsSwitchToLettersAfterNine() {+ assertEquals("1", sudokuSymbol(1))+ assertEquals("9", sudokuSymbol(9))+ assertEquals("A", sudokuSymbol(10))+ assertEquals("B", sudokuSymbol(11))+ assertEquals("C", sudokuSymbol(12))+ }++ @Test+ fun targetCluesUsesFractionWithSidePlusOneFloor() {+ assertEquals(48, Difficulty.EASY.targetClues(BoardSize.NINE))+ assertEquals(37, Difficulty.MEDIUM.targetClues(BoardSize.NINE))+ assertEquals(29, Difficulty.HARD.targetClues(BoardSize.NINE))+ assertEquals(22, Difficulty.EXPERT.targetClues(BoardSize.NINE))+ for (size in BoardSize.entries) for (difficulty in Difficulty.entries) {+ assertTrue(difficulty.targetClues(size) >= size.side + 1)+ }+ assertEquals(0.60, Difficulty.EASY.clueFraction)+ assertEquals(0.28, Difficulty.EXPERT.clueFraction)+ }++ @Test+ fun gameConfigDefaultsAndVariant() {+ val config = GameConfig()+ assertEquals(BoardSize.NINE, config.size)+ assertEquals(Difficulty.MEDIUM, config.difficulty)+ assertFalse(config.answerMode)+ assertEquals("NINE_MEDIUM", config.variant)+ assertEquals(+ "TWELVE_EXPERT",+ GameConfig(BoardSize.TWELVE, Difficulty.EXPERT, answerMode = true).variant,+ )+ }++ @Test+ fun fromPuzzleCreatesFreshState() {+ val puzzle = Puzzle(+ size = BoardSize.SIX,+ difficulty = Difficulty.HARD,+ givens = List(36) { if (it % 7 == 0) 3 else 0 },+ solution = List(36) { (it % 6) + 1 },+ )+ val state = SudokuGameState.from(puzzle, answerMode = true)+ assertEquals(BoardSize.SIX, state.size)+ assertEquals(Difficulty.HARD, state.difficulty)+ assertEquals(puzzle.givens, state.givens)+ assertEquals(puzzle.solution, state.solution)+ assertEquals(List(36) { 0 }, state.entries)+ assertEquals(List(36) { 0 }, state.notes)+ assertEquals(-1, state.selected)+ assertFalse(state.notesMode)+ assertEquals(0, state.moveCount)+ assertEquals(0, state.elapsedSeconds)+ assertEquals(0, state.hintsUsed)+ assertFalse(state.isWon)+ assertFalse(state.usedUndo)+ assertTrue(state.answerMode)+ assertEquals(ANSWER_MODE_LIVES, state.livesRemaining)+ assertEquals("SIX_HARD", state.variant)+ assertFalse(state.isGameOver)+ assertFalse(state.isComplete)+ }++ @Test+ fun valueAtPrefersGivensAndDigitCompleteCountsAllCopies() {+ val givens = MutableList(36) { 0 }.also { it[0] = 5; it[1] = 5 }+ val state = SudokuGameState(+ size = BoardSize.SIX, difficulty = Difficulty.EASY,+ givens = givens, solution = List(36) { 1 },+ entries = List(36) { 0 }, notes = List(36) { 0 },+ )+ assertEquals(5, state.valueAt(0))+ assertEquals(0, state.valueAt(2))+ assertTrue(state.isGiven(0))+ assertFalse(state.isGiven(2))+ assertFalse(state.isDigitComplete(5))+ val entries = MutableList(36) { 0 }+ entries[2] = 5; entries[3] = 5; entries[4] = 5; entries[5] = 5+ assertTrue(state.copy(entries = entries).isDigitComplete(5))+ }++ @Test+ fun snapshotHoldsEntriesAndNotes() {+ val snapshot = SudokuSnapshot(entries = listOf(1, 0), notes = listOf(2, 4))+ assertEquals(listOf(1, 0), snapshot.entries)+ assertEquals(listOf(2, 4), snapshot.notes)+ assertEquals(snapshot, SudokuSnapshot(listOf(1, 0), listOf(2, 4)))+ }+}
games/sudoku/src/test/java/com/vayunmathur/games/sudoku/data/SudokuStatsRepositoryTest.kt
diff --git a/games/sudoku/src/test/java/com/vayunmathur/games/sudoku/data/SudokuStatsRepositoryTest.kt b/games/sudoku/src/test/java/com/vayunmathur/games/sudoku/data/SudokuStatsRepositoryTest.ktnew file mode 100644index 0000000000..8f1cb1366a--- /dev/null+++ b/games/sudoku/src/test/java/com/vayunmathur/games/sudoku/data/SudokuStatsRepositoryTest.kt@@ -0,0 +1,133 @@+package com.vayunmathur.games.sudoku.data++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull++@RunWith(RobolectricTestRunner::class)+class SudokuStatsRepositoryTest {++ private val context: Context get() = ApplicationProvider.getApplicationContext()+ private lateinit var repo: SudokuStatsRepository++ @BeforeTest+ fun setUp() {+ context.getSharedPreferences("sudoku_stats", Context.MODE_PRIVATE).edit().clear().commit()+ repo = SudokuStatsRepository(context)+ }++ @Test+ fun defaultsAreEmptyForEveryVariant() {+ for (size in BoardSize.entries) for (difficulty in Difficulty.entries) {+ assertEquals(GameStats(), repo.getStats(size, difficulty))+ }+ assertEquals(GameStats(), repo.getSizeStats(BoardSize.NINE))+ assertEquals(0, repo.getTotalGamesWon())+ assertEquals(0, repo.getBestWinStreak())+ assertNull(repo.getBestTime(Difficulty.EASY))+ }++ @Test+ fun recordPlayedOnlyIncrementsPlayedForThatVariant() {+ repo.recordGamePlayed(BoardSize.SIX, Difficulty.EASY)+ repo.recordGamePlayed(BoardSize.SIX, Difficulty.EASY)+ repo.recordGamePlayed(BoardSize.NINE, Difficulty.HARD)++ assertEquals(2, repo.getStats(BoardSize.SIX, Difficulty.EASY).gamesPlayed)+ assertEquals(1, repo.getStats(BoardSize.NINE, Difficulty.HARD).gamesPlayed)+ assertEquals(0, repo.getStats(BoardSize.SIX, Difficulty.HARD).gamesPlayed)+ assertEquals(0, repo.getStats(BoardSize.SIX, Difficulty.EASY).gamesWon)+ }++ @Test+ fun recordWonUpdatesWinsStreaksAndBestTimeWithMin() {+ repo.recordGameWon(BoardSize.NINE, Difficulty.MEDIUM, 200)+ var stats = repo.getStats(BoardSize.NINE, Difficulty.MEDIUM)+ assertEquals(1, stats.gamesWon)+ assertEquals(1, stats.currentWinStreak)+ assertEquals(1, stats.bestWinStreak)+ assertEquals(200, stats.bestTimeSeconds)++ repo.recordGameWon(BoardSize.NINE, Difficulty.MEDIUM, 350)+ stats = repo.getStats(BoardSize.NINE, Difficulty.MEDIUM)+ assertEquals(2, stats.gamesWon)+ assertEquals(2, stats.currentWinStreak)+ assertEquals(200, stats.bestTimeSeconds, "slower win must not replace best time")++ repo.recordGameWon(BoardSize.NINE, Difficulty.MEDIUM, 120)+ assertEquals(120, repo.getStats(BoardSize.NINE, Difficulty.MEDIUM).bestTimeSeconds)+ }++ @Test+ fun recordLostResetsCurrentStreakButKeepsBestStreakAndWins() {+ repo.recordGameWon(BoardSize.SIX, Difficulty.HARD, 90)+ repo.recordGameWon(BoardSize.SIX, Difficulty.HARD, 80)+ repo.recordGameLost(BoardSize.SIX, Difficulty.HARD)+ val stats = repo.getStats(BoardSize.SIX, Difficulty.HARD)+ assertEquals(0, stats.currentWinStreak)+ assertEquals(2, stats.bestWinStreak)+ assertEquals(2, stats.gamesWon)+ assertEquals(80, stats.bestTimeSeconds)++ // Losing a variant with no history is a harmless no-op record.+ repo.recordGameLost(BoardSize.TWELVE, Difficulty.EASY)+ assertEquals(GameStats(), repo.getStats(BoardSize.TWELVE, Difficulty.EASY).copy(currentWinStreak = 0))+ }++ @Test+ fun sizeStatsAggregatesAcrossDifficulties() {+ repo.recordGamePlayed(BoardSize.SIX, Difficulty.EASY)+ repo.recordGamePlayed(BoardSize.SIX, Difficulty.EXPERT)+ repo.recordGameWon(BoardSize.SIX, Difficulty.EASY, 300)+ repo.recordGameWon(BoardSize.SIX, Difficulty.EXPERT, 500)+ repo.recordGameWon(BoardSize.SIX, Difficulty.EXPERT, 400)+ repo.recordGamePlayed(BoardSize.NINE, Difficulty.EASY)++ val agg = repo.getSizeStats(BoardSize.SIX)+ assertEquals(2, agg.gamesPlayed)+ assertEquals(3, agg.gamesWon)+ assertEquals(2, agg.currentWinStreak, "max current streak across difficulties")+ assertEquals(2, agg.bestWinStreak)+ assertEquals(300, agg.bestTimeSeconds, "min best time across difficulties")+ assertEquals(1, repo.getSizeStats(BoardSize.NINE).gamesPlayed)+ assertEquals(GameStats(), repo.getSizeStats(BoardSize.TWELVE))+ }++ @Test+ fun totalsBestStreakAndBestTimeSpanAllVariants() {+ repo.recordGameWon(BoardSize.SIX, Difficulty.EASY, 111)+ repo.recordGameWon(BoardSize.NINE, Difficulty.EASY, 99)+ repo.recordGameWon(BoardSize.NINE, Difficulty.EASY, 130)+ repo.recordGameWon(BoardSize.TWELVE, Difficulty.EXPERT, 700)++ assertEquals(4, repo.getTotalGamesWon())+ assertEquals(2, repo.getBestWinStreak())+ assertEquals(99, repo.getBestTime(Difficulty.EASY))+ assertEquals(700, repo.getBestTime(Difficulty.EXPERT))+ assertNull(repo.getBestTime(Difficulty.HARD))+ }++ @Test+ fun statsPersistAcrossRepositoryInstances() {+ repo.recordGamePlayed(BoardSize.TWELVE, Difficulty.MEDIUM)+ repo.recordGameWon(BoardSize.TWELVE, Difficulty.MEDIUM, 42)+ val reopened = SudokuStatsRepository(context)+ val stats = reopened.getStats(BoardSize.TWELVE, Difficulty.MEDIUM)+ assertEquals(1, stats.gamesPlayed)+ assertEquals(1, stats.gamesWon)+ assertEquals(42, stats.bestTimeSeconds)+ }++ @Test+ fun gameStatsDefaultsDistinguishNoTimeFromInstant() {+ val stats = GameStats()+ assertEquals(Int.MAX_VALUE, stats.bestTimeSeconds)+ assertEquals(0, stats.gamesPlayed)+ assertEquals(stats, GameStats(0, 0, 0, 0, Int.MAX_VALUE))+ }+}
games/sudoku/src/test/java/com/vayunmathur/games/sudoku/platform/SudokuAchievementsAndMiscTest.kt
diff --git a/games/sudoku/src/test/java/com/vayunmathur/games/sudoku/platform/SudokuAchievementsAndMiscTest.kt b/games/sudoku/src/test/java/com/vayunmathur/games/sudoku/platform/SudokuAchievementsAndMiscTest.ktnew file mode 100644index 0000000000..f817caed07--- /dev/null+++ b/games/sudoku/src/test/java/com/vayunmathur/games/sudoku/platform/SudokuAchievementsAndMiscTest.kt@@ -0,0 +1,108 @@+package com.vayunmathur.games.sudoku.platform++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.games.sudoku.Route+import com.vayunmathur.games.sudoku.data.BoardSize+import com.vayunmathur.games.sudoku.data.Difficulty+import com.vayunmathur.games.sudoku.data.GameConfig+import com.vayunmathur.games.sudoku.data.SudokuStatsRepository+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.runBlocking+import kotlinx.serialization.json.Json+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)+class SudokuAchievementsAndMiscTest {++ private val context: Context get() = ApplicationProvider.getApplicationContext()+ private lateinit var stats: SudokuStatsRepository++ @BeforeTest+ fun setUp() {+ context.getSharedPreferences("sudoku_stats", Context.MODE_PRIVATE).edit().clear().commit()+ stats = SudokuStatsRepository(context)+ }++ private fun manager(): SudokuAchievementsManager {+ val json = context.assets.open("achievements.json").bufferedReader().readText()+ return SudokuAchievementsManager(context, json, stats)+ }++ @Test+ fun checkExistingWithNoWinsUnlocksNothingButReportsZeroProgress() {+ val manager = manager()+ manager.checkExistingAchievements()+ assertEquals(300, SudokuAchievementsManager.SPEED_SECONDS)+ val statuses = runBlocking { manager.getAchievementStatuses().first() }+ assertEquals(manager.achievements.size, statuses.size)+ assertTrue(statuses.none { it.isUnlocked } || statuses.any { it.progress == 0 })+ assertTrue(statuses.all { it.progress == 0 })+ }++ @Test+ fun checkExistingBackfillsFromSeededStats() {+ // Wins on every size, including a fast 9x9 expert win: every back-fill branch fires.+ stats.recordGameWon(BoardSize.SIX, Difficulty.EASY, 400)+ stats.recordGameWon(BoardSize.NINE, Difficulty.EXPERT, 120)+ stats.recordGameWon(BoardSize.TWELVE, Difficulty.MEDIUM, 800)+ val manager = manager()+ manager.checkExistingAchievements()+ // Calls are idempotent: a second pass must not throw or change the achievement set.+ manager.checkExistingAchievements()+ assertEquals(10, manager.achievements.size)+ assertTrue(manager.achievements.any { it.id == "every_size" })+ }++ @Test+ fun backupAgentDeclaresSudokuFiles() {+ val agent = AppBackupAgent()+ assertEquals(listOf("sudoku_stats"), agent.prefNames)+ assertEquals(listOf("datastore_default"), agent.datastoreNames)+ }++ @Test+ fun uiStateAndRejectedDigitDefaultsAndEquality() {+ val state = SudokuUiState()+ assertEquals(null, state.game)+ assertEquals(false, state.canUndo)+ assertEquals(false, state.generating)+ assertEquals(null, state.rejectedDigit)+ assertEquals(RejectedDigit(7, 2L), RejectedDigit(7, 2L))+ assertTrue(RejectedDigit(7, 2L) != RejectedDigit(7, 3L))+ assertEquals(+ SudokuUiState(generating = true),+ SudokuUiState(game = null, canUndo = false, generating = true, rejectedDigit = null),+ )+ }++ @Test+ fun noopActionsDoNothing() {+ val actions = SudokuActions.Noop+ actions.selectCell(1); actions.enterDigit(1); actions.clearCell()+ actions.toggleNotesMode(); actions.hint(); actions.undo(); actions.restart(); actions.giveUp()+ // Reaching here without effect or crash is the contract; state is the caller's.+ assertTrue(actions === SudokuActions.Noop)+ }++ @Test+ fun routesCarryConfigAndSerialize() {+ val config = GameConfig(BoardSize.TWELVE, Difficulty.EXPERT, answerMode = true)+ val route = Route.Game(config)+ assertEquals(config, route.config)+ assertEquals(Route.Home, Route.Home)+ assertEquals(Route.GameCenter, Route.GameCenter)+ assertTrue(Route.Home != Route.GameCenter)++ val encoded = Json.encodeToString(Route.serializer(), Route.Game(config))+ val decoded = Json.decodeFromString(Route.serializer(), encoded)+ assertEquals(Route.Game(config), decoded)+ val homeEncoded = Json.encodeToString(Route.serializer(), Route.Home)+ assertEquals(Route.Home, Json.decodeFromString(Route.serializer(), homeEncoded))+ }+}
games/sudoku/src/test/java/com/vayunmathur/games/sudoku/platform/SudokuViewModelTest.kt
diff --git a/games/sudoku/src/test/java/com/vayunmathur/games/sudoku/platform/SudokuViewModelTest.kt b/games/sudoku/src/test/java/com/vayunmathur/games/sudoku/platform/SudokuViewModelTest.ktnew file mode 100644index 0000000000..535d28c0a8--- /dev/null+++ b/games/sudoku/src/test/java/com/vayunmathur/games/sudoku/platform/SudokuViewModelTest.kt@@ -0,0 +1,353 @@+package com.vayunmathur.games.sudoku.platform++import android.app.Application+import android.content.Context+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.games.sudoku.data.BoardSize+import com.vayunmathur.games.sudoku.data.Difficulty+import com.vayunmathur.games.sudoku.data.GameConfig+import com.vayunmathur.games.sudoku.data.SudokuDataStore+import com.vayunmathur.games.sudoku.data.SudokuStatsRepository+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.ExperimentalCoroutinesApi+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.launch+import kotlinx.coroutines.runBlocking+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.assertNull+import kotlin.test.assertTrue++@OptIn(ExperimentalCoroutinesApi::class)+@RunWith(RobolectricTestRunner::class)+class SudokuViewModelTest {++ private val app: Application get() = ApplicationProvider.getApplicationContext()+ private val stats: SudokuStatsRepository get() = SudokuStatsRepository(app)++ @BeforeTest+ fun setUp() {+ Dispatchers.setMain(Dispatchers.Unconfined)+ app.getSharedPreferences("sudoku_stats", Context.MODE_PRIVATE).edit().clear().commit()+ runBlocking { SudokuDataStore(app).setAnswerMode(false) }+ }++ @AfterTest+ fun tearDown() = Dispatchers.resetMain()++ private fun await(desc: String, cond: () -> Boolean) {+ val deadline = System.currentTimeMillis() + 20_000+ while (System.currentTimeMillis() < deadline) {+ if (cond()) return+ Thread.sleep(25)+ }+ assertTrue(cond(), "timed out: $desc")+ }++ private fun startedVm(config: GameConfig = GameConfig(BoardSize.SIX, Difficulty.EASY)): SudokuViewModel {+ val vm = SudokuViewModel(app)+ vm.newGame(config)+ await("game dealt") { vm.uiState.value.game != null }+ return vm+ }++ private fun blank(vm: SudokuViewModel): Int {+ val game = vm.uiState.value.game!!+ return game.givens.indices.first { game.givens[it] == 0 }+ }++ private fun given(vm: SudokuViewModel): Int {+ val game = vm.uiState.value.game!!+ return game.givens.indices.first { game.givens[it] != 0 }+ }++ @Test+ fun actionsWithNoGameAreNoOps() {+ val vm = SudokuViewModel(app)+ assertNull(vm.uiState.value.game)+ assertFalse(vm.hasActiveGame())+ vm.selectCell(0); vm.enterDigit(1); vm.clearCell(); vm.toggleNotesMode()+ vm.hint(); vm.undo(); vm.restart(); vm.giveUp(); vm.incrementTimer()+ vm.dismissAchievementNotification()+ assertNull(vm.uiState.value.game)+ assertFalse(vm.uiState.value.canUndo)+ }++ @Test+ fun newGameDealsPlayablePuzzleAndRecordsPlayed() {+ val vm = startedVm()+ val state = vm.uiState.value+ val game = assertNotNull(state.game)+ assertFalse(state.generating)+ assertEquals(BoardSize.SIX, game.size)+ assertEquals(Difficulty.EASY, game.difficulty)+ assertEquals(game.solution.size, game.givens.size)+ assertTrue(game.givens.any { it == 0 })+ assertTrue(vm.hasActiveGame())+ assertEquals(1, stats.getStats(BoardSize.SIX, Difficulty.EASY).gamesPlayed)+ assertEquals(1, vm.getStats(GameConfig(BoardSize.SIX, Difficulty.EASY)).gamesPlayed)+ assertEquals(1, vm.getSizeStats(BoardSize.SIX).gamesPlayed)+ }++ @Test+ fun selectCellTogglesAndDigitPlacementEraseAndUndo() {+ val vm = startedVm()+ val cell = blank(vm)+ val game = vm.uiState.value.game!!+ val correct = game.solution[cell]++ vm.selectCell(cell)+ assertEquals(cell, vm.uiState.value.game!!.selected)+ vm.selectCell(cell)+ assertEquals(-1, vm.uiState.value.game!!.selected, "re-selecting deselects")+ vm.selectCell(cell)++ vm.enterDigit(correct)+ var after = vm.uiState.value.game!!+ assertEquals(correct, after.valueAt(cell))+ assertEquals(1, after.moveCount)+ assertTrue(vm.uiState.value.canUndo)++ // Re-tapping the shown digit erases it.+ vm.enterDigit(correct)+ after = vm.uiState.value.game!!+ assertEquals(0, after.valueAt(cell))+ assertEquals(2, after.moveCount)++ vm.enterDigit(correct)+ vm.undo()+ after = vm.uiState.value.game!!+ assertEquals(0, after.valueAt(cell), "undo restores the pre-placement board")+ assertTrue(after.usedUndo)+ assertTrue(vm.uiState.value.canUndo, "earlier snapshots remain")++ // Given cells cannot be selected for writing or cleared.+ val givenCell = given(vm)+ vm.selectCell(givenCell)+ val before = vm.uiState.value.game!!+ vm.enterDigit((before.solution[givenCell] % before.size.side) + 1)+ vm.clearCell()+ assertEquals(before.entries, vm.uiState.value.game!!.entries)+ }++ @Test+ fun notesModeTogglesPencilMarksAndClearCellClearsEntryAndNotes() {+ val vm = startedVm()+ val cell = blank(vm)+ val game = vm.uiState.value.game!!+ vm.selectCell(cell)+ vm.toggleNotesMode()+ assertTrue(vm.uiState.value.game!!.notesMode)+ vm.enterDigit(2)+ var after = vm.uiState.value.game!!+ assertEquals(1 shl 1, after.notes[cell])+ assertEquals(0, after.valueAt(cell))+ vm.enterDigit(2)+ assertEquals(0, vm.uiState.value.game!!.notes[cell], "second note tap toggles the mark off")+ vm.enterDigit(3)+ vm.toggleNotesMode()+ assertFalse(vm.uiState.value.game!!.notesMode)+ vm.clearCell()+ after = vm.uiState.value.game!!+ assertEquals(0, after.notes[cell])+ assertEquals(0, after.valueAt(cell))+ // Clearing with nothing selected is a no-op (selection is still cell, clear again harmless).+ vm.selectCell(cell)+ val snapshot = vm.uiState.value.game!!+ vm.clearCell()+ assertEquals(snapshot.moveCount, vm.uiState.value.game!!.moveCount)+ }++ @Test+ fun hintCorrectsWrongEntryFirstThenFillsSelectedBlank() {+ val vm = startedVm()+ val cell = blank(vm)+ val game = vm.uiState.value.game!!+ val wrong = (1..game.size.side).first { it != game.solution[cell] }+ vm.selectCell(cell)+ vm.enterDigit(wrong)+ assertTrue(vm.uiState.value.game!!.isWrong(cell))++ vm.hint()+ var after = vm.uiState.value.game!!+ assertEquals(game.solution[cell], after.valueAt(cell), "hint fixes the wrong cell first")+ assertEquals(1, after.hintsUsed)+ assertEquals(cell, after.selected)++ // Fill everything except one blank via hints targeted at selection, then final hint wins.+ var guard = 0+ while (!vm.uiState.value.game!!.isComplete && guard++ < 100) {+ val next = vm.uiState.value.game!!.blankIndices().firstOrNull() ?: break+ vm.selectCell(next)+ vm.hint()+ }+ after = vm.uiState.value.game!!+ assertTrue(after.isComplete)+ assertTrue(after.isWon)+ val hints = after.hintsUsed+ vm.hint()+ assertEquals(hints, vm.uiState.value.game!!.hintsUsed, "hint after win is a no-op")+ }++ @Test+ fun hintWithoutSelectionFillsFirstBlank() {+ val vm = startedVm()+ val firstBlank = blank(vm)+ vm.hint()+ val game = vm.uiState.value.game!!+ assertEquals(game.solution[firstBlank], game.valueAt(firstBlank))+ assertEquals(firstBlank, game.selected)+ assertEquals(1, game.hintsUsed)+ }++ @Test+ fun timerIncrementsAndRestartResetsProgressButKeepsPuzzle() {+ val vm = startedVm()+ val cell = blank(vm)+ val original = vm.uiState.value.game!!+ vm.selectCell(cell)+ vm.enterDigit(original.solution[cell])+ vm.incrementTimer(); vm.incrementTimer()+ assertEquals(2, vm.uiState.value.game!!.elapsedSeconds)++ vm.restart()+ val after = vm.uiState.value.game!!+ assertEquals(original.givens, after.givens)+ assertEquals(original.solution, after.solution)+ assertEquals(List(after.size.cellCount) { 0 }, after.entries)+ assertEquals(0, after.moveCount)+ assertEquals(0, after.elapsedSeconds)+ assertEquals(0, after.hintsUsed)+ assertEquals(-1, after.selected)+ assertFalse(after.isWon)+ assertFalse(vm.uiState.value.canUndo)+ assertTrue(vm.hasActiveGame())+ }++ @Test+ fun giveUpClearsGameAndBreaksStreak() {+ stats.recordGameWon(BoardSize.SIX, Difficulty.EASY, 60)+ assertEquals(1, stats.getStats(BoardSize.SIX, Difficulty.EASY).currentWinStreak)+ val vm = startedVm()+ vm.giveUp()+ assertNull(vm.uiState.value.game)+ assertFalse(vm.hasActiveGame())+ assertEquals(0, stats.getStats(BoardSize.SIX, Difficulty.EASY).currentWinStreak)+ }++ @Test+ fun completingBoardWinsRecordsStatsAndStopsTimer() {+ val vm = startedVm()+ vm.incrementTimer()+ var guard = 0+ while (guard++ < 100) {+ val game = vm.uiState.value.game!!+ val next = game.blankIndices().firstOrNull() ?: break+ vm.selectCell(next)+ vm.enterDigit(game.solution[next])+ }+ val won = vm.uiState.value.game!!+ assertTrue(won.isComplete)+ assertTrue(won.isWon)+ assertEquals(-1, won.selected)+ assertFalse(vm.hasActiveGame())+ assertEquals(1, stats.getStats(BoardSize.SIX, Difficulty.EASY).gamesWon)+ val elapsed = won.elapsedSeconds+ vm.incrementTimer()+ assertEquals(elapsed, vm.uiState.value.game!!.elapsedSeconds, "timer stops after win")+ // Further digits are ignored on a won game.+ vm.selectCell(0)+ val entries = vm.uiState.value.game!!.entries+ vm.enterDigit(1)+ assertEquals(entries, vm.uiState.value.game!!.entries)+ }++ @Test+ fun answerModeRejectsWrongDigitsCostsLivesAndEndsGame() {+ stats.recordGameWon(BoardSize.SIX, Difficulty.EASY, 60)+ val vm = startedVm(GameConfig(BoardSize.SIX, Difficulty.EASY, answerMode = true))+ val cell = blank(vm)+ val game = vm.uiState.value.game!!+ assertTrue(game.answerMode)+ assertEquals(3, game.livesRemaining)+ val wrong = (1..game.size.side).first { it != game.solution[cell] }+ vm.selectCell(cell)++ vm.enterDigit(wrong)+ var after = vm.uiState.value.game!!+ assertEquals(0, after.valueAt(cell), "rejected digit is never placed")+ assertEquals(2, after.livesRemaining)+ assertEquals(wrong, vm.uiState.value.rejectedDigit?.digit)+ assertEquals(1L, vm.uiState.value.rejectedDigit?.attempt)+ assertFalse(vm.uiState.value.canUndo, "rejection pushes no undo history")++ vm.enterDigit(wrong)+ assertEquals(2L, vm.uiState.value.rejectedDigit?.attempt, "repeat rejection gets a new attempt")+ vm.enterDigit(wrong)+ after = vm.uiState.value.game!!+ assertEquals(0, after.livesRemaining)+ assertTrue(after.isGameOver)+ assertEquals(0, stats.getStats(BoardSize.SIX, Difficulty.EASY).currentWinStreak,+ "losing the last life records a loss")+ vm.incrementTimer()+ assertEquals(0, after.elapsedSeconds)++ // Correct digits still place in answer mode (before game over this is the path); after+ // game over input is ignored, verified by unchanged entries.+ val entries = after.entries+ vm.enterDigit(after.solution[cell])+ assertEquals(entries, vm.uiState.value.game!!.entries)++ vm.restart()+ val restarted = vm.uiState.value.game!!+ assertEquals(3, restarted.livesRemaining, "restart refills lives")+ assertFalse(restarted.isGameOver)+ }++ @Test+ fun answerModeCorrectDigitPlacesWithoutCostingLife() {+ val vm = startedVm(GameConfig(BoardSize.SIX, Difficulty.EASY, answerMode = true))+ val cell = blank(vm)+ val correct = vm.uiState.value.game!!.solution[cell]+ vm.selectCell(cell)+ vm.enterDigit(correct)+ val after = vm.uiState.value.game!!+ assertEquals(correct, after.valueAt(cell))+ assertEquals(3, after.livesRemaining)+ assertNull(vm.uiState.value.rejectedDigit)+ }++ @Test+ fun setAnswerModePersistsAndFlowReflectsItWhenCollected() {+ val vm = SudokuViewModel(app)+ val collector = CoroutineScope(Dispatchers.Unconfined).launch { vm.answerMode.collect {} }+ try {+ assertFalse(vm.answerMode.value)+ vm.setAnswerMode(true)+ await("answerMode flow true") { vm.answerMode.value }+ assertTrue(runBlocking { SudokuDataStore(app).answerMode.first() })+ vm.setAnswerMode(false)+ await("answerMode flow false") { !vm.answerMode.value }+ } finally {+ collector.cancel()+ }+ }++ @Test+ fun achievementsManagerIsLoadedFromAssets() {+ val vm = SudokuViewModel(app)+ assertTrue(vm.achievementsManager.achievements.any { it.id == "first_win" })+ assertTrue(vm.achievementsManager.achievements.any { it.id == "wins_50" })+ vm.dismissAchievementNotification()+ assertNull(vm.achievementsManager.newAchievement.value)+ }+}
games/sudoku/src/test/java/com/vayunmathur/games/sudoku/ui/SudokuHomeAndGameScreenTest.kt
diff --git a/games/sudoku/src/test/java/com/vayunmathur/games/sudoku/ui/SudokuHomeAndGameScreenTest.kt b/games/sudoku/src/test/java/com/vayunmathur/games/sudoku/ui/SudokuHomeAndGameScreenTest.ktnew file mode 100644index 0000000000..decb1be75a--- /dev/null+++ b/games/sudoku/src/test/java/com/vayunmathur/games/sudoku/ui/SudokuHomeAndGameScreenTest.kt@@ -0,0 +1,164 @@+package com.vayunmathur.games.sudoku.ui++import android.app.Application+import android.content.Context+import androidx.compose.ui.test.assertCountEquals+import androidx.compose.ui.test.junit4.createComposeRule+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.sudoku.Navigation+import com.vayunmathur.games.sudoku.R+import com.vayunmathur.games.sudoku.Route+import com.vayunmathur.games.sudoku.data.BoardSize+import com.vayunmathur.games.sudoku.data.Difficulty+import com.vayunmathur.games.sudoku.data.GameConfig+import com.vayunmathur.games.sudoku.platform.SudokuViewModel+import com.vayunmathur.library.util.NavBackStack+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.ExperimentalCoroutinesApi+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.assertIs+import kotlin.test.assertTrue++@OptIn(ExperimentalCoroutinesApi::class)+@RunWith(RobolectricTestRunner::class)+class SudokuHomeAndGameScreenTest {++ @get:Rule val rule = createComposeRule()+ private val app: Application get() = ApplicationProvider.getApplicationContext()+ private val ctx: Context get() = app+ private fun str(id: Int) = ctx.getString(id)++ @BeforeTest+ fun setUp() {+ Dispatchers.setMain(Dispatchers.Unconfined)+ app.getSharedPreferences("sudoku_stats", Context.MODE_PRIVATE).edit().clear().commit()+ }++ @AfterTest+ fun tearDown() = Dispatchers.resetMain()++ private fun await(desc: String, cond: () -> Boolean) {+ val deadline = System.currentTimeMillis() + 20_000+ while (System.currentTimeMillis() < deadline) {+ if (cond()) return+ Thread.sleep(25)+ }+ assertTrue(cond(), "timed out: $desc")+ }++ private fun backStack() = NavBackStack(arrayOf<Route>(Route.Home))++ @Test+ fun homeShowsPickersStatsAndNewGameNavigatesWithChosenConfig() {+ val vm = SudokuViewModel(app)+ val stack = backStack()+ rule.setContent { HomeScreen(stack, vm) }+ rule.onNodeWithText(str(R.string.board_size)).assertExists()+ rule.onNodeWithText(str(R.string.difficulty)).assertExists()+ rule.onNodeWithText(str(R.string.answer_mode)).assertExists()+ rule.onAllNodesWithText(str(R.string.size_six)).assertCountEquals(2)+ rule.onNodeWithText(str(com.vayunmathur.library.ui.R.string.new_game)).assertExists()++ rule.onAllNodesWithText(str(R.string.size_six))[0].performClick()+ rule.onNodeWithText(str(R.string.difficulty_expert)).performClick()+ rule.onNodeWithText(str(com.vayunmathur.library.ui.R.string.new_game)).performClick()++ assertEquals(2, stack.backStack.size)+ val route = assertIs<Route.Game>(stack.backStack.last())+ assertEquals(BoardSize.SIX, route.config.size)+ assertEquals(Difficulty.EXPERT, route.config.difficulty)+ }++ @Test+ fun homeContinueResumesActiveGame() {+ val vm = SudokuViewModel(app)+ vm.newGame(GameConfig(BoardSize.SIX, Difficulty.EASY))+ await("game dealt") { vm.uiState.value.game != null }+ val stack = backStack()+ rule.setContent { HomeScreen(stack, vm) }+ rule.onNodeWithText(str(com.vayunmathur.library.ui.R.string.continue_label))+ .assertExists().performClick()+ val route = assertIs<Route.Game>(stack.backStack.last())+ assertEquals(BoardSize.SIX, route.config.size)+ assertEquals(Difficulty.EASY, route.config.difficulty)+ }++ @Test+ fun homeSizeCardsShowRecordedStats() {+ val vm = SudokuViewModel(app)+ vm.newGame(GameConfig(BoardSize.SIX, Difficulty.EASY))+ await("game dealt") { vm.uiState.value.game != null }+ // Finish it through the public actions so the win lands in the stats the cards read.+ var guard = 0+ while (guard++ < 100) {+ val game = vm.uiState.value.game!!+ val next = game.blankIndices().firstOrNull() ?: break+ vm.selectCell(next)+ vm.enterDigit(game.solution[next])+ }+ assertTrue(vm.uiState.value.game!!.isWon)+ rule.setContent { HomeScreen(backStack(), vm) }+ rule.onAllNodesWithText("1/1").assertCountEquals(1)+ rule.onAllNodesWithText(str(R.string.won)).assertCountEquals(3)+ }++ @Test+ fun gameScreenRendersDealtGameBoard() {+ val vm = SudokuViewModel(app)+ vm.newGame(GameConfig(BoardSize.SIX, Difficulty.EASY))+ await("game dealt") { vm.uiState.value.game != null }+ val stack = backStack()+ rule.setContent { GameScreen(stack, vm, GameConfig(BoardSize.SIX, Difficulty.EASY)) }+ rule.onNodeWithText(str(R.string.hint)).assertExists()+ rule.onNodeWithText(str(R.string.erase)).assertExists()+ }++ @Test+ fun gameScreenDealsWhenEnteredWithoutGame() {+ val vm = SudokuViewModel(app)+ val stack = backStack()+ rule.setContent { GameScreen(stack, vm, GameConfig(BoardSize.SIX, Difficulty.EASY)) }+ await("game dealt by GameScreen") { vm.uiState.value.game != null }+ rule.onNodeWithText(str(R.string.hint)).assertExists()+ }++ @Test+ fun navigationShowsHome() {+ val vm = SudokuViewModel(app)+ rule.setContent { Navigation(vm) }+ rule.onNodeWithText(str(com.vayunmathur.library.ui.R.string.new_game)).assertExists()+ rule.onNodeWithText(str(R.string.board_size)).assertExists()+ }++ @Test+ fun navigationNewGameOpensBoard() {+ val vm = SudokuViewModel(app)+ rule.setContent { Navigation(vm) }+ rule.onNodeWithText(str(com.vayunmathur.library.ui.R.string.new_game)).performClick()+ await("game dealt via navigation") { vm.uiState.value.game != null }+ rule.onNodeWithText(str(R.string.hint)).assertExists()+ rule.onNodeWithText(str(R.string.erase)).assertExists()+ }++ @Test+ fun navigationGameCenterOpensAndBackReturnsHome() {+ val vm = SudokuViewModel(app)+ rule.setContent { Navigation(vm) }+ // The app-bar trophy carries the Badges icon description.+ rule.onNodeWithContentDescription("Badges").performClick()+ rule.onNodeWithText(str(com.vayunmathur.library.ui.R.string.title_game_center)).assertExists()+ rule.onNodeWithText("Solved").assertExists()+ }+}
games/sudoku/src/test/java/com/vayunmathur/games/sudoku/ui/SudokuScreensTest.kt
diff --git a/games/sudoku/src/test/java/com/vayunmathur/games/sudoku/ui/SudokuScreensTest.kt b/games/sudoku/src/test/java/com/vayunmathur/games/sudoku/ui/SudokuScreensTest.ktnew file mode 100644index 0000000000..22e27becb5--- /dev/null+++ b/games/sudoku/src/test/java/com/vayunmathur/games/sudoku/ui/SudokuScreensTest.kt@@ -0,0 +1,236 @@+package com.vayunmathur.games.sudoku.ui++import android.content.Context+import androidx.compose.foundation.layout.Column+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.setValue+import androidx.compose.ui.test.assertCountEquals+import androidx.compose.ui.test.assertIsNotEnabled+import androidx.compose.ui.test.junit4.createComposeRule+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.sudoku.R+import com.vayunmathur.games.sudoku.data.BoardSize+import com.vayunmathur.games.sudoku.data.Difficulty+import com.vayunmathur.games.sudoku.data.SudokuGameState+import com.vayunmathur.games.sudoku.domain.SudokuGenerator+import com.vayunmathur.games.sudoku.platform.RejectedDigit+import com.vayunmathur.games.sudoku.platform.SudokuActions+import com.vayunmathur.games.sudoku.platform.SudokuUiState+import com.vayunmathur.library.ui.Text+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.random.Random+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)+class SudokuScreensTest {++ @get:Rule val rule = createComposeRule()+ private val ctx: Context get() = ApplicationProvider.getApplicationContext()+ private fun str(id: Int) = ctx.getString(id)++ private class RecordingActions : SudokuActions {+ val digits = mutableListOf<Int>()+ val cells = mutableListOf<Int>()+ var notesToggles = 0+ var clears = 0+ var hints = 0+ var undos = 0+ var restarts = 0+ var giveUps = 0+ override fun selectCell(index: Int) { cells += index }+ override fun enterDigit(digit: Int) { digits += digit }+ override fun clearCell() { clears++ }+ override fun toggleNotesMode() { notesToggles++ }+ override fun hint() { hints++ }+ override fun undo() { undos++ }+ override fun restart() { restarts++ }+ override fun giveUp() { giveUps++ }+ }++ private fun freshGame(+ size: BoardSize = BoardSize.SIX,+ difficulty: Difficulty = Difficulty.EASY,+ answerMode: Boolean = false,+ ): SudokuGameState {+ val puzzle = SudokuGenerator.generate(size, difficulty, Random(1))+ return SudokuGameState.from(puzzle, answerMode = answerMode)+ }++ @Test+ fun boardShowsSpinnerStateWhenNoGame() {+ var exits = 0+ rule.setContent {+ GameBoardScreen(state = SudokuUiState(), actions = SudokuActions.Noop, onExit = { exits++ })+ }+ rule.onNodeWithText(str(R.string.app_name)).assertExists()+ assertEquals(0, exits)+ }++ @Test+ fun boardActionsDigitAndCellClicksReachActions() {+ val actions = RecordingActions()+ val game = freshGame()+ var exits = 0+ rule.setContent {+ GameBoardScreen(+ state = SudokuUiState(game = game, canUndo = true),+ actions = actions,+ onExit = { exits++ },+ )+ }+ rule.onNodeWithContentDescription(ctx.getString(R.string.cd_digit_key, "1")).performClick()+ assertEquals(listOf(1), actions.digits)++ rule.onNodeWithText(str(R.string.notes)).performClick()+ rule.onNodeWithText(str(R.string.erase)).performClick()+ rule.onNodeWithText(str(com.vayunmathur.library.ui.R.string.undo)).performClick()+ rule.onNodeWithText(str(R.string.hint)).performClick()+ assertEquals(1, actions.notesToggles)+ assertEquals(1, actions.clears)+ assertEquals(1, actions.undos)+ assertEquals(1, actions.hints)+ assertEquals(0, exits)+ }++ @Test+ fun boardUndoDisabledWithoutHistoryAndGiveUpDialogDismisses() {+ val actions = RecordingActions()+ rule.setContent {+ GameBoardScreen(+ state = SudokuUiState(game = freshGame(), canUndo = false),+ actions = actions,+ onExit = {},+ )+ }+ rule.onNodeWithText(str(com.vayunmathur.library.ui.R.string.undo)).assertIsNotEnabled()+ rule.onNodeWithText(str(R.string.give_up)).performClick()+ rule.onNodeWithText(str(R.string.confirm_give_up_title)).assertExists()+ rule.onNodeWithText(str(R.string.confirm_give_up_message)).assertExists()+ rule.onNodeWithText(str(com.vayunmathur.library.ui.R.string.cancel)).performClick()+ rule.onNodeWithText(str(R.string.confirm_give_up_title)).assertDoesNotExist()+ assertEquals(0, actions.giveUps)+ }++ @Test+ fun boardGiveUpDialogConfirmGivesUpAndExits() {+ val actions = RecordingActions()+ var exits = 0+ rule.setContent {+ GameBoardScreen(+ state = SudokuUiState(game = freshGame()),+ actions = actions,+ onExit = { exits++ },+ )+ }+ rule.onNodeWithText(str(R.string.give_up)).performClick()+ // Two "Give Up" labels exist (board button + dialog confirm); click every match's last.+ val nodes = rule.onAllNodesWithText(str(R.string.give_up))+ nodes[1].performClick()+ assertEquals(1, actions.giveUps)+ assertEquals(1, exits)+ }++ @Test+ fun wonBoardShowsOverlayStatsAndPlayAgainRestarts() {+ val actions = RecordingActions()+ val base = freshGame()+ val entries = List(base.size.cellCount) { if (base.isGiven(it)) 0 else base.solution[it] }+ val won = base.copy(entries = entries, isWon = true, hintsUsed = 2, elapsedSeconds = 65)+ rule.setContent {+ GameBoardScreen(state = SudokuUiState(game = won), actions = actions, onExit = {})+ }+ rule.onNodeWithText(str(R.string.congratulations)).assertExists()+ rule.onAllNodesWithText("${str(R.string.hints_used)}: 2").assertCountEquals(2)+ rule.onNodeWithText("Play Again").performClick()+ assertEquals(1, actions.restarts)+ }++ @Test+ fun wonBoardGiveUpSkipsConfirmation() {+ val actions = RecordingActions()+ var exits = 0+ val base = freshGame()+ val entries = List(base.size.cellCount) { if (base.isGiven(it)) 0 else base.solution[it] }+ val won = base.copy(entries = entries, isWon = true)+ rule.setContent {+ GameBoardScreen(state = SudokuUiState(game = won), actions = actions, onExit = { exits++ })+ }+ // Overlay covers the board's Give Up button, so this asserts the overlay renders instead;+ // the direct give-up branch is covered by the dialog tests with an unfinished game.+ rule.onNodeWithText(str(R.string.congratulations)).assertExists()+ assertEquals(0, actions.giveUps)+ assertEquals(0, exits)+ }++ @Test+ fun gameOverBoardShowsOutOfLivesAndTryAgainRestarts() {+ val actions = RecordingActions()+ val over = freshGame(answerMode = true).copy(livesRemaining = 0, hintsUsed = 1)+ assertTrue(over.isGameOver)+ rule.setContent {+ GameBoardScreen(+ state = SudokuUiState(game = over, rejectedDigit = RejectedDigit(2, 1L)),+ actions = actions,+ onExit = {},+ )+ }+ rule.onNodeWithText(str(R.string.out_of_lives)).assertExists()+ rule.onNodeWithText(str(R.string.out_of_lives_message)).assertExists()+ rule.onNodeWithText(str(R.string.try_again)).performClick()+ assertEquals(1, actions.restarts)+ }++ @Test+ fun answerModeBoardShowsHintsAndNotesModeState() {+ val actions = RecordingActions()+ val game = freshGame(answerMode = true).copy(notesMode = true, hintsUsed = 3, livesRemaining = 2)+ rule.setContent {+ GameBoardScreen(state = SudokuUiState(game = game), actions = actions, onExit = {})+ }+ rule.onNodeWithText("${str(R.string.hints_used)}: 3").assertExists()+ rule.onNodeWithText(str(R.string.notes)).assertExists().performClick()+ assertEquals(1, actions.notesToggles)+ }++ @Test+ fun boardRendersForEverySizeWithEntriesAndNotes() {+ var current by mutableStateOf(SudokuUiState(game = freshGame()))+ rule.setContent {+ GameBoardScreen(state = current, actions = SudokuActions.Noop, onExit = {})+ }+ for (size in BoardSize.entries) {+ val base = freshGame(size, Difficulty.MEDIUM)+ val blank = base.givens.indices.first { base.givens[it] == 0 }+ val notes = base.notes.toMutableList().also { it[blank] = 0b101 }+ val styled = base.copy(notes = notes, selected = blank, elapsedSeconds = 3661)+ current = SudokuUiState(game = styled)+ rule.onNodeWithText(str(R.string.hint)).assertExists()+ }+ }++ @Test+ fun displayNamesCoverEverySizeAndDifficulty() {+ rule.setContent {+ Column {+ for (size in BoardSize.entries) Text(size.displayName())+ for (difficulty in Difficulty.entries) Text(difficulty.displayName())+ }+ }+ rule.onNodeWithText(str(R.string.size_six)).assertExists()+ rule.onNodeWithText(str(R.string.size_nine)).assertExists()+ rule.onNodeWithText(str(R.string.size_twelve)).assertExists()+ rule.onNodeWithText(str(R.string.difficulty_expert)).assertExists()+ rule.onNodeWithText(str(com.vayunmathur.library.ui.R.string.easy)).assertExists()+ rule.onNodeWithText(str(com.vayunmathur.library.ui.R.string.medium)).assertExists()+ rule.onNodeWithText(str(com.vayunmathur.library.ui.R.string.hard)).assertExists()+ }+}
games/sudoku/src/test/java/com/vayunmathur/games/sudoku/ui/components/SudokuComponentsTest.kt
diff --git a/games/sudoku/src/test/java/com/vayunmathur/games/sudoku/ui/components/SudokuComponentsTest.kt b/games/sudoku/src/test/java/com/vayunmathur/games/sudoku/ui/components/SudokuComponentsTest.ktnew file mode 100644index 0000000000..0feaecad4c--- /dev/null+++ b/games/sudoku/src/test/java/com/vayunmathur/games/sudoku/ui/components/SudokuComponentsTest.kt@@ -0,0 +1,136 @@+package com.vayunmathur.games.sudoku.ui.components++import android.content.Context+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.setValue+import androidx.compose.ui.test.assertIsNotEnabled+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithContentDescription+import androidx.compose.ui.test.performClick+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.games.sudoku.R+import com.vayunmathur.games.sudoku.data.BoardSize+import com.vayunmathur.games.sudoku.data.Difficulty+import com.vayunmathur.games.sudoku.data.SudokuGameState+import com.vayunmathur.games.sudoku.domain.SudokuGenerator+import com.vayunmathur.games.sudoku.platform.RejectedDigit+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.random.Random+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)+class SudokuComponentsTest {++ @get:Rule val rule = createComposeRule()+ private val ctx: Context get() = ApplicationProvider.getApplicationContext()++ private fun game(+ size: BoardSize = BoardSize.SIX,+ notesMode: Boolean = false,+ answerMode: Boolean = false,+ ): SudokuGameState {+ val puzzle = SudokuGenerator.generate(size, Difficulty.EASY, Random(1))+ return SudokuGameState.from(puzzle, answerMode = answerMode).copy(notesMode = notesMode)+ }++ private fun cellDesc(game: SudokuGameState, index: Int): String {+ val side = game.size.side+ val spoken = if (game.valueAt(index) == 0) ctx.getString(R.string.cd_empty)+ else com.vayunmathur.games.sudoku.data.sudokuSymbol(game.valueAt(index))+ return ctx.getString(R.string.cd_cell, index / side + 1, index % side + 1, spoken)+ }++ @Test+ fun gridRendersCellsAndReportsSelection() {+ val game = game()+ val selected = mutableListOf<Int>()+ rule.setContent { SudokuGrid(game = game, onSelect = { selected += it }) }+ rule.onNodeWithContentDescription(cellDesc(game, 0)).assertExists().performClick()+ rule.onNodeWithContentDescription(cellDesc(game, game.size.side + 1)).performClick()+ assertEquals(listOf(0, game.size.side + 1), selected)+ }++ @Test+ fun gridRendersNotesSelectionAndSameValueStatesForAllSizes() {+ var clicks = 0+ var current by mutableStateOf(game())+ rule.setContent { SudokuGrid(game = current, onSelect = { clicks++ }) }+ for (size in BoardSize.entries) {+ val base = game(size)+ val blank = base.givens.indices.first { base.givens[it] == 0 }+ val mask = (1 shl 0) or (1 shl (size.side - 1))+ val notes = base.notes.toMutableList().also { it[blank] = mask }+ val entryIndex = base.givens.indices.last { base.givens[it] == 0 }+ val entries = base.entries.toMutableList().also { it[entryIndex] = base.solution[entryIndex] }+ val styled = base.copy(notes = notes, entries = entries, selected = entryIndex)+ current = styled+ clicks = 0+ rule.onNodeWithContentDescription(cellDesc(styled, blank)).assertExists().performClick()+ assertEquals(1, clicks, "size $size")+ }+ }++ @Test+ fun numberPadReportsDigitsForAllSizes() {+ val tapped = mutableListOf<Int>()+ var current by mutableStateOf(game())+ rule.setContent { NumberPad(game = current, onDigit = { tapped += it }) }+ for (size in BoardSize.entries) {+ tapped.clear()+ current = game(size)+ val label = com.vayunmathur.games.sudoku.data.sudokuSymbol(size.side)+ rule.onNodeWithContentDescription(ctx.getString(R.string.cd_digit_key, label))+ .assertExists().performClick()+ rule.onNodeWithContentDescription(ctx.getString(R.string.cd_digit_key, "1")).performClick()+ assertEquals(listOf(size.side, 1), tapped, "size $size")+ }+ }++ @Test+ fun numberPadNotesModeUsesNoteKeys() {+ val tapped = mutableListOf<Int>()+ rule.setContent { NumberPad(game = game(notesMode = true), onDigit = { tapped += it }) }+ rule.onNodeWithContentDescription(ctx.getString(R.string.cd_note_key, "3"))+ .assertExists().performClick()+ assertEquals(listOf(3), tapped)+ }++ @Test+ fun numberPadDisablesCompletedDigitOnlyInAnswerModeAndShowsRejection() {+ // Fill every copy of digit 1 correctly, so in answer mode its key is done.+ val base = game(answerMode = true)+ val entries = base.entries.toMutableList()+ for (index in base.solution.indices) {+ if (base.solution[index] == 1 && base.givens[index] == 0) entries[index] = 1+ }+ val completed = base.copy(entries = entries)+ assertTrue(completed.isDigitComplete(1))+ val tapped = mutableListOf<Int>()+ rule.setContent {+ NumberPad(game = completed, onDigit = { tapped += it }, rejected = RejectedDigit(2, 1L))+ }+ rule.onNodeWithContentDescription(ctx.getString(R.string.cd_digit_key, "1"))+ .assertIsNotEnabled()+ rule.onNodeWithContentDescription(ctx.getString(R.string.cd_digit_key, "2"))+ .assertExists().performClick()+ assertEquals(listOf(2), tapped, "only the enabled key reports a tap")++ // Same completed digit stays enabled in classic mode.+ rule.onNodeWithContentDescription(ctx.getString(R.string.cd_digit_key, "3")).performClick()+ assertEquals(listOf(2, 3), tapped)+ }++ @Test+ fun numberPadTwelveUsesLetterKeys() {+ val tapped = mutableListOf<Int>()+ rule.setContent { NumberPad(game = game(BoardSize.TWELVE), onDigit = { tapped += it }) }+ rule.onNodeWithContentDescription(ctx.getString(R.string.cd_digit_key, "A")).performClick()+ rule.onNodeWithContentDescription(ctx.getString(R.string.cd_digit_key, "C")).performClick()+ assertEquals(listOf(10, 12), tapped)+ }+}