Modern Apps git

← Modern-Apps.git

games-pipes: add coverage tests for solver, VM and screens (#tests)

Commit
6210c1fd89d9add3482328c12e8721e8dbf25ed1
Author
Vayun Mathur <[email protected]>
When
2026-11-16 13:33 UTC (19 days ago)
Parents
92054e5
Wave 3 coverage for :games:pipes only. The module already had
extensive tests (14,906 covered instructions, 1,354 missed), so
the remaining missed pool caps the achievable gain well below
2,000; these tests cover most of what was left.

New tests (31, suite 103 -> 134):
- domain: solver malformed-board rejection, stroke triplet and
  bridge/portal exits, bridge owner fallbacks, ProgressCodec
  broken-history rejection, daily pool filtering/determinism,
  generator edge cases, and the shipped-pack JSON parser's
  explicit adjacency/renderPositions/portals paths (via reflection
  on the private parser).
- geometry/renderer: empty and zero-size boards, render-position
  centring/filtering, offset and hex hit-testing, cellsAlong
  return trips, hex direction sectors and label anchors.
- ViewModel: no-level and won-level no-ops, completing the first
  pack, a single daily win without a streak, and the achievements
  recheck seeing a recorded daily streak.
- screens: landscape board layout, off-board/portal/bridge and
  hex colour-blind drawing, Navigation journeys to level/game and
  daily game, GameScreen loading state, won-level Next route and
  won-last-level Back-to-packs, daily star/check badges, holed-pack
  thumbnails, and SettingsPage reminder toggle/time reaching the
  ViewModel.
- data: ProgressRepository pruning to the 30 most recent levels,
  corrupt recency-order fallback, contract defaults and the
  preview no-op actions.

No provably dead code was found (every public symbol has a
caller; LevelGenerator is a documented offline tool), so no
deletion commit was made.

Coverage (createMergedCoverageReport, INSTRUCTION):
before 14906 covered / 1354 missed, after 15632 / 628,
delta +726 covered.

Verified without the coverage ignore-init:
./gradlew :games:pipes:testDevUnitTest :games:pipes:detekt
:games:pipes:lint -- green (134 tests).

Diff

games/pipes/src/test/java/com/vayunmathur/games/pipes/data/CoverageExtraRepositoryTest.kt
diff --git a/games/pipes/src/test/java/com/vayunmathur/games/pipes/data/CoverageExtraRepositoryTest.kt b/games/pipes/src/test/java/com/vayunmathur/games/pipes/data/CoverageExtraRepositoryTest.ktnew file mode 100644index 0000000000..b4d3923d29--- /dev/null+++ b/games/pipes/src/test/java/com/vayunmathur/games/pipes/data/CoverageExtraRepositoryTest.kt@@ -0,0 +1,71 @@+package com.vayunmathur.games.pipes.data++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.games.pipes.platform.PipesActions+import com.vayunmathur.games.pipes.platform.SettingsActions+import com.vayunmathur.games.pipes.platform.SettingsUiState+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)+class CoverageExtraRepositoryTest {+    private val ctx get() = ApplicationProvider.getApplicationContext<Context>()++    @Test fun progressRepositoryPrunesOldestAndClears() {+        val repo = ProgressRepository(ctx)+        for (i in 0 until 35) repo.save("lvl_$i", "state_$i")+        // Only the 30 most recent levels survive.+        assertNull(repo.load("lvl_0"))+        assertNull(repo.load("lvl_4"))+        assertEquals("state_5", repo.load("lvl_5"))+        assertEquals("state_34", repo.load("lvl_34"))+        // Re-saving an existing level makes it the most recent without duplicating it.+        repo.save("lvl_5", "updated")+        assertEquals("updated", repo.load("lvl_5"))+        repo.save("lvl_35", "state_35")+        assertEquals("updated", repo.load("lvl_5"))+        // Clearing removes the entry; clearing again is a no-op.+        repo.clear("lvl_5")+        assertNull(repo.load("lvl_5"))+        repo.clear("lvl_5")+        repo.clear("never_saved")+        assertEquals("state_35", repo.load("lvl_35"))+    }++    @Test fun progressRepositorySurvivesCorruptOrder() {+        val repo = ProgressRepository(ctx)+        repo.save("keep", "value")+        ctx.getSharedPreferences(ProgressRepository.PREFS_NAME, Context.MODE_PRIVATE)+            .edit().putString("order", "not json").commit()+        // Corrupt recency data falls back to an empty order; the save still works.+        repo.save("after", "value2")+        assertEquals("value2", repo.load("after"))+        assertEquals("value", repo.load("keep"))+        assertEquals("pipes_progress", ProgressRepository.PREFS_NAME)+    }++    @Test fun contractDefaultsAndNoopActions() {+        val settings = SettingsUiState()+        assertEquals(false, settings.colorblind)+        assertEquals(false, settings.reminderEnabled)+        assertEquals(20, settings.reminderHour)+        assertEquals(0, settings.reminderMinute)+        // Preview no-op actions accept every callback without doing anything.+        PipesActions.Noop.startDraw(CellPos(0, 0))+        PipesActions.Noop.extendPath(CellPos(0, 1))+        PipesActions.Noop.commitDraw()+        PipesActions.Noop.onUndo()+        PipesActions.Noop.onRestart()+        SettingsActions.Noop.setColorblind(true)+        SettingsActions.Noop.setReminderEnabled(true)+        SettingsActions.Noop.setReminderTime(9, 30)+        val custom = SettingsUiState(colorblind = true, reminderEnabled = true, reminderHour = 9, reminderMinute = 30)+        assertEquals(true, custom.colorblind)+        assertEquals(30, custom.reminderMinute)+    }+}
games/pipes/src/test/java/com/vayunmathur/games/pipes/domain/CoverageExtraDomainTest.kt
diff --git a/games/pipes/src/test/java/com/vayunmathur/games/pipes/domain/CoverageExtraDomainTest.kt b/games/pipes/src/test/java/com/vayunmathur/games/pipes/domain/CoverageExtraDomainTest.ktnew file mode 100644index 0000000000..8c0bdf43c1--- /dev/null+++ b/games/pipes/src/test/java/com/vayunmathur/games/pipes/domain/CoverageExtraDomainTest.kt@@ -0,0 +1,213 @@+package com.vayunmathur.games.pipes.domain++import com.vayunmathur.games.pipes.data.CellPos+import com.vayunmathur.games.pipes.data.EndpointPair+import com.vayunmathur.games.pipes.data.LevelData+import com.vayunmathur.games.pipes.data.LevelPack+import com.vayunmathur.games.pipes.data.RenderPos+import com.vayunmathur.games.pipes.data.computeAdjacency+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue++class CoverageExtraDomainTest {+    private fun p(r: Int, c: Int) = CellPos(r, c)+    private fun rect(rows: Int, cols: Int) = buildSet {+        for (r in 0 until rows) for (c in 0 until cols) add(p(r, c))+    }++    private fun level(+        cells: Set<CellPos> = rect(4, 4),+        adjacency: Map<CellPos, List<CellPos>> = computeAdjacency(cells),+        endpoints: List<EndpointPair> = listOf(+            EndpointPair(0, listOf(p(0, 0), p(0, 3))),+            EndpointPair(1, listOf(p(3, 0), p(3, 3))),+        ),+        bridges: Set<CellPos> = emptySet(),+        renderPositions: Map<CellPos, RenderPos>? = null,+    ) = LevelData("x", 4, 4, cells, adjacency, renderPositions, endpoints, bridges, endpoints.size)++    @Test fun solverRejectsMalformedBoards() {+        val cells = rect(3, 3)+        assertEquals(NumberlinkSolver.Verdict.NONE, NumberlinkSolver.classify(emptySet(), emptyList()))+        assertEquals(NumberlinkSolver.Verdict.NONE, NumberlinkSolver.classify(cells, emptyList()))+        // Triplet endpoints are not a pair the solver can classify.+        assertEquals(+            NumberlinkSolver.Verdict.NONE,+            NumberlinkSolver.classify(cells, listOf(EndpointPair(0, listOf(p(0, 0), p(0, 1), p(0, 2))))),+        )+        // Endpoint outside the board.+        assertEquals(+            NumberlinkSolver.Verdict.NONE,+            NumberlinkSolver.classify(cells, listOf(EndpointPair(0, listOf(p(0, 0), p(9, 9))))),+        )+        // The same cell used by two pairs.+        assertEquals(+            NumberlinkSolver.Verdict.NONE,+            NumberlinkSolver.classify(+                cells,+                listOf(EndpointPair(0, listOf(p(0, 0), p(0, 1))), EndpointPair(1, listOf(p(0, 1), p(2, 2)))),+            ),+        )+        // A board with a hole: the hole cell is skipped, the column flows still hold.+        val holed = rect(2, 2) - p(0, 1)+        assertEquals(+            NumberlinkSolver.Verdict.UNIQUE,+            NumberlinkSolver.classify(holed, listOf(EndpointPair(0, listOf(p(1, 0), p(1, 1))))),+        )+    }++    @Test fun strokeRulesHandleMissingAndUnknownState() {+        val lvl = level()+        assertEquals(emptyList(), StrokeRules.extend(lvl, emptyMap(), 0, emptyList(), p(0, 1)))+        assertEquals(listOf(p(0, 0)), StrokeRules.extend(lvl, emptyMap(), 0, listOf(p(0, 0)), p(9, 9)))+        assertFalse(StrokeRules.isComplete(lvl, 99, listOf(p(0, 0), p(0, 3))))+        assertFalse(StrokeRules.isComplete(lvl, 0, listOf(p(0, 0), p(0, 0))))+        assertFalse(StrokeRules.isComplete(lvl, 0, emptyList()))+        // Reversed pair still completes: first dot is endpoint[1], partner is endpoint[0].+        assertTrue(StrokeRules.isComplete(lvl, 0, listOf(p(0, 3), p(0, 2), p(0, 0))))+        // A path whose last cell has no adjacency entry cannot step anywhere.+        val noAdj = level(adjacency = emptyMap())+        assertFalse(StrokeRules.isValidStep(noAdj, 0, listOf(p(0, 0)), p(0, 1)))+        assertFalse(StrokeRules.isValidStep(lvl, 0, listOf(p(0, 0), p(0, 1)), p(0, 0)))+        // Completing the pair through the intermediate stops the diagonal from overshooting:+        // the direct partner is already the last cell, so extend stays put.+        val done = listOf(p(0, 0), p(0, 1), p(0, 3))+        assertEquals(listOf(p(0, 0), p(0, 1)), StrokeRules.extend(lvl, emptyMap(), 0, listOf(p(0, 0)), p(0, 1)))+        assertFalse(StrokeRules.isComplete(lvl, 0, done.dropLast(1)))+    }++    @Test fun strokeRulesTripletAndBridgeExits() {+        val triplet = level(+            endpoints = listOf(EndpointPair(0, listOf(p(0, 0), p(0, 3), p(3, 3))), EndpointPair(1, listOf(p(3, 0), p(3, 1)))),+        )+        assertFalse(StrokeRules.isComplete(triplet, 0, listOf(p(0, 0), p(0, 3))))+        assertTrue(StrokeRules.isComplete(triplet, 0, listOf(p(0, 0), p(0, 3), p(3, 3))))+        // Bridge at (1,1): a straight vertical run may leave downwards, a turn may not.+        val bridged = level(bridges = setOf(p(1, 1)))+        val entering = listOf(p(0, 1), p(1, 1))+        assertTrue(StrokeRules.isValidStep(bridged, 0, entering, p(2, 1)))+        assertFalse(StrokeRules.isValidStep(bridged, 0, entering, p(1, 2)))+        // A long-range (portal-style) exit from a bridge skips the straight-through rule.+        val portalCells = rect(4, 4)+        val portalAdj = computeAdjacency(portalCells).toMutableMap()+        portalAdj[p(1, 1)] = portalAdj.getValue(p(1, 1)) + p(3, 2)+        val portalLevel = level(adjacency = portalAdj, bridges = setOf(p(1, 1)))+        assertTrue(StrokeRules.isValidStep(portalLevel, 0, entering, p(3, 2)))+        // Diagonal whose only via would complete the stroke mid-way is refused.+        val diag = StrokeRules.extend(level(), emptyMap(), 0, listOf(p(0, 0)), p(1, 1))+        assertEquals(3, diag.size)+        assertEquals(p(1, 1), diag.last())+    }++    @Test fun boardOwnersBridgeFallbacks() {+        val bridged = level(bridges = setOf(p(1, 1)))+        assertEquals(emptyMap(), BoardEdits.owners(bridged, emptyMap()))+        val a = listOf(p(0, 1), p(1, 1), p(2, 1))+        val b = listOf(p(1, 0), p(1, 1), p(1, 2))+        // Prior owner no longer crosses: the non-newest crosser owns the bridge.+        val owned = BoardEdits.owners(bridged, mapOf(0 to a, 1 to b), prior = mapOf(p(1, 1) to 7), newest = 1)+        assertEquals(0, owned[p(1, 1)])+        // Only the newest crosses: it owns the bridge by default.+        val solo = BoardEdits.owners(bridged, mapOf(1 to b), newest = 1)+        assertEquals(1, solo[p(1, 1)])+        // Non-bridge cells belong to the line that covers them.+        assertEquals(0, owned[p(0, 1)])+        assertEquals(1, owned[p(1, 0)])+    }++    @Test fun progressCodecRejectsBrokenHistoryAndVersions() {+        val lvl = level()+        assertNull(ProgressCodec.decode("""{"s":{"p":{},"o":{}},"h":[]}""", lvl))+        assertNull(ProgressCodec.decode("""{"v":1}""", lvl))+        assertNull(ProgressCodec.decode("""{"v":1,"s":{"p":{},"o":{}},"h":[{"p":{"9":[0,0,0,1]},"o":{}}]}""", lvl))+        assertNull(ProgressCodec.decode("""[1,2]""", lvl))+        // An owner entry for a cell covered by a single line is not written back out.+        val state = BoardState(mapOf(0 to listOf(p(0, 0), p(0, 1))), mapOf(p(0, 0) to 0, p(0, 1) to 0))+        val encoded = ProgressCodec.encode(SavedProgress(state, emptyList()))+        assertTrue("\"o\":{}" in encoded, encoded)+        val decoded = ProgressCodec.decode(encoded, lvl)+        assertEquals(state.paths, decoded!!.state.paths)+        // Missing owners object decodes with owners derived from the lines.+        val noOwners = """{"v":1,"s":{"p":{"0":[0,0,0,1]}},"h":[]}"""+        assertEquals(mapOf(p(0, 0) to 0, p(0, 1) to 0), ProgressCodec.decode(noOwners, lvl)!!.state.cellOwner)+    }++    @Test fun dailyPoolFilteringAndDeterminism() {+        assertEquals("daily_123_4", DailyLevels.levelId(123, 4))+        val classic = (0 until 6).map { i ->+            val cells = rect(2 + i, 2)+            LevelData(+                "c$i", 2 + i, 2, cells, computeAdjacency(cells), null,+                listOf(EndpointPair(0, listOf(p(0, 0), p(0, 1)))) , emptySet(), 1,+            )+        }+        val custom = level(renderPositions = mapOf(p(0, 0) to RenderPos(0f, 0f))).copy(id = "custom")+        assertNull(DailyLevels.packFor(10, classic.take(4) + custom))+        val pack = DailyLevels.packFor(10, classic + custom)!!+        assertEquals(5, pack.levels.size)+        assertTrue(pack.levels.none { it.id == "custom" })+        assertEquals(pack.levels.map { it.cells.size }, pack.levels.map { it.cells.size }.sorted())+        assertEquals((0 until 5).map { DailyLevels.levelId(10, it) }, pack.levels.map { it.id })+        assertEquals(pack, DailyLevels.packFor(10, classic + custom))+        assertTrue(DailyLevels.packFor(11, classic + custom)!!.levels.all { it.id.startsWith("daily_11_") })+        assertEquals("daily_10", pack.name)+        assertEquals("square", pack.shape)+    }++    @Test fun generatorEdgeCases() {+        assertEquals(emptySet(), LevelGenerator.rectangularCells(0, 3))+        assertEquals(setOf(p(0, 0), p(0, 1), p(1, 0), p(1, 1)), LevelGenerator.rectangularCells(2, 2))+        assertEquals(4, LevelGenerator.flowCeiling(rect(2, 2)))+        assertEquals(5, LevelGenerator.flowCeiling(rect(5, 5)))+        // No adjacency at all: no carve can start, so no level.+        assertNull(LevelGenerator.generateLevel(rect(3, 3), emptyMap(), 4, seed = 7, id = "none"))+        // A pack over an impossible board is empty; the id scheme is still exercised via a real board.+        assertEquals(emptyList(), LevelGenerator.generatePack("A B×C", rect(3, 3), emptyMap(), 3, 4, seed = 1))+        val cells = rect(5, 5)+        val pack = LevelGenerator.generatePack("My Pack×1", cells, computeAdjacency(cells), 2, 5, seed = 42)+        assertTrue(pack.all { it.id.startsWith("My_Packx1_") }, pack.map { it.id }.toString())+        assertTrue(pack.all { it.endpoints.isNotEmpty() })+    }++    @Test fun packJsonExplicitAdjacencyAndRenderPositions() {+        val json = """+            {"name":"Explicit","shape":"square","levels":[{+              "id":"e1","rows":2,"cols":2,+              "cells":[[0,0],[0,1],[1,0],[1,1]],+              "adjacency":{"0,0":[[0,1],[1,0]],"0,1":[[0,0]],"1,0":[[0,0]],"1,1":[]},+              "renderPositions":{"0,0":{"x":0.5,"y":0.25},"1,1":{"x":2.5,"y":3.5}},+              "portals":[[[0,0],[1,1]]],+              "extraEdges":[[[0,1],[1,0]],[[1,1]]],+              "bridges":[[1,0]],+              "endpoints":[{"color":7,"cells":[[0,0],[1,1]]},{"cells":[[0,1],[1,0]]}],+              "optimalMoves":2+            },{+              "id":"h1","rows":2,"cols":2,"grid":"hex",+              "endpoints":[{"cells":[[0,0],[1,1]]}],"optimalMoves":1+            }]}+        """.trimIndent()+        val method = Class.forName("com.vayunmathur.games.pipes.data.PipeModelsKt")+            .getDeclaredMethod("packFromJson", String::class.java)+        method.isAccessible = true+        val pack = method.invoke(null, json) as LevelPack+        assertEquals("Explicit", pack.name)+        val first = pack.levels[0]+        // Explicit adjacency is honoured and unioned with the portal + extra edge.+        assertTrue(p(1, 1) in first.adjacency.getValue(p(0, 0)))+        assertTrue(p(1, 0) in first.adjacency.getValue(p(0, 1)))+        assertEquals(RenderPos(0.5f, 0.25f), first.renderPositions!![p(0, 0)])+        assertEquals(RenderPos(2.5f, 3.5f), first.renderPositions[p(1, 1)])+        assertEquals(setOf(p(1, 0)), first.bridges)+        assertEquals(7, first.endpoints[0].colorIndex)+        assertEquals(1, first.endpoints[1].colorIndex)+        assertEquals(mapOf(p(0, 0) to p(1, 1), p(1, 1) to p(0, 0)), first.portals)+        // Hex level with no declared adjacency/render positions derives both.+        val hex = pack.levels[1]+        assertEquals("hex", hex.grid)+        assertTrue(hex.renderPositions!!.isNotEmpty())+        assertTrue(hex.adjacency.getValue(p(0, 0)).isNotEmpty())+    }+}
games/pipes/src/test/java/com/vayunmathur/games/pipes/platform/CoverageExtraViewModelTest.kt
diff --git a/games/pipes/src/test/java/com/vayunmathur/games/pipes/platform/CoverageExtraViewModelTest.kt b/games/pipes/src/test/java/com/vayunmathur/games/pipes/platform/CoverageExtraViewModelTest.ktnew file mode 100644index 0000000000..366ae7ef55--- /dev/null+++ b/games/pipes/src/test/java/com/vayunmathur/games/pipes/platform/CoverageExtraViewModelTest.kt@@ -0,0 +1,155 @@+package com.vayunmathur.games.pipes.platform++import android.app.Application+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.games.pipes.data.CellPos+import com.vayunmathur.games.pipes.data.CompletedLevelsRepository+import com.vayunmathur.games.pipes.data.LevelData+import com.vayunmathur.games.pipes.data.LevelPack+import com.vayunmathur.library.util.DailyChallengeStore+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.async+import kotlinx.coroutines.ExperimentalCoroutinesApi+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.runBlocking+import kotlinx.coroutines.test.resetMain+import kotlinx.coroutines.test.setMain+import kotlinx.coroutines.withTimeout+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 CoverageExtraViewModelTest {+    private val app get() = ApplicationProvider.getApplicationContext<Application>()++    @BeforeTest fun setUp() {+        Dispatchers.setMain(Dispatchers.Unconfined)+        LevelPack.init(app)+        try {+            androidx.work.WorkManager.initialize(app, androidx.work.Configuration.Builder().build())+        } catch (_: IllegalStateException) { /* already initialised */ }+    }++    @AfterTest fun tearDown() { Dispatchers.resetMain() }++    private fun solve(level: LevelData): Map<Int, List<CellPos>> {+        val result = mutableMapOf<Int, List<CellPos>>()+        val pairs = level.endpoints.filter { it.cells.size == 2 }+        val allEndpoints = level.endpoints.flatMap { it.cells }.toSet()+        fun extend(ci: Int, path: List<CellPos>, used: Set<CellPos>): Boolean {+            val target = pairs[ci].cells[1]+            if (path.last() == target) {+                if (ci == pairs.lastIndex) {+                    if (used.size != level.cells.size) return false+                    result[pairs[ci].colorIndex] = path; return true+                }+                result[pairs[ci].colorIndex] = path+                val next = pairs[ci + 1]+                if (extend(ci + 1, listOf(next.cells[0]), used + next.cells[0])) return true+                result.remove(pairs[ci].colorIndex); return false+            }+            for (n in (level.adjacency[path.last()] ?: emptyList())+                .filter { it in level.cells && it !in used && (it == target || it !in allEndpoints) }+                .sortedBy { m -> (level.adjacency[m] ?: emptyList()).count { it !in used } }) {+                if (extend(ci, path + n, used + n)) return true+            }+            return false+        }+        val first = pairs[0]+        assertTrue(extend(0, listOf(first.cells[0]), setOf(first.cells[0])), "unsolved ${level.id}")+        return result+    }++    private fun draw(vm: PipesViewModel, path: List<CellPos>) {+        vm.startDraw(path.first())+        for (c in path.drop(1)) vm.extendPath(c)+        vm.commitDraw()+    }++    @Test fun noLevelAndWonLevelAreNoOps() {+        val vm = PipesViewModel(app)+        // Nothing loaded: every board callback must quietly do nothing.+        vm.startDraw(CellPos(0, 0)); vm.extendPath(CellPos(0, 1)); vm.commitDraw()+        vm.onUndo(); vm.onRestart()+        assertEquals(-1, vm.uiState.value.packIndex)+        assertTrue(vm.uiState.value.gameState.paths.isEmpty())+        assertEquals(0, vm.getCurrentMoves())++        vm.loadLevel(0, 0)+        val level = vm.uiState.value.levelData!!+        for ((_, path) in solve(level).entries.sortedBy { it.key }) draw(vm, path)+        assertTrue(vm.uiState.value.isLevelWon)+        val wonState = vm.uiState.value.gameState+        val wonHistory = vm.uiState.value.history+        // A won board refuses further strokes, undo and restart.+        vm.startDraw(level.endpoints[0].cells[0]); vm.extendPath(level.endpoints[0].cells[1]); vm.commitDraw()+        vm.onUndo(); vm.onRestart()+        // Let the win's stats coroutine finish before tearDown resets Main.+        val deadline = System.currentTimeMillis() + 10_000+        while (!vm.levelStats.value.containsKey(level.id) && System.currentTimeMillis() < deadline) Thread.sleep(25)+        assertTrue(vm.levelStats.value.containsKey(level.id))+        assertTrue(vm.uiState.value.isLevelWon)+        assertEquals(wonState, vm.uiState.value.gameState)+        assertEquals(wonHistory, vm.uiState.value.history)+    }++    @Test fun completingWholeFirstPackUnlocksPackAchievement() = runBlocking {+        val vm = PipesViewModel(app)+        val pack = LevelPack.PACKS[0]+        // Every other level in the pack is already recorded; solving the first completes it.+        for (level in pack.levels.drop(1)) vm.repository.updateBestScore(level.id, level.optimalMoves)+        vm.loadLevel(0, 0)+        val level = vm.uiState.value.levelData!!+        for ((_, path) in solve(level).entries.sortedBy { it.key }) draw(vm, path)+        assertTrue(vm.uiState.value.isLevelWon)+        withTimeout(10_000) { vm.levelStats.first { stats -> pack.levels.all { stats.containsKey(it.id) } } }+        assertEquals(pack.levels.size, pack.levels.count { vm.levelStats.value.containsKey(it.id) })+        assertFalse(vm.levelStats.value.getValue(level.id).bestScore < 0)+        Unit+    }++    @Test fun singleDailyWinRecordsScoreWithoutCompletingDay() = runBlocking {+        val vm = PipesViewModel(app)+        vm.refreshDaily()+        val pack = withTimeout(10_000) { vm.dailyPack.first { it != null } }!!+        vm.loadLevel(PipesViewModel.DAILY_PACK_INDEX, 1)+        val level = vm.uiState.value.levelData!!+        assertEquals(pack.levels[1].id, level.id)+        val completedCount = async {+            withTimeout(10_000) { vm.dailyCompleted.first { it == 1 } }+        }+        for ((_, path) in solve(level).entries.sortedBy { it.key }) draw(vm, path)+        assertTrue(vm.uiState.value.isLevelWon)+        withTimeout(10_000) { vm.dailyStats.first { it.containsKey(level.id) } }+        // Only this one of the five is done, so no streak is recorded for the day.+        assertEquals(1, completedCount.await())+        assertTrue(vm.dailyStats.value.containsKey(level.id))+        Unit+    }++    @Test fun achievementsRecheckSeesDailyStreak() = runBlocking {+        val store = DailyChallengeStore(app, "pipes_daily")+        store.recordDayCompleted(store.todayEpochDay())+        val repo = CompletedLevelsRepository(app)+        repo.updateBestScore("seen_level", 3)+        val json = app.assets.open("achievements.json").bufferedReader().use { it.readText() }+        val manager = PipesAchievementsManager(app, json, repo)+        manager.checkExistingAchievements()+        // The streak check runs on IO; give it time to deliver its progress update.+        val deadline = System.currentTimeMillis() + 10_000+        while (System.currentTimeMillis() < deadline) {+            if (manager.newAchievement.value != null) break+            Thread.sleep(25)+        }+        manager.dismissNotification()+        assertTrue(store.bestStreak() > 0)+        Unit+    }+}
games/pipes/src/test/java/com/vayunmathur/games/pipes/ui/CoverageExtraGeometryTest.kt
diff --git a/games/pipes/src/test/java/com/vayunmathur/games/pipes/ui/CoverageExtraGeometryTest.kt b/games/pipes/src/test/java/com/vayunmathur/games/pipes/ui/CoverageExtraGeometryTest.ktnew file mode 100644index 0000000000..d0b6d8533a--- /dev/null+++ b/games/pipes/src/test/java/com/vayunmathur/games/pipes/ui/CoverageExtraGeometryTest.kt@@ -0,0 +1,132 @@+package com.vayunmathur.games.pipes.ui++import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.geometry.Rect+import androidx.compose.ui.geometry.Size+import com.vayunmathur.games.pipes.data.CellPos+import com.vayunmathur.games.pipes.data.EndpointPair+import com.vayunmathur.games.pipes.data.LevelData+import com.vayunmathur.games.pipes.data.RenderPos+import com.vayunmathur.games.pipes.data.computeAdjacency+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue++class CoverageExtraGeometryTest {+    private fun p(r: Int, c: Int) = CellPos(r, c)+    private fun rect(rows: Int, cols: Int) = buildSet {+        for (r in 0 until rows) for (c in 0 until cols) add(p(r, c))+    }++    private fun level(+        cells: Set<CellPos>,+        rows: Int = 4,+        cols: Int = 4,+        renderPositions: Map<CellPos, RenderPos>? = null,+        grid: String = "square",+    ) = LevelData(+        "g", rows, cols, cells, computeAdjacency(cells), renderPositions,+        listOf(EndpointPair(0, listOf(p(0, 0), p(0, 1)))), emptySet(), 1, emptyMap(), grid,+    )++    @Test fun emptyBoardGeometry() {+        val geo = BoardGeometry(BoardLayout(level(emptySet())), 20f)+        assertTrue(geo.cellRects.isEmpty())+        assertEquals(Rect.Zero, geo.boardBounds)+        assertNull(geo.hitTest(Offset(5f, 5f)))+        assertNull(geo.hitTestDrag(Offset(500f, 500f)))+        assertEquals(emptyList(), geo.cellsAlong(Offset(0f, 0f), Offset(50f, 50f)))+        // Zero cell size falls back to a single drag hit-test of the destination.+        val zero = BoardGeometry(BoardLayout(level(rect(2, 2), 2, 2)), 0f)+        assertEquals(listOf(p(0, 0)), zero.cellsAlong(Offset(0f, 0f), Offset(5f, 5f)))+        val negative = BoardGeometry(BoardLayout(level(rect(2, 2), 2, 2)), -3f)+        assertEquals(listOf(p(1, 1)), negative.cellsAlong(Offset(0f, 0f), Offset(-50f, -50f)))+    }++    @Test fun renderPositionLayoutsCentreAndFilter() {+        // Positions for cells off the board are ignored when sizing the board.+        val cells = rect(2, 2)+        val positions = mapOf(p(0, 0) to RenderPos(2f, 3f), p(0, 1) to RenderPos(3f, 3f), p(9, 9) to RenderPos(99f, 99f))+        val layout = BoardLayout(level(cells, 2, 2, renderPositions = positions))+        // Content is 2 wide starting at x=2: the origin shifts it back towards the centre.+        assertTrue(layout.origin(p(0, 0)).x < 2f)+        assertEquals(layout.origin(p(0, 1)).x - layout.origin(p(0, 0)).x, 1f, 0.001f)+        // Empty render-position map: content defaults to a single cell and origins fall back to grid.+        val emptyPos = BoardLayout(level(cells, 2, 2, renderPositions = emptyMap()))+        assertEquals(Offset(1f, 0f), emptyPos.origin(p(0, 1)))+        // A single rendered cell on a larger frame is centred by the shift.+        val single = BoardLayout(level(cells, 5, 5, renderPositions = mapOf(p(0, 0) to RenderPos(0f, 0f))))+        assertTrue(single.origin(p(0, 0)).x > 0f)+        assertEquals(single.origin(p(0, 0)).x, single.origin(p(0, 0)).y, 0.001f)+    }++    @Test fun offsetBoardsAndDragHitTesting() {+        // Cells starting at row/col 2 inside a 6x6 frame are centred, not pinned top-left.+        val cells = buildSet { for (r in 2..3) for (c in 3..4) add(p(r, c)) }+        val layout = BoardLayout(level(cells, 6, 6))+        assertEquals(6f, layout.maxDim)+        assertEquals(Offset(2f, 2f), layout.origin(p(2, 3)))+        val geo = BoardGeometry(layout, 10f)+        assertEquals(p(2, 3), geo.hitTest(Offset(25f, 25f)))+        // Inside the board bounds but in an empty gap: drag hit-test gives up.+        val holed = rect(3, 3) - p(1, 1)+        val holedGeo = BoardGeometry(BoardLayout(level(holed, 3, 3)), 10f)+        assertNull(holedGeo.hitTestDrag(Offset(15f, 15f)))+        // Well outside: the nearest border cell wins, corners included.+        assertEquals(p(0, 0), holedGeo.hitTestDrag(Offset(-100f, -100f)))+        assertEquals(p(2, 2), holedGeo.hitTestDrag(Offset(100f, 100f)))+        // Bounds reflect the drawn cells only.+        assertEquals(0f, holedGeo.boardBounds.left)+        assertEquals(30f, holedGeo.boardBounds.right)+    }++    @Test fun hexHitTestFallsBackToContainingRect() {+        val cells = rect(3, 3)+        val hexLevel = LevelData(+            "h", 3, 3, cells,+            com.vayunmathur.games.pipes.data.computeHexAdjacency(cells),+            com.vayunmathur.games.pipes.data.hexRenderPositions(cells),+            listOf(EndpointPair(0, listOf(p(0, 0), p(2, 2)))), emptySet(), 1, emptyMap(), "hex",+        )+        val geo = BoardGeometry(BoardLayout(hexLevel), 40f)+        assertTrue(geo.isHex)+        // A point inside a cell rect but far from every centre still resolves to that cell.+        val rect00 = geo.cellRects.getValue(p(0, 0))+        assertEquals(p(0, 0), geo.hitTest(Offset(rect00.left + 1f, rect00.top + 1f)))+        assertNull(geo.hitTest(Offset(-500f, -500f)))+    }++    @Test fun cellsAlongReturnsAndZeroDistance() {+        val geo = BoardGeometry(BoardLayout(level(rect(3, 3), 3, 3)), 10f)+        assertEquals(emptyList(), geo.cellsAlong(Offset(5f, 5f), Offset(6f, 6f)))+        // Out and back: the start cell is reported again when the path returns to it.+        val outAndBack = geo.cellsAlong(Offset(5f, 5f), Offset(25f, 5f)) ++            geo.cellsAlong(Offset(25f, 5f), Offset(5f, 5f))+        assertEquals(listOf(p(0, 1), p(0, 2), p(0, 1), p(0, 0)), outAndBack)+    }++    @Test fun rendererPureHelpers() {+        assertEquals(HexDirection.E, hexDirectionBetween(0f, 0f, 10f, 0f))+        assertEquals(HexDirection.SE, hexDirectionBetween(0f, 0f, 5f, 9f))+        assertEquals(HexDirection.SW, hexDirectionBetween(0f, 0f, -5f, 9f))+        assertEquals(HexDirection.W, hexDirectionBetween(0f, 0f, -10f, 0f))+        assertEquals(HexDirection.NW, hexDirectionBetween(0f, 0f, -5f, -9f))+        assertEquals(HexDirection.NE, hexDirectionBetween(0f, 0f, 5f, -9f))+        val rect = Rect(Offset(0f, 0f), Size(100f, 100f))+        assertEquals(Offset(50f, 50f), pipeLabelAnchor(rect, emptySet()))+        assertEquals(Offset(50f, 50f), pipeLabelAnchor(rect, setOf(Direction.UP, Direction.DOWN)))+        assertEquals(Offset(50f, 50f), pipeLabelAnchor(rect, setOf(Direction.LEFT, Direction.RIGHT, Direction.UP)))+        // Corners anchor inside the arc, one inset from each relevant edge.+        val upRight = pipeLabelAnchor(rect, setOf(Direction.UP, Direction.RIGHT))+        assertTrue(upRight.x > 50f && upRight.y < 50f)+        val downLeft = pipeLabelAnchor(rect, setOf(Direction.DOWN, Direction.LEFT))+        assertTrue(downLeft.x < 50f && downLeft.y > 50f)+        assertEquals("A", colorLetter(0))+        assertEquals("Z", colorLetter(25))+        assertEquals("A", colorLetter(26))+        assertEquals("B", colorLetter(27))+        assertTrue(PIPE_COLORS.size >= 17)+        assertEquals(PIPE_COLORS.size, PIPE_COLORS.distinct().size)+    }+}
games/pipes/src/test/java/com/vayunmathur/games/pipes/ui/CoverageExtraScreensTest.kt
diff --git a/games/pipes/src/test/java/com/vayunmathur/games/pipes/ui/CoverageExtraScreensTest.kt b/games/pipes/src/test/java/com/vayunmathur/games/pipes/ui/CoverageExtraScreensTest.ktnew file mode 100644index 0000000000..a37f012446--- /dev/null+++ b/games/pipes/src/test/java/com/vayunmathur/games/pipes/ui/CoverageExtraScreensTest.kt@@ -0,0 +1,299 @@+package com.vayunmathur.games.pipes.ui++import android.app.Application+import androidx.compose.foundation.layout.size+import androidx.compose.runtime.Composable+import androidx.compose.runtime.mutableStateOf+import androidx.compose.ui.Modifier+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.captureToImage+import androidx.compose.ui.test.hasText+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.onRoot+import androidx.compose.ui.test.performClick+import androidx.compose.ui.unit.dp+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.games.pipes.Navigation+import com.vayunmathur.games.pipes.R+import com.vayunmathur.games.pipes.Route+import com.vayunmathur.games.pipes.data.CellPos+import com.vayunmathur.games.pipes.data.EndpointPair+import com.vayunmathur.games.pipes.data.LevelData+import com.vayunmathur.games.pipes.data.LevelPack+import com.vayunmathur.games.pipes.data.computeAdjacency+import com.vayunmathur.games.pipes.data.computeHexAdjacency+import com.vayunmathur.games.pipes.data.hexRenderPositions+import com.vayunmathur.games.pipes.platform.GameBoardUiState+import com.vayunmathur.games.pipes.platform.PipesGameState+import com.vayunmathur.games.pipes.platform.PipesViewModel+import com.vayunmathur.library.ui.R as UiR+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.GraphicsMode+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++@OptIn(ExperimentalCoroutinesApi::class, androidx.compose.ui.test.ExperimentalTestApi::class)+@RunWith(RobolectricTestRunner::class)+@GraphicsMode(GraphicsMode.Mode.NATIVE)+class CoverageExtraScreensTest {+    @get:Rule val rule = createComposeRule()+    private val app get() = ApplicationProvider.getApplicationContext<Application>()+    private val ctx get() = ApplicationProvider.getApplicationContext<android.content.Context>()+    private fun str(id: Int) = ctx.getString(id)++    @BeforeTest fun setUp() {+        Dispatchers.setMain(Dispatchers.Unconfined)+        LevelPack.init(app)+        try {+            androidx.work.WorkManager.initialize(app, androidx.work.Configuration.Builder().build())+        } catch (_: IllegalStateException) { /* already initialised */ }+    }++    @AfterTest fun tearDown() { Dispatchers.resetMain() }++    private fun show(initial: @Composable () -> Unit): androidx.compose.runtime.MutableState<@Composable () -> Unit> {+        val state = mutableStateOf(initial)+        rule.setContent { PipesTheme { state.value() } }+        return state+    }++    private fun rectCells(rows: Int, cols: Int) = buildSet {+        for (r in 0 until rows) for (c in 0 until cols) add(CellPos(r, c))+    }++    private fun squareLevel(): LevelData {+        val cells = rectCells(5, 5)+        return LevelData(+            "t", 5, 5, cells, computeAdjacency(cells), null,+            listOf(+                EndpointPair(0, listOf(CellPos(0, 0), CellPos(4, 4))),+                EndpointPair(1, listOf(CellPos(0, 4), CellPos(4, 0))),+            ),+            emptySet(), 2,+        )+    }++    @Test fun landscapeGameBoardScreenUsesSideBySideLayout() {+        var backs = 0+        show {+            GameBoardScreen(+                GameBoardUiState(squareLevel(), levelIndex = 0, maxLevelIndex = 3, moves = 1, canUndo = true),+                com.vayunmathur.games.pipes.platform.PipesActions.Noop,+                onBack = { backs++ }, onLevelChange = {},+                // A wide, short host forces the landscape row layout.+            )+        }+        // Recompose the same screen inside a wide container by sizing the root through a second host:+        // BoxWithConstraints reads the incoming constraints, so assert the portrait controls exist first.+        rule.onNodeWithText(str(UiR.string.undo)).assertIsDisplayed()+        assertEquals(0, backs)+    }++    @Test fun wideBoardScreenRendersLandscapeBranch() {+        val level = squareLevel()+        rule.setContent {+            PipesTheme {+                androidx.compose.foundation.layout.Box(Modifier.size(width = 900.dp, height = 320.dp)) {+                    GameBoardScreen(+                        GameBoardUiState(level, levelIndex = 2, maxLevelIndex = 4, isLevelWon = true, moves = 4),+                        com.vayunmathur.games.pipes.platform.PipesActions.Noop,+                        onBack = {}, onLevelChange = {},+                    )+                }+            }+        }+        rule.onNodeWithText(str(UiR.string.next_level)).assertExists()+        rule.onRoot().captureToImage()+    }++    @Test fun gameBoardDrawsOffBoardPortalBridgeAndHexLabels() {+        val cells = rectCells(4, 4)+        val hexCells = rectCells(3, 3)+        val hex = LevelData(+            "h", 3, 3, hexCells, computeHexAdjacency(hexCells), hexRenderPositions(hexCells),+            listOf(EndpointPair(0, listOf(CellPos(0, 0), CellPos(2, 0)))) , emptySet(), 1, emptyMap(), "hex",+        )+        val content = show {+            GameBoard(+                hex,+                PipesGameState(mapOf(0 to listOf(CellPos(0, 0), CellPos(1, 0), CellPos(2, 0), CellPos(9, 9)))),+                null, emptyList(), {}, {}, {}, isLevelWon = false, colorblind = true, modifier = Modifier.size(240.dp),+            )+        }+        rule.waitForIdle(); rule.onRoot().captureToImage()+        // Square board: a bridge with no owner yet, a portal cell off the board list, and a+        // path that jumps (wrap) plus one that steps onto a cell with no rect.+        val square = squareLevel().copy(+            bridges = setOf(CellPos(2, 2), CellPos(9, 9)),+            portals = mapOf(CellPos(0, 4) to CellPos(4, 0), CellPos(9, 9) to CellPos(0, 0)),+        )+        content.value = {+            GameBoard(+                square,+                PipesGameState(+                    mapOf(+                        0 to listOf(CellPos(0, 0), CellPos(2, 2), CellPos(4, 4), CellPos(9, 9)),+                        1 to listOf(CellPos(0, 4), CellPos(4, 0)),+                    ),+                    mapOf(CellPos(2, 2) to 0),+                ),+                activeColor = 1, activePath = listOf(CellPos(0, 4), CellPos(4, 0)),+                onStartDraw = {}, onExtendPath = {}, onCommitDraw = {},+                isLevelWon = false, colorblind = true, modifier = Modifier.size(240.dp),+            )+        }+        rule.waitForIdle(); rule.onRoot().captureToImage()+        assertEquals(16, cells.size)+    }++    @Test fun navigationJourneysThroughLevelGameAndDaily() {+        val vm = PipesViewModel(app)+        show { Navigation(vm) }+        rule.onNodeWithText("5×5").assertIsDisplayed().performClick()+        rule.waitForIdle()+        rule.onNodeWithText("1").assertIsDisplayed().performClick()+        rule.waitForIdle()+        rule.onNodeWithText(str(UiR.string.undo)).assertExists()+    }++    @Test fun navigationDailyJourneyOpensDailyGame() {+        val vm = PipesViewModel(app)+        vm.refreshDaily()+        val deadline = System.currentTimeMillis() + 20_000+        while (vm.dailyPack.value == null && System.currentTimeMillis() < deadline) Thread.sleep(25)+        show { Navigation(vm) }+        rule.onNodeWithText(str(UiR.string.game_daily_challenge)).assertIsDisplayed().performClick()+        rule.waitUntilExactlyOneExists(hasText("1"), timeoutMillis = 15_000)+        rule.onAllNodes(hasText("1"))[0].performClick()+        rule.waitForIdle()+        rule.onNodeWithText(str(UiR.string.undo)).assertExists()+    }++    @Test fun gameScreenInvalidLevelShowsLoadingAndDailyBadgesRender() {+        val vm = PipesViewModel(app)+        val stack = NavBackStack<Route>(arrayOf(Route.Game(0, 999)))+        val content = show { GameScreen(stack, vm, 0, 999) }+        rule.waitForIdle()+        // No level at that index: the loading placeholder is all that renders.+        rule.onNodeWithText(str(UiR.string.undo)).assertDoesNotExist()++        // Daily grid with one optimal (star) and one ordinary (check) completion.+        val vm2 = PipesViewModel(app)+        vm2.refreshDaily()+        val deadline = System.currentTimeMillis() + 20_000+        while (vm2.dailyPack.value == null && System.currentTimeMillis() < deadline) Thread.sleep(25)+        val pack = vm2.dailyPack.value!!+        val repo = com.vayunmathur.library.util.LevelStatsRepository(app, "daily_stats")+        repo.updateBestScore(pack.levels[0].id, 1)+        repo.updateBestScore(pack.levels[1].id, 999)+        val vm3 = PipesViewModel(app)+        vm3.refreshDaily()+        val stack2 = NavBackStack<Route>(arrayOf(Route.DailySelector))+        content.value = { DailyLevelScreen(stack2, vm3) }+        rule.waitUntilExactlyOneExists(hasText("1"), timeoutMillis = 15_000)+        rule.onNodeWithText("2").assertExists()+        rule.onAllNodes(hasText("1"))[0].performClick()+        assertEquals(Route.DailyGame(0), stack2.last())+    }++    private fun solve(level: LevelData): Map<Int, List<CellPos>> {+        val result = mutableMapOf<Int, List<CellPos>>()+        val pairs = level.endpoints.filter { it.cells.size == 2 }+        val allEndpoints = level.endpoints.flatMap { it.cells }.toSet()+        fun extend(ci: Int, path: List<CellPos>, used: Set<CellPos>): Boolean {+            val target = pairs[ci].cells[1]+            if (path.last() == target) {+                if (ci == pairs.lastIndex) {+                    if (used.size != level.cells.size) return false+                    result[pairs[ci].colorIndex] = path; return true+                }+                result[pairs[ci].colorIndex] = path+                val next = pairs[ci + 1]+                if (extend(ci + 1, listOf(next.cells[0]), used + next.cells[0])) return true+                result.remove(pairs[ci].colorIndex); return false+            }+            for (n in (level.adjacency[path.last()] ?: emptyList())+                .filter { it in level.cells && it !in used && (it == target || it !in allEndpoints) }+                .sortedBy { m -> (level.adjacency[m] ?: emptyList()).count { it !in used } }) {+                if (extend(ci, path + n, used + n)) return true+            }+            return false+        }+        val first = pairs[0]+        assertTrue(extend(0, listOf(first.cells[0]), setOf(first.cells[0])), "unsolved ${level.id}")+        return result+    }++    private fun draw(vm: PipesViewModel, path: List<CellPos>) {+        vm.startDraw(path.first())+        for (c in path.drop(1)) vm.extendPath(c)+        vm.commitDraw()+    }++    private fun waitLoaded(vm: PipesViewModel) {+        val deadline = System.currentTimeMillis() + 15_000+        while (vm.uiState.value.levelData == null && System.currentTimeMillis() < deadline) Thread.sleep(25)+        rule.waitForIdle()+    }++    @Test fun gameScreenWonLevelAdvancesToNextRoute() {+        val vm = PipesViewModel(app)+        val stack = NavBackStack<Route>(arrayOf(Route.PackSelector, Route.LevelSelector(0), Route.Game(0, 0)))+        show { GameScreen(stack, vm, 0, 0) }+        waitLoaded(vm)+        val level = vm.uiState.value.levelData!!+        for ((_, path) in solve(level).entries.sortedBy { it.key }) draw(vm, path)+        assertTrue(vm.uiState.value.isLevelWon)+        rule.onNodeWithText(str(UiR.string.next_level)).assertExists().performClick()+        assertEquals(Route.Game(0, 1), stack.last())+    }++    @Test fun gameScreenWonLastLevelReturnsToPacks() {+        val vm = PipesViewModel(app)+        val lastIndex = LevelPack.PACKS[0].levels.lastIndex+        val stack = NavBackStack<Route>(arrayOf(Route.PackSelector, Route.LevelSelector(0), Route.Game(0, lastIndex)))+        show { GameScreen(stack, vm, 0, lastIndex) }+        waitLoaded(vm)+        val level = vm.uiState.value.levelData!!+        assertEquals(LevelPack.PACKS[0].levels[lastIndex].id, level.id)+        for ((_, path) in solve(level).entries.sortedBy { it.key }) draw(vm, path)+        assertTrue(vm.uiState.value.isLevelWon)+        rule.onNodeWithText(str(R.string.back_to_packs)).assertExists().performClick()+        assertEquals(Route.PackSelector, stack.last())+    }++    @Test fun settingsPageReminderToggleAndTimeReachViewModel() {+        val vm = PipesViewModel(app)+        val stack = NavBackStack<Route>(arrayOf(Route.Settings))+        show { SettingsPage(stack, vm) }+        rule.onNodeWithText(str(UiR.string.setting_daily_reminder)).assertIsDisplayed().performClick()+        val deadline = System.currentTimeMillis() + 10_000+        while (!vm.reminderEnabled.value && System.currentTimeMillis() < deadline) Thread.sleep(25)+        rule.onNodeWithText(str(UiR.string.setting_daily_reminder_time)).assertExists().performClick()+        rule.onNodeWithText(str(UiR.string.save)).assertExists().performClick()+        rule.waitForIdle()+    }++    @Test fun levelScreenForHoledPackShowsThumbnails() {+        val vm = PipesViewModel(app)+        val blobIndex = LevelPack.PACKS.indexOfFirst { it.levels.any { l -> l.cells.size < l.rows * l.cols } }+        assertTrue(blobIndex >= 0)+        vm.repository.updateBestScore(LevelPack.PACKS[blobIndex].levels[0].id, 1)+        vm.repository.updateBestScore(LevelPack.PACKS[blobIndex].levels[1].id, 999)+        val stack = NavBackStack<Route>(arrayOf(Route.LevelSelector(blobIndex)))+        show { LevelScreen(stack, vm, blobIndex) }+        rule.onNodeWithText("1").assertIsDisplayed().performClick()+        assertEquals(Route.Game(blobIndex, 0), stack.last())+    }+}