Modern Apps git

← Modern-Apps.git

games-chess: add tests for game logic and online play (67 tests)

Commit
97d77a93d88406e8b9dbffb9450f058096aea90c
Author
Vayun Mathur <[email protected]>
When
2026-11-15 19:00 UTC (20 days ago)
Parents
74e3fae
Add unit tests covering chess move rules (castling, en passant, pins, promotion, notation, FEN), Learn/Puzzle data and view models, OnlineChessViewModel and its server-event stream sinks, Lichess auth PKCE lifecycle and model parsing, plus Robolectric Compose game/online/learn/puzzle screens. All assertions are on real board state and uiState.

Skipped: LichessApi HTTP paths (hard-bound to the NetworkClient singleton, no fake-transport seam) and MainActivity bootstrap glue.

Coverage (JaCoCo INSTRUCTION): covered 20,608 -> 25,584 (+4,976), missed 13,557 -> 8,592 (60.3% -> 74.9%).
Verified: :games:chess:testDevUnitTest (212 tests, 0 failures) :games:chess:detekt :games:chess:lint green.

Diff

games/chess/src/test/java/com/vayunmathur/games/chess/GameDialogsCoverageTest.kt
diff --git a/games/chess/src/test/java/com/vayunmathur/games/chess/GameDialogsCoverageTest.kt b/games/chess/src/test/java/com/vayunmathur/games/chess/GameDialogsCoverageTest.ktnew file mode 100644index 0000000000..e565b3f435--- /dev/null+++ b/games/chess/src/test/java/com/vayunmathur/games/chess/GameDialogsCoverageTest.kt@@ -0,0 +1,76 @@+package com.vayunmathur.games.chess++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.chess.data.PieceColor+import com.vayunmathur.games.chess.data.Position+import com.vayunmathur.games.chess.util.ChessActions+import com.vayunmathur.games.chess.util.ChessUiState+import com.vayunmathur.games.chess.util.Difficulty+import com.vayunmathur.games.chess.util.GameMode+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.Test+import kotlin.test.assertEquals++/** New-game dialog flows: AI settings pickers and their defaults. */+@RunWith(RobolectricTestRunner::class)+class GameDialogsCoverageTest {+    @get:Rule val rule = createComposeRule()+    private val ctx get() = ApplicationProvider.getApplicationContext<android.content.Context>()+    private fun str(id: Int, vararg args: Any) =+        if (args.isEmpty()) ctx.getString(id) else ctx.getString(id, *args)++    @Test fun `ai settings flow carries the picked colour and difficulty`() {+        val modes = mutableListOf<GameMode>()+        rule.setContent { NewGameDialog(onNewGame = { modes += it }, aiAvailable = true) }+        rule.onNodeWithText(str(R.string.human_vs_ai)).performClick()+        rule.onNodeWithText(str(R.string.play_as), substring = true).assertExists()+        rule.onNodeWithText(str(R.string.color_black)).performClick()+        rule.onNodeWithText(str(R.string.difficulty_master)).performClick()+        rule.onNodeWithText(str(R.string.start_game)).performClick()+        assertEquals(listOf<GameMode>(GameMode.VsAI(PieceColor.BLACK, Difficulty.GRANDMASTER)), modes)+    }++    @Test fun `ai settings start with white and intermediate by default`() {+        val modes = mutableListOf<GameMode>()+        rule.setContent { NewGameDialog(onNewGame = { modes += it }, aiAvailable = true) }+        rule.onNodeWithText(str(R.string.human_vs_ai)).performClick()+        rule.onNodeWithText(str(R.string.start_game)).performClick()+        assertEquals(listOf<GameMode>(GameMode.VsAI(PieceColor.WHITE, Difficulty.INTERMEDIATE)), modes)+    }+}++/** The expanded (wide-window) game layout with its side panel. */+@RunWith(RobolectricTestRunner::class)[email protected](qualifiers = "w1280dp-h800dp")+class ExpandedGameLayoutTest {+    @get:Rule val rule = createComposeRule()+    private val ctx get() = ApplicationProvider.getApplicationContext<android.content.Context>()+    private fun str(id: Int, vararg args: Any) =+        if (args.isEmpty()) ctx.getString(id) else ctx.getString(id, *args)+    private fun sq(file: Char, rank: Int) = Position(8 - rank, file - 'a')++    @Test fun `expanded layout shows the side panel with moves captures and status`() {+        var board = com.vayunmathur.games.chess.data.Board.initialState+        board = board.movePiece(sq('e', 2), sq('e', 4))+        board = board.movePiece(sq('d', 7), sq('d', 5))+        board = board.movePiece(sq('e', 4), sq('d', 5)) // exd5: a capture for the side panel+        var newGame = 0+        rule.setContent {+            ChessGameScreen(+                state = ChessUiState(board = board, turn = PieceColor.BLACK, gameStatus = "Check"),+                actions = ChessActions.Noop,+                onNewGame = { newGame++ },+                onOpenGameCenter = {},+            )+        }+        rule.onNodeWithText("exd5").assertExists()+        rule.onNodeWithText("Check").assertExists()+        rule.onNodeWithText(str(com.vayunmathur.library.ui.R.string.new_game)).performClick()+        assertEquals(1, newGame)+    }+}
games/chess/src/test/java/com/vayunmathur/games/chess/ScreensCoverageTest.kt
diff --git a/games/chess/src/test/java/com/vayunmathur/games/chess/ScreensCoverageTest.kt b/games/chess/src/test/java/com/vayunmathur/games/chess/ScreensCoverageTest.ktnew file mode 100644index 0000000000..21c0262d3b--- /dev/null+++ b/games/chess/src/test/java/com/vayunmathur/games/chess/ScreensCoverageTest.kt@@ -0,0 +1,243 @@+package com.vayunmathur.games.chess++import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.setValue+import androidx.compose.ui.test.assertCountEquals+import androidx.compose.ui.test.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.performClick+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.games.chess.data.Board+import com.vayunmathur.games.chess.data.LearnLevel+import com.vayunmathur.games.chess.data.LearnShape+import com.vayunmathur.games.chess.data.LearnStage+import com.vayunmathur.games.chess.data.PieceColor+import com.vayunmathur.games.chess.data.PieceType+import com.vayunmathur.games.chess.data.Position+import com.vayunmathur.games.chess.network.LichessTimeControl+import com.vayunmathur.games.chess.network.UciMove+import com.vayunmathur.games.chess.platform.OnlineAuth+import com.vayunmathur.games.chess.platform.OnlineChessUiState+import com.vayunmathur.games.chess.platform.OnlineConnection+import com.vayunmathur.games.chess.util.LearnUiState+import com.vayunmathur.games.chess.util.PuzzleActions+import com.vayunmathur.games.chess.util.PuzzleDifficulty+import com.vayunmathur.games.chess.util.PuzzleStatus+import com.vayunmathur.games.chess.util.PuzzleUiState+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.Test+import kotlin.test.assertEquals++/** Stateful-screen variants: online lobby/game, puzzle statuses, learn dialogs and board. */+@RunWith(RobolectricTestRunner::class)[email protected](qualifiers = "w800dp-h1280dp")+class ScreensCoverageTest {+    @get:Rule val rule = createComposeRule()+    private val ctx get() = ApplicationProvider.getApplicationContext<android.content.Context>()+    private fun str(id: Int, vararg args: Any) =+        if (args.isEmpty()) ctx.getString(id) else ctx.getString(id, *args)+    private fun sq(file: Char, rank: Int) = Position(8 - rank, file - 'a')++    private class RecordingPuzzleActions : PuzzleActions {+        val calls = mutableListOf<String>()+        override fun onSquareClick(position: Position) { calls += "click" }+        override fun onPromote(pieceType: PieceType) { calls += "promote:$pieceType" }+        override fun onCancelPromotion() { calls += "cancelPromotion" }+        override fun loadRandom(difficulty: PuzzleDifficulty) { calls += "load:$difficulty" }+        override fun retry() { calls += "retry" }+        override fun showSolution() { calls += "showSolution" }+    }++    // -- Online ---------------------------------------------------------------++    @Test fun `online lobby shows signing in then challenging progress`() {+        var state by mutableStateOf(OnlineChessUiState(auth = OnlineAuth.SigningIn))+        rule.setContent { ChessOnlineScreen(state) }+        rule.onNodeWithText(str(R.string.online_signing_in)).assertExists()+        state = OnlineChessUiState(+            auth = OnlineAuth.SignedIn("ada"),+            connection = OnlineConnection.Challenging("bob"),+            challengeUsername = "bob",+        )+        rule.waitForIdle()+        rule.onNodeWithText(str(R.string.online_challenge_sent, "bob"), substring = true).assertExists()+        rule.onNodeWithText(str(R.string.online_signed_in_as, "ada")).assertExists()+    }++    @Test fun `online lobby signed in shows time controls and the challenge field`() {+        rule.setContent {+            ChessOnlineScreen(+                OnlineChessUiState(+                    auth = OnlineAuth.SignedIn("ada"),+                    selectedTimeControl = LichessTimeControl.RAPID_10_0,+                )+            )+        }+        for (label in listOf("1+0", "3+2", "5+3", "10+0")) {+            rule.onNodeWithText(label).assertExists()+        }+        rule.onNodeWithText(str(R.string.online_sign_out)).assertExists()+        rule.onNodeWithText(str(R.string.online_challenge_username)).assertExists()+    }++    @Test fun `online game shows clocks reconnecting and the abort bar until the first move`() {+        val playing = OnlineConnection.Playing(+            gameId = "g1", localColor = PieceColor.WHITE, opponentName = "bob",+            whiteClockMs = 180_000, blackClockMs = 65_000, reconnecting = true,+        )+        var connection by mutableStateOf<OnlineConnection>(playing)+        rule.setContent {+            ChessOnlineScreen(OnlineChessUiState(auth = OnlineAuth.SignedIn("ada"), connection = connection))+        }+        rule.onNodeWithText(str(R.string.online_reconnecting)).assertExists()+        rule.onNodeWithText("${str(R.string.color_white)} 3:00", substring = true).assertExists()+        rule.onNodeWithText("${str(R.string.color_black)} 1:05", substring = true).assertExists()+        rule.onNodeWithText(str(R.string.online_abort_confirm)).assertExists()+        rule.onNodeWithText(str(R.string.online_resign_confirm)).assertExists()+        connection = playing.copy(+            board = Board.initialState.movePiece(sq('e', 2), sq('e', 4)), reconnecting = false,+        )+        rule.waitForIdle()+        rule.onNodeWithText(str(R.string.online_abort_confirm)).assertDoesNotExist()+        rule.onNodeWithText(str(R.string.online_resign_confirm)).assertExists()+    }++    @Test fun `online game over shows the result and a staged promotion shows the picker`() {+        var connection by mutableStateOf<OnlineConnection>(+            OnlineConnection.Playing(+                gameId = "g1", localColor = PieceColor.BLACK, opponentName = "bob", resultText = "You win!",+            )+        )+        rule.setContent {+            ChessOnlineScreen(OnlineChessUiState(auth = OnlineAuth.SignedIn("ada"), connection = connection))+        }+        rule.onNodeWithText("You win!").assertExists()+        rule.onNodeWithText(str(R.string.online_back_to_lobby)).assertExists()+        val board = Board.fromFen("8/P7/8/8/8/8/k6K/8 w - - 0 1")+        connection = OnlineConnection.Playing(+            gameId = "g2", localColor = PieceColor.WHITE, board = board,+            pendingPromotion = UciMove(sq('a', 7), sq('a', 8)),+        )+        rule.waitForIdle()+        rule.onNodeWithText(str(R.string.promote_pawn)).assertExists()+    }++    // -- Puzzle ---------------------------------------------------------------++    @Test fun `puzzle screen renders every status and routes failed actions`() {+        val actions = RecordingPuzzleActions()+        var state by mutableStateOf(PuzzleUiState(status = PuzzleStatus.Loading, rating = 1234))+        rule.setContent { PuzzleBoardScreen(state, actions) }+        for ((status, text) in listOf(+            PuzzleStatus.Loading to str(R.string.puzzle_loading),+            PuzzleStatus.Solving to str(R.string.puzzle_your_move),+            PuzzleStatus.Solved to str(R.string.puzzle_solved),+            PuzzleStatus.ShowingSolution to str(R.string.puzzle_show_solution),+        )) {+            state = PuzzleUiState(status = status, rating = 1234)+            rule.waitForIdle()+            rule.onNodeWithText(text).assertExists()+            rule.onNodeWithText(str(R.string.puzzle_rating, 1234)).assertExists()+        }+        state = PuzzleUiState(status = PuzzleStatus.Failed, rating = 900)+        rule.waitForIdle()+        rule.onNodeWithText(str(R.string.puzzle_failed)).assertExists()+        rule.onNodeWithText(str(com.vayunmathur.library.ui.R.string.retry)).performClick()+        rule.onNodeWithText(str(R.string.puzzle_show_solution)).performClick()+        rule.onNodeWithText(str(R.string.puzzle_next)).performClick()+        assertEquals(listOf("retry", "showSolution", "load:EASY"), actions.calls)+    }++    @Test fun `puzzle difficulty selector routes through actions`() {+        val actions = RecordingPuzzleActions()+        rule.setContent {+            PuzzleBoardScreen(+                PuzzleUiState(status = PuzzleStatus.Solving, difficulty = PuzzleDifficulty.EASY), actions)+        }+        rule.onNodeWithText(str(com.vayunmathur.library.ui.R.string.hard)).performClick()+        rule.onNodeWithText(str(com.vayunmathur.library.ui.R.string.easy)).assertExists()+        assertEquals(listOf("load:HARD"), actions.calls)+    }++    @Test fun `puzzle promotion dialog routes the picked piece through actions`() {+        val actions = RecordingPuzzleActions()+        val stepped = Board.fromFen("8/P7/8/8/8/8/k6K/8 w - - 0 1")+            .movePiece(sq('a', 7), sq('a', 8))+        rule.setContent {+            PuzzleBoardScreen(PuzzleUiState(board = stepped, status = PuzzleStatus.Solving), actions)+        }+        rule.onNodeWithText(str(R.string.promote_pawn)).assertExists()+        rule.onNode(+            hasClickAction() and androidx.compose.ui.test.hasContentDescription(+                str(R.string.piece_white_queen)+            )+        ).performClick()+        assertEquals(listOf("promote:QUEEN"), actions.calls)+    }++    // -- Learn ----------------------------------------------------------------++    private fun stage(levels: Int = 3) = LearnStage(+        id = 7, key = "rook", title = "Rook", subtitle = "The rook",+        intro = "Learn the rook.", complete = "Stage done.",+        levels = List(levels) {+            LearnLevel(goal = "Collect", fen = "8/8/8/8/8/8/4R3/8 w - - 0 1", goalType = "apples")+        },+    )++    @Test fun `learn stepper shows numbers and earned stars and routes selection`() {+        val selected = mutableListOf<Int>()+        rule.setContent {+            LevelStepper(count = 4, current = 1, stars = listOf(3, 0, 1, 0), onSelect = { selected += it })+        }+        rule.onNodeWithText("2").performClick()+        assertEquals(listOf(1), selected)+        rule.onAllNodesWithText("โ˜…", substring = true).assertCountEquals(2)+    }++    @Test fun `learn stage intro dialog renders and starts`() {+        var started = 0+        rule.setContent { StageIntroDialog(stage(3), onStart = { started++ }) }+        rule.onNodeWithText(str(R.string.learn_stage_number, 7, "Rook")).assertExists()+        rule.onNodeWithText("Learn the rook.").assertExists()+        rule.onNodeWithText(str(R.string.learn_lets_go)).performClick()+        assertEquals(1, started)+    }++    @Test fun `learn stage complete dialog shows score and next stage`() {+        var next = 0; var back = 0+        rule.setContent {+            StageCompleteDialog(+                stage = stage(2), stageStars = listOf(3, 3), score = 1250,+                nextTitle = "Bishop", onNext = { next++ }, onBackToMenu = { back++ },+            )+        }+        rule.onNodeWithText(str(R.string.learn_your_score, 1250)).assertExists()+        rule.onNodeWithText("Stage done.").assertExists()+        rule.onNodeWithText(str(R.string.learn_next_stage, "Bishop")).performClick()+        rule.onNodeWithText(str(R.string.learn_back_to_menu)).performClick()+        assertEquals(1, next)+        assertEquals(1, back)+    }++    @Test fun `learn board renders apples and shapes and forwards clicks`() {+        val clicks = mutableListOf<Position>()+        val ui = LearnUiState(+            board = Board.fromFen("8/8/8/8/8/8/4R3/8 w - - 0 1"),+            apples = setOf(sq('e', 7)),+            shapes = listOf(LearnShape("e2", "e7"), LearnShape("a1")),+            playerColor = PieceColor.WHITE,+        )+        rule.setContent { LearnBoard(ui, onSquareClick = { clicks += it }) }+        rule.onAllNodes(hasClickAction())[6 * 8 + 4].performClick() // e2+        assertEquals(listOf(sq('e', 2)), clicks)+        rule.onAllNodes(+            androidx.compose.ui.test.hasContentDescription(str(R.string.piece_white_rook), substring = true)+        ).assertCountEquals(1)+    }+}
games/chess/src/test/java/com/vayunmathur/games/chess/auth/AuthCoverageTest.kt
diff --git a/games/chess/src/test/java/com/vayunmathur/games/chess/auth/AuthCoverageTest.kt b/games/chess/src/test/java/com/vayunmathur/games/chess/auth/AuthCoverageTest.ktnew file mode 100644index 0000000000..068a4176dd--- /dev/null+++ b/games/chess/src/test/java/com/vayunmathur/games/chess/auth/AuthCoverageTest.kt@@ -0,0 +1,94 @@+package com.vayunmathur.games.chess.auth++import android.app.Application+import android.content.Intent+import androidx.core.net.toUri+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.games.chess.platform.OnlineAuth+import com.vayunmathur.games.chess.platform.OnlineChessViewModel+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.ExperimentalCoroutinesApi+import kotlinx.coroutines.flow.update+import kotlinx.coroutines.runBlocking+import kotlinx.coroutines.test.resetMain+import kotlinx.coroutines.test.setMain+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertIs+import kotlin.test.assertTrue++/** PKCE sign-in state machine: pending attempt, state validation, redirect bridge. */+@OptIn(ExperimentalCoroutinesApi::class)+@RunWith(RobolectricTestRunner::class)+class AuthCoverageTest {+    private val app get() = ApplicationProvider.getApplicationContext<Application>()+    // Custom Tabs need an Activity context; the manager is constructed with one here.+    private val activity: android.app.Activity by lazy {+        org.robolectric.Robolectric.buildActivity(android.app.Activity::class.java).create().get()+    }++    @BeforeTest fun setUp() {+        Dispatchers.setMain(Dispatchers.Unconfined)+        runBlocking { LichessTokenStore(app).clear() }+    }+    @AfterTest fun tearDown() {+        runBlocking { LichessTokenStore(app).clear() }+        Dispatchers.resetMain()+    }++    @Test fun `a mismatched state is rejected and consumes the pending attempt`() { runBlocking {+        val manager = LichessAuthManager(activity, LichessTokenStore(app))+        manager.startSignIn()+        val mismatch = runCatching {+            manager.finishSignIn(LichessAuthManager.AuthRedirect("code", "forged-state"))+        }.exceptionOrNull()+        assertIs<IllegalStateException>(mismatch)+        assertTrue(mismatch.message!!.contains("mismatch"), mismatch.message)+        val second = runCatching {+            manager.finishSignIn(LichessAuthManager.AuthRedirect("code", "forged-state"))+        }.exceptionOrNull()+        assertIs<IllegalStateException>(second)+        assertTrue(second.message!!.contains("No pending"), second.message)+    } }++    @Test fun `restarting sign in abandons the earlier attempt`() { runBlocking {+        val manager = LichessAuthManager(activity, LichessTokenStore(app))+        manager.startSignIn()+        manager.startSignIn() // only the newest state may complete+        val outcome = runCatching {+            manager.finishSignIn(LichessAuthManager.AuthRedirect("code", "stale-state"))+        }.exceptionOrNull()+        assertIs<IllegalStateException>(outcome)+    } }++    @Test fun `the bridge drops foreign intents and forwards our callback`() {+        LichessAuthBridge.onRedirect(Intent()) // no data: ignored, must not throw+        LichessAuthBridge.onRedirect(+            Intent().setData("https://example.com/?code=x&state=y".toUri())+        )+        LichessAuthBridge.onRedirect(+            Intent().setData("modernapps://lichess-callback?code=abc&state=xyz".toUri())+        )+    }++    @Test fun `a redirect with no pending attempt fails the view model sign in`() {+        val vm = OnlineChessViewModel(app)+        vm.uiStateFlow.update { it.copy(auth = OnlineAuth.SigningIn) }+        LichessAuthBridge.onRedirect(+            Intent().setData("modernapps://lichess-callback?code=abc&state=xyz".toUri())+        )+        val deadline = System.currentTimeMillis() + 10_000+        while (System.currentTimeMillis() < deadline &&+            vm.uiState.value.authError != OnlineAuth.Error.SignInFailed+        ) {+            Thread.sleep(40)+        }+        assertEquals(OnlineAuth.Error.SignInFailed, vm.uiState.value.authError)+        assertEquals(OnlineAuth.SignedOut, vm.uiState.value.auth)+        vm.signOut()+    }+}
games/chess/src/test/java/com/vayunmathur/games/chess/data/ChessLogicCoverageTest.kt
diff --git a/games/chess/src/test/java/com/vayunmathur/games/chess/data/ChessLogicCoverageTest.kt b/games/chess/src/test/java/com/vayunmathur/games/chess/data/ChessLogicCoverageTest.ktnew file mode 100644index 0000000000..465e9b18e7--- /dev/null+++ b/games/chess/src/test/java/com/vayunmathur/games/chess/data/ChessLogicCoverageTest.kt@@ -0,0 +1,283 @@+package com.vayunmathur.games.chess.data++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFailsWith+import kotlin.test.assertFalse+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++/** Castling, en passant, pins, notation ambiguity, promotion expansion and FEN edges. */+class ChessLogicCoverageTest {+    private fun sq(file: Char, rank: Int) = Position(8 - rank, file - 'a')+    private fun board(vararg placements: Pair<Position, Piece>): Board {+        val grid = MutableList(8) { MutableList<Piece?>(8) { null } }+        for ((pos, piece) in placements) grid[pos.row][pos.col] = piece+        return Board(grid.map { it.toList() })+    }+    private fun piece(type: PieceType, color: PieceColor, moved: Boolean = false) =+        Piece(type, color, hasMoved = moved)++    private fun castleBoard() = board(+        sq('e', 1) to piece(PieceType.KING, PieceColor.WHITE),+        sq('a', 1) to piece(PieceType.ROOK, PieceColor.WHITE),+        sq('h', 1) to piece(PieceType.ROOK, PieceColor.WHITE),+        sq('e', 8) to piece(PieceType.KING, PieceColor.BLACK),+        sq('a', 8) to piece(PieceType.ROOK, PieceColor.BLACK),+        sq('h', 8) to piece(PieceType.ROOK, PieceColor.BLACK),+    )++    @Test fun `castling both sides legal and movePiece relocates the rook`() {+        val b = castleBoard()+        assertTrue(b.isValidMove(sq('e', 1), sq('g', 1)))+        assertTrue(b.isValidMove(sq('e', 1), sq('c', 1)))+        val kingside = b.movePiece(sq('e', 1), sq('g', 1))+        assertEquals(PieceType.KING, kingside.pieces[sq('g', 1).row][sq('g', 1).col]?.type)+        assertEquals(PieceType.ROOK, kingside.pieces[sq('f', 1).row][sq('f', 1).col]?.type)+        assertNull(kingside.pieces[sq('h', 1).row][sq('h', 1).col])+        assertEquals("O-O", kingside.lastMove.toString())+        val queenside = b.movePiece(sq('e', 1), sq('c', 1))+        assertEquals(PieceType.ROOK, queenside.pieces[sq('d', 1).row][sq('d', 1).col]?.type)+        assertEquals("O-O-O", queenside.lastMove.toString())+    }++    @Test fun `castling blocked by pieces between king and rook`() {+        val b = board(+            sq('e', 1) to piece(PieceType.KING, PieceColor.WHITE),+            sq('f', 1) to piece(PieceType.KNIGHT, PieceColor.WHITE),+            sq('b', 1) to piece(PieceType.KNIGHT, PieceColor.WHITE),+            sq('a', 1) to piece(PieceType.ROOK, PieceColor.WHITE),+            sq('h', 1) to piece(PieceType.ROOK, PieceColor.WHITE),+            sq('e', 8) to piece(PieceType.KING, PieceColor.BLACK),+        )+        assertFalse(b.isValidMove(sq('e', 1), sq('g', 1)), "knight on f1 blocks kingside")+        assertFalse(b.isValidMove(sq('e', 1), sq('c', 1)), "knight on b1 blocks queenside")+    }++    @Test fun `castling through check and out of check is illegal but queenside may stay legal`() {+        val throughCheck = board(+            sq('e', 1) to piece(PieceType.KING, PieceColor.WHITE),+            sq('a', 1) to piece(PieceType.ROOK, PieceColor.WHITE),+            sq('h', 1) to piece(PieceType.ROOK, PieceColor.WHITE),+            sq('e', 8) to piece(PieceType.KING, PieceColor.BLACK),+            sq('f', 8) to piece(PieceType.ROOK, PieceColor.BLACK),+        )+        assertFalse(throughCheck.isKingInCheck(PieceColor.WHITE))+        assertFalse(throughCheck.isValidMove(sq('e', 1), sq('g', 1)), "f1 is attacked by the f8 rook")+        assertTrue(throughCheck.isValidMove(sq('e', 1), sq('c', 1)))+        val inCheck = board(+            sq('e', 1) to piece(PieceType.KING, PieceColor.WHITE),+            sq('a', 1) to piece(PieceType.ROOK, PieceColor.WHITE),+            sq('h', 1) to piece(PieceType.ROOK, PieceColor.WHITE),+            sq('e', 8) to piece(PieceType.KING, PieceColor.BLACK),+            sq('e', 7) to piece(PieceType.ROOK, PieceColor.BLACK),+        )+        assertTrue(inCheck.isKingInCheck(PieceColor.WHITE))+        assertFalse(inCheck.isValidMove(sq('e', 1), sq('g', 1)))+        assertFalse(inCheck.isValidMove(sq('e', 1), sq('c', 1)))+    }++    @Test fun `castling requires unmoved king and rook`() {+        val kingMoved = board(+            sq('e', 1) to piece(PieceType.KING, PieceColor.WHITE, moved = true),+            sq('h', 1) to piece(PieceType.ROOK, PieceColor.WHITE),+            sq('e', 8) to piece(PieceType.KING, PieceColor.BLACK),+        )+        assertFalse(kingMoved.isValidMove(sq('e', 1), sq('g', 1)))+        assertTrue(kingMoved.isValidMove(sq('e', 1), sq('f', 1)), "ordinary king step still legal")+        val rookMoved = board(+            sq('e', 1) to piece(PieceType.KING, PieceColor.WHITE),+            sq('h', 1) to piece(PieceType.ROOK, PieceColor.WHITE, moved = true),+            sq('e', 8) to piece(PieceType.KING, PieceColor.BLACK),+        )+        assertFalse(rookMoved.isValidMove(sq('e', 1), sq('g', 1)))+    }++    @Test fun `en passant capture for white removes the double-stepped pawn`() {+        var b = Board.initialState+        b = b.movePiece(sq('e', 2), sq('e', 4))+        b = b.movePiece(sq('a', 7), sq('a', 6))+        b = b.movePiece(sq('e', 4), sq('e', 5))+        b = b.movePiece(sq('d', 7), sq('d', 5))+        assertTrue(b.isValidMove(sq('e', 5), sq('d', 6)))+        val after = b.movePiece(sq('e', 5), sq('d', 6))+        assertNull(after.pieces[sq('d', 5).row][sq('d', 5).col], "captured pawn leaves d5")+        assertEquals(PieceType.PAWN, after.pieces[sq('d', 6).row][sq('d', 6).col]?.type)+        assertEquals(PieceColor.WHITE, after.pieces[sq('d', 6).row][sq('d', 6).col]?.color)+        assertTrue(after.capturedByWhite.any { it.type == PieceType.PAWN && it.color == PieceColor.BLACK })+        assertEquals("exd6", after.lastMove.toString())+    }++    @Test fun `en passant expires and black can capture en passant`() {+        var b = Board.initialState+        b = b.movePiece(sq('e', 2), sq('e', 4))+        b = b.movePiece(sq('a', 7), sq('a', 6))+        b = b.movePiece(sq('e', 4), sq('e', 5))+        b = b.movePiece(sq('d', 7), sq('d', 5))+        b = b.movePiece(sq('g', 1), sq('f', 3)) // white spends a move: the chance is gone+        b = b.movePiece(sq('a', 6), sq('a', 5))+        assertFalse(b.isValidMove(sq('e', 5), sq('d', 6)))++        var black = Board.initialState+        black = black.movePiece(sq('a', 2), sq('a', 3))+        black = black.movePiece(sq('e', 7), sq('e', 5))+        black = black.movePiece(sq('a', 3), sq('a', 4))+        black = black.movePiece(sq('e', 5), sq('e', 4))+        black = black.movePiece(sq('d', 2), sq('d', 4))+        assertTrue(black.isValidMove(sq('e', 4), sq('d', 3)))+        val after = black.movePiece(sq('e', 4), sq('d', 3))+        assertNull(after.pieces[sq('d', 4).row][sq('d', 4).col])+        assertTrue(after.capturedByBlack.any { it.type == PieceType.PAWN })+    }++    @Test fun `pawn double step needs a clear path and captures need a victim`() {+        val blocked = board(+            sq('e', 1) to piece(PieceType.KING, PieceColor.WHITE),+            sq('e', 8) to piece(PieceType.KING, PieceColor.BLACK),+            sq('e', 2) to piece(PieceType.PAWN, PieceColor.WHITE),+            sq('e', 3) to piece(PieceType.PAWN, PieceColor.BLACK),+        )+        assertFalse(blocked.isValidMove(sq('e', 2), sq('e', 3)), "cannot step onto a piece")+        assertFalse(blocked.isValidMove(sq('e', 2), sq('e', 4)), "cannot jump over a piece")+        assertFalse(blocked.isValidMove(sq('e', 2), sq('d', 3)), "no diagonal without a capture")+        val open = board(+            sq('e', 1) to piece(PieceType.KING, PieceColor.WHITE),+            sq('e', 8) to piece(PieceType.KING, PieceColor.BLACK),+            sq('e', 2) to piece(PieceType.PAWN, PieceColor.WHITE),+            sq('d', 3) to piece(PieceType.PAWN, PieceColor.BLACK),+        )+        assertTrue(open.isValidMove(sq('e', 2), sq('e', 4)))+        assertTrue(open.isValidMove(sq('e', 2), sq('d', 3)))+    }++    @Test fun `a pinned piece is pseudo-legal but not legal`() {+        val b = board(+            sq('e', 1) to piece(PieceType.KING, PieceColor.WHITE),+            sq('e', 2) to piece(PieceType.ROOK, PieceColor.WHITE),+            sq('e', 8) to piece(PieceType.ROOK, PieceColor.BLACK),+            sq('a', 8) to piece(PieceType.KING, PieceColor.BLACK),+        )+        assertFalse(b.isKingInCheck(PieceColor.WHITE), "the rook currently shields the king")+        assertTrue(b.isPseudoLegalMove(sq('e', 2), sq('d', 2)))+        assertFalse(b.isValidMove(sq('e', 2), sq('d', 2)), "sidestep exposes the king")+        assertTrue(b.isValidMove(sq('e', 2), sq('e', 8)), "capturing the attacker resolves it")+    }++    @Test fun `legalMoves expands promotions four ways including captures`() {+        val b = board(+            sq('e', 1) to piece(PieceType.KING, PieceColor.WHITE),+            sq('e', 8) to piece(PieceType.KING, PieceColor.BLACK),+            sq('a', 7) to piece(PieceType.PAWN, PieceColor.WHITE),+            sq('b', 8) to piece(PieceType.ROOK, PieceColor.BLACK),+        )+        val promos = b.legalMoves(PieceColor.WHITE)+            .filter { it.start == sq('a', 7) }+        assertEquals(8, promos.size, "push and capture, each with four promotion pieces")+        assertEquals(Board.PROMOTION_CHOICES.toSet(), promos.mapNotNull { it.promotedTo }.toSet())+        assertTrue(promos.filter { it.end == sq('b', 8) }.all { it.capturedPiece?.type == PieceType.ROOK })+        assertEquals(+            listOf(PieceType.QUEEN, PieceType.ROOK, PieceType.BISHOP, PieceType.KNIGHT),+            Board.PROMOTION_CHOICES,+        )+    }++    @Test fun `promotePawn rewrites the last move and clears the pending square`() {+        val b = board(+            sq('e', 1) to piece(PieceType.KING, PieceColor.WHITE),+            sq('e', 8) to piece(PieceType.KING, PieceColor.BLACK),+            sq('a', 7) to piece(PieceType.PAWN, PieceColor.WHITE),+        )+        val stepped = b.movePiece(sq('a', 7), sq('a', 8))+        assertEquals(sq('a', 8), stepped.promotionPosition)+        val promoted = stepped.promotePawn(sq('a', 8), PieceType.KNIGHT)+        assertEquals(PieceType.KNIGHT, promoted.pieces[sq('a', 8).row][sq('a', 8).col]?.type)+        assertNull(promoted.promotionPosition)+        assertEquals(PieceType.KNIGHT, promoted.lastMove?.promotedTo)+        assertEquals("a8=N", promoted.lastMove.toString())+    }++    @Test fun `notation disambiguates by file rank or both`() {+        val byFile = board(+            sq('b', 1) to piece(PieceType.KNIGHT, PieceColor.WHITE),+            sq('f', 3) to piece(PieceType.KNIGHT, PieceColor.WHITE),+        )+        assertEquals("Nbd2", byFile.movePiece(sq('b', 1), sq('d', 2)).lastMove.toString())+        val byRank = board(+            sq('b', 1) to piece(PieceType.KNIGHT, PieceColor.WHITE),+            sq('b', 3) to piece(PieceType.KNIGHT, PieceColor.WHITE),+        )+        assertEquals("N1d2", byRank.movePiece(sq('b', 1), sq('d', 2)).lastMove.toString())+        val byBoth = board(+            sq('b', 1) to piece(PieceType.KNIGHT, PieceColor.WHITE),+            sq('b', 3) to piece(PieceType.KNIGHT, PieceColor.WHITE),+            sq('f', 1) to piece(PieceType.KNIGHT, PieceColor.WHITE),+        )+        assertEquals("Nb1d2", byBoth.movePiece(sq('b', 1), sq('d', 2)).lastMove.toString())+        val plain = Move(sq('e', 2), sq('e', 4), Piece(PieceType.PAWN, PieceColor.WHITE))+        assertEquals("e4", plain.toString())+    }++    @Test fun `notation marks check and checkmate`() {+        val check = board(+            sq('e', 1) to piece(PieceType.KING, PieceColor.WHITE),+            sq('d', 1) to piece(PieceType.QUEEN, PieceColor.WHITE),+            sq('e', 8) to piece(PieceType.KING, PieceColor.BLACK),+        )+        assertEquals("Qd7+", check.movePiece(sq('d', 1), sq('d', 7)).lastMove.toString())+        var game = Board.initialState+        game = game.movePiece(sq('f', 2), sq('f', 3))+        game = game.movePiece(sq('e', 7), sq('e', 5))+        game = game.movePiece(sq('g', 2), sq('g', 4))+        game = game.movePiece(sq('d', 8), sq('h', 4))+        assertEquals("Qh4#", game.lastMove.toString())+        assertTrue(game.isCheckmate(PieceColor.WHITE))+    }++    @Test fun `insufficient material bishops must share a square colour`() {+        val twoWhiteBishops = board(+            sq('e', 1) to piece(PieceType.KING, PieceColor.WHITE),+            sq('c', 1) to piece(PieceType.BISHOP, PieceColor.WHITE),+            sq('e', 3) to piece(PieceType.BISHOP, PieceColor.WHITE),+            sq('e', 8) to piece(PieceType.KING, PieceColor.BLACK),+        )+        assertTrue(twoWhiteBishops.isInsufficientMaterial(), "same-colour bishops can never mate")+        val bishopAndKnight = board(+            sq('e', 1) to piece(PieceType.KING, PieceColor.WHITE),+            sq('c', 1) to piece(PieceType.BISHOP, PieceColor.WHITE),+            sq('e', 8) to piece(PieceType.KING, PieceColor.BLACK),+            sq('g', 8) to piece(PieceType.KNIGHT, PieceColor.BLACK),+        )+        assertFalse(bishopAndKnight.isInsufficientMaterial())+        assertEquals(2, Board.initialState.kingCount())+        assertEquals(2, twoWhiteBishops.kingCount())+    }++    @Test fun `fen round trips castling en passant and turn`() {+        assertEquals(+            "rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq e3 0 1",+            Board.initialState.movePiece(sq('e', 2), sq('e', 4)).toFen(),+        )+        val castle = Board.fromFen("r3k2r/8/8/8/8/8/8/R3K2R w KQkq - 0 1")+        assertTrue(castle.isValidMove(sq('e', 1), sq('g', 1)))+        assertTrue(castle.isValidMove(sq('e', 8), sq('c', 8)))+        assertTrue(castle.toFen().contains(" KQkq "))+        val noRights = Board.fromFen("r3k2r/8/8/8/8/8/8/R3K2R w - - 0 1")+        assertFalse(noRights.isValidMove(sq('e', 1), sq('g', 1)), "FEN '-' marks king and rook moved")+        val afterKingMove = castle.movePiece(sq('e', 1), sq('d', 1))+        assertTrue(afterKingMove.toFen().contains(" kq "), afterKingMove.toFen())+        val ep = Board.fromFen("8/8/8/3pP3/8/8/8/4K2k w - d6 0 1")+        assertTrue(ep.isValidMove(sq('e', 5), sq('d', 6)), "FEN en-passant target enables the capture")+        assertFailsWith<IllegalArgumentException> { Board.fromFen("8/8/8/8/8/8/8/4X3 w - - 0 1") }+        val blackToMove = Board.fromFen("8/8/8/8/8/8/8/4K2k b - - 0 1")+        assertNotNull(blackToMove.pieces[sq('e', 1).row][sq('e', 1).col])+    }++    @Test fun `movePiece on an empty square throws and empty-board queries are safe`() {+        val empty = board(sq('e', 1) to piece(PieceType.KING, PieceColor.WHITE))+        assertFailsWith<IllegalStateException> { empty.movePiece(sq('a', 1), sq('a', 2)) }+        assertFalse(empty.isValidMove(sq('a', 1), sq('a', 2)))+        assertFalse(empty.isKingInCheck(PieceColor.BLACK), "no black king: not in check")+        assertFalse(empty.hasLegalMoves(PieceColor.BLACK))+    }+}
games/chess/src/test/java/com/vayunmathur/games/chess/data/LearnAndPuzzleDataTest.kt
diff --git a/games/chess/src/test/java/com/vayunmathur/games/chess/data/LearnAndPuzzleDataTest.kt b/games/chess/src/test/java/com/vayunmathur/games/chess/data/LearnAndPuzzleDataTest.ktnew file mode 100644index 0000000000..cf34423970--- /dev/null+++ b/games/chess/src/test/java/com/vayunmathur/games/chess/data/LearnAndPuzzleDataTest.kt@@ -0,0 +1,203 @@+package com.vayunmathur.games.chess.data++import com.vayunmathur.games.chess.util.captures+import com.vayunmathur.games.chess.util.countColor+import com.vayunmathur.games.chess.util.detectCaptureMove+import com.vayunmathur.games.chess.util.isFailingMove+import com.vayunmathur.games.chess.util.isSuccess+import com.vayunmathur.games.chess.util.positionsOf+import java.nio.ByteBuffer+import java.nio.ByteOrder+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++/** Learn goal evaluation branches and the binary puzzle record decoder. */+class LearnAndPuzzleDataTest {+    private fun sq(file: Char, rank: Int) = Position(8 - rank, file - 'a')+    private fun board(vararg placements: Pair<Position, Piece>): Board {+        val grid = MutableList(8) { MutableList<Piece?>(8) { null } }+        for ((pos, piece) in placements) grid[pos.row][pos.col] = piece+        return Board(grid.map { it.toList() })+    }+    private fun level(+        goalType: String,+        detectCapture: String? = null,+        n: Int? = null,+        nbMoves: Int = 1,+        failOn: List<String> = emptyList(),+        offPath: List<String> = emptyList(),+    ) = LearnLevel(+        goal = "goal", fen = "8/8/8/8/8/8/8/8 w - - 0 1", goalType = goalType,+        nbMoves = nbMoves, detectCapture = detectCapture, n = n,+        failIfWhitePawnOn = failOn, failIfPieceOffPath = offPath,+    )++    @Test fun `learn level derived properties parse squares and colour`() {+        val black = LearnLevel(goal = "g", fen = "8/8/8/8/8/8/8/8 b - - 0 1", color = "black",+            goalType = "apples", apples = "e7 g5  ")+        assertEquals(PieceColor.BLACK, black.playerColor)+        assertEquals(listOf(sq('e', 7), sq('g', 5)), black.appleSquares)+        val bare = LearnLevel(goal = "g", fen = "8/8/8/8/8/8/8/8 w - - 0 1", goalType = "apples")+        assertEquals(PieceColor.WHITE, bare.playerColor)+        assertEquals(emptyList(), bare.appleSquares)+        assertEquals(sq('e', 4), square("e4"))+        assertEquals(Triple(sq('e', 2), sq('e', 4), null), parseUci("e2e4"))+        assertEquals(PieceType.ROOK, parseUci("a7a8r").third)+        assertNull(parseUci("a7a8x").third, "unknown promotion letter decodes to no promotion")+    }++    @Test fun `buildBoard plants apples as enemy pawns unless empty or occupied`() {+        val rookLevel = LearnLevel(goal = "g", fen = "8/8/8/8/8/8/4R3/8 w - - 0 1",+            goalType = "apples", apples = "e7")+        val built = LearnRepository.buildBoard(rookLevel)+        val apple = built.pieces[sq('e', 7).row][sq('e', 7).col]+        assertEquals(PieceType.PAWN, apple?.type)+        assertEquals(PieceColor.BLACK, apple?.color, "white player collects black apple pawns")+        val empty = LearnRepository.buildBoard(rookLevel.copy(emptyApples = true))+        assertNull(empty.pieces[sq('e', 7).row][sq('e', 7).col])+        val blackPlayer = LearnRepository.buildBoard(rookLevel.copy(color = "black"))+        assertEquals(PieceColor.WHITE, blackPlayer.pieces[sq('e', 7).row][sq('e', 7).col]?.color)+    }++    @Test fun `success evaluation covers check mate escape castle and captureAll`() {+        val mate = board(+            sq('a', 8) to Piece(PieceType.KING, PieceColor.BLACK),+            sq('b', 7) to Piece(PieceType.QUEEN, PieceColor.WHITE),+            sq('c', 6) to Piece(PieceType.KING, PieceColor.WHITE),+        )+        assertTrue(isSuccess(level("mate"), mate, emptySet(), PieceColor.WHITE))+        assertTrue(isSuccess(level("check"), mate, emptySet(), PieceColor.WHITE))+        assertTrue(isSuccess(level("checkIn"), mate, emptySet(), PieceColor.WHITE))+        assertFalse(isSuccess(level("escapeCheck"), mate, emptySet(), PieceColor.BLACK),+            "the mated king is still in check")+        assertTrue(isSuccess(level("escapeCheck"), mate, emptySet(), PieceColor.WHITE))+        assertTrue(isSuccess(level("protection"), mate, emptySet(), PieceColor.WHITE))+        assertFalse(isSuccess(level("captureAll"), mate, emptySet(), PieceColor.WHITE))+        val noBlack = board(sq('e', 1) to Piece(PieceType.KING, PieceColor.WHITE))+        assertTrue(isSuccess(level("captureAll"), noBlack, emptySet(), PieceColor.WHITE))+        val castled = Board.fromFen("r3k2r/8/8/8/8/8/8/R3K2R w KQkq - 0 1")+            .movePiece(sq('e', 1), sq('g', 1))+        assertTrue(isSuccess(level("castle"), castled, emptySet(), PieceColor.WHITE))+        assertFalse(isSuccess(level("castle"), mate, emptySet(), PieceColor.WHITE))+        assertFalse(isSuccess(level("unknownGoal"), mate, setOf(sq('a', 1)), PieceColor.WHITE),+            "unknown goals fall back to collecting every apple")+    }++    @Test fun `detectCapture distinguishes any capture from an unprotected one`() {+        val hanging = board(+            sq('e', 1) to Piece(PieceType.KING, PieceColor.WHITE),+            sq('e', 8) to Piece(PieceType.KING, PieceColor.BLACK),+            sq('d', 4) to Piece(PieceType.QUEEN, PieceColor.WHITE),+            sq('d', 8) to Piece(PieceType.QUEEN, PieceColor.BLACK),+        )+        assertEquals(sq('d', 8) to sq('d', 4),+            detectCaptureMove(level("captureAll", detectCapture = "all"), hanging, PieceColor.WHITE))+        assertEquals(sq('d', 8) to sq('d', 4),+            detectCaptureMove(level("captureAll", detectCapture = "unprotected"), hanging, PieceColor.WHITE),+            "nothing defends the queen on d4")+        val defended = board(+            sq('e', 1) to Piece(PieceType.KING, PieceColor.WHITE),+            sq('e', 8) to Piece(PieceType.KING, PieceColor.BLACK),+            sq('d', 4) to Piece(PieceType.QUEEN, PieceColor.WHITE),+            sq('c', 3) to Piece(PieceType.PAWN, PieceColor.WHITE),+            sq('d', 8) to Piece(PieceType.QUEEN, PieceColor.BLACK),+        )+        assertNull(detectCaptureMove(level("captureAll", detectCapture = "unprotected"), defended, PieceColor.WHITE),+            "the c3 pawn recaptures on d4, so the queen is protected")+        assertNotNull(detectCaptureMove(level("captureAll", detectCapture = "all"), defended, PieceColor.WHITE))+        assertNull(detectCaptureMove(level("captureAll", detectCapture = "none"), hanging, PieceColor.WHITE))+        assertEquals(1, captures(hanging, PieceColor.BLACK).size)+        assertEquals(listOf(sq('d', 4), sq('e', 1)), positionsOf(hanging, PieceColor.WHITE))+        assertEquals(2, countColor(hanging, PieceColor.BLACK))+    }++    @Test fun `failing move covers path constraints and timed check goals`() {+        val pawnAstray = board(+            sq('e', 1) to Piece(PieceType.KING, PieceColor.WHITE),+            sq('e', 8) to Piece(PieceType.KING, PieceColor.BLACK),+            sq('e', 4) to Piece(PieceType.PAWN, PieceColor.WHITE),+        )+        assertTrue(isFailingMove(level("apples", failOn = listOf("e4")), pawnAstray, PieceColor.WHITE, 1))+        assertFalse(isFailingMove(level("apples", failOn = listOf("e5")), pawnAstray, PieceColor.WHITE, 1))+        assertTrue(isFailingMove(level("apples", offPath = listOf("e1", "e8")), pawnAstray, PieceColor.WHITE, 1),+            "the pawn left the allowed path squares")+        assertFalse(isFailingMove(+            level("apples", offPath = listOf("e1", "e8", "e4")), pawnAstray, PieceColor.WHITE, 1))+        val kings = board(+            sq('e', 1) to Piece(PieceType.KING, PieceColor.WHITE),+            sq('e', 8) to Piece(PieceType.KING, PieceColor.BLACK),+        )+        assertFalse(isFailingMove(level("checkIn", n = 3), kings, PieceColor.WHITE, 1),+            "checkIn still has moves left")+        assertTrue(isFailingMove(level("checkIn", n = 3), kings, PieceColor.WHITE, 3),+            "checkIn out of moves without check fails")+        assertTrue(isFailingMove(level("escapeCheck"), board(+            sq('e', 1) to Piece(PieceType.KING, PieceColor.WHITE),+            sq('e', 8) to Piece(PieceType.KING, PieceColor.BLACK),+            sq('e', 7) to Piece(PieceType.ROOK, PieceColor.BLACK),+        ), PieceColor.WHITE, 1), "still in check after the move")+    }++    /** Builds one binary puzzle record at offset 0 (see PuzzleRepository format). */+    private fun record(flags: Int, ep: Int, rating: Int, moves: List<Int>, nibbles: Map<Int, Int>): ByteArray {+        val bytes = ByteArray(37 + 2 * moves.size)+        for ((square, nibble) in nibbles) {+            val b = square / 2+            bytes[b] = if (square % 2 == 0) {+                (bytes[b].toInt() or nibble).toByte()+            } else {+                (bytes[b].toInt() or (nibble shl 4)).toByte()+            }+        }+        bytes[32] = flags.toByte()+        bytes[33] = ep.toByte()+        val bb = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN)+        bb.putShort(34, rating.toShort())+        bytes[36] = moves.size.toByte()+        moves.forEachIndexed { i, m -> bb.putShort(37 + 2 * i, m.toShort()) }+        return bytes+    }++    private fun moveBits(from: Int, to: Int, promo: Int = 0) = from or (to shl 6) or (promo shl 12)++    @Test fun `puzzle record decoder reads pieces side castling ep rating and moves`() {+        // WK e1 (square 60, king=1 white), BK e8 (square 4, king=1 black=9), WP a7 (square 8, pawn=6)+        val bytes = record(+            flags = 0x01 or 0x02 or 0x10, // black to move, white kingside + black queenside rights+            ep = 19, // d6+            rating = 1500,+            moves = listOf(moveBits(52, 36), moveBits(8, 0, promo = 1), moveBits(6, 22, promo = 4)),+            nibbles = mapOf(60 to 1, 4 to 9, 8 to 6),+        )+        val puzzle = PuzzleRepository.decodeRecord(bytes, 0)+        assertEquals(1500, puzzle.rating)+        assertEquals(3, puzzle.solution.size)+        assertEquals(Position(6, 4), puzzle.solution[0].from) // e2+        assertEquals(Position(4, 4), puzzle.solution[0].to) // e4+        assertNull(puzzle.solution[0].promotion)+        assertEquals(PieceType.QUEEN, puzzle.solution[1].promotion)+        assertEquals(PieceType.KNIGHT, puzzle.solution[2].promotion)+        val king = puzzle.board.pieces[7][4]+        assertEquals(PieceType.KING, king?.type)+        assertFalse(king!!.hasMoved, "a retained castling right keeps the king unmoved")+        assertEquals(PieceType.PAWN, puzzle.board.pieces[1][0]?.type) // a7+        assertNotNull(puzzle.board.lastMove, "ep target seeds a synthetic last move")+    }++    @Test fun `puzzle record without ep or promotion decodes plainly`() {+        val bytes = record(+            flags = 0, ep = 0xFF, rating = 400,+            moves = listOf(moveBits(62, 45, promo = 2), moveBits(57, 42, promo = 3)),+            nibbles = mapOf(62 to 1, 6 to 9),+        )+        val puzzle = PuzzleRepository.decodeRecord(bytes, 0)+        assertEquals(400, puzzle.rating)+        assertEquals(PieceType.ROOK, puzzle.solution[0].promotion)+        assertEquals(PieceType.BISHOP, puzzle.solution[1].promotion)+        assertTrue(puzzle.board.pieces[7][6]?.hasMoved == true, "no castling rights: king counts as moved")+    }+}
games/chess/src/test/java/com/vayunmathur/games/chess/network/LichessModelsCoverageTest.kt
diff --git a/games/chess/src/test/java/com/vayunmathur/games/chess/network/LichessModelsCoverageTest.kt b/games/chess/src/test/java/com/vayunmathur/games/chess/network/LichessModelsCoverageTest.ktnew file mode 100644index 0000000000..7284d7aaf3--- /dev/null+++ b/games/chess/src/test/java/com/vayunmathur/games/chess/network/LichessModelsCoverageTest.kt@@ -0,0 +1,77 @@+package com.vayunmathur.games.chess.network++import com.vayunmathur.games.chess.data.PieceColor+import com.vayunmathur.games.chess.data.PieceType+import com.vayunmathur.games.chess.data.Position+import kotlinx.serialization.json.Json+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFailsWith+import kotlin.test.assertFalse+import kotlin.test.assertIs+import kotlin.test.assertNull+import kotlin.test.assertTrue++/** Envelope defaults, colour/promotion mappings and game-line decoding edges. */+class LichessModelsCoverageTest {+    private val json = Json { ignoreUnknownKeys = true; isLenient = true }++    @Test fun `event envelopes tolerate missing payloads and map every kind`() {+        fun event(payload: String) = json.decodeFromString(LichessEventEnvelope.serializer(), payload).toEvent()+        val declined = event("""{"type":"challengeDeclined","challenge":{"id":"c9"}}""")+        assertIs<LichessEvent.ChallengeDeclined>(declined)+        assertEquals("c9", declined.id)+        val challenge = event("""{"type":"challenge","challenge":{"id":"c1","challenger":{"username":"eve"},"destUser":{"username":"ada"}}}""")+        assertIs<LichessEvent.Challenge>(challenge)+        assertEquals("eve", challenge.challenger)+        val bareStart = event("""{"type":"gameStart"}""")+        assertIs<LichessEvent.GameStart>(bareStart)+        assertEquals("", bareStart.gameId)+        assertEquals(PieceColor.WHITE, bareStart.color, "a missing colour defaults to white")+        val blackStart = event("""{"type":"gameStart","game":{"gameId":"g","color":"black","opponent":{"username":"zed"}}}""")+        assertIs<LichessEvent.GameStart>(blackStart)+        assertEquals(PieceColor.BLACK, blackStart.color)+        assertIs<LichessEvent.Ignored>(event("""{"type":"challengeCancelled","challenge":{"id":"x"}}"""))+    }++    @Test fun `uci helpers cover defensive branches`() {+        assertEquals(PieceType.KNIGHT, parseUci("b7b8k").promotion, "the never-sent k maps to knight")+        assertEquals('q', PieceType.KING.toUciPromotion())+        assertEquals('q', PieceType.PAWN.toUciPromotion())+        assertEquals('r', PieceType.ROOK.toUciPromotion())+        assertEquals("white", PieceColor.WHITE.toLichessColor())+        assertEquals("black", PieceColor.BLACK.toLichessColor())+        assertFailsWith<IllegalArgumentException> { promotionFromUci('x') }+        assertEquals("a1", Position(7, 0).toUciSquare())+        assertEquals("h8", Position(0, 7).toUciSquare())+        assertEquals(UciMove(Position(6, 4), Position(4, 4)), parseUci("e2e4"))+        assertNull(parseUci("e2e4").promotion)+        assertEquals(listOf("e2e4"), splitUciMoves("  e2e4  "))+    }++    @Test fun `game full colour resolution and profile defaults`() {+        val both = GameFull(white = LichessPlayer(id = "me"), black = LichessPlayer(id = "me"))+        assertEquals(PieceColor.WHITE, both.myColor("me"), "an id on both sides resolves to white")+        val neither = GameFull(white = LichessPlayer(id = "a"), black = LichessPlayer(id = "b"))+        assertEquals(PieceColor.WHITE, neither.myColor("stranger"))+        val profile = json.decodeFromString(LichessProfile.serializer(), """{}""")+        assertEquals("", profile.id)+        assertEquals("", profile.username)+        assertFalse(GameState(status = "created").isTerminal)+        assertTrue(GameState(status = "noStart").isTerminal)+        assertTrue(GameState(status = "variantEnd").isTerminal)+        assertEquals("5+3", LichessTimeControl.RAPID_5_3.label)+        assertEquals(10, LichessTimeControl.RAPID_10_0.minutes)+    }++    @Test fun `decodeGameLine survives non-object and typeless payloads`() {+        assertIs<LichessGameUpdate.Ignored>(decodeGameLine(json.parseToJsonElement("""[]"""), json))+        assertIs<LichessGameUpdate.Ignored>(decodeGameLine(json.parseToJsonElement("""{"moves":"e2e4"}"""), json))+        assertIs<LichessGameUpdate.Ignored>(decodeGameLine(json.parseToJsonElement("""{"type":42}"""), json))+        val state = decodeGameLine(+            json.parseToJsonElement("""{"type":"gameState","moves":"e2e4","status":"mate","winner":"black"}"""), json)+        assertIs<LichessGameUpdate.State>(state)+        assertEquals("black", state.state.winner)+        assertTrue(state.state.isTerminal)+    }+}
games/chess/src/test/java/com/vayunmathur/games/chess/platform/OnlineStreamCoverageTest.kt
diff --git a/games/chess/src/test/java/com/vayunmathur/games/chess/platform/OnlineStreamCoverageTest.kt b/games/chess/src/test/java/com/vayunmathur/games/chess/platform/OnlineStreamCoverageTest.ktnew file mode 100644index 0000000000..85debb9184--- /dev/null+++ b/games/chess/src/test/java/com/vayunmathur/games/chess/platform/OnlineStreamCoverageTest.kt@@ -0,0 +1,198 @@+package com.vayunmathur.games.chess.platform++import android.app.Application+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.games.chess.R+import com.vayunmathur.games.chess.auth.LichessTokenStore+import com.vayunmathur.games.chess.data.Board+import com.vayunmathur.games.chess.data.PieceColor+import com.vayunmathur.games.chess.data.PieceType+import com.vayunmathur.games.chess.data.Position+import com.vayunmathur.games.chess.network.GameFull+import com.vayunmathur.games.chess.network.GameState+import com.vayunmathur.games.chess.network.LichessEvent+import com.vayunmathur.games.chess.network.LichessGameUpdate+import com.vayunmathur.games.chess.network.LichessPlayer+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.ExperimentalCoroutinesApi+import kotlinx.coroutines.flow.update+import kotlinx.coroutines.runBlocking+import kotlinx.coroutines.suspendCancellableCoroutine+import kotlinx.coroutines.test.resetMain+import kotlinx.coroutines.test.setMain+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import java.lang.reflect.InvocationTargetException+import kotlin.coroutines.Continuation+import kotlin.coroutines.intrinsics.COROUTINE_SUSPENDED+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Server-event handling of [OnlineChessViewModel]: `onEvent`/`onGameUpdate` are the+ * private sinks of the NDJSON streams, and [LichessApi] is a concrete class bound to+ * the real [com.vayunmathur.library.network.NetworkClient], so there is no fake+ * transport to drive them with. The tests invoke the sinks reflectively and assert+ * the resulting public [OnlineChessViewModel.uiState] transitions โ€” the same state+ * the screens render.+ */+@OptIn(ExperimentalCoroutinesApi::class)+@RunWith(RobolectricTestRunner::class)+class OnlineStreamCoverageTest {+    private val app get() = ApplicationProvider.getApplicationContext<Application>()+    private fun sq(file: Char, rank: Int) = Position(8 - rank, file - 'a')++    @BeforeTest fun setUp() {+        Dispatchers.setMain(Dispatchers.Unconfined)+        runBlocking { LichessTokenStore(app).clear() }+    }+    @AfterTest fun tearDown() {+        runBlocking { LichessTokenStore(app).clear() }+        Dispatchers.resetMain()+    }++    /** Invokes a private `suspend fun` on the VM and suspends until it completes. */+    private suspend fun invokeSink(vm: OnlineChessViewModel, name: String, arg: Any) {+        val method = OnlineChessViewModel::class.java+            .getDeclaredMethod(name, arg.javaClass.interfaces.firstOrNull() ?: arg.javaClass, Continuation::class.java)+        method.isAccessible = true+        suspendCancellableCoroutine { cont ->+            val result = try {+                method.invoke(vm, arg, cont)+            } catch (e: InvocationTargetException) {+                cont.resumeWith(Result.failure(e.cause ?: e))+                return@suspendCancellableCoroutine+            }+            if (result != COROUTINE_SUSPENDED) cont.resumeWith(Result.success(result))+        }+    }++    private suspend fun onEvent(vm: OnlineChessViewModel, event: LichessEvent) =+        invokeSink(vm, "onEvent", event)++    private suspend fun onGameUpdate(vm: OnlineChessViewModel, update: LichessGameUpdate) =+        invokeSink(vm, "onGameUpdate", update)++    private fun playing(vm: OnlineChessViewModel) =+        vm.uiState.value.connection as OnlineConnection.Playing++    @Test fun `game start enters playing and game finish for another id is ignored`() = runBlocking {+        val vm = OnlineChessViewModel(app)+        onEvent(vm, LichessEvent.GameStart("g1", PieceColor.WHITE, "bob"))+        val started = playing(vm)+        assertEquals("g1", started.gameId)+        assertEquals("bob", started.opponentName)+        assertEquals(Board.initialState, started.board)+        onEvent(vm, LichessEvent.GameFinish("someone-else"))+        assertEquals("g1", playing(vm).gameId, "a finish for another game must not detach ours")+        onEvent(vm, LichessEvent.Ignored)+        assertEquals("g1", playing(vm).gameId)+        vm.signOut()+    }++    @Test fun `challenge declined returns a challenging lobby to idle with a notice`() = runBlocking {+        val vm = OnlineChessViewModel(app)+        onEvent(vm, LichessEvent.ChallengeDeclined("c1")) // not challenging: ignored+        assertEquals(OnlineConnection.Idle, vm.uiState.value.connection)+        assertNull(vm.uiState.value.lobbyNotice)+        vm.uiStateFlow.update { it.copy(connection = OnlineConnection.Challenging("bob")) }+        onEvent(vm, LichessEvent.ChallengeDeclined("c1"))+        assertEquals(OnlineConnection.Idle, vm.uiState.value.connection)+        assertEquals(OnlineLobby.Notice.ChallengeDeclined, vm.uiState.value.lobbyNotice)+        onEvent(vm, LichessEvent.Challenge("c2", "eve")) // incoming: declined server-side, lobby untouched+        assertEquals(OnlineConnection.Idle, vm.uiState.value.connection)+        vm.signOut()+    }++    @Test fun `game full resolves my colour and state deltas replay only the unseen tail`() = runBlocking {+        LichessTokenStore(app).saveUserId("me")+        val vm = OnlineChessViewModel(app)+        vm.uiStateFlow.update {+            it.copy(connection = OnlineConnection.Playing("g1", PieceColor.WHITE, opponentName = null))+        }+        val full = GameFull(+            id = "g1",+            white = LichessPlayer(id = "opp", name = "olga"),+            black = LichessPlayer(id = "me", name = "ada"),+            state = GameState(moves = "", wtime = 61_000, btime = 62_000, status = "started"),+        )+        onGameUpdate(vm, LichessGameUpdate.Full(full))+        var state = playing(vm)+        assertEquals(PieceColor.BLACK, state.localColor)+        assertEquals("olga", state.opponentName)+        assertEquals(61_000L, state.whiteClockMs)+        assertEquals(0L + 62_000L, state.blackClockMs)++        onGameUpdate(vm, LichessGameUpdate.State(GameState(moves = "e2e4 e7e5 g1f3", status = "started")))+        state = playing(vm)+        assertEquals(PieceType.KNIGHT, state.board.pieces[sq('f', 3).row][sq('f', 3).col]?.type)+        assertEquals(PieceColor.BLACK, state.turn, "three half-moves played: black to move")+        // A re-sent full list replays nothing twice; a tail with an illegal token stops there.+        onGameUpdate(vm, LichessGameUpdate.State(GameState(moves = "e2e4 e7e5 g1f3 g8f6 e2e3", status = "started")))+        state = playing(vm)+        assertEquals(PieceType.KNIGHT, state.board.pieces[sq('f', 6).row][sq('f', 6).col]?.type)+        assertEquals(4, state.board.moves.size, "the stale e2e3 token ends the replay")+        onGameUpdate(vm, LichessGameUpdate.Ignored)+        assertEquals(4, playing(vm).board.moves.size)+        vm.signOut()+    }++    @Test fun `promotion and castling tails are replayed with their piece choices`() = runBlocking {+        LichessTokenStore(app).saveUserId("me")+        val vm = OnlineChessViewModel(app)+        val promoBoard = Board.fromFen("8/P7/8/8/8/8/k6K/8 w - - 0 1")+        vm.uiStateFlow.update {+            it.copy(connection = OnlineConnection.Playing("g1", PieceColor.WHITE, board = promoBoard))+        }+        onGameUpdate(vm, LichessGameUpdate.State(GameState(moves = "a7a8q", status = "started")))+        assertEquals(PieceType.QUEEN, playing(vm).board.pieces[sq('a', 8).row][sq('a', 8).col]?.type)++        val castleVm = OnlineChessViewModel(app)+        val castleBoard = Board.fromFen("r3k2r/8/8/8/8/8/8/R3K2R w KQkq - 0 1")+        castleVm.uiStateFlow.update {+            it.copy(connection = OnlineConnection.Playing("g2", PieceColor.WHITE, board = castleBoard))+        }+        onGameUpdate(castleVm, LichessGameUpdate.State(GameState(moves = "e1g1", status = "started")))+        assertEquals(PieceType.ROOK, playing(castleVm).board.pieces[sq('f', 1).row][sq('f', 1).col]?.type)+        assertEquals(PieceColor.BLACK, playing(castleVm).turn)+        vm.signOut(); castleVm.signOut()+    }++    @Test fun `terminal states map to localised results and a full update without identity is dropped`() = runBlocking {+        val vm = OnlineChessViewModel(app)+        vm.uiStateFlow.update {+            it.copy(connection = OnlineConnection.Playing("g1", PieceColor.BLACK, opponentName = "bob"))+        }+        onGameUpdate(vm, LichessGameUpdate.State(+            GameState(moves = "e2e4", status = "resign", winner = "white")))+        assertEquals(app.getString(R.string.online_result_resigned), playing(vm).resultText,+            "white won on resign and I hold black: I resigned")+        onGameUpdate(vm, LichessGameUpdate.State(+            GameState(moves = "e2e4", status = "resign", winner = "black")))+        assertEquals(app.getString(R.string.online_result_opponent_resigned), playing(vm).resultText)+        onGameUpdate(vm, LichessGameUpdate.State(+            GameState(moves = "e2e4", status = "draw", winner = null)))+        assertEquals(app.getString(R.string.online_result_draw), playing(vm).resultText)+        onGameUpdate(vm, LichessGameUpdate.State(+            GameState(moves = "e2e4", status = "mate", winner = "black")))+        assertEquals(app.getString(R.string.online_result_win), playing(vm).resultText)+        onGameUpdate(vm, LichessGameUpdate.State(+            GameState(moves = "e2e4", status = "mate", winner = "white")))+        assertEquals(app.getString(R.string.online_result_loss), playing(vm).resultText)+        onGameUpdate(vm, LichessGameUpdate.State(+            GameState(moves = "e2e4", status = "aborted", winner = null)))+        assertEquals(app.getString(R.string.online_result_draw), playing(vm).resultText)++        LichessTokenStore(app).clear() // no stored identity: gameFull cannot resolve my colour+        val before = vm.uiState.value+        onGameUpdate(vm, LichessGameUpdate.Full(GameFull(id = "g9")))+        assertEquals(before, vm.uiState.value)+        assertNotNull(playing(vm).resultText)+        vm.signOut()+    }+}
games/chess/src/test/java/com/vayunmathur/games/chess/platform/OnlineViewModelCoverageTest.kt
diff --git a/games/chess/src/test/java/com/vayunmathur/games/chess/platform/OnlineViewModelCoverageTest.kt b/games/chess/src/test/java/com/vayunmathur/games/chess/platform/OnlineViewModelCoverageTest.ktnew file mode 100644index 0000000000..4673ee2591--- /dev/null+++ b/games/chess/src/test/java/com/vayunmathur/games/chess/platform/OnlineViewModelCoverageTest.kt@@ -0,0 +1,180 @@+package com.vayunmathur.games.chess.platform++import android.app.Application+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.games.chess.R+import com.vayunmathur.games.chess.auth.LichessTokenStore+import com.vayunmathur.games.chess.data.Board+import com.vayunmathur.games.chess.data.PieceColor+import com.vayunmathur.games.chess.data.PieceType+import com.vayunmathur.games.chess.data.Position+import com.vayunmathur.games.chess.network.LichessTimeControl+import com.vayunmathur.games.chess.network.UciMove+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.ExperimentalCoroutinesApi+import kotlinx.coroutines.flow.update+import kotlinx.coroutines.runBlocking+import kotlinx.coroutines.test.resetMain+import kotlinx.coroutines.test.setMain+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Online ViewModel behaviour driven through its `uiStateFlow` test seam: the board+ * only changes on server echoes, so local interaction is selection, deselection and+ * promotion staging โ€” all assertable without any network.+ */+@OptIn(ExperimentalCoroutinesApi::class)+@RunWith(RobolectricTestRunner::class)+class OnlineViewModelCoverageTest {+    private val app get() = ApplicationProvider.getApplicationContext<Application>()+    private fun sq(file: Char, rank: Int) = Position(8 - rank, file - 'a')++    @BeforeTest fun setUp() {+        Dispatchers.setMain(Dispatchers.Unconfined)+        runBlocking { LichessTokenStore(app).clear() }+    }+    @AfterTest fun tearDown() {+        runBlocking { LichessTokenStore(app).clear() }+        Dispatchers.resetMain()+    }++    private fun playingVm(+        board: Board = Board.initialState,+        turn: PieceColor = PieceColor.WHITE,+        localColor: PieceColor = PieceColor.WHITE,+        resultText: String? = null,+        pending: UciMove? = null,+    ): OnlineChessViewModel {+        val vm = OnlineChessViewModel(app)+        vm.uiStateFlow.update {+            it.copy(+                auth = OnlineAuth.SignedIn("ada"),+                connection = OnlineConnection.Playing(+                    gameId = "game-1", localColor = localColor, opponentName = "bob",+                    board = board, turn = turn, resultText = resultText,+                    pendingPromotion = pending,+                ),+            )+        }+        return vm+    }++    private fun playing(vm: OnlineChessViewModel) =+        vm.uiState.value.connection as OnlineConnection.Playing++    @Test fun `selection selects own piece, deselects on illegal target, ignores enemy and empty`() {+        val vm = playingVm()+        vm.onSquareClick(sq('e', 7)) // black pawn on white's move+        assertNull(playing(vm).selectedPiece)+        vm.onSquareClick(sq('e', 4)) // empty square with nothing selected+        assertNull(playing(vm).selectedPiece)+        vm.onSquareClick(sq('e', 2))+        assertEquals(sq('e', 2), playing(vm).selectedPiece)+        vm.onSquareClick(sq('e', 5)) // illegal pawn jump: deselect only, board untouched+        assertNull(playing(vm).selectedPiece)+        assertEquals(Board.initialState, playing(vm).board)+    }++    @Test fun `clicks are ignored when it is not our turn or the game is over`() {+        val opponentTurn = playingVm(turn = PieceColor.BLACK)+        opponentTurn.onSquareClick(sq('e', 7))+        assertNull(playing(opponentTurn).selectedPiece)+        val over = playingVm(resultText = "You won")+        over.onSquareClick(sq('e', 2))+        assertNull(playing(over).selectedPiece)+        assertEquals(Board.initialState, playing(over).board)+    }++    @Test fun `promotion is staged without touching the board and cancels cleanly`() {+        val board = Board.fromFen("8/P7/8/8/8/8/k6K/8 w - - 0 1")+        val vm = playingVm(board = board)+        vm.onSquareClick(sq('a', 7))+        assertEquals(sq('a', 7), playing(vm).selectedPiece)+        vm.onSquareClick(sq('a', 8))+        val staged = playing(vm)+        assertEquals(UciMove(sq('a', 7), sq('a', 8)), staged.pendingPromotion)+        assertEquals(board, staged.board, "the confirmed position does not move before the server echo")+        assertNull(staged.selectedPiece)+        vm.onSquareClick(sq('a', 7)) // the modal promotion choice owns input+        assertNull(playing(vm).selectedPiece)+        vm.onCancelPromotion()+        assertNull(playing(vm).pendingPromotion)+        assertEquals(board, playing(vm).board)+        vm.onCancelPromotion() // nothing staged: no-op+        vm.onPromote(PieceType.QUEEN) // nothing staged: no-op, and no network call is made+        assertEquals(board, playing(vm).board)+    }++    @Test fun `drop mirrors taps including the same-square and reselect paths`() {+        val vm = playingVm()+        vm.onSquareDrop(sq('e', 2), sq('e', 2))+        assertEquals(sq('e', 2), playing(vm).selectedPiece)+        vm.onSquareDrop(sq('e', 2), sq('e', 5)) // illegal drop target deselects+        assertNull(playing(vm).selectedPiece)+        vm.onSquareDrop(sq('d', 2), sq('d', 5)) // press selects d2, illegal release target deselects+        assertNull(playing(vm).selectedPiece)+        assertEquals(Board.initialState, playing(vm).board)+    }++    @Test fun `lobby guards and session resets`() {+        val vm = OnlineChessViewModel(app)+        vm.uiStateFlow.update {+            it.copy(+                auth = OnlineAuth.SigningIn,+                connection = OnlineConnection.Seeking(LichessTimeControl.BLITZ_3_2),+                lobbyError = OnlineLobby.Error.SeekFailed,+                lobbyNotice = OnlineLobby.Notice.ChallengeDeclined,+                authError = OnlineAuth.Error.Expired,+            )+        }+        vm.signIn() // already signing in: ignored+        assertEquals(OnlineAuth.SigningIn, vm.uiState.value.auth)+        vm.quickSeek() // already seeking: ignored+        assertTrue(vm.uiState.value.connection is OnlineConnection.Seeking)+        vm.onChallengeUsernameChange("bob")+        vm.challenge() // seeking blocks challenging+        assertTrue(vm.uiState.value.connection is OnlineConnection.Seeking)+        vm.cancelSeek()+        assertEquals(OnlineConnection.Idle, vm.uiState.value.connection)+        vm.dismissLobbyMessage()+        assertNull(vm.uiState.value.lobbyError)+        assertNull(vm.uiState.value.lobbyNotice)+        assertNull(vm.uiState.value.authError)+        assertEquals(+            app.getString(R.string.online_auth_expired),+            vm.authErrorText(OnlineAuth.Error.Expired),+        )+        vm.selectTimeControl(LichessTimeControl.BULLET)+        assertEquals("1+0", vm.uiState.value.selectedTimeControl.label)+        assertEquals(LichessTimeControl.PRESETS, listOf(+            LichessTimeControl.BULLET, LichessTimeControl.BLITZ_3_2,+            LichessTimeControl.RAPID_5_3, LichessTimeControl.RAPID_10_0,+        ))+    }++    @Test fun `back to lobby and sign out reset the session`() {+        val vm = playingVm()+        vm.onSquareClick(sq('e', 2))+        vm.backToLobby()+        assertEquals(OnlineConnection.Idle, vm.uiState.value.connection)+        val inGame = playingVm()+        assertTrue(playing(inGame).canAbort, "no moves yet: abort is offered")+        val moved = Board.initialState.movePiece(sq('e', 2), sq('e', 4))+        val afterMove = playingVm(board = moved, turn = PieceColor.BLACK)+        assertFalse(playing(afterMove).canAbort)+        inGame.signOut()+        assertEquals(OnlineChessUiState(), inGame.uiState.value)+        assertFalse(inGame.uiState.value.isBoardFlipped)+        val black = playingVm(localColor = PieceColor.BLACK, turn = PieceColor.BLACK)+        assertTrue(black.uiState.value.isBoardFlipped)+        assertEquals(PieceColor.BLACK, black.uiState.value.turn)+    }+}
games/chess/src/test/java/com/vayunmathur/games/chess/util/ViewModelCoverageTest.kt
diff --git a/games/chess/src/test/java/com/vayunmathur/games/chess/util/ViewModelCoverageTest.kt b/games/chess/src/test/java/com/vayunmathur/games/chess/util/ViewModelCoverageTest.ktnew file mode 100644index 0000000000..e123059f99--- /dev/null+++ b/games/chess/src/test/java/com/vayunmathur/games/chess/util/ViewModelCoverageTest.kt@@ -0,0 +1,276 @@+package com.vayunmathur.games.chess.util++import android.app.Application+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.games.chess.R+import com.vayunmathur.games.chess.data.PieceColor+import com.vayunmathur.games.chess.data.PieceType+import com.vayunmathur.games.chess.data.Position+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.ExperimentalCoroutinesApi+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.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++/** Deeper behavioural flows for Chess/Puzzle/Learn ViewModels via their public actions. */+@OptIn(ExperimentalCoroutinesApi::class)+@RunWith(RobolectricTestRunner::class)+class ViewModelCoverageTest {+    private val app get() = ApplicationProvider.getApplicationContext<Application>()+    private fun sq(file: Char, rank: Int) = Position(8 - rank, file - 'a')++    @BeforeTest fun setUp() { Dispatchers.setMain(Dispatchers.Unconfined) }+    @AfterTest fun tearDown() { Dispatchers.resetMain() }++    private fun await(desc: String, timeoutMs: Long = 15_000, cond: () -> Boolean) {+        val deadline = System.currentTimeMillis() + timeoutMs+        while (System.currentTimeMillis() < deadline) {+            if (cond()) return+            Thread.sleep(40)+        }+        assertTrue(cond(), "timed out waiting for $desc")+    }++    // -- ChessViewModel -------------------------------------------------------++    @Test fun `chess drop commits a move and same-square drop only selects`() {+        val vm = ChessViewModel(app)+        vm.onSquareDrop(sq('e', 2), sq('e', 2))+        assertEquals(sq('e', 2), vm.uiState.value.selectedPiece)+        assertEquals(PieceColor.WHITE, vm.uiState.value.turn)+        vm.onSquareDrop(sq('e', 2), sq('e', 5)) // illegal target: deselects, no move+        assertNull(vm.uiState.value.selectedPiece)+        assertEquals(PieceColor.WHITE, vm.uiState.value.turn)+        vm.onSquareDrop(sq('e', 2), sq('e', 4)) // legal drop plays the move+        assertEquals(PieceColor.BLACK, vm.uiState.value.turn)+        assertEquals(PieceType.PAWN, vm.uiState.value.board.pieces[sq('e', 4).row][sq('e', 4).col]?.type)+        assertNull(vm.uiState.value.selectedPiece)+    }++    @Test fun `chess check is reported without ending the game and the king can capture out`() {+        val vm = ChessViewModel(app)+        fun move(f1: Char, r1: Int, f2: Char, r2: Int) {+            vm.onSquareClick(sq(f1, r1)); vm.onSquareClick(sq(f2, r2))+        }+        move('e', 2, 'e', 4); move('e', 7, 'e', 5)+        move('d', 1, 'h', 5); move('b', 8, 'c', 6)+        move('h', 5, 'f', 7) // Qxf7++        val checked = vm.uiState.value+        assertNull(checked.gameResult)+        assertEquals(app.getString(R.string.check), checked.gameStatus)+        assertEquals(PieceColor.BLACK, checked.turn)+        move('e', 8, 'f', 7) // Kxf7+        assertEquals(PieceColor.WHITE, vm.uiState.value.turn)+        assertEquals(PieceType.KING, vm.uiState.value.board.pieces[sq('f', 7).row][sq('f', 7).col]?.type)+        assertTrue(vm.uiState.value.board.capturedByBlack.any { it.type == PieceType.QUEEN })+    }++    @Test fun `chess new game after mate resets the board and win scoring`() {+        val vm = ChessViewModel(app)+        fun move(f1: Char, r1: Int, f2: Char, r2: Int) {+            vm.onSquareClick(sq(f1, r1)); vm.onSquareClick(sq(f2, r2))+        }+        move('f', 2, 'f', 3); move('e', 7, 'e', 5); move('g', 2, 'g', 4); move('d', 8, 'h', 4)+        assertTrue(vm.uiState.value.gameResult is GameResult.Checkmate)+        assertTrue(vm.claimWinScoring())+        vm.onNewGame(GameMode.TwoPlayer)+        val fresh = vm.uiState.value+        assertNull(fresh.gameResult)+        assertEquals(PieceColor.WHITE, fresh.turn)+        assertEquals(32, fresh.board.pieces.flatten().count { it != null })+        assertTrue(vm.claimWinScoring(), "a new game may be scored again")+        assertTrue(GameResult.Stalemate.isGameOver)+        assertEquals(4, Difficulty.entries.size)+        assertTrue(Difficulty.entries.zipWithNext().all { (a, b) -> a.elo < b.elo },+            "difficulty ratings ascend")+    }++    // -- PuzzleViewModel ------------------------------------------------------++    @Test fun `puzzle drop plays the expected move and same-square drop selects`() {+        val vm = PuzzleViewModel(app)+        vm.loadRandom(PuzzleDifficulty.EASY)+        await("solving") { vm.uiState.value.status == PuzzleStatus.Solving }+        val st = vm.uiState.value+        val expected = st.puzzle!!.solution[st.solutionIndex]+        vm.onSquareDrop(expected.from, expected.from)+        assertEquals(expected.from, vm.uiState.value.selectedPiece)+        vm.onSquareDrop(expected.from, expected.to)+        if (vm.uiState.value.board.promotionPosition != null && expected.promotion != null) {+            vm.onPromote(expected.promotion)+        }+        assertTrue(vm.uiState.value.status != PuzzleStatus.Failed, "the solution move must not fail")+        await("advanced") {+            vm.uiState.value.solutionIndex != st.solutionIndex ||+                vm.uiState.value.status == PuzzleStatus.Solved+        }+    }++    @Test fun `puzzle selection toggles reselects and an illegal target only deselects`() {+        val vm = PuzzleViewModel(app)+        vm.onCancelPromotion() // nothing pending: no-op+        vm.loadRandom(PuzzleDifficulty.MEDIUM)+        await("solving") { vm.uiState.value.status == PuzzleStatus.Solving }+        val st = vm.uiState.value+        val own = st.board.pieces.flatMapIndexed { r, row ->+            row.mapIndexedNotNull { c, p -> if (p?.color == st.playerColor) Position(r, c) else null }+        }+        assertTrue(own.size >= 2)+        vm.onSquareClick(own[0])+        assertEquals(own[0], vm.uiState.value.selectedPiece)+        vm.onSquareClick(own[1])+        assertEquals(own[1], vm.uiState.value.selectedPiece, "tapping a second own piece reselects")+        vm.onSquareClick(own[1])+        assertNull(vm.uiState.value.selectedPiece, "tapping the selected piece deselects")+        // Illegal target: an empty square the selected piece cannot reach.+        val legalEnds = st.board.legalMoves(st.playerColor).filter { it.start == own[0] }.map { it.end }.toSet()+        val illegal = (0 until 8).flatMap { r -> (0 until 8).map { c -> Position(r, c) } }+            .first { it !in legalEnds && st.board.pieces[it.row][it.col] == null }+        vm.onSquareClick(own[0])+        vm.onSquareClick(illegal)+        assertNull(vm.uiState.value.selectedPiece)+        assertEquals(PuzzleStatus.Solving, vm.uiState.value.status, "illegal clicks never fail a puzzle")+    }++    @Test fun `puzzle failed state can replay the solution to solved`() {+        val vm = PuzzleViewModel(app)+        vm.loadRandom(PuzzleDifficulty.EASY)+        await("solving") { vm.uiState.value.status == PuzzleStatus.Solving }+        val st = vm.uiState.value+        val expected = st.puzzle!!.solution[st.solutionIndex]+        val wrong = st.board.legalMoves(st.playerColor)+            .firstOrNull { it.start != expected.from || it.end != expected.to }+        kotlin.test.assertNotNull(wrong)+        vm.onSquareClick(wrong.start); vm.onSquareClick(wrong.end)+        await("failed") { vm.uiState.value.status == PuzzleStatus.Failed }+        vm.onSquareClick(expected.from) // input is closed while Failed+        assertNull(vm.uiState.value.selectedPiece)+        vm.showSolution()+        await("replayed") { vm.uiState.value.status == PuzzleStatus.Solved }+        assertEquals(st.puzzle!!.solution.size, vm.uiState.value.solutionIndex)+    }++    // -- LearnViewModel -------------------------------------------------------++    @Test fun `learn rook level completes on the apple and advances`() {+        val vm = LearnViewModel(app)+        vm.loadStage("chessPieces", "rook")+        await("stage") { vm.uiState.value.level != null }+        vm.goToLevel(0)+        val scoreBefore = vm.uiState.value.stageScore+        vm.onSquareClick(sq('e', 2))+        assertEquals(sq('e', 2), vm.uiState.value.selectedPiece)+        vm.onSquareClick(sq('e', 7)) // Rxe7 collects the only apple+        val done = vm.uiState.value+        assertEquals(LearnStatus.Completed, done.status)+        assertEquals(3, done.starsEarned, "one move is par: three stars")+        assertEquals(1, done.nbMoves)+        assertTrue(done.stageScore > scoreBefore, "apple points plus the completion bonus")+        vm.onSquareClick(sq('e', 7)) // completed levels ignore the board+        assertEquals(LearnStatus.Completed, vm.uiState.value.status)+        vm.nextLevel()+        assertEquals(1, vm.uiState.value.levelIndex)+        assertEquals(LearnStatus.Playing, vm.uiState.value.status)+    }++    @Test fun `learn drop completes like taps and a non-check move fails the check stage`() {+        val rook = LearnViewModel(app)+        rook.loadStage("chessPieces", "rook")+        await("rook stage") { rook.uiState.value.level != null }+        rook.goToLevel(0)+        rook.onSquareDrop(sq('e', 2), sq('e', 7))+        assertEquals(LearnStatus.Completed, rook.uiState.value.status)++        val check = LearnViewModel(app)+        check.loadStage("fundamentals", "check1")+        await("check stage") { check.uiState.value.level != null }+        check.goToLevel(0)+        check.onSquareClick(sq('a', 1))+        check.onSquareClick(sq('a', 2)) // Ra2 gives no check: the one-move goal is missed+        assertEquals(LearnStatus.Failed, check.uiState.value.status)+        check.retryLevel()+        assertEquals(LearnStatus.Playing, check.uiState.value.status)+        assertEquals(0, check.uiState.value.levelIndex)+        check.onSquareClick(sq('a', 1))+        check.onSquareClick(sq('e', 1)) // Re1+ down the e-file, out of the bishop's reach+        assertEquals(LearnStatus.Completed, check.uiState.value.status)+    }++    @Test fun `learn hanging a piece is punished by the capture then fails`() {+        val vm = LearnViewModel(app)+        vm.loadStage("fundamentals", "check1")+        await("check stage") { vm.uiState.value.level != null }+        vm.goToLevel(0)+        vm.onSquareClick(sq('a', 1))+        vm.onSquareClick(sq('h', 1)) // Rh1 hangs to the c6 bishop and gives no check+        await("punished") { vm.uiState.value.status == LearnStatus.Failed }+        val bishop = vm.uiState.value.board.pieces[sq('h', 1).row][sq('h', 1).col]+        assertEquals(PieceType.BISHOP, bishop?.type)+        assertEquals(PieceColor.BLACK, bishop?.color)+    }++    @Test fun `learn en passant scenario waits for the opponent then accepts the capture`() {+        val vm = LearnViewModel(app)+        vm.loadStage("intermediate", "enpassant")+        await("enpassant stage") { vm.uiState.value.level != null }+        vm.goToLevel(0)+        // Black plays d7d5 first; only then is it the player's turn.+        await("opponent setup") {+            vm.uiState.value.board.pieces[sq('d', 5).row][sq('d', 5).col]?.color == PieceColor.BLACK+        }+        vm.onSquareClick(sq('c', 5))+        vm.onSquareClick(sq('d', 6)) // cxd6 en passant finishes the script+        assertEquals(LearnStatus.Completed, vm.uiState.value.status)+        assertNull(vm.uiState.value.board.pieces[sq('d', 5).row][sq('d', 5).col])+    }++    @Test fun `learn castling completes and level navigation guards its bounds`() {+        val vm = LearnViewModel(app)+        vm.loadStage("intermediate", "castling")+        await("castle stage") { vm.uiState.value.level != null }+        vm.goToLevel(0)+        vm.goToLevel(-1)+        assertEquals(0, vm.uiState.value.levelIndex)+        vm.onSquareClick(sq('e', 1))+        vm.onSquareClick(sq('g', 1)) // O-O+        assertEquals(LearnStatus.Completed, vm.uiState.value.status)+        assertEquals(PieceType.ROOK, vm.uiState.value.board.pieces[sq('f', 1).row][sq('f', 1).col]?.type)++        val king = LearnViewModel(app)+        king.loadStage("chessPieces", "king")+        await("king stage") { king.uiState.value.level != null }+        val last = king.uiState.value.stage!!.levels.lastIndex+        king.goToLevel(last)+        king.nextLevel()+        assertTrue(king.uiState.value.stageFinished, "next past the final level finishes the stage")+        assertNotNull(king.uiState.value.stage)+    }++    @Test fun `learn promotion choice promotes to the picked piece`() {+        val vm = LearnViewModel(app)+        vm.loadStage("chessPieces", "pawn")+        await("pawn stage") { vm.uiState.value.level != null }+        vm.goToLevel(0)+        fun move(from: Position, to: Position) {+            if (vm.uiState.value.selectedPiece != from) vm.onSquareClick(from)+            vm.onSquareClick(to)+        }+        move(sq('a', 5), sq('a', 6))+        move(sq('a', 6), sq('a', 7))+        move(sq('a', 7), sq('a', 8))+        assertNotNull(vm.uiState.value.board.promotionPosition)+        vm.onPromote(PieceType.KNIGHT)+        assertNull(vm.uiState.value.board.promotionPosition)+        assertEquals(PieceType.KNIGHT, vm.uiState.value.board.pieces[sq('a', 8).row][sq('a', 8).col]?.type)+        vm.onCancelPromotion() // nothing pending any more: no-op+        assertEquals(PieceType.KNIGHT, vm.uiState.value.board.pieces[sq('a', 8).row][sq('a', 8).col]?.type)+    }+}