Modern Apps git

← Modern-Apps.git

games-unblockjam: add tests for solver, viewmodel, screens and drag

Commit
75e026c96af8bed03e1a8f620a311dd4eba4f4eb
Author
Vayun Mathur <[email protected]>
When
2026-11-07 06:18 UTC (29 days ago)
Parents
cf7228a
Coverage (merged INSTRUCTION): 22.3% (2139/9595) -> 92.79%
(8903/9595), above the 85% target.

New tests (8 files, 68 unit tests in the module suite, all passing):
- RushHourSolverEdgeTest: malformed boards, unsolvable/fixed boards,
  maxStates cap, exploration level reconstruction.
- LevelDataTest: pack JSON parsing, Y-flip, colour defaults/prefixes,
  wall/size pack indices.
- UnblockJamViewModelTest: load/move-collapse/undo/restart/win state
  machine, move counting, daily pack generation and daily win
  persistence, reminder setters, repository counters.
- NavigationScreensTest: pack/level/game/settings screens (portrait,
  landscape, won states), themes, DailyLevelPage, and full
  Navigation from pack list into a game.
- BoardDragTest: real touch swipes on the board (vertical/horizontal
  moves, exit win, blocked/small/won drags) via a testTag on the
  board.
- BlockDragGesturesTest: isMoveValid bounds/overlap/touching.
- ContractsAndManagersTest: Game/Settings actions defaults, UI state
  data classes, CompletedLevelsRepository counters,
  AchievementsManager pack completion, AppBackupAgent, Route
  serialization round-trips.
- MainActivityTest: activity launch initializes the level packs.

Bugs fixed: none. Untestable remainder: the Navigation settings and
game-center entry lambdas and GamePage level-change action are only
reachable via unlabeled top-bar icon clicks; DailyReminder reschedule
goes through WorkManager. Verified with
gslot ./gradlew :games:unblockjam:testDevUnitTest (68 tests, 0
failures), :games:unblockjam:createMergedCoverageReport, and
:games:unblockjam:lint + :metadata (detekt unavailable from the
Maven mirror: detekt-metrics/rules-naming 2.0.0-alpha.6 not found).

(cherry picked from commit 488665f1272f9183df7a0a40bc2e61fda0639463)

Diff

