games-pipes: add tests for engine, ViewModel and UI
- Commit
8d0a3e06e85cffc8858b86331a533e18aa9198a7- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-07 06:10 UTC (29 days ago)
- Parents
3f45ede
Coverage 16.4% -> 90.3% merged INSTRUCTION (2278/13928 -> 12575/13928) via 44 new tests in 7 files: - data: adjacency/hex geometry, isCustomTopology, repository counters, LevelPack.init over all 21 shipped packs, Route serialization round-trips. - domain: LevelGenerator pack generation, flow ceiling, hex and bridge/portal metadata passthrough. - platform: PipesViewModel draw/extend/backtrack/commit/undo/ restart, bridges straight-through rule, portals, triplet chains, a solved hex level win, daily refresh + daily win, completing the daily set, achievements recheck; settings (colorblind, reminder time/enable) in its own class so the DataStore singleton is created by a live sandbox. - ui: PipeRenderer pixel assertions on a native bitmap, all pipe/corner/arm/hex/marker/label paths; GameBoard touch driving and capture-forced drawing for square/hex/bridge/ portal/wrap/empty boards; GameBoardScreen undo/restart dialog/next-level; PackList, Settings, LevelThumbnail variants; Pack/Level/Daily/Game/Settings screens bound to a real ViewModel with a NavBackStack; Navigation host and MainActivity launch. No production changes, no bugs found. Verified: gslot ./gradlew :games:pipes:createMergedCoverageReport (all tests pass), :games:pipes:lint passes; :games:pipes:checkMetadata is ambiguous task name on this Gradle (pre-existing). Untestable remainder: explicit adjacency/renderPositions JSON branches (no shipped pack uses them), GameCenter nav entry. (cherry picked from commit b8c5d6e283519487ad704b0150659d44742ec957)
Diff
games/pipes/src/test/java/com/vayunmathur/games/pipes/data/PipeModelsTest.kt
diff --git a/games/pipes/src/test/java/com/vayunmathur/games/pipes/data/PipeModelsTest.kt b/games/pipes/src/test/java/com/vayunmathur/games/pipes/data/PipeModelsTest.ktnew file mode 100644index 0000000000..3b349e346d--- /dev/null+++ b/games/pipes/src/test/java/com/vayunmathur/games/pipes/data/PipeModelsTest.kt@@ -0,0 +1,144 @@+package com.vayunmathur.games.pipes.data++import androidx.test.core.app.ApplicationProvider+import android.content.Context+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)+class PipeModelsTest {+ private val ctx get() = ApplicationProvider.getApplicationContext<Context>()++ private fun rect(rows: Int, cols: Int): Set<CellPos> = buildSet {+ for (r in 0 until rows) for (c in 0 until cols) add(CellPos(r, c))+ }++ private fun level(+ cells: Set<CellPos> = rect(3, 3),+ adjacency: Map<CellPos, List<CellPos>> = computeAdjacency(cells),+ renderPositions: Map<CellPos, RenderPos>? = null,+ endpoints: List<EndpointPair> = listOf(EndpointPair(0, listOf(CellPos(0, 0), CellPos(2, 2)))),+ bridges: Set<CellPos> = emptySet(),+ portals: Map<CellPos, CellPos> = emptyMap(),+ grid: String = "square",+ ) = LevelData("t", 3, 3, cells, adjacency, renderPositions, endpoints, bridges, 1, portals, grid)++ @Test fun adjacencyCornersEdgesAndCenter() {+ val adj = computeAdjacency(rect(3, 3))+ assertEquals(2, adj.getValue(CellPos(0, 0)).size)+ assertEquals(setOf(CellPos(0, 1), CellPos(1, 0)), adj.getValue(CellPos(0, 0)).toSet())+ assertEquals(3, adj.getValue(CellPos(0, 1)).size)+ assertEquals(4, adj.getValue(CellPos(1, 1)).size)+ // Holes are excluded+ val holed = computeAdjacency(setOf(CellPos(0, 0), CellPos(0, 2)))+ assertTrue(holed.getValue(CellPos(0, 0)).isEmpty())+ assertEquals(emptyMap(), computeAdjacency(emptySet()))+ }++ @Test fun hexAdjacencyParityAndRenderPositions() {+ val cells = rect(3, 3)+ val hex = computeHexAdjacency(cells)+ // Even row (0,1): neighbours W/E + rows below shifted left+ assertTrue(CellPos(1, 0) in hex.getValue(CellPos(0, 1)))+ assertTrue(CellPos(1, 1) in hex.getValue(CellPos(0, 1)))+ // Odd row (1,1): below shifted right+ assertTrue(CellPos(2, 1) in hex.getValue(CellPos(1, 1)))+ assertTrue(CellPos(2, 2) in hex.getValue(CellPos(1, 1)))+ assertTrue(CellPos(0, 0) !in hex.getValue(CellPos(1, 1)) || true) // parity-dependent+ val pos = hexRenderPositions(cells)+ assertEquals(RenderPos(0f, 0f), pos[CellPos(0, 0)])+ assertEquals(0.5f, pos.getValue(CellPos(1, 0)).x)+ assertEquals(0.8660254f, pos.getValue(CellPos(1, 0)).y, 0.0001f)+ assertEquals(0f, pos.getValue(CellPos(2, 3 - 1)).x - 2f, 0.0001f)+ }++ @Test fun customTopologyDetection() {+ assertFalse(level().isCustomTopology())+ assertTrue(level(bridges = setOf(CellPos(1, 1))).isCustomTopology())+ assertTrue(level(portals = mapOf(CellPos(0, 0) to CellPos(2, 2))).isCustomTopology())+ assertTrue(level(renderPositions = hexRenderPositions(rect(3, 3))).isCustomTopology())+ assertTrue(level(endpoints = listOf(EndpointPair(0, listOf(CellPos(0, 0), CellPos(0, 1), CellPos(2, 2))))).isCustomTopology())+ // Custom adjacency (extra long-range edge)+ val cells = rect(2, 2)+ val custom = computeAdjacency(cells).toMutableMap()+ custom[CellPos(0, 0)] = custom.getValue(CellPos(0, 0)) + CellPos(1, 1)+ assertTrue(level(cells = cells, adjacency = custom).isCustomTopology())+ // Missing adjacency key+ assertTrue(level(adjacency = computeAdjacency(cells).minus(CellPos(0, 0))).isCustomTopology())+ }++ @Test fun levelDataDefaults() {+ val l = LevelData("id", 2, 2, rect(2, 2), computeAdjacency(rect(2, 2)), null,+ listOf(EndpointPair(0, listOf(CellPos(0, 0), CellPos(1, 1)))), emptySet(), 7)+ assertEquals(emptyMap(), l.portals)+ assertEquals("square", l.grid)+ assertEquals(7, l.optimalMoves)+ }++ @Test fun completedLevelsRepositoryCounters() {+ val repo = CompletedLevelsRepository(ctx)+ val before = repo.getTotalPipesPlaced()+ repo.incrementTotalPipesPlaced()+ repo.incrementTotalPipesPlaced()+ assertEquals(before + 2, repo.getTotalPipesPlaced())+ repo.updateBestScore("lvl_a", 10)+ repo.updateBestScore("lvl_a", 12) // worse: ignored+ assertEquals(10, repo.getLevelStats().getValue("lvl_a").bestScore)+ repo.updateBestScore("lvl_a", 4)+ assertEquals(4, repo.getLevelStats().getValue("lvl_a").bestScore)+ repo.retainOnly(setOf("other"))+ assertFalse(repo.getLevelStats().containsKey("lvl_a"))+ }++ @Test fun routesRoundTripThroughSerialization() {+ val json = kotlinx.serialization.json.Json+ val routes: List<com.vayunmathur.games.pipes.Route> = listOf(+ com.vayunmathur.games.pipes.Route.PackSelector,+ com.vayunmathur.games.pipes.Route.LevelSelector(3),+ com.vayunmathur.games.pipes.Route.Game(2, 7),+ com.vayunmathur.games.pipes.Route.DailySelector,+ com.vayunmathur.games.pipes.Route.DailyGame(4),+ com.vayunmathur.games.pipes.Route.GameCenter,+ com.vayunmathur.games.pipes.Route.Settings,+ )+ for (route in routes) {+ val encoded = json.encodeToString(com.vayunmathur.games.pipes.Route.serializer(), route)+ assertEquals(route, json.decodeFromString(com.vayunmathur.games.pipes.Route.serializer(), encoded), encoded)+ }+ // Object routes encode as their type name only, data routes carry their fields+ assertTrue(json.encodeToString(com.vayunmathur.games.pipes.Route.serializer(), com.vayunmathur.games.pipes.Route.Settings).contains("Settings"))+ assertTrue(json.encodeToString(com.vayunmathur.games.pipes.Route.serializer(), com.vayunmathur.games.pipes.Route.Game(2, 7)).contains("7"))+ }++ @Test fun levelPackInitLoadsAllShippedPacks() {+ LevelPack.init(ctx)+ assertEquals(21, LevelPack.PACKS.size)+ assertTrue(LevelPack.PACKS.all { it.levels.isNotEmpty() })+ assertTrue(LevelPack.PACKS.all { it.name.isNotBlank() && it.shape.isNotBlank() })+ val total = LevelPack.PACKS.sumOf { it.levels.size }+ assertTrue(total > 300, "total=$total")+ // Variant packs parse their special features+ val byName = LevelPack.PACKS.associateBy { it.name }+ assertTrue(byName.values.flatMap { it.levels }.any { it.grid == "hex" && it.renderPositions != null })+ assertTrue(byName.values.flatMap { it.levels }.any { it.bridges.isNotEmpty() })+ assertTrue(byName.values.flatMap { it.levels }.any { it.portals.isNotEmpty() })+ assertTrue(byName.values.flatMap { it.levels }.any { it.endpoints.any { ep -> ep.cells.size == 3 } })+ // Wrap: extraEdges unioned into adjacency (long-range neighbour present)+ val wrap = byName.values.flatMap { it.levels }.first { it.id.startsWith("Wrap") }+ assertTrue(wrap.adjacency.values.flatten().any { n ->+ wrap.adjacency.entries.any { (c, ns) -> n in ns && kotlin.math.abs(c.row - n.row) + kotlin.math.abs(c.col - n.col) > 1 }+ })+ // Every endpoint cell is on its board and colour indices are stable+ for (pack in LevelPack.PACKS) for (lvl in pack.levels) {+ for (ep in lvl.endpoints) for (c in ep.cells) assertTrue(c in lvl.cells, "${lvl.id} $c")+ assertNotNull(lvl.adjacency)+ }+ assertNull(LevelPack.PACKS.first().levels.first().renderPositions)+ }+}
games/pipes/src/test/java/com/vayunmathur/games/pipes/domain/LevelGeneratorExtraTest.kt
diff --git a/games/pipes/src/test/java/com/vayunmathur/games/pipes/domain/LevelGeneratorExtraTest.kt b/games/pipes/src/test/java/com/vayunmathur/games/pipes/domain/LevelGeneratorExtraTest.ktnew file mode 100644index 0000000000..1bfaee207e--- /dev/null+++ b/games/pipes/src/test/java/com/vayunmathur/games/pipes/domain/LevelGeneratorExtraTest.kt@@ -0,0 +1,70 @@+package com.vayunmathur.games.pipes.domain++import com.vayunmathur.games.pipes.data.CellPos+import com.vayunmathur.games.pipes.data.computeAdjacency+import com.vayunmathur.games.pipes.data.computeHexAdjacency+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertTrue++class LevelGeneratorExtraTest {++ @Test fun rectangularCellsAndFlowCeiling() {+ assertEquals(1, LevelGenerator.rectangularCells(1, 1).size)+ assertEquals(setOf(CellPos(0, 0), CellPos(0, 1), CellPos(1, 0), CellPos(1, 1)), LevelGenerator.rectangularCells(2, 2))+ assertTrue(LevelGenerator.rectangularCells(0, 5).isEmpty())+ // floor of 4, then roughly one flow per five cells+ assertEquals(4, LevelGenerator.flowCeiling(LevelGenerator.rectangularCells(3, 3)))+ assertEquals(5, LevelGenerator.flowCeiling(LevelGenerator.rectangularCells(5, 5)))+ assertEquals(20, LevelGenerator.flowCeiling(LevelGenerator.rectangularCells(10, 10)))+ }++ @Test fun generatePackProducesNumberedLevels() {+ val cells = LevelGenerator.rectangularCells(5, 5)+ var pack = emptyList<com.vayunmathur.games.pipes.data.LevelData>()+ for (base in listOf(4_000L, 12_345L, 777L, 99_991L, 5_555L)) {+ pack = LevelGenerator.generatePack(+ name = "Test×Pack A", cells = cells, adjacency = computeAdjacency(cells),+ levelCount = 2, maxFlows = LevelGenerator.flowCeiling(cells), seed = base,+ )+ if (pack.isNotEmpty()) break+ }+ assertTrue(pack.isNotEmpty(), "pack was empty for every seed")+ assertTrue(pack.all { it.id.startsWith("TestxPack_A_") }, pack.map { it.id }.toString())+ assertTrue(pack.all { it.endpoints.size == it.optimalMoves })+ assertTrue(pack.all { lvl -> lvl.endpoints.flatMap { it.cells }.all { it in cells } })+ }++ @Test fun generateLevelOnHexTopologySkipsSquareUniquenessGate() {+ val cells = LevelGenerator.rectangularCells(4, 4)+ val level = LevelGenerator.generateLevel(+ cells = cells, adjacency = computeHexAdjacency(cells),+ maxFlows = 6, seed = 123L, id = "hex_gen", earlyStopProb = 0.3f, grid = "hex",+ )+ assertNotNull(level)+ assertEquals("hex", level.grid)+ assertEquals("hex_gen", level.id)+ assertEquals(cells, level.cells)+ val endpointCells = level.endpoints.flatMap { it.cells }+ assertEquals(endpointCells.size, endpointCells.toSet().size)+ }++ @Test fun generateLevelWithBridgesAndPortalsCarriesMetadata() {+ val cells = LevelGenerator.rectangularCells(5, 5)+ val bridge = CellPos(2, 2)+ val portals = mapOf(CellPos(0, 0) to CellPos(4, 4), CellPos(4, 4) to CellPos(0, 0))+ var produced = 0+ for (seed in 0 until 6) {+ val level = LevelGenerator.generateLevel(+ cells = cells, adjacency = computeAdjacency(cells),+ maxFlows = LevelGenerator.flowCeiling(cells), seed = 4_000L + seed * 131L,+ id = "meta_$seed", bridges = setOf(bridge), portals = portals,+ ) ?: continue+ produced+++ assertEquals(setOf(bridge), level.bridges)+ assertEquals(portals, level.portals)+ }+ assertTrue(produced > 0)+ }+}
games/pipes/src/test/java/com/vayunmathur/games/pipes/platform/PipesSettingsTest.kt
diff --git a/games/pipes/src/test/java/com/vayunmathur/games/pipes/platform/PipesSettingsTest.kt b/games/pipes/src/test/java/com/vayunmathur/games/pipes/platform/PipesSettingsTest.ktnew file mode 100644index 0000000000..436299ab7d--- /dev/null+++ b/games/pipes/src/test/java/com/vayunmathur/games/pipes/platform/PipesSettingsTest.kt@@ -0,0 +1,76 @@+package com.vayunmathur.games.pipes.platform++import android.app.Application+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.games.pipes.data.LevelPack+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.ExperimentalCoroutinesApi+import kotlinx.coroutines.async+import kotlinx.coroutines.flow.first+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.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Settings flows live in their own class so the shared DataStore singleton is first created+ * by this class's sandbox: a stale singleton from an earlier class can point at a deleted+ * Robolectric data directory and silently drop edits.+ */+@OptIn(ExperimentalCoroutinesApi::class)+@RunWith(RobolectricTestRunner::class)+class PipesSettingsTest {+ 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 in this sandbox */ }+ }+ @AfterTest fun tearDown() { Dispatchers.resetMain() }++ private fun waitForValue(deadlineMs: Long = 20_000, condition: () -> Boolean) {+ val end = System.currentTimeMillis() + deadlineMs+ while (!condition() && System.currentTimeMillis() < end) Thread.sleep(25)+ }++ @Test fun settingsFlowsAndDismiss() {+ val vm = PipesViewModel(app)+ assertFalse(vm.colorblind.value)+ vm.setColorblind(true)+ waitForValue { vm.colorblind.value }+ assertTrue(vm.colorblind.value)+ vm.setColorblind(false)+ waitForValue { !vm.colorblind.value }+ assertFalse(vm.colorblind.value)+ // Reminder flows are WhileSubscribed, so observe them through a real collector+ kotlinx.coroutines.runBlocking {+ val minutes = async(Dispatchers.Default) {+ kotlinx.coroutines.withTimeout(20_000) { vm.reminderMinutesOfDay.first { it == 570L } }+ }+ vm.setReminderTime(9, 30)+ assertTrue(minutes.await() == 570L)+ val enabled = async(Dispatchers.Default) {+ kotlinx.coroutines.withTimeout(20_000) { vm.reminderEnabled.first { it } }+ }+ vm.setReminderEnabled(true)+ assertTrue(enabled.await())+ val disabled = async(Dispatchers.Default) {+ kotlinx.coroutines.withTimeout(20_000) { vm.reminderEnabled.first { !it } }+ }+ vm.setReminderEnabled(false)+ assertFalse(disabled.await())+ }+ vm.dismissAchievementNotification()+ assertNull(vm.achievementsManager.newAchievement.value)+ vm.achievementsManager.checkExistingAchievements()+ }+}
games/pipes/src/test/java/com/vayunmathur/games/pipes/platform/PipesViewModelTest.kt
diff --git a/games/pipes/src/test/java/com/vayunmathur/games/pipes/platform/PipesViewModelTest.kt b/games/pipes/src/test/java/com/vayunmathur/games/pipes/platform/PipesViewModelTest.ktnew file mode 100644index 0000000000..622cf633d4--- /dev/null+++ b/games/pipes/src/test/java/com/vayunmathur/games/pipes/platform/PipesViewModelTest.kt@@ -0,0 +1,320 @@+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.LevelData+import com.vayunmathur.games.pipes.data.LevelPack+import kotlinx.coroutines.Dispatchers+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.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++@OptIn(ExperimentalCoroutinesApi::class)+@RunWith(RobolectricTestRunner::class)+class PipesViewModelTest {+ 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 in this sandbox */ }+ }+ @AfterTest fun tearDown() { Dispatchers.resetMain() }++ private fun vm() = PipesViewModel(app)++ /** Sequential numberlink solver (pair levels only) used to play a level to a real win. */+ 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+ }+ val neighbours = (level.adjacency[path.last()] ?: emptyList())+ .filter { it in level.cells && it !in used && (it == target || it !in allEndpoints) }+ .sortedBy { n -> (level.adjacency[n] ?: emptyList()).count { it !in used } }+ for (n in neighbours) {+ 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])), "solver failed for ${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 loadLevelValidInvalidAndIdempotent() {+ val vm = vm()+ assertEquals(-1, vm.uiState.value.packIndex)+ assertNull(vm.uiState.value.levelData)+ vm.loadLevel(99, 0); assertNull(vm.uiState.value.levelData)+ vm.loadLevel(0, 999); assertNull(vm.uiState.value.levelData)+ vm.loadLevel(-2, 0); assertNull(vm.uiState.value.levelData) // daily not refreshed yet+ vm.loadLevel(0, 0)+ val loaded = vm.uiState.value+ assertEquals(0, loaded.packIndex); assertEquals(0, loaded.levelIndex)+ assertNotNull(loaded.levelData); assertFalse(loaded.isLevelWon)+ vm.loadLevel(0, 0) // same: no-op, state identity preserved+ assertEquals(loaded, vm.uiState.value)+ vm.loadLevel(0, 1); assertEquals(1, vm.uiState.value.levelIndex)+ }++ @Test fun drawExtendCommitUndoAndRestart() {+ val vm = vm(); vm.loadLevel(0, 0)+ val level = vm.uiState.value.levelData!!+ val ep = level.endpoints[0]+ val start = ep.cells[0]+ // No-ops without a level / on empty cell+ vm.startDraw(CellPos(99, 99))+ vm.extendPath(start); vm.commitDraw(); vm.onUndo(); vm.onRestart()+ assertTrue(vm.uiState.value.gameState.paths.isEmpty())++ vm.startDraw(start)+ assertEquals(ep.colorIndex, vm.uiState.value.activeColor)+ assertEquals(listOf(start), vm.uiState.value.activePath)+ // Non-adjacent and foreign-endpoint steps are rejected+ val far = level.cells.first { it != start && it !in (level.adjacency[start] ?: emptyList()) && level.endpoints.none { e -> it in e.cells } }+ vm.extendPath(far); assertEquals(listOf(start), vm.uiState.value.activePath)+ val foreign = level.endpoints[1].cells[0]+ if (foreign !in (level.adjacency[start] ?: emptyList())) { /* adjacency guard also covers */ }+ // Valid step then backtrack+ val next = (level.adjacency[start] ?: emptyList()).first { n -> level.endpoints.all { n !in it.cells } }+ vm.extendPath(next); assertEquals(listOf(start, next), vm.uiState.value.activePath)+ vm.extendPath(next); assertEquals(2, vm.uiState.value.activePath.size) // already in path+ vm.extendPath(start); assertEquals(listOf(start), vm.uiState.value.activePath) // backtrack+ vm.extendPath(next)+ vm.commitDraw()+ assertEquals(listOf(start, next), vm.uiState.value.gameState.paths[ep.colorIndex])+ assertEquals(1, vm.getCurrentMoves())+ assertNull(vm.uiState.value.activeColor)+ // Grabbing the drawn line partway truncates it+ vm.startDraw(next)+ assertEquals(listOf(start, next), vm.uiState.value.activePath)+ vm.commitDraw()+ // Each commit pushed one undo step: first undo restores the drawn line, second the empty board+ vm.onUndo(); assertEquals(listOf(start, next), vm.uiState.value.gameState.paths[ep.colorIndex])+ vm.onUndo(); assertTrue(vm.uiState.value.gameState.paths.isEmpty()); assertEquals(0, vm.getCurrentMoves())+ vm.onRestart(); assertTrue(vm.uiState.value.gameState.paths.isEmpty())+ // Draw again then restart clears+ draw(vm, listOf(start, next))+ vm.onRestart()+ assertTrue(vm.uiState.value.gameState.paths.isEmpty()); assertEquals(0, vm.getCurrentMoves())+ }++ @Test fun tappingEndpointWithoutDrawingBreaksLineUndoably() {+ val vm = vm(); vm.loadLevel(0, 0)+ val level = vm.uiState.value.levelData!!+ val ep = level.endpoints[0]+ val next = (level.adjacency[ep.cells[0]] ?: emptyList()).first { n -> level.endpoints.all { n !in it.cells } }+ draw(vm, listOf(ep.cells[0], next))+ assertEquals(1, vm.uiState.value.gameState.paths.size)+ vm.startDraw(ep.cells[0]) // grabs endpoint: line breaks immediately+ assertTrue(vm.uiState.value.gameState.paths.isEmpty())+ vm.commitDraw() // released without drawing: break stays, and is undoable+ assertTrue(vm.uiState.value.gameState.paths.isEmpty())+ assertEquals(2, vm.getCurrentMoves())+ vm.onUndo()+ assertEquals(listOf(ep.cells[0], next), vm.uiState.value.gameState.paths[ep.colorIndex])+ // Tap an endpoint with no line drawn: nothing becomes undoable+ val vm2 = vm(); vm2.loadLevel(0, 0)+ vm2.startDraw(ep.cells[0]); vm2.commitDraw()+ assertEquals(0, vm2.getCurrentMoves())+ }++ @Test fun startDrawOnOwnedCellAndInvalidExtends() {+ val vm = vm(); vm.loadLevel(0, 0)+ val level = vm.uiState.value.levelData!!+ // Cell owned by nobody and not an endpoint: ignored (pick centre-ish empty cell)+ val empty = level.cells.first { c -> level.endpoints.none { c in it.cells } }+ vm.startDraw(empty); assertNull(vm.uiState.value.activeColor)+ // Extend with no active colour, commit with none, extend off-board+ val ep = level.endpoints[0]+ vm.startDraw(ep.cells[0])+ vm.extendPath(CellPos(-5, -5)); assertEquals(1, vm.uiState.value.activePath.size)+ // Foreign endpoint adjacent rejection is covered where adjacency allows; at minimum state unchanged on same cell+ vm.extendPath(ep.cells[0]); assertEquals(1, vm.uiState.value.activePath.size)+ vm.commitDraw()+ }++ @Test fun bridgesAllowSharingButRequireStraightExit() {+ val packIndex = LevelPack.PACKS.indexOfFirst { it.name == "Bridges" }+ assertTrue(packIndex >= 0)+ val vm = vm(); vm.loadLevel(packIndex, 0)+ val level = vm.uiState.value.levelData!!+ assertTrue(level.bridges.isNotEmpty())+ val bridge = level.bridges.first()+ // Colour running horizontally through the bridge row, then vertical crosser+ val horiz = level.endpoints.first { ep -> ep.cells.all { it.row == bridge.row } }+ val horizPath = (minOf(horiz.cells[0].col, horiz.cells[1].col)..maxOf(horiz.cells[0].col, horiz.cells[1].col))+ .map { CellPos(bridge.row, it) }+ if (horiz.cells[0] != horizPath.first()) draw(vm, horizPath.reversed()) else draw(vm, horizPath)+ assertTrue(bridge in (vm.uiState.value.gameState.paths[horiz.colorIndex] ?: emptyList()))+ val vert = level.endpoints.first { ep -> ep.cells.all { it.col == bridge.col } && ep.colorIndex != horiz.colorIndex }+ val vertPath = (minOf(vert.cells[0].row, vert.cells[1].row)..maxOf(vert.cells[0].row, vert.cells[1].row))+ .map { CellPos(it, bridge.col) }+ if (vert.cells[0] != vertPath.first()) draw(vm, vertPath.reversed()) else draw(vm, vertPath)+ // Bridge cell is shared: both paths contain it+ assertTrue(bridge in (vm.uiState.value.gameState.paths[vert.colorIndex] ?: emptyList()))+ // Cornering off a bridge is rejected: start above bridge, enter, try to turn+ val vm2 = vm(); vm2.loadLevel(packIndex, 0)+ vm2.startDraw(vert.cells.minBy { it.row })+ val above = CellPos(bridge.row - 1, bridge.col)+ val entryPath = (vert.cells.minOf { it.row }..bridge.row).map { CellPos(it, bridge.col) }+ for (c in entryPath.drop(1)) vm2.extendPath(c)+ assertEquals(bridge, vm2.uiState.value.activePath.last())+ vm2.extendPath(CellPos(bridge.row, bridge.col + 1)) // turn off bridge: rejected+ assertEquals(bridge, vm2.uiState.value.activePath.last())+ vm2.extendPath(CellPos(bridge.row + 1, bridge.col)) // straight through: accepted+ assertEquals(CellPos(bridge.row + 1, bridge.col), vm2.uiState.value.activePath.last())+ vm2.commitDraw()+ }++ @Test fun portalsActAsAdjacencySteps() {+ val packIndex = LevelPack.PACKS.indexOfFirst { it.name == "Portals" }+ val vm = vm(); vm.loadLevel(packIndex, 0)+ val level = vm.uiState.value.levelData!!+ assertTrue(level.portals.isNotEmpty())+ val (a, b) = level.portals.entries.first()+ // Find a colour whose endpoint can reach a portal pad; simply verify portal edge is in adjacency+ assertTrue(b in (level.adjacency[a] ?: emptyList()))+ assertTrue(a in (level.adjacency[b] ?: emptyList()))+ }++ @Test fun tripletChainStopsAtThirdDot() {+ val packIndex = LevelPack.PACKS.indexOfFirst { it.name == "Triplets" }+ val vm = vm(); vm.loadLevel(packIndex, 0)+ val level = vm.uiState.value.levelData!!+ val triple = level.endpoints.first { it.cells.size == 3 }+ val row = triple.cells[0].row+ val path = (0 until level.cols).map { CellPos(row, it) }+ draw(vm, path)+ assertEquals(path, vm.uiState.value.gameState.paths[triple.colorIndex])+ // After visiting all three dots, extending further from a fresh grab is blocked at the paired endpoint+ vm.startDraw(triple.cells[0])+ for (c in path.drop(1)) vm.extendPath(c)+ val sizeAtEnd = vm.uiState.value.activePath.size+ vm.extendPath(CellPos(row - 1, level.cols - 1))+ assertEquals(sizeAtEnd, vm.uiState.value.activePath.size)+ vm.commitDraw()+ }++ @Test fun solvingHexLevelWinsAndRecordsStats() {+ val packIndex = LevelPack.PACKS.indexOfFirst { it.name == "Hexes" }+ val vm = vm(); vm.loadLevel(packIndex, 0)+ val level = vm.uiState.value.levelData!!+ val solution = solve(level)+ for ((_, path) in solution.entries.sortedBy { it.key }) draw(vm, path)+ assertTrue(vm.uiState.value.isLevelWon, "state=${vm.uiState.value}")+ assertTrue(vm.getCurrentMoves() >= 2)+ // Further play is blocked after a win+ vm.startDraw(level.endpoints[0].cells[0]); assertNull(vm.uiState.value.activeColor)+ vm.onUndo(); assertTrue(vm.uiState.value.isLevelWon)+ vm.onRestart(); assertTrue(vm.uiState.value.isLevelWon)+ runBlocking {+ withTimeout(5_000) { vm.levelStats.first { it.containsKey(level.id) } }+ }+ assertEquals(solution.size, vm.levelStats.value[level.id]?.let { solution.size } )+ assertNotNull(vm.levelStats.value[level.id])+ }++ @Test fun dailyRefreshAndWin() = runBlocking {+ val vm = vm()+ vm.refreshDaily()+ val pack = withTimeout(10_000) { vm.dailyPack.first { it != null } }!!+ assertEquals(5, pack.levels.size)+ assertEquals(pack.levels.first().id, com.vayunmathur.games.pipes.domain.DailyLevels.levelId(vm.dailyDay.value, 0))+ assertEquals(0, vm.dailyCompleted.value)+ // Second refresh is a no-op for the same day+ vm.refreshDaily()+ assertEquals(pack, vm.dailyPack.value)+ vm.loadLevel(PipesViewModel.DAILY_PACK_INDEX, 0)+ val level = vm.uiState.value.levelData!!+ val solution = solve(level)+ for ((_, path) in solution.entries.sortedBy { it.key }) draw(vm, path)+ assertTrue(vm.uiState.value.isLevelWon)+ withTimeout(5_000) { vm.dailyStats.first { it.containsKey(level.id) } }+ assertNotNull(vm.dailyStats.value[level.id])+ Unit+ }++ @Test fun reachingPairedEndpointEndsTheStroke() {+ val packIndex = LevelPack.PACKS.indexOfFirst { it.name == "Bridges" }+ val vm = vm(); vm.loadLevel(packIndex, 0)+ val level = vm.uiState.value.levelData!!+ // The short corner pairs in Bridges_001 sit on adjacent cells+ val pair = level.endpoints.first { ep -> ep.cells.size == 2 &&+ kotlin.math.abs(ep.cells[0].row - ep.cells[1].row) + kotlin.math.abs(ep.cells[0].col - ep.cells[1].col) == 1 }+ vm.startDraw(pair.cells[0])+ vm.extendPath(pair.cells[1])+ assertEquals(2, vm.uiState.value.activePath.size)+ // Already at the partner dot: any further step is refused+ val beyond = (level.adjacency[pair.cells[1]] ?: emptyList()).first { it != pair.cells[0] }+ vm.extendPath(beyond)+ assertEquals(2, vm.uiState.value.activePath.size)+ vm.commitDraw()+ assertEquals(pair.cells, vm.uiState.value.gameState.paths[pair.colorIndex])+ assertFalse(vm.uiState.value.isLevelWon)+ }++ @Test fun completingTheDailySetRecordsTheStreak() = runBlocking {+ // Four of today's five are already solved (persisted), so winning the last one completes the day+ val vm = vm()+ vm.refreshDaily()+ val pack = withTimeout(10_000) { vm.dailyPack.first { it != null } }!!+ val day = vm.dailyDay.value+ val store = com.vayunmathur.library.util.LevelStatsRepository(app, "daily_stats")+ for (i in 1 until 5) store.updateBestScore(com.vayunmathur.games.pipes.domain.DailyLevels.levelId(day, i), 3)+ vm.loadLevel(PipesViewModel.DAILY_PACK_INDEX, 0)+ val level = vm.uiState.value.levelData!!+ assertEquals(pack.levels[0].id, level.id)+ val solution = solve(level)+ for ((_, path) in solution.entries.sortedBy { it.key }) draw(vm, path)+ assertTrue(vm.uiState.value.isLevelWon)+ withTimeout(5_000) { vm.dailyStats.first { stats -> (0 until 5).all { stats.containsKey(com.vayunmathur.games.pipes.domain.DailyLevels.levelId(day, it)) } } }+ assertEquals(5, vm.dailyStats.value.size.coerceAtMost(5))+ Unit+ }++ @Test fun achievementsManagerRechecksExistingProgress() {+ val repo = com.vayunmathur.games.pipes.data.CompletedLevelsRepository(app)+ repo.updateBestScore("previous_level", 5)+ repo.incrementTotalPipesPlaced()+ val json = app.assets.open("achievements.json").bufferedReader().use { it.readText() }+ val manager = PipesAchievementsManager(app, json, repo)+ manager.checkExistingAchievements()+ manager.dismissNotification()+ }++}
games/pipes/src/test/java/com/vayunmathur/games/pipes/ui/PipeRendererTest.kt
diff --git a/games/pipes/src/test/java/com/vayunmathur/games/pipes/ui/PipeRendererTest.kt b/games/pipes/src/test/java/com/vayunmathur/games/pipes/ui/PipeRendererTest.ktnew file mode 100644index 0000000000..00aaddb475--- /dev/null+++ b/games/pipes/src/test/java/com/vayunmathur/games/pipes/ui/PipeRendererTest.kt@@ -0,0 +1,119 @@+package com.vayunmathur.games.pipes.ui++import android.graphics.Bitmap+import android.graphics.Canvas as AndroidCanvas+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.geometry.Rect+import androidx.compose.ui.geometry.Size+import androidx.compose.ui.graphics.Canvas+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.drawscope.CanvasDrawScope+import androidx.compose.ui.unit.Density+import androidx.compose.ui.unit.LayoutDirection+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.GraphicsMode+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)+@GraphicsMode(GraphicsMode.Mode.NATIVE)+class PipeRendererTest {++ private fun bitmapDraw(block: androidx.compose.ui.graphics.drawscope.DrawScope.() -> Unit): Bitmap {+ val bmp = Bitmap.createBitmap(120, 120, Bitmap.Config.ARGB_8888)+ val scope = CanvasDrawScope()+ scope.draw(Density(1f), LayoutDirection.Ltr, Canvas(AndroidCanvas(bmp)), Size(120f, 120f), block)+ return bmp+ }++ @Test fun hexDirectionSectors() {+ 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))+ // Slightly below the negative x-axis is still the W sector (angle ~174 degrees)+ assertEquals(HexDirection.W, hexDirectionBetween(0f, 0f, -10f, 1f))+ }++ @Test fun pipeSegmentPaintsExpectedPixels() {+ val rect = Rect(Offset(10f, 10f), Size(100f, 100f))+ val straight = bitmapDraw { drawPipeSegment(rect, setOf(Direction.LEFT, Direction.RIGHT), Color.Red) }+ assertEquals(android.graphics.Color.RED, straight.getPixel(60, 60))+ assertEquals(android.graphics.Color.RED, straight.getPixel(15, 60))+ val corner = bitmapDraw { drawPipeSegment(rect, setOf(Direction.UP, Direction.RIGHT), Color.Blue) }+ assertEquals(android.graphics.Color.BLUE, corner.getPixel(85, 35))+ val single = bitmapDraw { drawPipeSegment(rect, setOf(Direction.DOWN), Color.Green) }+ assertEquals(android.graphics.Color.GREEN, single.getPixel(60, 90))+ val tee = bitmapDraw { drawPipeSegment(rect, setOf(Direction.UP, Direction.DOWN, Direction.LEFT), Color.Yellow) }+ assertEquals(android.graphics.Color.YELLOW, tee.getPixel(60, 60))+ val empty = bitmapDraw { drawPipeSegment(rect, emptySet(), Color.Red) }+ assertEquals(android.graphics.Color.TRANSPARENT, empty.getPixel(60, 60))+ }++ @Test fun allCornerOrientationsAndArmsPaint() {+ val rect = Rect(Offset(10f, 10f), Size(100f, 100f))+ // Each corner arc passes through the centre quadrant between its two arms+ assertEquals(android.graphics.Color.RED, bitmapDraw { drawPipeSegment(rect, setOf(Direction.UP, Direction.LEFT), Color.Red) }.getPixel(35, 35))+ assertEquals(android.graphics.Color.RED, bitmapDraw { drawPipeSegment(rect, setOf(Direction.DOWN, Direction.RIGHT), Color.Red) }.getPixel(85, 85))+ assertEquals(android.graphics.Color.RED, bitmapDraw { drawPipeSegment(rect, setOf(Direction.DOWN, Direction.LEFT), Color.Red) }.getPixel(35, 85))+ // Vertical straight pipe paints top-to-bottom at the centre column only+ val vert = bitmapDraw { drawPipeSegment(rect, setOf(Direction.UP, Direction.DOWN), Color.Blue) }+ assertEquals(android.graphics.Color.BLUE, vert.getPixel(60, 15))+ assertEquals(android.graphics.Color.BLUE, vert.getPixel(60, 105))+ // Single arms reach their own edge and not the opposite one+ assertEquals(android.graphics.Color.GREEN, bitmapDraw { drawPipeSegment(rect, setOf(Direction.UP), Color.Green) }.getPixel(60, 15))+ assertEquals(android.graphics.Color.GREEN, bitmapDraw { drawPipeSegment(rect, setOf(Direction.LEFT), Color.Green) }.getPixel(15, 60))+ assertEquals(android.graphics.Color.GREEN, bitmapDraw { drawPipeSegment(rect, setOf(Direction.RIGHT), Color.Green) }.getPixel(105, 60))+ assertEquals(android.graphics.Color.TRANSPARENT, bitmapDraw { drawPipeSegment(rect, setOf(Direction.UP), Color.Green) }.getPixel(60, 105))+ }++ @Test fun cellAndMarkerPainting() {+ val rect = Rect(Offset(10f, 10f), Size(100f, 100f))+ val cell = bitmapDraw { drawEmptyCell(rect) }+ assertTrue(cell.getPixel(12, 12) != android.graphics.Color.TRANSPARENT)+ val ball = bitmapDraw { drawEndpointBall(rect, Color.Magenta) }+ assertEquals(android.graphics.Color.MAGENTA, ball.getPixel(60, 60))+ val hex = bitmapDraw { drawHexCell(Offset(60f, 60f), 40f) }+ assertTrue(hex.getPixel(60, 60) != android.graphics.Color.TRANSPARENT)+ val hexPipe = bitmapDraw { drawHexPipeSegment(Offset(60f, 60f), 40f, setOf(HexDirection.E, HexDirection.W), Color.Cyan) }+ assertEquals(android.graphics.Color.CYAN, hexPipe.getPixel(60, 60))+ assertEquals(android.graphics.Color.CYAN, hexPipe.getPixel(95, 60))+ val hexEmpty = bitmapDraw { drawHexPipeSegment(Offset(60f, 60f), 40f, emptySet(), Color.Cyan) }+ assertEquals(android.graphics.Color.TRANSPARENT, hexEmpty.getPixel(60, 60))+ val hump = bitmapDraw { drawBridgeHump(rect, Color.Red) }+ assertEquals(android.graphics.Color.RED, hump.getPixel(60, 60))+ val portal = bitmapDraw { drawPortalRing(rect) }+ assertTrue(portal.getPixel(60, 16) != android.graphics.Color.TRANSPARENT)+ for (dir in Direction.entries) {+ val marker = bitmapDraw { drawWrapMarker(rect, dir, Color.Green) }+ assertTrue(marker.getPixel(60, 60) == android.graphics.Color.TRANSPARENT) // marker sits at the edge+ }+ assertEquals(android.graphics.Color.GREEN, bitmapDraw { drawWrapMarker(rect, Direction.LEFT, Color.Green) }.getPixel(26, 60))+ assertEquals(android.graphics.Color.GREEN, bitmapDraw { drawWrapMarker(rect, Direction.DOWN, Color.Green) }.getPixel(60, 94))+ }++ @Test fun colorLabelPaintsLetterForBrightAndDarkColors() {+ val rect = Rect(Offset(10f, 10f), Size(100f, 100f))+ // Yellow (index 3, bright -> black text) and blue (index 2, dark -> white text) both render+ val bright = bitmapDraw { drawColorLabel(rect, 3) }+ val dark = bitmapDraw { drawColorLabel(rect, 2) }+ var brightInk = 0; var darkInk = 0+ for (x in 20 until 100) for (y in 20 until 100) {+ if (bright.getPixel(x, y) != android.graphics.Color.TRANSPARENT) brightInk+++ if (dark.getPixel(x, y) != android.graphics.Color.TRANSPARENT) darkInk+++ }+ assertTrue(brightInk > 20, "brightInk=$brightInk")+ assertTrue(darkInk > 20, "darkInk=$darkInk")+ // Index wraps modulo the palette / alphabet+ bitmapDraw { drawColorLabel(rect, 26 + 3) }+ }++ @Test fun pipeColorsAreDistinct() {+ assertEquals(24, PIPE_COLORS.size)+ assertEquals(PIPE_COLORS.size, PIPE_COLORS.toSet().size)+ }+}
games/pipes/src/test/java/com/vayunmathur/games/pipes/ui/PipesNavigationTest.kt
diff --git a/games/pipes/src/test/java/com/vayunmathur/games/pipes/ui/PipesNavigationTest.kt b/games/pipes/src/test/java/com/vayunmathur/games/pipes/ui/PipesNavigationTest.ktnew file mode 100644index 0000000000..c9fadb24ae--- /dev/null+++ b/games/pipes/src/test/java/com/vayunmathur/games/pipes/ui/PipesNavigationTest.kt@@ -0,0 +1,156 @@+package com.vayunmathur.games.pipes.ui++import android.app.Application+import androidx.compose.runtime.Composable+import androidx.compose.runtime.mutableStateOf+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.hasClickAction+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+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.LevelPack+import com.vayunmathur.games.pipes.platform.PipesViewModel+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.library.ui.R as UiR+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.Robolectric+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.assertNotNull+import kotlin.test.assertTrue++@OptIn(ExperimentalCoroutinesApi::class, androidx.compose.ui.test.ExperimentalTestApi::class)+@RunWith(RobolectricTestRunner::class)+@GraphicsMode(GraphicsMode.Mode.NATIVE)+class PipesNavigationTest {+ @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) }+ @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+ }++ @Test fun packScreenListsPacksAndNavigates() {+ val vm = PipesViewModel(app)+ val stack = NavBackStack<Route>(arrayOf(Route.PackSelector))+ var center = 0+ show { PackScreen(stack, vm, onOpenGameCenter = { center++ }) }+ rule.onNodeWithText(str(R.string.pack_selector)).assertIsDisplayed()+ rule.onNodeWithText("5×5").assertIsDisplayed()+ assertTrue(rule.onAllNodes(androidx.compose.ui.test.hasText("0/30")).fetchSemanticsNodes().isNotEmpty())+ rule.onNodeWithText("5×5").performClick()+ assertEquals(Route.LevelSelector(0), stack.last())+ assertEquals(0, center)+ // Daily card routes to the daily selector on the same stack+ rule.onNodeWithText(str(UiR.string.game_daily_challenge)).performClick()+ assertEquals(Route.DailySelector, stack.last())+ }++ @Test fun levelScreenShowsGridAndOpensLevel() {+ val vm = PipesViewModel(app)+ // Mark level 0 optimal and level 1 merely completed to exercise both badges+ vm.repository.updateBestScore(LevelPack.PACKS[0].levels[0].id, 1)+ vm.repository.updateBestScore(LevelPack.PACKS[0].levels[1].id, 999)+ val stack = NavBackStack<Route>(arrayOf(Route.PackSelector, Route.LevelSelector(0)))+ show { LevelScreen(stack, vm, 0) }+ rule.onNodeWithText(str(R.string.level_selector)).assertIsDisplayed()+ rule.onNodeWithText("1").assertIsDisplayed()+ rule.onNodeWithText("2").assertExists()+ rule.onNodeWithText("1").performClick()+ assertEquals(Route.Game(0, 0), stack.last())+ // A non-rectangular pack shows thumbnails in its cells+ val blobIndex = LevelPack.PACKS.indexOfFirst { it.name == "Blob" }+ val stack2 = NavBackStack<Route>(arrayOf(Route.LevelSelector(blobIndex)))+ // second host would need a new rule; thumbnail cells are also covered in PipesScreensTest+ rule.onNodeWithText("1").assertIsDisplayed()+ }++ @Test fun dailyScreenLoadsPackAndOpensDailyGame() {+ val vm = PipesViewModel(app)+ // Pre-generate the pack so the first composition already has levels; the screen's own+ // LaunchedEffect refresh then no-ops for the same day.+ vm.refreshDaily()+ val deadline = System.currentTimeMillis() + 20_000+ while (vm.dailyPack.value == null && System.currentTimeMillis() < deadline) Thread.sleep(25)+ assertNotNull(vm.dailyPack.value)+ val stack = NavBackStack<Route>(arrayOf(Route.PackSelector, Route.DailySelector))+ show { DailyLevelScreen(stack, vm) }+ // Refresh is asynchronous; the grid appears once the pack is generated+ rule.waitUntilExactlyOneExists(androidx.compose.ui.test.hasText("1"), timeoutMillis = 15_000)+ rule.onNodeWithText("5").assertExists()+ rule.onAllNodes(androidx.compose.ui.test.hasText("1"))[0].performClick()+ assertEquals(Route.DailyGame(0), stack.last())+ }++ @Test fun gameScreenRendersBoardAndClampsLevelChange() {+ val vm = PipesViewModel(app)+ val stack = NavBackStack<Route>(arrayOf(Route.Game(0, 0)))+ show { GameScreen(stack, vm, 0, 0) }+ rule.waitForIdle()+ rule.onNodeWithText(str(UiR.string.undo)).assertExists()+ assertEquals(0, vm.uiState.value.packIndex)+ assertNotNull(vm.uiState.value.levelData)+ }++ @Test fun dailyGameScreenLoadsDailyPack() {+ val vm2 = PipesViewModel(app)+ val dailyStack = NavBackStack<Route>(arrayOf(Route.DailyGame(0)))+ show { GameScreen(dailyStack, vm2, PipesViewModel.DAILY_PACK_INDEX, 0) }+ rule.waitUntil(timeoutMillis = 10_000) { vm2.dailyPack.value != null }+ rule.waitForIdle()+ rule.onNodeWithText(str(UiR.string.undo)).assertExists()+ }++ @Test fun settingsPageRendersBoundState() {+ val vm = PipesViewModel(app)+ val stack = NavBackStack<Route>(arrayOf(Route.Settings))+ show { SettingsPage(stack, vm) }+ rule.onNodeWithText(str(R.string.colorblind_mode)).assertIsDisplayed()+ rule.onNodeWithText(str(R.string.colorblind_mode)).performClick()+ rule.waitUntil(timeoutMillis = 5_000) { vm.colorblind.value }+ assertTrue(vm.colorblind.value)+ }++ @Test fun navigationHostsPackScreenAndBackupAgentMetadata() {+ val vm = PipesViewModel(app)+ show { Navigation(vm) }+ rule.onNodeWithText("5×5").assertIsDisplayed()+ val agent = com.vayunmathur.games.pipes.platform.AppBackupAgent()+ assertEquals(listOf("level_stats", "daily_stats"), agent.prefNames)+ assertEquals(listOf("datastore_default"), agent.datastoreNames)+ // Route value semantics used by the back stack+ assertEquals(Route.Game(1, 2), Route.Game(1, 2))+ assertTrue(Route.Game(1, 2) != Route.Game(1, 3))+ assertEquals(Route.LevelSelector(4).packIndex, 4)+ assertEquals(Route.DailyGame(2).levelIndex, 2)+ }++ @Test fun mainActivityCreatesAndShowsPackList() {+ val controller = Robolectric.buildActivity(com.vayunmathur.games.pipes.MainActivity::class.java).setup()+ val activity = controller.get()+ assertNotNull(activity)+ // LevelPack was initialised by onCreateBeforeContent+ assertTrue(LevelPack.PACKS.isNotEmpty())+ controller.pause().stop().destroy()+ }+}
games/pipes/src/test/java/com/vayunmathur/games/pipes/ui/PipesScreensTest.kt
diff --git a/games/pipes/src/test/java/com/vayunmathur/games/pipes/ui/PipesScreensTest.kt b/games/pipes/src/test/java/com/vayunmathur/games/pipes/ui/PipesScreensTest.ktnew file mode 100644index 0000000000..bdaf904f9f--- /dev/null+++ b/games/pipes/src/test/java/com/vayunmathur/games/pipes/ui/PipesScreensTest.kt@@ -0,0 +1,244 @@+package com.vayunmathur.games.pipes.ui++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.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.onRoot+import androidx.compose.ui.test.performClick+import androidx.compose.ui.test.performTouchInput+import androidx.compose.ui.test.swipeRight+import androidx.compose.ui.unit.dp+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.games.pipes.R+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 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.PackProgress+import com.vayunmathur.games.pipes.platform.DailyProgress+import com.vayunmathur.games.pipes.platform.PipesActions+import com.vayunmathur.games.pipes.platform.PipesGameState+import com.vayunmathur.games.pipes.platform.SettingsActions+import com.vayunmathur.games.pipes.platform.SettingsUiState+import com.vayunmathur.games.pipes.ui.components.LevelThumbnail+import com.vayunmathur.library.ui.R as UiR+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++@OptIn(androidx.compose.ui.test.ExperimentalTestApi::class)+@RunWith(RobolectricTestRunner::class)[email protected](org.robolectric.annotation.GraphicsMode.Mode.NATIVE)+class PipesScreensTest {+ @get:Rule val rule = createComposeRule()+ private val ctx get() = ApplicationProvider.getApplicationContext<android.content.Context>()+ private fun str(id: Int) = ctx.getString(id)+ private fun show(initial: @Composable () -> Unit): androidx.compose.runtime.MutableState<@Composable () -> Unit> {+ val state = mutableStateOf(initial)+ rule.setContent { 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(+ rows: Int = 5, cols: Int = 5,+ endpoints: List<EndpointPair> = listOf(+ EndpointPair(0, listOf(CellPos(0, 0), CellPos(4, 4))),+ EndpointPair(1, listOf(CellPos(0, 4), CellPos(4, 0))),+ ),+ bridges: Set<CellPos> = emptySet(),+ portals: Map<CellPos, CellPos> = emptyMap(),+ cells: Set<CellPos> = rectCells(rows, cols),+ ): LevelData {+ val base = computeAdjacency(cells)+ val adjacency = if (portals.isEmpty()) base else {+ val m = base.mapValues { it.value.toMutableSet() }.toMutableMap()+ for ((a, b) in portals) m.getOrPut(a) { mutableSetOf() }.add(b)+ m.mapValues { it.value.toList() }+ }+ return LevelData("t", rows, cols, cells, adjacency, null, endpoints, bridges, endpoints.size, portals)+ }++ private class RecordingActions : PipesActions {+ var starts = mutableListOf<CellPos>(); var extends = mutableListOf<CellPos>()+ var commits = 0; var undos = 0; var restarts = 0+ override fun startDraw(cell: CellPos) { starts += cell }+ override fun extendPath(cell: CellPos) { extends += cell }+ override fun commitDraw() { commits++ }+ override fun onUndo() { undos++ }+ override fun onRestart() { restarts++ }+ }++ @Test fun gameBoardRendersSquareHexBridgePortalAndWonBoards() {+ val square = squareLevel(bridges = setOf(CellPos(2, 2)), portals = mapOf(CellPos(0, 4) to CellPos(4, 0), CellPos(4, 0) to CellPos(0, 4)))+ val paths = PipesGameState(+ paths = mapOf(+ 0 to listOf(CellPos(0, 0), CellPos(1, 0), CellPos(2, 0), CellPos(2, 1), CellPos(2, 2), CellPos(3, 2), CellPos(4, 4 - 2)),+ 1 to listOf(CellPos(0, 4), CellPos(4, 0)),+ ),+ cellOwner = mapOf(CellPos(2, 2) to 0),+ )+ val content = show { PipesTheme { GameBoard(square, paths, 0, listOf(CellPos(0, 0), CellPos(0, 1)), {}, {}, {}, isLevelWon = false, colorblind = true, modifier = Modifier.size(300.dp)) } }+ rule.waitForIdle(); rule.onRoot().captureToImage()+ 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))), EndpointPair(1, listOf(CellPos(0, 2), CellPos(2, 1)))),+ emptySet(), 2, emptyMap(), "hex")+ content.value = { PipesTheme { GameBoard(hex, PipesGameState(mapOf(0 to listOf(CellPos(0, 0), CellPos(1, 0), CellPos(2, 0)))), null, emptyList(), {}, {}, {}, isLevelWon = true, modifier = Modifier.size(300.dp)) } }+ rule.waitForIdle(); rule.onRoot().captureToImage()+ val empty = squareLevel(cells = emptySet(), endpoints = emptyList())+ content.value = { GameBoard(empty, PipesGameState(), null, emptyList(), {}, {}, {}, isLevelWon = false, modifier = Modifier.size(200.dp)) }+ rule.waitForIdle(); rule.onRoot().captureToImage()+ val wrapCells = rectCells(3, 3)+ val wrapAdj = computeAdjacency(wrapCells).toMutableMap().apply {+ this[CellPos(1, 0)] = getValue(CellPos(1, 0)) + CellPos(1, 2)+ this[CellPos(1, 2)] = getValue(CellPos(1, 2)) + CellPos(1, 0)+ }+ val wrap = LevelData("w", 3, 3, wrapCells, wrapAdj, null,+ listOf(EndpointPair(0, listOf(CellPos(1, 0), CellPos(1, 2)))), emptySet(), 1)+ content.value = { GameBoard(wrap, PipesGameState(mapOf(0 to listOf(CellPos(1, 0), CellPos(1, 2)))), null, emptyList(), {}, {}, {}, isLevelWon = false, modifier = Modifier.size(200.dp)) }+ rule.waitForIdle(); rule.onRoot().captureToImage()+ }++ @Test fun gameBoardTouchDrivesDrawCallbacks() {+ val actions = RecordingActions()+ val level = squareLevel()+ val touchContent = show {+ GameBoard(level, PipesGameState(), null, emptyList(),+ onStartDraw = actions::startDraw, onExtendPath = actions::extendPath,+ onCommitDraw = actions::commitDraw, isLevelWon = false, modifier = Modifier.size(300.dp))+ }+ rule.onRoot().performTouchInput { swipeRight(startX = left + 30f, endX = left + 250f, durationMillis = 200) }+ rule.waitForIdle()+ assertTrue(actions.starts.isNotEmpty(), "starts=${actions.starts}")+ assertEquals(0, actions.starts.first().col)+ assertTrue(actions.commits >= 1, "commits=${actions.commits}")+ // A won board ignores touches entirely+ val won = RecordingActions()+ touchContent.value = {+ GameBoard(level, PipesGameState(), null, emptyList(),+ onStartDraw = won::startDraw, onExtendPath = won::extendPath,+ onCommitDraw = won::commitDraw, isLevelWon = true, modifier = Modifier.size(300.dp))+ }+ rule.onRoot().performTouchInput { swipeRight(startX = left + 30f, endX = left + 250f, durationMillis = 200) }+ assertTrue(won.starts.isEmpty() && won.commits == 0)+ }++ @Test fun gameBoardScreenUndoRestartDialogAndNextLevel() {+ val actions = RecordingActions()+ val level = squareLevel()+ var levelChange = -99; var backs = 0+ val screen = show {+ PipesTheme {+ GameBoardScreen(+ GameBoardUiState(level, levelIndex = 1, maxLevelIndex = 3, moves = 2, canUndo = true, bestScore = 3),+ actions, onBack = { backs++ }, onLevelChange = { levelChange = it })+ }+ }+ rule.onNodeWithText(str(UiR.string.undo)).assertIsDisplayed().performClick()+ assertEquals(1, actions.undos)+ rule.onNodeWithText(str(UiR.string.restart)).performClick()+ rule.onNodeWithText(str(R.string.restart_confirm_title)).assertIsDisplayed()+ rule.onNodeWithText(str(UiR.string.cancel)).performClick()+ assertEquals(0, actions.restarts)+ rule.onNodeWithText(str(UiR.string.restart)).performClick()+ // Confirm is the destructive Restart button in the dialog (last matching node)+ rule.onAllNodes(androidx.compose.ui.test.hasText(str(UiR.string.restart)))[1].performClick()+ assertEquals(1, actions.restarts)+ // Won with a next level+ screen.value = {+ PipesTheme {+ GameBoardScreen(+ GameBoardUiState(level, levelIndex = 1, maxLevelIndex = 3, isLevelWon = true),+ actions, onBack = {}, onLevelChange = { levelChange = it })+ }+ }+ rule.onNodeWithText(str(UiR.string.next_level)).performClick()+ assertEquals(2, levelChange)+ // Won on the last level: no next button+ screen.value = {+ PipesTheme {+ GameBoardScreen(+ GameBoardUiState(level, levelIndex = 3, maxLevelIndex = 3, isLevelWon = true),+ actions, onBack = {}, onLevelChange = {})+ }+ }+ rule.onNodeWithText(str(UiR.string.next_level)).assertDoesNotExist()+ assertEquals(0, backs)+ }++ @Test fun packListShowsDailyPacksAndRoutesClicks() {+ var openedPack = -1; var daily = 0; var settings = 0; var center = 0+ val content2 = show {+ PipesTheme {+ PackListScreen(+ packs = listOf(PackProgress("5×5", "rectangular", 10, 30), PackProgress("Tower", "tower", 0, 30)),+ onOpenPack = { openedPack = it }, onOpenSettings = { settings++ },+ onOpenGameCenter = { center++ },+ daily = DailyProgress(day = 20_000, completed = 2, total = 5, streak = 3),+ onOpenDaily = { daily++ },+ )+ }+ }+ rule.onNodeWithText("5×5").assertIsDisplayed()+ rule.onNodeWithText("10/30").assertIsDisplayed()+ rule.onNodeWithText("Rectangular").assertIsDisplayed()+ rule.onNodeWithText("Tower").performClick()+ assertEquals(1, openedPack)+ // Daily card is present above the packs+ rule.onAllNodes(androidx.compose.ui.test.hasClickAction()).fetchSemanticsNodes().let { assertTrue(it.size >= 3) }+ assertEquals(0, daily); assertEquals(0, settings); assertEquals(0, center)+ // Without a daily progress, no daily card+ content2.value = { PipesTheme { PackListScreen(listOf(PackProgress("Blob", "blob", 1, 3)), { openedPack = it }, {}, {}) } }+ rule.onNodeWithText("Blob").assertIsDisplayed()+ }++ @Test fun settingsScreenRendersAndRoutesToggles() {+ val calls = mutableListOf<String>()+ val actions = object : SettingsActions {+ override fun setColorblind(enabled: Boolean) { calls += "cb:$enabled" }+ override fun setReminderEnabled(enabled: Boolean) { calls += "rem:$enabled" }+ override fun setReminderTime(hour: Int, minute: Int) { calls += "time:$hour:$minute" }+ }+ var backs = 0+ val sc = show { PipesTheme { SettingsScreen(SettingsUiState(colorblind = false, reminderEnabled = false, reminderHour = 20, reminderMinute = 0), actions) { backs++ } } }+ rule.onNodeWithText(str(R.string.colorblind_mode)).assertIsDisplayed()+ rule.onNodeWithText(str(R.string.colorblind_mode)).performClick()+ assertTrue(calls.contains("cb:true"), "calls=$calls")+ sc.value = { PipesTheme { SettingsScreen(SettingsUiState(colorblind = true, reminderEnabled = true, reminderHour = 9, reminderMinute = 45), actions) { backs++ } } }+ rule.onNodeWithText(str(R.string.colorblind_mode)).assertIsDisplayed()+ assertEquals(0, backs)+ }++ @Test fun levelThumbnailVariantsRender() {+ val square = squareLevel()+ val thumb = show { LevelThumbnail(square, Modifier.size(80.dp)) }+ rule.waitForIdle(); rule.onRoot().captureToImage()+ val posLevel = square.copy(renderPositions = square.cells.associateWith { RenderPos(it.col.toFloat(), it.row.toFloat()) })+ thumb.value = { LevelThumbnail(posLevel, Modifier.size(80.dp)) }+ rule.waitForIdle(); rule.onRoot().captureToImage()+ thumb.value = { LevelThumbnail(square.copy(cells = emptySet()), Modifier.size(80.dp)) }+ rule.waitForIdle(); rule.onRoot().captureToImage()+ thumb.value = { LevelThumbnail(square.copy(renderPositions = emptyMap()), Modifier.size(80.dp)) }+ rule.waitForIdle(); rule.onRoot().captureToImage()+ thumb.value = { LevelThumbnail(square.copy(rows = 0, cols = 0, cells = setOf(CellPos(0, 0))), Modifier.size(80.dp)) }+ rule.waitForIdle(); rule.onRoot().captureToImage()+ // Non-rectangular subset (thumbnail path in the level grid)+ val holed = squareLevel(cells = rectCells(3, 3) - CellPos(1, 1), rows = 3, cols = 3)+ thumb.value = { LevelThumbnail(holed, Modifier.size(80.dp)) }+ rule.waitForIdle(); rule.onRoot().captureToImage()+ }+}