games-sudoku: add solver, ViewModel and portrait tests (#tests)
- Commit
92054e56d30bcbcb30d56ca79270de6fa0063a9d- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-16 13:30 UTC (19 days ago)
- Parents
a21b366
Coverage wave 3 for :games:sudoku. The module already had a broad suite, so the report showed only 676 missed instructions out of 10518 at baseline; the +2000 gain target cannot be reached from missed instructions that do not exist. These tests close the reachable gaps the fresh report actually listed instead. - domain: a known 9x9 puzzle solves to its known grid, one-clue digs stay unique, column/box contradictions and a candidate-less cell are rejected, the solver recovers after a failed load, and generated puzzles across seeds and difficulties are sub-grids of their unique legal solution. - platform: 9x9, Expert and every-size win paths record the right stats variants, give-up after a win records no loss, hints with a given or filled selection fill the first blank, undo history is capped at 200 and exhausts cleanly, restart after an answer-mode loss keeps the puzzle and its rules, and re-tap erase clears the cell notes. - data: cross-size best times, sparse size aggregation with best-streak/min-time semantics, GameStats serialization with unknown keys, given-over-entry precedence, column/box/three-way conflicts, digit-complete overshoot, and DataStore flows emitting every change while collected. - ui: the portrait (stacked) GameBoardScreen branch that the landscape suites never composed, won and out-of-lives overlays in portrait, a 12x12 portrait board with letter note keys, a settled rejection flash, home settings switches toggling the ViewModel flows, GameCenter back navigation, GameScreen back pop, and a native-graphics grid draw test that finally rasterises the grid lines Robolectric legacy graphics never draws. Dead code: none deleted. The only main-source symbols with no in-module caller are public API surface (SudokuStatsRepository. getBestTime, SudokuViewModel.hasActiveGame) already exercised by tests, plus framework entry points, so none is provably dead. Verified: createMergedCoverageReport INSTRUCTION covered 9842 -> 10203 (+361, missed 676 -> 315); 166 tests, 0 failures. ./gradlew :games:sudoku:testDevUnitTest :games:sudoku:detekt :games:sudoku:lint without the ignore-failures init is green.
Diff
games/sudoku/src/test/java/com/vayunmathur/games/sudoku/data/SudokuStatsDeepTest.kt
diff --git a/games/sudoku/src/test/java/com/vayunmathur/games/sudoku/data/SudokuStatsDeepTest.kt b/games/sudoku/src/test/java/com/vayunmathur/games/sudoku/data/SudokuStatsDeepTest.ktnew file mode 100644index 0000000000..6634034f24--- /dev/null+++ b/games/sudoku/src/test/java/com/vayunmathur/games/sudoku/data/SudokuStatsDeepTest.kt@@ -0,0 +1,174 @@+package com.vayunmathur.games.sudoku.data++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import kotlinx.coroutines.async+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.flow.take+import kotlinx.coroutines.flow.toList+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.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Stats aggregation and board-state rules beyond the first suite: cross-size+ * best times, sparse per-difficulty records, column/box conflicts, and the+ * given-over-entry precedence of [SudokuGameState.valueAt].+ */+@RunWith(RobolectricTestRunner::class)+class SudokuStatsDeepTest {++ 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 dataStoreFlowsEmitEveryChangeWhileCollected() = runBlocking {+ val store = SudokuDataStore(context)+ // Whatever a previous test left stored, toggling away and back is two real changes.+ val answerStart = store.answerMode.first()+ val answerSeen = async { store.answerMode.take(3).toList() }+ store.setAnswerMode(!answerStart)+ store.setAnswerMode(answerStart)+ assertEquals(listOf(answerStart, !answerStart, answerStart), answerSeen.await())++ val highlightStart = store.highlightMistakes.first()+ val highlightSeen = async { store.highlightMistakes.take(3).toList() }+ store.setHighlightMistakes(!highlightStart)+ store.setHighlightMistakes(highlightStart)+ assertEquals(listOf(highlightStart, !highlightStart, highlightStart), highlightSeen.await())+ }++ @Test+ fun bestTimeIsTheFastestWinForThatDifficultyAcrossSizes() {+ repo.recordGameWon(BoardSize.SIX, Difficulty.EASY, 500)+ repo.recordGameWon(BoardSize.NINE, Difficulty.EASY, 300)+ repo.recordGameWon(BoardSize.TWELVE, Difficulty.EASY, 400)+ repo.recordGameWon(BoardSize.NINE, Difficulty.HARD, 250)+ assertEquals(300, repo.getBestTime(Difficulty.EASY))+ assertEquals(250, repo.getBestTime(Difficulty.HARD))+ assertNull(repo.getBestTime(Difficulty.MEDIUM))+ // A loss records no time and must not disturb the best.+ repo.recordGameLost(BoardSize.NINE, Difficulty.EASY)+ assertEquals(300, repo.getBestTime(Difficulty.EASY))+ }++ @Test+ fun sizeStatsWithSparseDifficultiesTakeMaxStreakAndMinTime() {+ repo.recordGameWon(BoardSize.NINE, Difficulty.EASY, 600)+ repo.recordGameWon(BoardSize.NINE, Difficulty.EASY, 550)+ repo.recordGameWon(BoardSize.NINE, Difficulty.EXPERT, 200)+ // Only EASY and EXPERT have records; the aggregate must not invent the others.+ val agg = repo.getSizeStats(BoardSize.NINE)+ assertEquals(3, agg.gamesWon)+ assertEquals(0, agg.gamesPlayed, "wins recorded directly do not count as played")+ assertEquals(2, agg.currentWinStreak, "the best current streak, not the sum")+ assertEquals(2, agg.bestWinStreak)+ assertEquals(200, agg.bestTimeSeconds)+ assertEquals(2, repo.getBestWinStreak())+ assertEquals(3, repo.getTotalGamesWon())+ }++ @Test+ fun streakAcrossSizesIsTheBestSingleSizeStreak() {+ repeat(3) { repo.recordGameWon(BoardSize.SIX, Difficulty.MEDIUM, 100 + it) }+ repeat(2) { repo.recordGameWon(BoardSize.TWELVE, Difficulty.MEDIUM, 800 + it) }+ repo.recordGameLost(BoardSize.SIX, Difficulty.MEDIUM)+ assertEquals(3, repo.getBestWinStreak(), "best streak is historical: the 6x6 record of 3 stands")+ assertEquals(0, repo.getStats(BoardSize.SIX, Difficulty.MEDIUM).currentWinStreak)+ assertEquals(3, repo.getStats(BoardSize.SIX, Difficulty.MEDIUM).bestWinStreak)+ assertEquals(5, repo.getTotalGamesWon())+ }++ @Test+ fun gameStatsSerializesAndDefaultsRoundTrip() {+ val stats = GameStats(gamesPlayed = 4, gamesWon = 3, currentWinStreak = 2, bestWinStreak = 2, bestTimeSeconds = 77)+ // The repository's own Json configuration, which tolerates unknown keys.+ val json = Json { ignoreUnknownKeys = true }+ val decoded = json.decodeFromString<GameStats>(json.encodeToString(GameStats.serializer(), stats))+ assertEquals(stats, decoded)+ // Unknown keys from a newer version must not break decoding of an older record.+ val withExtra = json.decodeFromString<GameStats>("""{"gamesPlayed":1,"futureField":true}""")+ assertEquals(1, withExtra.gamesPlayed)+ assertEquals(Int.MAX_VALUE, withExtra.bestTimeSeconds)+ }++ @Test+ fun valueAtPrefersTheGivenOverAnyStoredEntry() {+ val givens = MutableList(36) { 0 }.also { it[10] = 5 }+ val entries = MutableList(36) { 0 }.also { it[10] = 2; it[11] = 3 }+ val state = SudokuGameState(+ size = BoardSize.SIX, difficulty = Difficulty.EASY,+ givens = givens, solution = List(36) { 1 },+ entries = entries, notes = List(36) { 0 },+ )+ assertEquals(5, state.valueAt(10), "the printed clue always wins over a stored entry")+ assertEquals(3, state.valueAt(11))+ assertTrue(state.isGiven(10))+ assertFalse(state.isGiven(11))+ }++ @Test+ fun conflictsAreFoundInColumnsAndBoxesNotJustRows() {+ fun stateWith(vararg placements: Pair<Int, Int>): SudokuGameState {+ val entries = MutableList(36) { 0 }+ placements.forEach { (index, digit) -> entries[index] = digit }+ return SudokuGameState(+ size = BoardSize.SIX, difficulty = Difficulty.EASY,+ givens = List(36) { 0 }, solution = List(36) { 1 },+ entries = entries, notes = List(36) { 0 },+ )+ }+ // Same column (0 and 12 are two rows apart in column 0), different rows and boxes.+ assertEquals(setOf(0, 12), stateWith(0 to 4, 12 to 4).conflictingIndices())+ // Same 2x3 box (0 and 7), different row and column.+ assertEquals(setOf(0, 7), stateWith(0 to 6, 7 to 6).conflictingIndices())+ // Different row, column and box: no conflict even with the same digit.+ assertTrue(stateWith(0 to 4, 15 to 4).conflictingIndices().isEmpty())+ // Three copies of one digit in a row mark all three cells.+ assertEquals(setOf(0, 1, 2), stateWith(0 to 3, 1 to 3, 2 to 3).conflictingIndices())+ }++ @Test+ fun digitCompleteCountsDuplicatesAndOvershoot() {+ val entries = MutableList(36) { 0 }+ // Seven copies of 5 on a 6x6 (one too many): complete, and never negative-counted.+ for (index in 0..6) entries[index] = 5+ val state = SudokuGameState(+ size = BoardSize.SIX, difficulty = Difficulty.EASY,+ givens = List(36) { 0 }, solution = List(36) { 1 },+ entries = entries, notes = List(36) { 0 },+ )+ assertTrue(state.isDigitComplete(5))+ assertFalse(state.isDigitComplete(4))+ assertEquals(36 - 7, state.blankIndices().size)+ }++ @Test+ fun everyClueOfACompleteBoardMatchesAndWrongListIsSorted() {+ val solution = (0 until 36).map { (it % 6) + 1 }+ val state = SudokuGameState(+ size = BoardSize.SIX, difficulty = Difficulty.EASY,+ givens = List(36) { 0 }, solution = solution,+ entries = solution.toMutableList().also { it[20] = 1; it[3] = 2 },+ notes = List(36) { 0 },+ )+ // Entries were copied from the solution, so indices 3 and 20 are wrong only+ // if the replacement differs there; compute the expectation from the data.+ val expectedWrong = state.entries.indices.filter { state.entries[it] != solution[it] }+ assertEquals(expectedWrong, state.wrongIndices())+ assertEquals(expectedWrong.isEmpty(), state.isComplete)+ }+}
games/sudoku/src/test/java/com/vayunmathur/games/sudoku/domain/SudokuSolverDeepTest.kt
diff --git a/games/sudoku/src/test/java/com/vayunmathur/games/sudoku/domain/SudokuSolverDeepTest.kt b/games/sudoku/src/test/java/com/vayunmathur/games/sudoku/domain/SudokuSolverDeepTest.ktnew file mode 100644index 0000000000..35d4630d69--- /dev/null+++ b/games/sudoku/src/test/java/com/vayunmathur/games/sudoku/domain/SudokuSolverDeepTest.kt@@ -0,0 +1,161 @@+package com.vayunmathur.games.sudoku.domain++import com.vayunmathur.games.sudoku.data.BoardSize+import com.vayunmathur.games.sudoku.data.Difficulty+import kotlin.random.Random+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotEquals+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Deeper solver/generator rules than the smoke-level suites: a known published+ * puzzle must solve to its known grid, contradictions in each kind of unit must+ * be rejected, and every generated puzzle must be a sub-grid of its own unique+ * solution.+ */+class SudokuSolverDeepTest {++ private val classicPuzzle = listOf(+ 5, 3, 0, 0, 7, 0, 0, 0, 0,+ 6, 0, 0, 1, 9, 5, 0, 0, 0,+ 0, 9, 8, 0, 0, 0, 0, 6, 0,+ 8, 0, 0, 0, 6, 0, 0, 0, 3,+ 4, 0, 0, 8, 0, 3, 0, 0, 1,+ 7, 0, 0, 0, 2, 0, 0, 0, 6,+ 0, 6, 0, 0, 0, 0, 2, 8, 0,+ 0, 0, 0, 4, 1, 9, 0, 0, 5,+ 0, 0, 0, 0, 8, 0, 0, 7, 9,+ )+ private val classicSolution = listOf(+ 5, 3, 4, 6, 7, 8, 9, 1, 2,+ 6, 7, 2, 1, 9, 5, 3, 4, 8,+ 1, 9, 8, 3, 4, 2, 5, 6, 7,+ 8, 5, 9, 7, 6, 1, 4, 2, 3,+ 4, 2, 6, 8, 5, 3, 7, 9, 1,+ 7, 1, 3, 9, 2, 4, 8, 5, 6,+ 9, 6, 1, 5, 3, 7, 2, 8, 4,+ 2, 8, 7, 4, 1, 9, 6, 3, 5,+ 3, 4, 5, 2, 8, 6, 1, 7, 9,+ )++ @Test+ fun knownPuzzleSolvesToItsKnownSolution() {+ val solver = SudokuSolver(BoardSize.NINE)+ assertEquals(classicSolution, solver.solve(classicPuzzle))+ assertEquals(1, SudokuSolver(BoardSize.NINE).countSolutions(classicPuzzle))+ // Every given survives into the solution at the same index.+ classicPuzzle.forEachIndexed { index, given ->+ if (given != 0) assertEquals(given, classicSolution[index], "given at $index")+ }+ }++ @Test+ fun removingOneClueFromAFullGridKeepsItUnique() {+ val solver = SudokuSolver(BoardSize.NINE)+ for (index in listOf(0, 40, 80)) {+ val dug = classicSolution.toMutableList().also { it[index] = 0 }+ assertEquals(1, solver.countSolutions(dug), "one blank at $index")+ assertEquals(classicSolution, solver.solve(dug))+ }+ }++ @Test+ fun contradictionsInColumnAndBoxAreRejected() {+ val size = BoardSize.SIX+ val columnClash = blank(size).toMutableList().also { it[0] = 4; it[size.side] = 4 }+ assertNull(SudokuSolver(size).solve(columnClash))+ assertEquals(0, SudokuSolver(size).countSolutions(columnClash))++ // Index 7 is row 1, column 1 on a 6x6: same 2x3 box as index 0, different row and column.+ val boxClash = blank(size).toMutableList().also { it[0] = 2; it[7] = 2 }+ assertNull(SudokuSolver(size).solve(boxClash))+ assertEquals(0, SudokuSolver(size).countSolutions(boxClash))+ }++ @Test+ fun aCellWithNoCandidatesIsUnsolvableWithoutAnyDuplicate() {+ val size = BoardSize.SIX+ // Cell 0 sees 2..6 in its row and 1 in its column: legal givens, no way to fill it.+ val grid = blank(size).toMutableList().also {+ it[1] = 2; it[2] = 3; it[3] = 4; it[4] = 5; it[5] = 6; it[size.side] = 1+ }+ assertNull(SudokuSolver(size).solve(grid))+ assertEquals(0, SudokuSolver(size).countSolutions(grid))+ }++ @Test+ fun solverRecoversAfterAFailedLoad() {+ val size = BoardSize.SIX+ val solver = SudokuSolver(size)+ val bad = blank(size).toMutableList().also { it[0] = 1; it[1] = 1 }+ assertNull(solver.solve(bad))+ // The scratch masks must be reset by the next load, not left poisoned by the clash.+ val solved = assertNotNull(solver.solve(blank(size), Random(3)))+ assertLegal(size, solved)+ assertEquals(1, solver.countSolutions(solved))+ }++ @Test+ fun unseededSolveIsTheDeterministicFirstCompletion() {+ val size = BoardSize.SIX+ val first = SudokuSolver(size).solve(blank(size))+ val second = SudokuSolver(size).solve(blank(size))+ assertEquals(first, second, "without an rng the digit order never changes")+ assertEquals((1..size.side).toList(), first!!.take(size.side), "first row is dealt in order")+ }++ @Test+ fun twelveByTwelveSolutionUsesLettersRangeDigits() {+ val size = BoardSize.TWELVE+ val solved = assertNotNull(SudokuSolver(size).solve(blank(size), Random(9)))+ assertLegal(size, solved)+ assertEquals((1..12).toSet(), solved.take(12).toSet())+ assertTrue(solved.all { it in 1..12 })+ }++ @Test+ fun generatedPuzzlesAreSubGridsOfTheirUniqueSolutionForManySeeds() {+ for (seed in 1L..4L) {+ for (difficulty in Difficulty.entries) {+ val puzzle = SudokuGenerator.generate(BoardSize.NINE, difficulty, Random(seed))+ assertLegal(BoardSize.NINE, puzzle.solution)+ puzzle.givens.forEachIndexed { index, given ->+ assertTrue(given == 0 || given == puzzle.solution[index], "seed $seed index $index")+ }+ assertEquals(1, SudokuSolver(BoardSize.NINE).countSolutions(puzzle.givens))+ val clues = puzzle.givens.count { it != 0 }+ assertTrue(clues >= difficulty.targetClues(BoardSize.NINE))+ assertTrue(clues < BoardSize.NINE.cellCount, "there must be blanks to play")+ }+ }+ }++ @Test+ fun generatedSixAndTwelveKeepUniquenessAcrossSeeds() {+ for (seed in listOf(5L, 6L)) {+ val six = SudokuGenerator.generate(BoardSize.SIX, Difficulty.HARD, Random(seed))+ assertEquals(1, SudokuSolver(BoardSize.SIX).countSolutions(six.givens))+ assertLegal(BoardSize.SIX, six.solution)+ }+ val twelve = SudokuGenerator.generate(BoardSize.TWELVE, Difficulty.MEDIUM, Random(5))+ assertEquals(1, SudokuSolver(BoardSize.TWELVE).countSolutions(twelve.givens))+ assertLegal(BoardSize.TWELVE, twelve.solution)+ assertNotEquals(+ SudokuGenerator.generate(BoardSize.NINE, Difficulty.MEDIUM, Random(1)).givens,+ SudokuGenerator.generate(BoardSize.NINE, Difficulty.MEDIUM, Random(2)).givens,+ )+ }++ @Test+ fun countWithZeroLimitBehaviourOnCompleteGrid() {+ val size = BoardSize.SIX+ val solved = assertNotNull(SudokuSolver(size).solve(blank(size), Random(7)))+ assertEquals(1, SudokuSolver(size).countSolutions(solved, limit = 100))+ // Asking again on the same instance still sees the same complete grid.+ val solver = SudokuSolver(size)+ assertEquals(solved, solver.solve(solved))+ }+}
games/sudoku/src/test/java/com/vayunmathur/games/sudoku/platform/SudokuViewModelDeepTest.kt
diff --git a/games/sudoku/src/test/java/com/vayunmathur/games/sudoku/platform/SudokuViewModelDeepTest.kt b/games/sudoku/src/test/java/com/vayunmathur/games/sudoku/platform/SudokuViewModelDeepTest.ktnew file mode 100644index 0000000000..a15d0ce7fe--- /dev/null+++ b/games/sudoku/src/test/java/com/vayunmathur/games/sudoku/platform/SudokuViewModelDeepTest.kt@@ -0,0 +1,273 @@+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.Dispatchers+import kotlinx.coroutines.ExperimentalCoroutinesApi+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++/**+ * Win-path and edge-path ViewModel behaviour the first suite did not reach:+ * wins on 9x9 and Expert (the size/difficulty achievement branches), a win that+ * completes every board size, undo-history capping, and input guards on ended+ * or unselected games.+ */+@OptIn(ExperimentalCoroutinesApi::class)+@RunWith(RobolectricTestRunner::class)+class SudokuViewModelDeepTest {++ 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) }+ runBlocking { SudokuDataStore(app).setHighlightMistakes(true) }+ }++ @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 solve(vm: SudokuViewModel) {+ var guard = 0+ while (guard++ < 200) {+ 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, "solving loop must win the game")+ }++ @Test+ fun winningNineByNineRecordsWinAndSizeStats() {+ val vm = startedVm(GameConfig(BoardSize.NINE, Difficulty.EASY))+ vm.incrementTimer()+ solve(vm)+ val won = vm.uiState.value.game!!+ assertEquals(BoardSize.NINE, won.size)+ assertTrue(won.isComplete)+ assertEquals(1, stats.getStats(BoardSize.NINE, Difficulty.EASY).gamesWon)+ assertEquals(1, stats.getSizeStats(BoardSize.NINE).gamesWon)+ assertEquals(1, vm.elapsedSeconds.value)+ vm.incrementTimer()+ assertEquals(1, vm.elapsedSeconds.value, "the clock stops on a 9x9 win too")+ }++ @Test+ fun winningExpertRecordsExpertVariantWin() {+ val vm = startedVm(GameConfig(BoardSize.SIX, Difficulty.EXPERT))+ solve(vm)+ assertEquals(1, stats.getStats(BoardSize.SIX, Difficulty.EXPERT).gamesWon)+ assertEquals(0, stats.getStats(BoardSize.SIX, Difficulty.EASY).gamesWon)+ }++ @Test+ fun winningNineAfterOtherSizesSeededCompletesEverySize() {+ // Wins already on the two other sizes: the 9x9 win is the one that+ // completes the set the every-size check looks at.+ stats.recordGameWon(BoardSize.SIX, Difficulty.EASY, 90)+ stats.recordGameWon(BoardSize.TWELVE, Difficulty.EASY, 900)+ val vm = startedVm(GameConfig(BoardSize.NINE, Difficulty.MEDIUM))+ solve(vm)+ assertTrue(BoardSize.entries.all { stats.getSizeStats(it).gamesWon > 0 })+ assertEquals(3, stats.getTotalGamesWon())+ assertEquals(1, stats.getStats(BoardSize.NINE, Difficulty.MEDIUM).currentWinStreak)+ }++ @Test+ fun winningWithHintsStillWinsButCountsThem() {+ val vm = startedVm(GameConfig(BoardSize.NINE, Difficulty.HARD))+ vm.hint()+ assertEquals(1, vm.uiState.value.game!!.hintsUsed)+ solve(vm)+ assertTrue(vm.uiState.value.game!!.hintsUsed >= 1)+ assertEquals(1, stats.getStats(BoardSize.NINE, Difficulty.HARD).gamesWon)+ }++ @Test+ fun giveUpAfterWinDoesNotRecordALoss() {+ val vm = startedVm()+ solve(vm)+ assertEquals(1, stats.getStats(BoardSize.SIX, Difficulty.EASY).currentWinStreak)+ vm.giveUp()+ assertNull(vm.uiState.value.game)+ assertEquals(+ 1,+ stats.getStats(BoardSize.SIX, Difficulty.EASY).currentWinStreak,+ "giving up a finished game must not break the streak it just earned",+ )+ assertEquals(1, stats.getStats(BoardSize.SIX, Difficulty.EASY).gamesWon)+ }++ @Test+ fun inputWithNoSelectionAndOnGivenCellsChangesNothing() {+ val vm = startedVm(GameConfig(BoardSize.SIX, Difficulty.EASY, answerMode = true))+ val game = vm.uiState.value.game!!+ assertEquals(-1, game.selected)+ vm.enterDigit(1)+ assertEquals(0, vm.uiState.value.game!!.moveCount)+ assertEquals(3, vm.uiState.value.game!!.livesRemaining)++ val given = game.givens.indices.first { game.givens[it] != 0 }+ vm.selectCell(given)+ val wrong = (1..game.size.side).first { it != game.solution[given] }+ vm.enterDigit(wrong)+ val after = vm.uiState.value.game!!+ assertEquals(3, after.livesRemaining, "tapping a given costs no life in answer mode")+ assertNull(vm.uiState.value.rejectedDigit)+ assertEquals(0, after.moveCount)+ vm.clearCell()+ assertEquals(game.entries, vm.uiState.value.game!!.entries)+ }++ @Test+ fun undoWithEmptyHistoryAndHintOnEndedBoardsAreNoOps() {+ val vm = startedVm()+ val before = vm.uiState.value.game!!+ vm.undo()+ assertEquals(before.entries, vm.uiState.value.game!!.entries)+ assertFalse(vm.uiState.value.game!!.usedUndo)+ assertFalse(vm.uiState.value.canUndo)++ solve(vm)+ val won = vm.uiState.value.game!!+ vm.clearCell()+ assertEquals(won.entries, vm.uiState.value.game!!.entries, "clearing a won board does nothing")+ }++ @Test+ fun hintWithGivenOrFilledSelectionFillsFirstBlank() {+ val vm = startedVm()+ val game = vm.uiState.value.game!!+ val given = game.givens.indices.first { game.givens[it] != 0 }+ val firstBlank = game.blankIndices().first()+ vm.selectCell(given)+ vm.hint()+ var after = vm.uiState.value.game!!+ assertEquals(game.solution[firstBlank], after.valueAt(firstBlank))+ assertEquals(firstBlank, after.selected)+ assertEquals(1, after.hintsUsed)++ // Now select that filled cell: the next hint must move on to a new blank.+ val nextBlank = after.blankIndices().first()+ vm.hint()+ after = vm.uiState.value.game!!+ assertEquals(after.solution[nextBlank], after.valueAt(nextBlank))+ assertEquals(2, after.hintsUsed)+ }++ @Test+ fun undoHistoryIsCappedAndExhaustsCleanly() {+ val vm = startedVm()+ val cell = vm.uiState.value.game!!.blankIndices().first()+ val digit = vm.uiState.value.game!!.solution[cell]+ vm.selectCell(cell)+ // Toggling one cell is a real move every time (place, erase, place, ...).+ repeat(205) { vm.enterDigit(digit) }+ assertTrue(vm.uiState.value.canUndo)+ var undos = 0+ while (vm.uiState.value.canUndo && undos < 300) {+ vm.undo()+ undos+++ }+ assertEquals(200, undos, "history is capped, so only the newest moves can be undone")+ assertFalse(vm.uiState.value.canUndo)+ assertTrue(vm.uiState.value.game!!.usedUndo)+ val settled = vm.uiState.value.game!!+ vm.undo()+ assertEquals(settled.entries, vm.uiState.value.game!!.entries)+ }++ @Test+ fun restartAfterAnswerModeLossKeepsPuzzleAndAnswerMode() {+ val vm = startedVm(GameConfig(BoardSize.SIX, Difficulty.EASY, answerMode = true))+ val game = vm.uiState.value.game!!+ val cell = game.blankIndices().first()+ val wrong = (1..game.size.side).first { it != game.solution[cell] }+ vm.selectCell(cell)+ repeat(3) { vm.enterDigit(wrong) }+ assertTrue(vm.uiState.value.game!!.isGameOver)+ assertNotNull(vm.uiState.value.rejectedDigit)++ vm.restart()+ val after = vm.uiState.value.game!!+ assertEquals(game.givens, after.givens)+ assertEquals(game.solution, after.solution)+ assertTrue(after.answerMode, "restart keeps the rules the game started with")+ assertEquals(3, after.livesRemaining)+ assertNull(vm.uiState.value.rejectedDigit, "a fresh attempt clears the rejection flash state")+ assertFalse(vm.uiState.value.canUndo)+ }++ @Test+ fun newGameForTwelveRecordsThatVariantAndDealsFullSizeBoard() {+ val vm = startedVm(GameConfig(BoardSize.TWELVE, Difficulty.MEDIUM))+ val game = vm.uiState.value.game!!+ assertEquals(144, game.givens.size)+ assertEquals(144, game.solution.size)+ assertEquals(1, stats.getStats(BoardSize.TWELVE, Difficulty.MEDIUM).gamesPlayed)+ assertEquals(game.variant, "TWELVE_MEDIUM")+ assertTrue(vm.hasActiveGame())+ }++ @Test+ fun erasingViaRetapAlsoClearsNotesOnThatCell() {+ val vm = startedVm()+ val game = vm.uiState.value.game!!+ val cell = game.blankIndices().first()+ val digit = game.solution[cell]+ // Pencil a mark on the cell, then write the digit over it, then re-tap to erase.+ vm.selectCell(cell)+ vm.toggleNotesMode()+ vm.enterDigit(digit)+ assertTrue(vm.uiState.value.game!!.notes[cell] != 0)+ vm.toggleNotesMode()+ vm.enterDigit(digit)+ assertEquals(digit, vm.uiState.value.game!!.valueAt(cell))+ assertEquals(0, vm.uiState.value.game!!.notes[cell], "placing a digit clears its own marks")+ vm.enterDigit(digit)+ val after = vm.uiState.value.game!!+ assertEquals(0, after.valueAt(cell))+ assertEquals(0, after.notes[cell])+ assertTrue(after.moveCount >= 3)+ }+}
games/sudoku/src/test/java/com/vayunmathur/games/sudoku/ui/SudokuGridDrawTest.kt
diff --git a/games/sudoku/src/test/java/com/vayunmathur/games/sudoku/ui/SudokuGridDrawTest.kt b/games/sudoku/src/test/java/com/vayunmathur/games/sudoku/ui/SudokuGridDrawTest.ktnew file mode 100644index 0000000000..15053825c5--- /dev/null+++ b/games/sudoku/src/test/java/com/vayunmathur/games/sudoku/ui/SudokuGridDrawTest.kt@@ -0,0 +1,52 @@+package com.vayunmathur.games.sudoku.ui++import androidx.compose.foundation.layout.size+import androidx.compose.runtime.getValue+import androidx.compose.runtime.setValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.test.captureToImage+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onRoot+import androidx.compose.ui.unit.dp+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.ui.components.SudokuGrid+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.GraphicsMode+import kotlin.random.Random+import kotlin.test.Test+import kotlin.test.assertTrue++/**+ * Actually rasterising the grid is the only way the line-drawing code runs:+ * under Robolectric's legacy graphics the compose tree is laid out but never+ * drawn, so a semantics-only test cannot reach it.+ */+@RunWith(RobolectricTestRunner::class)+@GraphicsMode(GraphicsMode.Mode.NATIVE)+class SudokuGridDrawTest {++ @get:Rule val rule = createComposeRule()++ @Test+ fun gridLinesAreDrawnForEveryBoardSize() {+ var current by androidx.compose.runtime.mutableStateOf(+ SudokuGameState.from(SudokuGenerator.generate(BoardSize.SIX, Difficulty.EASY, Random(2))),+ )+ rule.setContent {+ SudokuGrid(game = current, onSelect = {}, modifier = Modifier.size(360.dp))+ }+ for (size in BoardSize.entries) {+ current = SudokuGameState.from(+ SudokuGenerator.generate(size, Difficulty.EASY, Random(2)),+ )+ rule.waitForIdle()+ val image = rule.onRoot().captureToImage()+ assertTrue(image.width > 0 && image.height > 0, "captured ${size.name} board")+ }+ }+}
games/sudoku/src/test/java/com/vayunmathur/games/sudoku/ui/SudokuPortraitBoardTest.kt
diff --git a/games/sudoku/src/test/java/com/vayunmathur/games/sudoku/ui/SudokuPortraitBoardTest.kt b/games/sudoku/src/test/java/com/vayunmathur/games/sudoku/ui/SudokuPortraitBoardTest.ktnew file mode 100644index 0000000000..4cb1b8cdea--- /dev/null+++ b/games/sudoku/src/test/java/com/vayunmathur/games/sudoku/ui/SudokuPortraitBoardTest.kt@@ -0,0 +1,238 @@+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.compose.ui.test.performScrollTo+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.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.games.sudoku.platform.SudokuViewModel+import com.vayunmathur.games.sudoku.ui.components.NumberPad+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 org.robolectric.annotation.Config+import kotlin.random.Random+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/**+ * The portrait (stacked) board layout: tall, narrow windows put the grid above+ * the pad instead of beside it, and that whole branch is invisible to the+ * landscape/default-size suites.+ */+@OptIn(ExperimentalCoroutinesApi::class)+@RunWith(RobolectricTestRunner::class)+@Config(qualifiers = "w360dp-h800dp-port")+class SudokuPortraitBoardTest {++ @get:Rule val rule = createComposeRule()+ private val ctx: Context get() = ApplicationProvider.getApplicationContext()+ private val app: Application get() = ApplicationProvider.getApplicationContext()+ 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 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 playAgains = 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 playAgain() { playAgains++ }+ override fun giveUp() { giveUps++ }+ }++ private fun game(+ size: BoardSize = BoardSize.SIX,+ answerMode: Boolean = false,+ ): SudokuGameState =+ SudokuGameState.from(SudokuGenerator.generate(size, Difficulty.EASY, Random(1)), answerMode)++ @Test+ fun portraitBoardStacksAndEveryControlReachesActions() {+ val actions = RecordingActions()+ val game = game()+ var exits = 0+ rule.setContent {+ GameBoardScreen(+ state = SudokuUiState(game = game, canUndo = true),+ actions = actions,+ onExit = { exits++ },+ elapsedSeconds = { 125 },+ )+ }+ rule.onNodeWithText("6x6 · Easy").assertExists()+ rule.onAllNodesWithText("2:05", substring = true).assertCountEquals(1)++ val side = game.size.side+ rule.onNodeWithContentDescription(ctx.getString(R.string.cd_digit_key, "1")).performClick()+ 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(listOf(1), actions.digits)+ assertEquals(1, actions.notesToggles)+ assertEquals(1, actions.clears)+ assertEquals(1, actions.undos)+ assertEquals(1, actions.hints)+ assertEquals(0, exits)+ assertTrue(side > 0)+ }++ @Test+ fun portraitWonAndGameOverBoardsShowTheirOverlays() {+ val actions = RecordingActions()+ val base = game()+ val entries = List(base.size.cellCount) { if (base.isGiven(it)) 0 else base.solution[it] }+ val won = base.copy(entries = entries, isWon = true, hintsUsed = 1)+ rule.setContent {+ GameBoardScreen(+ state = SudokuUiState(game = won),+ actions = actions,+ onExit = {},+ elapsedSeconds = { 42 },+ )+ }+ rule.onNodeWithText(str(R.string.congratulations)).assertExists()+ rule.onNodeWithText("Play Again").performClick()+ assertEquals(1, actions.playAgains)+ }++ @Test+ fun portraitGameOverBoardShowsOutOfLivesOverlay() {+ val actions = RecordingActions()+ val over = game(answerMode = true).copy(livesRemaining = 0)+ rule.setContent {+ GameBoardScreen(state = SudokuUiState(game = over), actions = actions, onExit = {})+ }+ rule.onNodeWithText(str(R.string.out_of_lives)).assertExists()+ rule.onNodeWithText(str(R.string.try_again)).performClick()+ assertEquals(1, actions.restarts)+ }++ @Test+ fun portraitTwelveBoardRendersLetterPadAndNotes() {+ val actions = RecordingActions()+ val base = game(BoardSize.TWELVE)+ val blank = base.givens.indices.first { base.givens[it] == 0 }+ val styled = base.copy(+ notes = base.notes.toMutableList().also { it[blank] = (1 shl 9) or (1 shl 11) },+ selected = blank,+ notesMode = true,+ )+ rule.setContent {+ GameBoardScreen(state = SudokuUiState(game = styled), actions = actions, onExit = {})+ }+ rule.onNodeWithContentDescription(ctx.getString(R.string.cd_note_key, "A")).performClick()+ assertEquals(listOf(10), actions.digits)+ rule.onNodeWithText(str(R.string.hint)).assertExists()+ }++ @Test+ fun rejectedKeyFlashSettlesAfterItsDelay() {+ val game = game(answerMode = true)+ val tapped = mutableListOf<Int>()+ rule.mainClock.autoAdvance = false+ rule.setContent {+ NumberPad(game = game, onDigit = { tapped += it }, rejected = RejectedDigit(2, 1L))+ }+ rule.waitForIdle()+ rule.mainClock.advanceTimeBy(600)+ rule.waitForIdle()+ // After the flash settles the key is an ordinary key again.+ rule.onNodeWithContentDescription(ctx.getString(R.string.cd_digit_key, "2")).performClick()+ assertEquals(listOf(2), tapped)+ }++ private fun awaitValue(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")+ }++ @Test+ fun homeSwitchesToggleTheViewModelSettings() {+ val vm = SudokuViewModel(app)+ val stack = NavBackStack(arrayOf<Route>(Route.Home))+ rule.setContent { HomeScreen(stack, vm) }+ rule.onNodeWithText(str(R.string.answer_mode)).performScrollTo().performClick()+ awaitValue("answer mode on") { vm.answerMode.value }+ rule.onNodeWithText(str(R.string.answer_mode)).performClick()+ awaitValue("answer mode off") { !vm.answerMode.value }++ rule.onNodeWithText(str(R.string.highlight_mistakes)).performScrollTo().performClick()+ awaitValue("highlight off") { !vm.highlightMistakes.value }+ }++ @Test+ fun navigationGameCenterBackReturnsHome() {+ val vm = SudokuViewModel(app)+ rule.setContent { Navigation(vm) }+ rule.onNodeWithContentDescription("Badges").performClick()+ rule.waitForIdle()+ rule.onNodeWithText(str(com.vayunmathur.library.ui.R.string.title_game_center)).assertExists()+ rule.onNodeWithContentDescription("Back").performClick()+ rule.waitForIdle()+ rule.onNodeWithText(str(com.vayunmathur.library.ui.R.string.new_game)).assertExists()+ }++ @Test+ fun gameScreenBackPopsTheStack() {+ val vm = SudokuViewModel(app)+ val config = GameConfig(BoardSize.SIX, Difficulty.EASY)+ val stack = NavBackStack(arrayOf<Route>(Route.Home, Route.Game(config)))+ rule.setContent { GameScreen(stack, vm, config) }+ val deadline = System.currentTimeMillis() + 20_000+ while (vm.uiState.value.game == null && System.currentTimeMillis() < deadline) {+ Thread.sleep(25)+ }+ assertTrue(vm.uiState.value.game != null, "GameScreen deals its game")+ rule.onNodeWithContentDescription("Back").performClick()+ assertEquals(1, stack.backStack.size, "the board's back arrow pops the game route")+ }+}