games/unblockjam/src/test/java/com/vayunmathur/games/unblockjam/BoardDragTest.kt
diff --git a/games/unblockjam/src/test/java/com/vayunmathur/games/unblockjam/BoardDragTest.kt b/games/unblockjam/src/test/java/com/vayunmathur/games/unblockjam/BoardDragTest.ktnew file mode 100644index 0000000000..5fad0f6e18--- /dev/null+++ b/games/unblockjam/src/test/java/com/vayunmathur/games/unblockjam/BoardDragTest.kt@@ -0,0 +1,141 @@+package com.vayunmathur.games.unblockjam++import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.size+import androidx.compose.ui.Modifier+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.platform.testTag+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithTag+import androidx.compose.ui.test.performTouchInput+import androidx.compose.ui.test.swipe+import androidx.compose.ui.unit.dp+import com.vayunmathur.games.unblockjam.data.Block+import com.vayunmathur.games.unblockjam.data.Coord+import com.vayunmathur.games.unblockjam.data.Dimension+import com.vayunmathur.games.unblockjam.data.LevelData+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)+class BoardDragTest {+    @get:Rule val rule = createComposeRule()++    private fun level(blocks: List<Block>) = LevelData(+        id = "drag", dimension = Dimension(6, 6), exit = Coord(6, 2),+        blocks = blocks, optimalMoves = 1,+    )++    private fun openLevel() = level(+        listOf(+            Block(Coord(0, 2), Dimension(2, 1), false), // main+            Block(Coord(2, 1), Dimension(1, 3), false), // vertical blocker+            Block(Coord(4, 4), Dimension(2, 1), true), // fixed wall+            Block(Coord(0, 5), Dimension(2, 1), false), // spare horizontal+        )+    )++    private fun setBoard(level: LevelData, won: Boolean, onChanged: (LevelData) -> Unit, onWon: () -> Unit) {+        rule.setContent {+            Box(Modifier.size(360.dp)) {+                GameBoard(levelData = level, onLevelChanged = onChanged, onLevelWon = onWon, isLevelWon = won, modifier = Modifier.testTag("board"))+            }+        }+    }++    @Test+    fun draggingVerticalBlockDownReportsMovedLevel() {+        var changed: LevelData? = null+        var won = 0+        setBoard(openLevel(), false, { changed = it }, { won++ })+        // vertical blocker occupies x=2, y=1..3: centre (2.5/6, 2.5/6); drag down one cell+        rule.onNodeWithTag("board").performTouchInput {+            swipe(Offset(width * 2.5f / 6f, height * 2.5f / 6f), Offset(width * 2.5f / 6f, height * 3.5f / 6f), 300)+        }+        val result = assertNotNull(changed, "vertical drag should report a moved level")+        assertEquals(Coord(2, 2), result.blocks[1].position)+        assertEquals(1, result.lastMovedBlockIndex)+        assertEquals(0, won)+    }++    @Test+    fun draggingMainBlockToExitWins() {+        var changed: LevelData? = null+        var won = 0+        val free = level(+            listOf(+                Block(Coord(0, 2), Dimension(2, 1), false),+                Block(Coord(0, 5), Dimension(2, 1), false),+            )+        )+        setBoard(free, false, { changed = it }, { won++ })+        // main centre (1/6, 2.5/6); drag far right toward the exit+        rule.onNodeWithTag("board").performTouchInput {+            swipe(Offset(width / 6f, height * 2.5f / 6f), Offset(width * 0.97f, height * 2.5f / 6f), 400)+        }+        assertTrue(won >= 1, "dragging main block out should win, won=$won changed=$changed")+    }++    @Test+    fun smallDragThatStaysInCellResetsWithoutReporting() {+        var changed: LevelData? = null+        var won = 0+        setBoard(openLevel(), false, { changed = it }, { won++ })+        // tiny drag on the spare horizontal block: snaps back to its own cell+        rule.onNodeWithTag("board").performTouchInput {+            swipe(Offset(width / 6f, height * 5.5f / 6f), Offset(width / 6f + 5f, height * 5.5f / 6f), 200)+        }+        assertNull(changed)+        assertEquals(0, won)+    }++    @Test+    fun draggingBlockedMainBlockDoesNotReportOrWin() {+        var changed: LevelData? = null+        var won = 0+        setBoard(openLevel(), false, { changed = it }, { won++ })+        // main is blocked by the vertical blocker at x=2: rightward drag goes nowhere+        rule.onNodeWithTag("board").performTouchInput {+            swipe(Offset(width / 6f, height * 2.5f / 6f), Offset(width * 3f / 6f, height * 2.5f / 6f), 300)+        }+        assertNull(changed)+        assertEquals(0, won)+    }++    @Test+    fun dragsIgnoredWhenLevelAlreadyWon() {+        var changed: LevelData? = null+        var won = 0+        setBoard(openLevel(), true, { changed = it }, { won++ })+        rule.onNodeWithTag("board").performTouchInput {+            swipe(Offset(width * 2.5f / 6f, height * 2.5f / 6f), Offset(width * 2.5f / 6f, height * 3.5f / 6f), 300)+        }+        assertNull(changed)+        assertEquals(0, won)+    }++    @Test+    fun draggingHorizontalBlockLeftReportsMove() {+        var changed: LevelData? = null+        val lvl = level(+            listOf(+                Block(Coord(0, 2), Dimension(2, 1), false),+                Block(Coord(3, 5), Dimension(2, 1), false),+            )+        )+        setBoard(lvl, false, { changed = it }, {})+        // spare block centre (4/6, 5.5/6); drag left two cells+        rule.onNodeWithTag("board").performTouchInput {+            swipe(Offset(width * 4f / 6f, height * 5.5f / 6f), Offset(width * 2f / 6f, height * 5.5f / 6f), 300)+        }+        val result = assertNotNull(changed)+        assertEquals(Coord(1, 5), result.blocks[1].position)+        assertEquals(1, result.lastMovedBlockIndex)+    }+}
games/unblockjam/src/test/java/com/vayunmathur/games/unblockjam/MainActivityTest.kt
diff --git a/games/unblockjam/src/test/java/com/vayunmathur/games/unblockjam/MainActivityTest.kt b/games/unblockjam/src/test/java/com/vayunmathur/games/unblockjam/MainActivityTest.ktnew file mode 100644index 0000000000..66478e72ea--- /dev/null+++ b/games/unblockjam/src/test/java/com/vayunmathur/games/unblockjam/MainActivityTest.kt@@ -0,0 +1,28 @@+package com.vayunmathur.games.unblockjam++import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.games.unblockjam.data.LevelPack+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)+class MainActivityTest {+    @Test+    fun activityLaunchesAndInitializesPacks() {+        val controller = Robolectric.buildActivity(MainActivity::class.java).setup()+        val activity = controller.get()+        Shadows.shadowOf(android.os.Looper.getMainLooper()).idle()+        assertFalse(activity.isFinishing)+        assertEquals(7, LevelPack.PACKS.size)+        assertTrue(LevelPack.PACKS.all { it.levels.isNotEmpty() })+        val ctx = ApplicationProvider.getApplicationContext<android.content.Context>()+        assertEquals("Unblock Jam", ctx.getString(R.string.app_name))+        controller.pause().stop().destroy()+    }+}
games/unblockjam/src/test/java/com/vayunmathur/games/unblockjam/NavigationScreensTest.kt
diff --git a/games/unblockjam/src/test/java/com/vayunmathur/games/unblockjam/NavigationScreensTest.kt b/games/unblockjam/src/test/java/com/vayunmathur/games/unblockjam/NavigationScreensTest.ktnew file mode 100644index 0000000000..e90967d7d9--- /dev/null+++ b/games/unblockjam/src/test/java/com/vayunmathur/games/unblockjam/NavigationScreensTest.kt@@ -0,0 +1,322 @@+package com.vayunmathur.games.unblockjam++import android.app.Application+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.requiredSize+import androidx.compose.ui.Modifier+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.hasClickAction+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onAllNodesWithText+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.unblockjam.data.Block+import com.vayunmathur.games.unblockjam.data.Coord+import com.vayunmathur.games.unblockjam.data.Dimension+import com.vayunmathur.games.unblockjam.data.LevelData+import com.vayunmathur.games.unblockjam.data.LevelPack+import com.vayunmathur.games.unblockjam.data.PackColorScheme+import com.vayunmathur.games.unblockjam.platform.DailyProgress+import com.vayunmathur.games.unblockjam.platform.GameActions+import com.vayunmathur.games.unblockjam.platform.GameUiState+import com.vayunmathur.games.unblockjam.platform.SettingsActions+import com.vayunmathur.games.unblockjam.platform.SettingsUiState+import com.vayunmathur.games.unblockjam.platform.UnblockJamViewModel+import com.vayunmathur.games.unblockjam.ui.UnblockJamTheme+import com.vayunmathur.library.util.LevelStats+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.ExperimentalCoroutinesApi+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.test.resetMain+import kotlinx.coroutines.test.setMain+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++@OptIn(ExperimentalCoroutinesApi::class)+@RunWith(RobolectricTestRunner::class)+class NavigationScreensTest {+    @get:Rule val rule = createComposeRule()+    private val app get() = ApplicationProvider.getApplicationContext<Application>()+    private val ctx get() = app as android.content.Context+    private fun str(id: Int) = ctx.getString(id)++    @BeforeTest+    fun setUp() {+        Dispatchers.setMain(Dispatchers.Unconfined)+        if (LevelPack.PACKS.isEmpty()) LevelPack.init(app)+    }++    @AfterTest fun tearDown() { Dispatchers.resetMain() }++    private fun sampleLevel(id: String = "s1") = LevelData(+        id = id,+        dimension = Dimension(6, 6),+        exit = Coord(6, 2),+        blocks = listOf(+            Block(Coord(0, 2), Dimension(2, 1), false),+            Block(Coord(2, 1), Dimension(1, 3), false),+            Block(Coord(4, 4), Dimension(2, 1), true),+        ),+        optimalMoves = 2,+    )++    private class RecordingActions : GameActions {+        var moved: LevelData? = null+        var won = 0+        var undo = 0+        var restart = 0+        var levelChange: Int? = null+        override fun onBlockMoved(newLevelData: LevelData) { moved = newLevelData }+        override fun onLevelWon() { won++ }+        override fun onUndo() { undo++ }+        override fun onRestart() { restart++ }+        override fun onLevelChange(newIndex: Int) { levelChange = newIndex }+    }++    @Test+    fun packScreenListsPacksAndDailyAndRoutesClicks() {+        var openedPack: Int? = null+        var daily = 0; var center = 0; var settings = 0+        rule.setContent {+            UnblockJamTheme {+                PackScreen(+                    packNames = listOf("Alpha Pack", "Beta Pack"),+                    daily = DailyProgress(day = 20000, completed = 2, total = 5, streak = 3),+                    onOpenPack = { openedPack = it },+                    onOpenDaily = { daily++ },+                    onOpenGameCenter = { center++ },+                    onOpenSettings = { settings++ },+                )+            }+        }+        rule.onNodeWithText("Alpha Pack").assertIsDisplayed()+        rule.onNodeWithText("Beta Pack").assertIsDisplayed()+        rule.onNodeWithText("Beta Pack").performClick()+        assertEquals(1, openedPack)+        // daily card is first card: click by its completed text region if present, else via nodes+        val clickables = rule.onAllNodes(hasClickAction())+        assertTrue(clickables.fetchSemanticsNodes().size >= 3)+    }++    @Test+    fun packScreenWithoutDailyShowsOnlyPacks() {+        rule.setContent {+            PackScreen(packNames = listOf("Only Pack"), onOpenPack = {}, onOpenGameCenter = {})+        }+        rule.onNodeWithText("Only Pack").assertIsDisplayed()+        rule.onAllNodesWithText("Beta Pack").fetchSemanticsNodes().also { assertEquals(0, it.size) }+    }++    @Test+    fun levelScreenShowsCompletionStatesAndRoutesClicks() {+        val levels = listOf(sampleLevel("a"), sampleLevel("b"), sampleLevel("c"))+        var opened: Int? = null+        rule.setContent {+            LevelScreen(+                pack = LevelPack("TestPack", levels),+                levelStats = mapOf(+                    "a" to LevelStats(2), // <= optimal: star+                    "b" to LevelStats(9), // > optimal: check+                ),+                onOpenLevel = { opened = it },+            )+        }+        rule.onNodeWithText("1").assertIsDisplayed()+        rule.onNodeWithText("2").assertIsDisplayed()+        rule.onNodeWithText("3").assertIsDisplayed()+        rule.onNodeWithText("3").performClick()+        assertEquals(2, opened)+    }++    @Test+    fun gameScreenPortraitUndoRestartAndInfo() {+        val actions = RecordingActions()+        rule.setContent {+            GameScreen(+                state = GameUiState(+                    levelData = sampleLevel(), levelIndex = 0, maxLevelIndex = 4,+                    moves = 3, bestScore = 5, isCompleted = true, canUndo = true,+                ),+                actions = actions, onBack = {},+            )+        }+        rule.onNodeWithText(str(com.vayunmathur.library.ui.R.string.undo)).assertIsDisplayed()+        rule.onNodeWithText(str(com.vayunmathur.library.ui.R.string.undo)).performClick()+        assertEquals(1, actions.undo)+        rule.onNodeWithText(str(com.vayunmathur.library.ui.R.string.restart)).performClick()+        assertEquals(1, actions.restart)+        assertEquals(0, actions.won)+    }++    @Test+    fun gameScreenWonShowsNextLevelAndHidesUndo() {+        val actions = RecordingActions()+        rule.setContent {+            GameScreen(+                state = GameUiState(+                    levelData = sampleLevel(), levelIndex = 1, maxLevelIndex = 4,+                    moves = 2, isLevelWon = true, canUndo = true,+                ),+                actions = actions, onBack = {},+            )+        }+        rule.onNodeWithText(str(com.vayunmathur.library.ui.R.string.undo)).assertDoesNotExist()+        rule.onNodeWithText(str(R.string.next_level)).performClick()+        assertEquals(2, actions.levelChange)+    }++    @Test+    fun gameScreenWonAtLastLevelHasNoNextButton() {+        val actions = RecordingActions()+        rule.setContent {+            GameScreen(+                state = GameUiState(+                    levelData = sampleLevel(), levelIndex = 4, maxLevelIndex = 4, isLevelWon = true,+                ),+                actions = actions, onBack = {},+            )+        }+        rule.onNodeWithText(str(R.string.next_level)).assertDoesNotExist()+        assertEquals(null, actions.levelChange)+    }++    @Test+    fun gameScreenLandscapeLayoutRenders() {+        val actions = RecordingActions()+        rule.setContent {+            Box(Modifier.requiredSize(900.dp, 400.dp)) {+                GameScreen(+                    state = GameUiState(levelData = sampleLevel(), moves = 1, canUndo = false),+                    actions = actions, onBack = {},+                )+            }+        }+        rule.onNodeWithText(str(com.vayunmathur.library.ui.R.string.undo)).assertExists()+        // undo disabled when canUndo=false: click does nothing via semantics? assert no callback by state+        assertEquals(0, actions.undo)+    }++    @Test+    fun gameBoardWonStateRenders() {+        rule.setContent {+            GameBoard(+                levelData = sampleLevel(), onLevelChanged = {}, onLevelWon = {},+                isLevelWon = true,+            )+        }+        rule.onRoot().assertExists()+    }++    @Test+    fun settingsScreenRendersWithActions() {+        var enabledSeen: Boolean? = null+        var time: Pair<Int, Int>? = null+        val actions = object : SettingsActions {+            override fun setReminderEnabled(enabled: Boolean) { enabledSeen = enabled }+            override fun setReminderTime(hour: Int, minute: Int) { time = hour to minute }+        }+        // exercise the recording actions directly so defaults above are meaningful+        actions.setReminderEnabled(true); actions.setReminderTime(8, 15)+        assertEquals(true, enabledSeen); assertEquals(8 to 15, time)+        rule.setContent {+            SettingsScreen(+                state = SettingsUiState(reminderEnabled = false, reminderHour = 20, reminderMinute = 0),+                actions = GameActionsNoopSettings, onBack = {},+            )+        }+        rule.onNodeWithText(str(com.vayunmathur.library.ui.R.string.settings)).assertExists()+    }++    @Test+    fun themeWithoutPackRendersContent() {+        rule.setContent {+            UnblockJamTheme { com.vayunmathur.library.ui.Text("plain-theme") }+        }+        rule.onNodeWithText("plain-theme").assertIsDisplayed()+    }++    @Test+    fun themeWithPackColorsRendersContent() {+        val colored = LevelPack(+            "c", listOf(sampleLevel()),+            PackColorScheme(0xFF111111, 0xFF222222, 0xFF333333, 0xFF444444, 0xFF555555, 0xFF666666, 0xFF777777)+        )+        rule.setContent {+            UnblockJamTheme(pack = colored) { com.vayunmathur.library.ui.Text("colored-theme") }+        }+        rule.onNodeWithText("colored-theme").assertIsDisplayed()+    }++    @Test+    fun themeWithPackWithoutSchemeFallsBack() {+        val noScheme = LevelPack("n", listOf(sampleLevel()), null)+        rule.setContent {+            UnblockJamTheme(pack = noScheme) { com.vayunmathur.library.ui.Text("noscheme-theme") }+        }+        rule.onNodeWithText("noscheme-theme").assertIsDisplayed()+    }++    @Test+    fun fullNavigationFromPackToGameAndBackActions() {+        val vm = UnblockJamViewModel(app)+        rule.setContent { Navigation(vm) }+        rule.onNodeWithText(str(R.string.pack_selector)).assertExists()+        rule.onNodeWithText(LevelPack.PACKS[0].name).performClick()+        rule.onNodeWithText(str(R.string.level_selector)).assertExists()+        rule.onNodeWithText("1").performClick()+        rule.onNodeWithText(str(com.vayunmathur.library.ui.R.string.undo)).assertExists()+        assertEquals(0, vm.uiState.value.packIndex)+        assertEquals(0, vm.uiState.value.levelIndex)+    }++    @Test+    fun settingsPageBoundToViewModelRendersReminderSection() {+        val vm = UnblockJamViewModel(app)+        var back = 0+        rule.setContent { SettingsPage(vm, onBack = { back++ }) }+        rule.onNodeWithText(str(com.vayunmathur.library.ui.R.string.settings)).assertExists()+        rule.onNodeWithText(str(com.vayunmathur.library.ui.R.string.setting_daily_reminder)).assertExists()+        assertEquals(0, back)+    }++    @Test+    fun dailyLevelPageWithGeneratedPackOpensDailyGame() {+        val vm = UnblockJamViewModel(app)+        // generate the pack outside composition (solver work), then the page renders the grid+        vm.refreshDaily()+        kotlinx.coroutines.runBlocking {+            kotlinx.coroutines.withTimeout(120_000) {+                vm.dailyPack.first { it != null }+            }+        }+        val backStack = com.vayunmathur.library.util.NavBackStack<Route>(arrayOf(Route.DailySelector))+        rule.setContent { DailyLevelPage(backStack, vm) }+        rule.onNodeWithText(str(com.vayunmathur.library.ui.R.string.daily_challenge)).assertExists()+        rule.onNodeWithText("1").assertExists()+        rule.onNodeWithText("1").performClick()+        assertEquals(Route.DailyGame(0), backStack.backStack.last())+    }++    @Test+    fun dailyLevelPageWithoutPackShowsProgress() {+        val vm = UnblockJamViewModel(app)+        val backStack = com.vayunmathur.library.util.NavBackStack<Route>(arrayOf(Route.DailySelector))+        // pack is null at first composition: the page shows its loading box (generation is+        // launched, but we do not wait for the solver here)+        rule.setContent { DailyLevelPage(backStack, vm) }+        rule.onRoot().assertExists()+    }++    private companion object {+        val GameActionsNoopSettings: SettingsActions = SettingsActions.Noop+    }+}
games/unblockjam/src/test/java/com/vayunmathur/games/unblockjam/data/LevelDataTest.kt
diff --git a/games/unblockjam/src/test/java/com/vayunmathur/games/unblockjam/data/LevelDataTest.kt b/games/unblockjam/src/test/java/com/vayunmathur/games/unblockjam/data/LevelDataTest.ktnew file mode 100644index 0000000000..c49dac2724--- /dev/null+++ b/games/unblockjam/src/test/java/com/vayunmathur/games/unblockjam/data/LevelDataTest.kt@@ -0,0 +1,84 @@+package com.vayunmathur.games.unblockjam.data++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue++class LevelDataTest {++    @Test+    fun packFromJsonParsesLevelsAndFlipsYCoordinates() {+        val pack = packFromJson(+            """+            {"name":"Mini","levels":[+              {"id":"a","w":6,"h":6,"e":{"x":6,"y":2},"c":3,"b":[+                {"x":0,"y":3,"w":2,"h":1},+                {"x":2,"y":0,"w":1,"h":3,"fixed":true},+                {"w":2,"h":2}+              ]}+            ]}+            """.trimIndent()+        )+        assertEquals("Mini", pack.name)+        assertNull(pack.colorScheme)+        assertEquals(1, pack.levels.size)+        val level = pack.levels.single()+        assertEquals("a", level.id)+        assertEquals(Dimension(6, 6), level.dimension)+        // exit y in file is bottom-origin: 6 - 2 - 1 = 3+        assertEquals(Coord(6, 3), level.exit)+        assertEquals(3, level.optimalMoves)+        assertNull(level.lastMovedBlockIndex)+        // main block y: 6 - 3 - 1 = 2+        assertEquals(Block(Coord(0, 2), Dimension(2, 1), false), level.blocks[0])+        assertEquals(Block(Coord(2, 3), Dimension(1, 3), true), level.blocks[1])+        // missing x/y default to 0 then flipped: y = 6 - 0 - 2 = 4+        assertEquals(Block(Coord(0, 4), Dimension(2, 2), false), level.blocks[2])+    }++    @Test+    fun packFromJsonParsesColorsWithDefaultsAndPrefixes() {+        val pack = packFromJson(+            """+            {"name":"Colored","colors":{"primary":"#112233","secondary":"0xFF445566","primaryContainer":"nothex"},+             "levels":[{"id":"x","w":4,"h":4,"e":{"x":4,"y":1},"c":1,"b":[{"x":0,"y":2,"w":2,"h":1}]}]}+            """.trimIndent()+        )+        val colors = pack.colorScheme!!+        assertEquals(0x112233L, colors.primary)+        assertEquals(0xFF445566L, colors.secondary)+        // invalid hex falls back to the default orange container+        assertEquals(0xFFFFA500L, colors.primaryContainer)+        assertEquals(0xFF8B7E6AL, colors.tertiary)+        assertEquals(0xFFFFFFFFL, colors.onPrimary)+        assertEquals(0xFFFF0000L, colors.error)+    }++    @Test+    fun wallAndSizePackIndicesMatchFilePrefixes() {+        // PACK_FILES order: original, walls_1..3, size_7..9+        assertEquals(listOf(1, 2, 3), LevelPack.WALL_PACK_INDICES)+        assertEquals(listOf(4, 5, 6), LevelPack.SIZE_PACK_INDICES)+    }++    @Test+    fun dataClassDefaultsAndCopy() {+        val scheme = PackColorScheme(1, 2, 3, 4, 5, 6, 7)+        assertEquals(0xFFFFFFFFL, scheme.onPrimary)+        assertEquals(0xFFFFFFFFL, scheme.onSurface)+        assertEquals(0xFFFF0000L, scheme.error)+        assertEquals(scheme, scheme.copy())+        assertFalse(scheme == scheme.copy(primary = 9))++        val level = LevelData("id", Dimension(6, 6), Coord(6, 2), emptyList(), 5)+        assertNull(level.lastMovedBlockIndex)+        assertEquals(2, level.copy(lastMovedBlockIndex = 2).lastMovedBlockIndex)+        assertTrue(Coord(1, 2) == Coord(1, 2))+        assertFalse(Coord(1, 2) == Coord(2, 1))+        val pack = LevelPack("p", listOf(level))+        assertNull(pack.colorScheme)+        assertEquals(listOf(level), pack.copy(name = "q").levels)+    }+}
games/unblockjam/src/test/java/com/vayunmathur/games/unblockjam/domain/RushHourSolverEdgeTest.kt
diff --git a/games/unblockjam/src/test/java/com/vayunmathur/games/unblockjam/domain/RushHourSolverEdgeTest.kt b/games/unblockjam/src/test/java/com/vayunmathur/games/unblockjam/domain/RushHourSolverEdgeTest.ktnew file mode 100644index 0000000000..cca157ec7d--- /dev/null+++ b/games/unblockjam/src/test/java/com/vayunmathur/games/unblockjam/domain/RushHourSolverEdgeTest.kt@@ -0,0 +1,121 @@+package com.vayunmathur.games.unblockjam.domain++import com.vayunmathur.games.unblockjam.data.Block+import com.vayunmathur.games.unblockjam.data.Coord+import com.vayunmathur.games.unblockjam.data.Dimension+import com.vayunmathur.games.unblockjam.data.LevelData+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++class RushHourSolverEdgeTest {++    private fun level(+        blocks: List<Block>,+        dimension: Dimension = Dimension(6, 6),+        exit: Coord = Coord(6, 2),+    ) = LevelData("t", dimension, exit, blocks, 0)++    private fun hBlock(x: Int, y: Int, len: Int = 2, fixed: Boolean = false) =+        Block(Coord(x, y), Dimension(len, 1), fixed)++    private fun vBlock(x: Int, y: Int, len: Int = 2, fixed: Boolean = false) =+        Block(Coord(x, y), Dimension(1, len), fixed)++    @Test+    fun malformedBoardsReturnNull() {+        assertNull(RushHourSolver.explore(level(emptyList())))+        assertNull(RushHourSolver.optimalMoves(level(emptyList())))+        // vertical main block cannot drive out horizontally+        assertNull(RushHourSolver.explore(level(listOf(vBlock(0, 2)))))+        // main block off the exit row+        assertNull(RushHourSolver.explore(level(listOf(hBlock(0, 1)))))+        // too many blocks for bit packing+        val many = listOf(hBlock(0, 2)) + (1..16).map { vBlock(it % 6, (it * 2) % 5) }+        assertNull(RushHourSolver.explore(level(many)))+        // board extent too large+        assertNull(+            RushHourSolver.explore(+                level(listOf(hBlock(0, 2)), dimension = Dimension(17, 6))+            )+        )+        assertNull(+            RushHourSolver.explore(+                level(listOf(hBlock(0, 2)), dimension = Dimension(6, 17))+            )+        )+    }++    @Test+    fun openBoardWinsInOneAndExplorationRebuildsLevels() {+        val lvl = level(listOf(hBlock(0, 2), vBlock(4, 0)))+        assertEquals(1, RushHourSolver.optimalMoves(lvl))+        val exploration = assertNotNull(RushHourSolver.explore(lvl))+        assertEquals(0, exploration.startIndex)+        assertTrue(exploration.stateCount > 1)+        assertEquals(1, exploration.movesToWin(exploration.startIndex))+        // start state rebuilds the original layout+        assertEquals(lvl.blocks, exploration.levelAt(exploration.startIndex, lvl).blocks)+        // every state rebuilds a level that keeps ids and template blocks' shapes+        val other = exploration.levelAt(exploration.stateCount - 1, lvl)+        assertEquals("t", other.id)+        assertEquals(lvl.blocks.map { it.dimension }, other.blocks.map { it.dimension })+        assertEquals(lvl.blocks.map { it.fixed }, other.blocks.map { it.fixed })+        // a state where the blocker still blocks needs at least the winning move plus a move+        val distances = exploration.distanceToGoal+        assertTrue(distances.all { it >= 0 }, "open board: every state should reach a goal")+    }++    @Test+    fun blockedBoardRequiresMovingBlockerFirst() {+        // vertical blocker covering exit row at x=2; main cannot pass until it moves+        val lvl = level(listOf(hBlock(0, 2), vBlock(2, 1, len = 3)))+        assertEquals(2, RushHourSolver.optimalMoves(lvl))+    }++    @Test+    fun unsolvableBoardReturnsNullOptimalButExplores() {+        // horizontal block fixed on exit row ahead of main: can never be cleared+        val lvl = level(listOf(hBlock(0, 2), hBlock(3, 2, fixed = true)))+        val exploration = assertNotNull(RushHourSolver.explore(lvl))+        assertTrue(exploration.stateCount >= 1)+        assertEquals(-1, exploration.distanceToGoal[exploration.startIndex])+        assertNull(RushHourSolver.optimalMoves(lvl))+    }++    @Test+    fun fixedBlocksDoNotSlideButOthersDo() {+        // fixed vertical blocker can slide nowhere; an identical free blocker can move away+        val fixedBoard = level(listOf(hBlock(0, 2), vBlock(2, 2, fixed = true), vBlock(5, 0)))+        // blocker sits at (2,2)-(2,3): covers exit row, fixed, so only other moves exist;+        // main range is blocked, so winning requires... it cannot win: unsolvable+        assertNull(RushHourSolver.optimalMoves(fixedBoard))+        val freeBoard = level(listOf(hBlock(0, 2), vBlock(2, 2), vBlock(5, 0)))+        assertEquals(2, RushHourSolver.optimalMoves(freeBoard))+    }++    @Test+    fun maxStatesCapReturnsNull() {+        val lvl = level(listOf(hBlock(0, 2), vBlock(4, 0), vBlock(5, 3)))+        assertNull(RushHourSolver.explore(lvl, maxStates = 1))+        assertNull(RushHourSolver.optimalMoves(lvl, maxStates = 1))+        assertNotNull(RushHourSolver.explore(lvl, maxStates = 200_000))+    }++    @Test+    fun alreadyAtExitEdgeIsGoal() {+        val lvl = level(listOf(hBlock(4, 2)))+        assertEquals(1, RushHourSolver.optimalMoves(lvl))+    }++    @Test+    fun wideBlocksAndCrossLengthsAreRespected() {+        // 2x2 square block (crossLength 2) blocking exit row and row below+        val square = Block(Coord(3, 2), Dimension(2, 2), false)+        val lvl = level(listOf(hBlock(0, 2), square))+        // square can slide down/up/left/right; need move it off row 2 then drive out = 2+        assertEquals(2, RushHourSolver.optimalMoves(lvl))+    }+}
games/unblockjam/src/test/java/com/vayunmathur/games/unblockjam/platform/BlockDragGesturesTest.kt
diff --git a/games/unblockjam/src/test/java/com/vayunmathur/games/unblockjam/platform/BlockDragGesturesTest.kt b/games/unblockjam/src/test/java/com/vayunmathur/games/unblockjam/platform/BlockDragGesturesTest.ktnew file mode 100644index 0000000000..70be9d0cef--- /dev/null+++ b/games/unblockjam/src/test/java/com/vayunmathur/games/unblockjam/platform/BlockDragGesturesTest.kt@@ -0,0 +1,51 @@+package com.vayunmathur.games.unblockjam.platform++import com.vayunmathur.games.unblockjam.data.Block+import com.vayunmathur.games.unblockjam.data.Coord+import com.vayunmathur.games.unblockjam.data.Dimension+import kotlin.test.Test+import kotlin.test.assertFalse+import kotlin.test.assertTrue++class BlockDragGesturesTest {+    private val board = Dimension(6, 6)+    private fun h(x: Int, y: Int, len: Int = 2) = Block(Coord(x, y), Dimension(len, 1), false)+    private fun v(x: Int, y: Int, len: Int = 2) = Block(Coord(x, y), Dimension(1, len), false)++    @Test+    fun validMovesOnEmptyBoard() {+        assertTrue(isMoveValid(h(0, 0), emptyList(), board))+        assertTrue(isMoveValid(h(4, 5), emptyList(), board))+        assertTrue(isMoveValid(v(5, 4), emptyList(), board))+        assertTrue(isMoveValid(Block(Coord(0, 0), Dimension(6, 6), false), emptyList(), board))+    }++    @Test+    fun outOfBoundsMovesRejected() {+        assertFalse(isMoveValid(h(-1, 0), emptyList(), board))+        assertFalse(isMoveValid(h(0, -1), emptyList(), board))+        assertFalse(isMoveValid(h(5, 0), emptyList(), board)) // 5+2 > 6+        assertFalse(isMoveValid(v(0, 5), emptyList(), board))+        assertFalse(isMoveValid(h(0, 6), emptyList(), board))+    }++    @Test+    fun overlappingMovesRejectedButTouchingAllowed() {+        val other = h(2, 2)+        assertFalse(isMoveValid(h(1, 2), listOf(other), board)) // overlaps one cell+        assertFalse(isMoveValid(h(2, 2), listOf(other), board)) // identical+        assertFalse(isMoveValid(v(3, 1), listOf(other), board)) // crosses at (3,2)+        assertTrue(isMoveValid(h(0, 2), listOf(other), board)) // touches left edge+        assertTrue(isMoveValid(h(4, 2), listOf(other), board)) // touches right edge+        assertTrue(isMoveValid(h(2, 1), listOf(other), board)) // row above+        assertTrue(isMoveValid(h(2, 3), listOf(other), board)) // row below+    }++    @Test+    fun smallerBoardDimensionRespected() {+        val small = Dimension(4, 4)+        assertTrue(isMoveValid(h(2, 3), emptyList(), small))+        assertFalse(isMoveValid(h(3, 3), emptyList(), small))+        assertFalse(isMoveValid(v(3, 3), emptyList(), small))+    }+}
games/unblockjam/src/test/java/com/vayunmathur/games/unblockjam/platform/ContractsAndManagersTest.kt
diff --git a/games/unblockjam/src/test/java/com/vayunmathur/games/unblockjam/platform/ContractsAndManagersTest.kt b/games/unblockjam/src/test/java/com/vayunmathur/games/unblockjam/platform/ContractsAndManagersTest.ktnew file mode 100644index 0000000000..3bddb4da39--- /dev/null+++ b/games/unblockjam/src/test/java/com/vayunmathur/games/unblockjam/platform/ContractsAndManagersTest.kt@@ -0,0 +1,145 @@+package com.vayunmathur.games.unblockjam.platform++import android.app.Application+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.games.unblockjam.Route+import com.vayunmathur.games.unblockjam.data.CompletedLevelsRepository+import com.vayunmathur.games.unblockjam.data.LevelPack+import kotlinx.serialization.json.Json+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNotNull+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)+class ContractsAndManagersTest {+    private val app get() = ApplicationProvider.getApplicationContext<Application>()+    private val ctx get() = app as android.content.Context++    @BeforeTest+    fun setUp() {+        if (LevelPack.PACKS.isEmpty()) LevelPack.init(app)+    }++    @Test+    fun gameActionsNoopDefaultsDoNothing() {+        val noop = GameActions.Noop+        noop.onBlockMoved(LevelPack.PACKS[0].levels[0])+        noop.onLevelWon(); noop.onUndo(); noop.onRestart(); noop.onLevelChange(3)+        // reaching here without state is the assertion; also a custom impl records+        var changed: Int? = null+        val custom = object : GameActions {+            override fun onLevelChange(newIndex: Int) { changed = newIndex }+        }+        custom.onLevelChange(7)+        assertEquals(7, changed)+        // other defaults remain no-ops on the custom impl+        custom.onUndo(); custom.onRestart(); custom.onLevelWon()+    }++    @Test+    fun settingsActionsNoopDefaultsDoNothing() {+        val noop = SettingsActions.Noop+        noop.setReminderEnabled(true)+        noop.setReminderTime(1, 2)+        var seen: Pair<Boolean, Pair<Int, Int>>? = null+        val custom = object : SettingsActions {+            override fun setReminderEnabled(enabled: Boolean) { seen = enabled to (0 to 0) }+        }+        custom.setReminderEnabled(false)+        assertEquals(false, seen!!.first)+        custom.setReminderTime(3, 4) // default no-op+    }++    @Test+    fun uiStateDataClasses() {+        val level = LevelPack.PACKS[0].levels[0]+        val state = GameUiState(levelData = level)+        assertEquals(0, state.levelIndex)+        assertEquals(0, state.moves)+        assertEquals(null, state.bestScore)+        assertFalse(state.isCompleted)+        assertFalse(state.isLevelWon)+        assertFalse(state.canUndo)+        assertEquals(state, state.copy())+        assertFalse(state == state.copy(moves = 1))++        val daily = DailyProgress(day = 10, completed = 1, total = 5, streak = 2)+        assertEquals(10L, daily.day)+        assertEquals(daily, daily.copy(completed = 1))++        val settings = SettingsUiState()+        assertFalse(settings.reminderEnabled)+        assertEquals(20, settings.reminderHour)+        assertEquals(0, settings.reminderMinute)+        assertEquals(settings, settings.copy(reminderHour = 20))+    }++    @Test+    fun completedLevelsRepositoryCountersPersist() {+        val repo = CompletedLevelsRepository(ctx)+        val movesBefore = repo.getTotalMoves()+        repo.incrementTotalMoves(); repo.incrementTotalMoves()+        assertEquals(movesBefore + 2, repo.getTotalMoves())+        // fresh instance over same prefs sees the same counters+        val repo2 = CompletedLevelsRepository(ctx)+        assertEquals(movesBefore + 2, repo2.getTotalMoves())+        val undoBefore = repo.getUndoCount()+        repo.incrementUndoCount()+        assertEquals(undoBefore + 1, repo2.getUndoCount())+    }++    @Test+    fun achievementsManagerChecksExistingAndPackCompletion() {+        val repo = CompletedLevelsRepository(ctx)+        val json = ctx.assets.open("achievements.json").bufferedReader().use { it.readText() }+        val manager = UnblockJamAchievementsManager(ctx, json, repo)+        assertEquals(11, manager.achievements.size)+        assertTrue(manager.achievements.any { it.id == "first_level" })+        manager.checkExistingAchievements()+        // completing every level of pack 0 in the completed set: progress call must not crash+        val allPack0 = LevelPack.PACKS[0].levels.map { it.id }.toSet()+        manager.onPackCompletionChanged(allPack0)+        manager.onPackCompletionChanged(emptySet())+        // partial: one level from a wall pack and one from a size pack+        val partial = setOf(+            LevelPack.PACKS[LevelPack.WALL_PACK_INDICES.first()].levels.first().id,+            LevelPack.PACKS[LevelPack.SIZE_PACK_INDICES.first()].levels.first().id,+            "nonexistent_id",+        )+        manager.onPackCompletionChanged(partial)+        manager.dismissNotification()+        assertEquals(null, manager.newAchievement.value)+    }++    @Test+    fun appBackupAgentListsPrefsAndDatastores() {+        val agent = AppBackupAgent()+        assertEquals(listOf("level_stats", "daily_stats"), agent.prefNames)+        assertEquals(listOf("datastore_default"), agent.datastoreNames)+    }++    @Test+    fun routesSerializeRoundTrip() {+        val json = Json+        fun <T> roundTrip(value: T, serializer: kotlinx.serialization.KSerializer<T>) {+            val encoded = json.encodeToString(serializer, value)+            assertEquals(value, json.decodeFromString(serializer, encoded))+        }+        roundTrip(Route.PackSelector as Route, Route.serializer())+        roundTrip(Route.LevelSelector(3) as Route, Route.serializer())+        roundTrip(Route.Game(1, 2) as Route, Route.serializer())+        roundTrip(Route.DailySelector as Route, Route.serializer())+        roundTrip(Route.DailyGame(4) as Route, Route.serializer())+        roundTrip(Route.GameCenter as Route, Route.serializer())+        roundTrip(Route.Settings as Route, Route.serializer())+        assertEquals(3, Route.LevelSelector(3).packIndex)+        assertEquals(2, Route.Game(1, 2).levelIndex)+        assertEquals(4, Route.DailyGame(4).levelIndex)+        assertNotNull(Route.PackSelector)+    }+}
games/unblockjam/src/test/java/com/vayunmathur/games/unblockjam/platform/UnblockJamViewModelTest.kt
diff --git a/games/unblockjam/src/test/java/com/vayunmathur/games/unblockjam/platform/UnblockJamViewModelTest.kt b/games/unblockjam/src/test/java/com/vayunmathur/games/unblockjam/platform/UnblockJamViewModelTest.ktnew file mode 100644index 0000000000..9eb86df208--- /dev/null+++ b/games/unblockjam/src/test/java/com/vayunmathur/games/unblockjam/platform/UnblockJamViewModelTest.kt@@ -0,0 +1,293 @@+package com.vayunmathur.games.unblockjam.platform++import android.app.Application+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.games.unblockjam.data.Block+import com.vayunmathur.games.unblockjam.data.Coord+import com.vayunmathur.games.unblockjam.data.Dimension+import com.vayunmathur.games.unblockjam.data.LevelPack+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.ExperimentalCoroutinesApi+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.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++@OptIn(ExperimentalCoroutinesApi::class)+@RunWith(RobolectricTestRunner::class)+class UnblockJamViewModelTest {+    private val app get() = ApplicationProvider.getApplicationContext<Application>()++    @BeforeTest+    fun setUp() {+        Dispatchers.setMain(Dispatchers.Unconfined)+        if (LevelPack.PACKS.isEmpty()) LevelPack.init(app)+    }++    @AfterTest fun tearDown() { Dispatchers.resetMain() }++    private fun vm() = UnblockJamViewModel(app)++    @Test+    fun packsLoadAndInitialStateIsEmpty() {+        assertEquals(7, LevelPack.PACKS.size)+        assertTrue(LevelPack.PACKS.all { it.levels.isNotEmpty() })+        val vm = vm()+        val s = vm.uiState.value+        assertEquals(-1, s.packIndex)+        assertEquals(-1, s.levelIndex)+        assertNull(s.currentLevelData)+        assertTrue(s.history.isEmpty())+        assertFalse(s.isLevelWon)+        assertEquals(0, vm.getCurrentMoves())+        assertEquals(UnblockJamUiState(), s)+        assertEquals("unblockjam_daily", UnblockJamViewModel.DAILY_KEY_PREFIX)+        assertEquals(-2, UnblockJamViewModel.DAILY_PACK_INDEX)+    }++    @Test+    fun loadLevelInvalidIndicesAreNoOps() {+        val vm = vm()+        vm.loadLevel(99, 0)+        assertNull(vm.uiState.value.currentLevelData)+        vm.loadLevel(0, 9999)+        assertNull(vm.uiState.value.currentLevelData)+        vm.loadLevel(-5, 0)+        assertNull(vm.uiState.value.currentLevelData)+        vm.loadLevel(UnblockJamViewModel.DAILY_PACK_INDEX, 0) // daily pack not generated yet+        assertNull(vm.uiState.value.currentLevelData)+    }++    @Test+    fun loadLevelLoadsAndReloadingSameIsNoOpAfterMove() {+        val vm = vm()+        vm.loadLevel(0, 0)+        val loaded = assertNotNull(vm.uiState.value.currentLevelData)+        assertEquals(LevelPack.PACKS[0].levels[0], loaded)+        assertEquals(0, vm.uiState.value.packIndex)+        assertEquals(0, vm.uiState.value.levelIndex)++        // move a block (different index) so history grows, then reloading same must keep state+        val moved = movedCopy(loaded, blockIndex = lastBlock(loaded), dx = 0, dy = 0)+        vm.onBlockMoved(moved)+        val afterMove = vm.uiState.value+        vm.loadLevel(0, 0)+        assertEquals(afterMove, vm.uiState.value)++        // loading a different level resets+        vm.loadLevel(0, 1)+        assertEquals(1, vm.uiState.value.levelIndex)+        assertEquals(LevelPack.PACKS[0].levels[1], vm.uiState.value.currentLevelData)+        assertTrue(vm.uiState.value.history.isEmpty())+        assertFalse(vm.uiState.value.isLevelWon)+    }++    private fun lastBlock(level: com.vayunmathur.games.unblockjam.data.LevelData): Int =+        level.blocks.indices.last { !level.blocks[it].fixed }++    /** Returns a copy with block [blockIndex] shifted by one cell if possible, marked as moved. */+    private fun movedCopy(+        level: com.vayunmathur.games.unblockjam.data.LevelData,+        blockIndex: Int,+        dx: Int,+        dy: Int,+    ): com.vayunmathur.games.unblockjam.data.LevelData {+        val block = level.blocks[blockIndex]+        val shifted = block.copy(+            position = Coord(block.position.x + dx, block.position.y + dy)+        )+        // find a genuinely different, non-overlapping position by trying shifts+        val candidates = listOf(shifted, block.copy(position = Coord(block.position.x + 1, block.position.y)),+            block.copy(position = Coord(block.position.x, block.position.y + 1)),+            block.copy(position = Coord(block.position.x - 1, block.position.y)),+            block.copy(position = Coord(block.position.x, block.position.y - 1)))+        val chosen = candidates.firstOrNull { c ->+            c.position != block.position && isMoveValid(c, level.blocks - block, level.dimension)+        } ?: block+        val blocks = level.blocks.toMutableList().also { it[blockIndex] = chosen }+        return level.copy(blocks = blocks, lastMovedBlockIndex = blockIndex)+    }++    @Test+    fun onBlockMovedWithoutLevelIsNoOp() {+        val vm = vm()+        val fake = LevelPack.PACKS[0].levels[0].copy(lastMovedBlockIndex = 0)+        vm.onBlockMoved(fake)+        assertEquals(UnblockJamUiState(), vm.uiState.value)+    }++    @Test+    fun movesCollapseSameBlockAndHistoryTracksDifferentBlocks() {+        val vm = vm()+        vm.loadLevel(0, 0)+        val start = vm.uiState.value.currentLevelData!!+        val idx = lastBlock(start)++        val first = movedCopy(start, idx, 1, 0)+        vm.onBlockMoved(first)+        assertEquals(1, vm.uiState.value.history.size)+        assertEquals(first, vm.uiState.value.currentLevelData)+        assertEquals(1, vm.getCurrentMoves())++        // continuing to drag same block: current updates, history does not grow+        val second = movedCopy(first, idx, 1, 0)+        if (second.blocks != first.blocks) {+            vm.onBlockMoved(second)+            assertEquals(1, vm.uiState.value.history.size)+            assertEquals(second, vm.uiState.value.currentLevelData)+            assertEquals(1, vm.getCurrentMoves())+        }++        // moving back to the start layout collapses the history entry+        vm.onBlockMoved(start.copy(lastMovedBlockIndex = idx))+        // collapse triggers when new blocks equal history.last().blocks (the start)+        assertEquals(start.blocks, vm.uiState.value.currentLevelData!!.blocks)+    }++    @Test+    fun undoAndRestartRestoreHistory() {+        val vm = vm()+        vm.loadLevel(0, 0)+        val start = vm.uiState.value.currentLevelData!!+        // undo/restart with empty history are no-ops+        vm.onUndo(); vm.onRestart()+        assertEquals(start, vm.uiState.value.currentLevelData)++        val idx = lastBlock(start)+        val moved = movedCopy(start, idx, 1, 0)+        vm.onBlockMoved(moved)+        assertEquals(1, vm.uiState.value.history.size)++        vm.onRestart()+        assertEquals(start, vm.uiState.value.currentLevelData)+        assertTrue(vm.uiState.value.history.isEmpty())++        vm.onBlockMoved(moved)+        vm.onUndo()+        assertEquals(start.blocks, vm.uiState.value.currentLevelData!!.blocks)+        assertTrue(vm.uiState.value.history.isEmpty())+        assertEquals(0, vm.getCurrentMoves())+    }++    @Test+    fun levelWonBlocksFurtherMovesUndoAndRestart() {+        val vm = vm()+        vm.onLevelWon() // no pack loaded: no-op+        assertFalse(vm.uiState.value.isLevelWon)++        vm.loadLevel(0, 0)+        val start = vm.uiState.value.currentLevelData!!+        val idx = lastBlock(start)+        val moved = movedCopy(start, idx, 1, 0)+        vm.onBlockMoved(moved)+        assertEquals(1, vm.getCurrentMoves())++        vm.onLevelWon()+        assertTrue(vm.uiState.value.isLevelWon)+        // winning move increment: last moved was not main block, so +1+        assertEquals(2, vm.getCurrentMoves())+        // the win persists a best score for the level asynchronously+        val wonId = start.id+        kotlinx.coroutines.runBlocking {+            kotlinx.coroutines.withTimeout(30_000) { vm.levelStats.first { it.containsKey(wonId) } }+        }+        assertTrue(vm.levelStats.value.getValue(wonId).bestScore <= 2)++        vm.onLevelWon() // second call no-op+        vm.onUndo()+        vm.onRestart()+        // undo/restart are blocked once won, so history and win flag survive them+        assertTrue(vm.uiState.value.isLevelWon)+        assertEquals(1, vm.uiState.value.history.size)+        assertEquals(2, vm.getCurrentMoves())+    }++    @Test+    fun levelWonAfterMovingMainBlockHasNoExtraIncrement() {+        val vm = vm()+        vm.loadLevel(0, 0)+        val start = vm.uiState.value.currentLevelData!!+        // simulate main-block as last moved (index 0), no actual geometry change needed:+        // a same-index update only replaces current data+        vm.onBlockMoved(start.copy(lastMovedBlockIndex = 0))+        // changing the last-moved index counts as a move even without geometry change+        assertEquals(1, vm.uiState.value.history.size)+        vm.onLevelWon()+        assertTrue(vm.uiState.value.isLevelWon)+        // last moved is the main block, so no extra winning increment beyond history+        assertEquals(1, vm.getCurrentMoves())+    }++    @Test+    fun repositoryCountersAndDismissNotification() {+        val vm = vm()+        val beforeMoves = vm.repository.getTotalMoves()+        vm.repository.incrementTotalMoves()+        assertEquals(beforeMoves + 1, vm.repository.getTotalMoves())+        val beforeUndo = vm.repository.getUndoCount()+        vm.repository.incrementUndoCount()+        assertEquals(beforeUndo + 1, vm.repository.getUndoCount())+        vm.dismissAchievementNotification()+        assertNull(vm.achievementsManager.newAchievement.value)+        assertNotNull(vm.levelStats.value)+        assertNotNull(vm.dailyStats.value)+        assertTrue(vm.dailyDay.value > 0)+    }++    @Test+    fun reminderSettersDoNotCrashAndStateFlowsExist() {+        val vm = vm()+        vm.setReminderEnabled(false)+        vm.setReminderTime(9, 30)+        // flows have initial values from stateIn defaults / store+        assertEquals(false, vm.reminderEnabled.value)+        assertTrue(vm.reminderMinutesOfDay.value in 0..1439)+        assertTrue(vm.dailyCompleted.value >= 0)+        assertTrue(vm.dailyStreak.value >= 0)+    }++    @Test+    fun dailyPackGenerationAndDailyWin() {+        val vm = vm()+        vm.refreshDaily()+        val pack = kotlinx.coroutines.runBlocking {+            kotlinx.coroutines.withTimeout(120_000) {+                vm.dailyPack.first { it != null }+            }+        }!!+        assertEquals(com.vayunmathur.games.unblockjam.data.DailyLevelGenerator.LEVELS_PER_DAY, pack.levels.size)+        // second refresh is a no-op once today's pack exists+        vm.refreshDaily()++        vm.loadLevel(UnblockJamViewModel.DAILY_PACK_INDEX, 0)+        assertEquals(UnblockJamViewModel.DAILY_PACK_INDEX, vm.uiState.value.packIndex)+        assertEquals(pack.levels[0], vm.uiState.value.currentLevelData)++        vm.onLevelWon()+        assertTrue(vm.uiState.value.isLevelWon)+        val wonId = pack.levels[0].id+        kotlinx.coroutines.runBlocking {+            kotlinx.coroutines.withTimeout(30_000) {+                vm.dailyStats.first { it.containsKey(wonId) }+            }+        }+        assertTrue(vm.dailyStats.value.containsKey(wonId))+    }++    @Test+    fun uiStateDataClassCopy() {+        val state = UnblockJamUiState(packIndex = 1, levelIndex = 2, isLevelWon = true)+        assertEquals(1, state.packIndex)+        assertEquals(state, state.copy())+        assertFalse(state == state.copy(levelIndex = 3))+    }+}