Modern Apps git

← Modern-Apps.git

games/kart: add tests for race logic, gamepads, host, ViewModel and screens

Commit
bb155229e8e5e39a14f93b67edfc423d68c5153b
Author
Vayun Mathur <[email protected]>
When
2026-11-07 06:11 UTC (29 days ago)
Parents
037bd8f
Merged INSTRUCTION coverage 12.3% -> 86.0% (6108/7100).

New maintained tests: domain edges for KartRules/LapTracker/
GameInputLoop/PlaceholderRace/RumbleDecider, DataStore and pairing
store round-trips, GamepadDirect seating/key/motion/hat handling
under Robolectric, KartHost lifecycle with both pairing-store and
legacy-prefs paths, KartNative guarded calls, KartViewModel garage
load, countdown, native tick publishing and the placeholder race
running to Results and banking the next cup, all KartGameScreen
phases under createComposeRule, KartSurfaceView callbacks,
MainActivity event routing, and Route serialization.

Testability: KartNative.isAvailable is now a var with an internal
setter so host tests can force the placeholder race on machines
where the Rust engine loads; production behaviour is unchanged.

Untestable remainder: ControllerHost handshake-only device-key
load/save paths in KartHost (need a paired phone session), the
native race finishing branch (engine needs a real Surface), and
the InputDeviceListener callbacks (Robolectric shadow does not
deliver them). ./check is blocked in this environment (detekt jar
absent from the mirror, cargo-clippy not installed); the full
testDevUnitTest suite passes via createMergedCoverageReport.

(cherry picked from commit cb216ee2fe95e3f5af32dbe40ead9bc27a1c3942)

Diff

games/kart/src/main/java/com/vayunmathur/games/kart/platform/KartNative.kt
diff --git a/games/kart/src/main/java/com/vayunmathur/games/kart/platform/KartNative.kt b/games/kart/src/main/java/com/vayunmathur/games/kart/platform/KartNative.ktindex bb8d5173f2..a1f123d6c3 100644--- a/games/kart/src/main/java/com/vayunmathur/games/kart/platform/KartNative.kt+++ b/games/kart/src/main/java/com/vayunmathur/games/kart/platform/KartNative.kt@@ -22,7 +22,7 @@ import com.vayunmathur.library.log.Log @Suppress("TooManyFunctions") object KartNative {     /** False until `libkart_engine` ships. The game checks this once per surface, like voxels. */-    val isAvailable: Boolean = try {+    var isAvailable: Boolean = try {         System.loadLibrary("kart_engine")         nativeInit()         Log.status("KartNative", "libkart_engine loaded")@@ -31,6 +31,8 @@ object KartNative {         Log.status("KartNative", "libkart_engine absent - running the placeholder race")         false     }+        // Internal so host tests can force the placeholder race on machines with the engine.+        internal set      /**      * Start (or restart) the native race. `playerIds` is the grid in seat order;
games/kart/src/test/java/com/vayunmathur/games/kart/MainActivityTest.kt
diff --git a/games/kart/src/test/java/com/vayunmathur/games/kart/MainActivityTest.kt b/games/kart/src/test/java/com/vayunmathur/games/kart/MainActivityTest.ktnew file mode 100644index 0000000000..ce11d748ad--- /dev/null+++ b/games/kart/src/test/java/com/vayunmathur/games/kart/MainActivityTest.kt@@ -0,0 +1,33 @@+package com.vayunmathur.games.kart++import android.view.KeyEvent+import android.view.MotionEvent+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.RobolectricTestRunner+import kotlin.test.Test+import kotlin.test.assertFalse+import kotlin.test.assertNotNull++@RunWith(RobolectricTestRunner::class)+class MainActivityTest {++    @Test fun activityLaunchesAndRoutesEventsAndDestroys() {+        val controller = Robolectric.buildActivity(MainActivity::class.java).setup()+        val activity = controller.get()+        assertNotNull(activity)++        // Unmapped keys / non-joystick motion fall through to the framework (false here:+        // no seated gamepad owns them under Robolectric).+        val key = KeyEvent(0L, 0L, KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_VOLUME_UP, 0, 0, 999, 0)+        assertFalse(activity.onKeyDown(KeyEvent.KEYCODE_VOLUME_UP, key))+        assertFalse(activity.onKeyUp(KeyEvent.KEYCODE_VOLUME_UP, key))+        val coords = arrayOf(MotionEvent.PointerCoords())+        val props = arrayOf(MotionEvent.PointerProperties().apply { id = 0 })+        val motion = MotionEvent.obtain(0L, 0L, MotionEvent.ACTION_MOVE, 1, props, coords, 0, 0, 1f, 1f, 999, 0, 0, 0, 0, 0)!!+        assertFalse(activity.onGenericMotionEvent(motion))+        motion.recycle()++        controller.pause().stop().destroy()+    }+}
games/kart/src/test/java/com/vayunmathur/games/kart/RouteTest.kt
diff --git a/games/kart/src/test/java/com/vayunmathur/games/kart/RouteTest.kt b/games/kart/src/test/java/com/vayunmathur/games/kart/RouteTest.ktnew file mode 100644index 0000000000..04b5b54253--- /dev/null+++ b/games/kart/src/test/java/com/vayunmathur/games/kart/RouteTest.kt@@ -0,0 +1,15 @@+package com.vayunmathur.games.kart++import kotlinx.serialization.json.Json+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertSame++class RouteTest {++    @Test fun gameRouteIsSingletonAndSerializes() {+        assertSame(Route.Game, Route.Game)+        val json = Json.encodeToString(Route.serializer(), Route.Game)+        assertEquals(Route.Game, Json.decodeFromString(Route.serializer(), json))+    }+}
games/kart/src/test/java/com/vayunmathur/games/kart/data/KartStoresTest.kt
diff --git a/games/kart/src/test/java/com/vayunmathur/games/kart/data/KartStoresTest.kt b/games/kart/src/test/java/com/vayunmathur/games/kart/data/KartStoresTest.ktnew file mode 100644index 0000000000..62910baef2--- /dev/null+++ b/games/kart/src/test/java/com/vayunmathur/games/kart/data/KartStoresTest.kt@@ -0,0 +1,69 @@+package com.vayunmathur.games.kart.data++import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.games.kart.platform.AppBackupAgent+import com.vayunmathur.games.kart.platform.KartPairingStore+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.Test+import kotlin.test.assertContentEquals+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)+class KartStoresTest {++    private val ctx get() = ApplicationProvider.getApplicationContext<android.content.Context>()++    @Test fun dataStoreDefaultsThenSaveCupRoundTrips() = runBlocking {+        val store = KartDataStore(ctx)+        assertEquals(0, store.currentCup.first())+        assertEquals(0, store.racesWon.first())+        assertEquals(0L, store.bestLapMs.first())+        store.saveCup(2)+        assertEquals(2, store.currentCup.first())+        // Saving the cup leaves lifetime counters untouched.+        assertEquals(0, store.racesWon.first())+        assertEquals(0L, store.bestLapMs.first())+        store.saveCup(0)+        assertEquals(0, store.currentCup.first())+    }++    @Test fun pairingStoreBytesKeysAndDeviceId() = runBlocking {+        val store = KartPairingStore(ctx)+        assertNull(store.getBytes("kem"))+        store.setBytes("kem", byteArrayOf(1, 2, 3))+        assertContentEquals(byteArrayOf(1, 2, 3), store.getBytes("kem"))+        // onlyIfAbsent must not overwrite an existing identity.+        store.setBytes("kem", byteArrayOf(9), onlyIfAbsent = true)+        assertContentEquals(byteArrayOf(1, 2, 3), store.getBytes("kem"))+        store.setBytes("kem", byteArrayOf(9), onlyIfAbsent = false)+        assertContentEquals(byteArrayOf(9), store.getBytes("kem"))++        assertNull(store.deviceKey("phone-1"))+        store.remember("phone-1", byteArrayOf(7, 8))+        assertContentEquals(byteArrayOf(7, 8), store.deviceKey("phone-1"))+        assertNull(store.deviceKey("phone-2"))++        val id1 = store.deviceId()+        val id2 = store.deviceId()+        assertTrue(id1.isNotBlank())+        assertEquals(id1, id2)+    }++    @Test fun modelsAndBackupAgent() {+        assertEquals(3, CUPS.size)+        assertEquals(listOf("Mushroom Cup", "Flower Cup", "Star Cup"), CUPS.map { it.name })+        assertTrue(CUPS.all { it.trackCount == 4 })+        assertEquals(listOf(0, 1, 2), CUPS.map { it.id })+        val progress = KartProgress()+        assertEquals(0, progress.currentCup)+        assertEquals(0, progress.racesWon)+        assertEquals(0L, progress.bestLapMs)+        assertEquals(KartProgress(1, 2, 3L), KartProgress(currentCup = 1, racesWon = 2, bestLapMs = 3L))+        assertEquals(listOf("settings"), AppBackupAgent().datastoreNames)+    }+}
games/kart/src/test/java/com/vayunmathur/games/kart/domain/KartLogicExtraTest.kt
diff --git a/games/kart/src/test/java/com/vayunmathur/games/kart/domain/KartLogicExtraTest.kt b/games/kart/src/test/java/com/vayunmathur/games/kart/domain/KartLogicExtraTest.ktnew file mode 100644index 0000000000..3bc28bcce2--- /dev/null+++ b/games/kart/src/test/java/com/vayunmathur/games/kart/domain/KartLogicExtraTest.kt@@ -0,0 +1,194 @@+package com.vayunmathur.games.kart.domain++import com.vayunmathur.games.kart.data.CUPS+import com.vayunmathur.sdk.controller.ControllerButton+import com.vayunmathur.sdk.controller.ControllerInput+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue++class KartLogicExtraTest {++    private fun input(+        buttons: Long = 0L,+        axes: List<Float> = List(6) { 0f },+    ) = ControllerInput(playerId = "p1", seq = 1, buttons = buttons, axes = axes)++    // --- KartRules ---++    @Test fun cupAtWrapsPastEndAndNegative() {+        assertEquals(CUPS[0], KartRules.cupAt(0))+        assertEquals(CUPS[1], KartRules.cupAt(1))+        assertEquals(CUPS[0], KartRules.cupAt(CUPS.size))+        assertEquals(CUPS[CUPS.size - 1], KartRules.cupAt(-1))+    }++    @Test fun isUnlockedBoundary() {+        assertTrue(KartRules.isUnlocked(0, 0))+        assertTrue(KartRules.isUnlocked(2, 2))+        assertFalse(KartRules.isUnlocked(1, 0))+        assertFalse(KartRules.isUnlocked(3, 2))+    }++    @Test fun nextCupEndsAtLast() {+        assertEquals(1, KartRules.nextCup(0))+        assertEquals(CUPS.size - 1, KartRules.nextCup(CUPS.size - 2))+        assertNull(KartRules.nextCup(CUPS.size - 1))+        assertNull(KartRules.nextCup(CUPS.size + 5))+    }++    // --- LapTracker ---++    @Test fun lapTickWithoutSeedRecordsNoDurationButAdvances() {+        val state = LapTracker.onLapTick(prevLap = 0, lap = 1, nowMs = 5_000L, state = LapTracker.State())+        assertNull(state.times.lastLapMs)+        assertNull(state.times.bestLapMs)+        assertEquals(5_000L, state.lastIncrementMs)+    }++    @Test fun lapTickClampsNegativeDurationAndKeepsBest() {+        var state = LapTracker.State(lastIncrementMs = 10_000L, times = LapTimes(lastLapMs = 100L, bestLapMs = 50L))+        state = LapTracker.onLapTick(prevLap = 1, lap = 2, nowMs = 9_000L, state = state)+        assertEquals(0L, state.times.lastLapMs)+        assertEquals(0L, state.times.bestLapMs) // 0 beats previous best via coerceAtMost? best = min(50,0)=0+    }++    @Test fun lapTickSlowerLapDoesNotReplaceBest() {+        var state = LapTracker.State(lastIncrementMs = 0L)+        state = LapTracker.onLapTick(0, 1, 20_000L, state)+        state = LapTracker.onLapTick(1, 2, 50_000L, state)+        assertEquals(30_000L, state.times.lastLapMs)+        assertEquals(20_000L, state.times.bestLapMs)+    }++    @Test fun lapDecreaseKeepsState() {+        val state = LapTracker.State(lastIncrementMs = 1_000L, times = LapTimes(5L, 5L))+        assertEquals(state, LapTracker.onLapTick(prevLap = 3, lap = 1, nowMs = 9_000L, state = state))+    }++    // --- GameInputLoop ---++    @Test fun curveDeadzoneEdgeAndMid() {+        assertEquals(0f, GameInputLoop.curve(0.149f))+        assertEquals(0f, GameInputLoop.curve(GameInputLoop.DEADZONE)) // t=0 at edge+        val mid = GameInputLoop.curve(0.5f)+        assertTrue(mid > 0f && mid < 0.5f, "mid=$mid")+        assertEquals(-mid, GameInputLoop.curve(-0.5f))+        assertEquals(1f, GameInputLoop.curve(2f)) // coerced rescale caps at full throw shaped value? t coerced 1 -> 1+    }++    @Test fun triggerAxesBeatStickAndBrakeAxisWorks() {+        // axes: LX, LY, RX, RY, throttle(trigger), brake(trigger)+        val c = GameInputLoop.normalize(input(axes = listOf(0f, 0f, 0f, 0f, 1f, 0.5f)))+        assertEquals(1f, c.throttle)+        assertTrue(c.brake > 0f)+    }++    @Test fun shortAxesListDefaultsToNeutral() {+        val c = GameInputLoop.normalize(input(axes = emptyList()))+        assertEquals(KartControl.NEUTRAL, c)+    }++    @Test fun leftShoulderAlsoDriftsAndBIsNotItem() {+        val drift = GameInputLoop.normalize(input(buttons = ControllerButton.LEFT_SHOULDER.bit))+        assertTrue(drift.drift)+        assertFalse(drift.itemUse)+        val b = GameInputLoop.normalize(input(buttons = ControllerButton.B.bit))+        assertFalse(b.itemUse)+        assertFalse(b.drift)+    }++    @Test fun dpadRightSteersAndStickOverridesDpad() {+        val dpad = GameInputLoop.normalize(input(buttons = ControllerButton.DPAD_RIGHT.bit))+        assertEquals(0.6f, dpad.steering)+        val stick = GameInputLoop.normalize(+            input(buttons = ControllerButton.DPAD_RIGHT.bit, axes = listOf(1f, 0f, 0f, 0f, 0f, 0f)),+        )+        assertEquals(1f, stick.steering)+    }++    @Test fun outputsAreCoerced() {+        val c = GameInputLoop.normalize(input(axes = listOf(5f, -5f, 0f, 0f, 5f, 0f)))+        assertTrue(c.steering in -1f..1f)+        assertTrue(c.throttle in 0f..1f)+        assertTrue(c.brake in 0f..1f)+    }++    // --- PlaceholderRace edges ---++    @Test fun unknownPlayerQueriesAreZeroAndWinnerNullBeforeFinish() {+        val race = PlaceholderRace(playerIds = listOf("p1"), aiCount = 0)+        assertEquals(0, race.lapOf("nobody"))+        assertEquals(0f, race.lapProgress("nobody"))+        assertNull(race.winner())+        assertFalse(race.finished)+        assertFalse(race.useItem("nobody"))+    }++    @Test fun brakeCanStopButNeverReverses() {+        val race = PlaceholderRace(playerIds = listOf("p1"), aiCount = 0)+        race.setControl("p1", KartControl(throttle = 0f, brake = 1f))+        race.tick(1f)+        assertEquals(0f, race.lapProgress("p1"))+    }++    @Test fun negativeAndHugeDtAreClamped() {+        val race = PlaceholderRace(playerIds = listOf("p1"), aiCount = 0)+        race.setControl("p1", KartControl(throttle = 1f))+        race.tick(-5f)+        assertEquals(0f, race.lapProgress("p1"))+        race.tick(100f) // clamped to 1s+        assertEquals(PlaceholderRace.TOP_SPEED / PlaceholderRace.TRACK_LENGTH, race.lapProgress("p1"), 0.0001f)+    }++    @Test fun leaderboardIncludesAiAndCupIndexWraps() {+        val race = PlaceholderRace(playerIds = listOf("p1"), aiCount = 2)+        val board = race.leaderboard()+        assertEquals(3, board.size)+        assertTrue("ai-0" in board && "ai-1" in board)+        assertEquals(0, race.cupIndex(0))+        assertEquals(0, race.cupIndex(CUPS.size))+        assertEquals(CUPS.size - 1, race.cupIndex(-1))+    }++    @Test fun finishedKartStopsAdvancingWhileOthersContinue() {+        val race = PlaceholderRace(playerIds = listOf("fast", "slow"), aiCount = 0, laps = 1)+        race.setControl("fast", KartControl(throttle = 1f))+        race.setControl("slow", KartControl(throttle = 0.1f))+        repeat(30) { race.tick(1f) }+        assertTrue(race.finished)+        val fastProgress = race.lapProgress("fast")+        repeat(5) { race.tick(1f) }+        // lapProgress wraps, so compare lap counts instead: fast stays at >=1 lap+        assertTrue(race.lapOf("fast") >= 1)+        assertEquals(fastProgress, race.lapProgress("fast"))+    }++    // --- RumbleDecider edges ---++    @Test fun customCooldownRespected() {+        val buzz = RumbleDecider.decide(+            prevOrder = listOf("a-remote", "you"),+            newOrder = listOf("you", "a-remote"),+            localPlayerIds = setOf("you"),+            lastBuzzMs = mapOf("a-remote" to 1_000L),+            nowMs = 1_500L,+            cooldownMs = 100L,+        )+        assertEquals(listOf("a-remote"), buzz)+    }++    @Test fun multipleLosersBuzzInNewOrder() {+        val buzz = RumbleDecider.decide(+            prevOrder = listOf("r1", "r2", "you"),+            newOrder = listOf("you", "r2", "r1"),+            localPlayerIds = setOf("you"),+            lastBuzzMs = emptyMap(),+            nowMs = 0L,+        )+        // r2: place 1->1? prev index1, new index1 => no. r1: 0->2 yes+        assertEquals(listOf("r1"), buzz)+    }+}
games/kart/src/test/java/com/vayunmathur/games/kart/platform/GamepadDirectTest.kt
diff --git a/games/kart/src/test/java/com/vayunmathur/games/kart/platform/GamepadDirectTest.kt b/games/kart/src/test/java/com/vayunmathur/games/kart/platform/GamepadDirectTest.ktnew file mode 100644index 0000000000..613367e786--- /dev/null+++ b/games/kart/src/test/java/com/vayunmathur/games/kart/platform/GamepadDirectTest.kt@@ -0,0 +1,191 @@+package com.vayunmathur.games.kart.platform++import android.content.Context+import android.hardware.input.InputManager+import android.view.InputDevice+import android.view.KeyEvent+import android.view.MotionEvent+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.games.kart.platform.GamepadDirect.Companion.axisSlotFor+import com.vayunmathur.games.kart.platform.GamepadDirect.Companion.isGamepad+import com.vayunmathur.games.kart.platform.GamepadDirect.Companion.keyCodeToBit+import com.vayunmathur.games.kart.platform.GamepadDirect.Companion.zeroWithin+import com.vayunmathur.sdk.controller.AXIS_BRAKE+import com.vayunmathur.sdk.controller.AXIS_LEFT_X+import com.vayunmathur.sdk.controller.AXIS_LEFT_Y+import com.vayunmathur.sdk.controller.AXIS_RIGHT_X+import com.vayunmathur.sdk.controller.AXIS_RIGHT_Y+import com.vayunmathur.sdk.controller.AXIS_THROTTLE+import com.vayunmathur.sdk.controller.ControllerButton+import com.vayunmathur.sdk.controller.ControllerInput+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows+import org.robolectric.shadows.InputDeviceBuilder+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)+class GamepadDirectTest {++    private val ctx get() = ApplicationProvider.getApplicationContext<Context>()+    private val inputManager get() = ctx.getSystemService(InputManager::class.java)++    private fun gamepad(id: Int, name: String = "Pad $id"): InputDevice =+        InputDeviceBuilder.newBuilder()+            .setId(id)+            .setName(name)+            .setSources(InputDevice.SOURCE_GAMEPAD or InputDevice.SOURCE_JOYSTICK)+            .addMotionRange(MotionEvent.AXIS_X, InputDevice.SOURCE_JOYSTICK, -1f, 1f, 0.1f, 0f, 1f)+            .addMotionRange(MotionEvent.AXIS_Y, InputDevice.SOURCE_JOYSTICK, -1f, 1f, 0.1f, 0f, 1f)+            .addMotionRange(MotionEvent.AXIS_Z, InputDevice.SOURCE_JOYSTICK, -1f, 1f, 0.1f, 0f, 1f)+            .addMotionRange(MotionEvent.AXIS_RZ, InputDevice.SOURCE_JOYSTICK, -1f, 1f, 0.1f, 0f, 1f)+            .addMotionRange(MotionEvent.AXIS_RTRIGGER, InputDevice.SOURCE_JOYSTICK, 0f, 1f, 0f, 0f, 1f)+            .addMotionRange(MotionEvent.AXIS_LTRIGGER, InputDevice.SOURCE_JOYSTICK, 0f, 1f, 0f, 0f, 1f)+            .build()++    private fun key(action: Int, code: Int, deviceId: Int, repeat: Int = 0) =+        KeyEvent(0L, 0L, action, code, repeat, 0, deviceId, 0)++    @Test fun companionMappings() {+        assertEquals(ControllerButton.A.bit, keyCodeToBit(KeyEvent.KEYCODE_BUTTON_A))+        assertEquals(ControllerButton.B.bit, keyCodeToBit(KeyEvent.KEYCODE_BUTTON_B))+        assertEquals(ControllerButton.X.bit, keyCodeToBit(KeyEvent.KEYCODE_BUTTON_X))+        assertEquals(ControllerButton.Y.bit, keyCodeToBit(KeyEvent.KEYCODE_BUTTON_Y))+        assertEquals(ControllerButton.LEFT_SHOULDER.bit, keyCodeToBit(KeyEvent.KEYCODE_BUTTON_L1))+        assertEquals(ControllerButton.RIGHT_SHOULDER.bit, keyCodeToBit(KeyEvent.KEYCODE_BUTTON_R1))+        assertEquals(ControllerButton.LEFT_TRIGGER.bit, keyCodeToBit(KeyEvent.KEYCODE_BUTTON_L2))+        assertEquals(ControllerButton.RIGHT_TRIGGER.bit, keyCodeToBit(KeyEvent.KEYCODE_BUTTON_R2))+        assertEquals(ControllerButton.START.bit, keyCodeToBit(KeyEvent.KEYCODE_BUTTON_START))+        assertEquals(ControllerButton.SELECT.bit, keyCodeToBit(KeyEvent.KEYCODE_BUTTON_SELECT))+        assertEquals(ControllerButton.LEFT_STICK.bit, keyCodeToBit(KeyEvent.KEYCODE_BUTTON_THUMBL))+        assertEquals(ControllerButton.RIGHT_STICK.bit, keyCodeToBit(KeyEvent.KEYCODE_BUTTON_THUMBR))+        assertEquals(ControllerButton.DPAD_UP.bit, keyCodeToBit(KeyEvent.KEYCODE_DPAD_UP))+        assertEquals(ControllerButton.DPAD_DOWN.bit, keyCodeToBit(KeyEvent.KEYCODE_DPAD_DOWN))+        assertEquals(ControllerButton.DPAD_LEFT.bit, keyCodeToBit(KeyEvent.KEYCODE_DPAD_LEFT))+        assertEquals(ControllerButton.DPAD_RIGHT.bit, keyCodeToBit(KeyEvent.KEYCODE_DPAD_RIGHT))+        assertNull(keyCodeToBit(KeyEvent.KEYCODE_VOLUME_UP))+        assertNull(keyCodeToBit(KeyEvent.KEYCODE_A))++        assertEquals(AXIS_LEFT_X, axisSlotFor(MotionEvent.AXIS_X))+        assertEquals(AXIS_LEFT_Y, axisSlotFor(MotionEvent.AXIS_Y))+        assertEquals(AXIS_RIGHT_X, axisSlotFor(MotionEvent.AXIS_Z))+        assertEquals(AXIS_RIGHT_Y, axisSlotFor(MotionEvent.AXIS_RZ))+        assertEquals(AXIS_THROTTLE, axisSlotFor(MotionEvent.AXIS_RTRIGGER))+        assertEquals(AXIS_BRAKE, axisSlotFor(MotionEvent.AXIS_LTRIGGER))+        assertNull(axisSlotFor(MotionEvent.AXIS_HAT_X))++        assertTrue(isGamepad(gamepad(41)))+        val keyboard = InputDeviceBuilder.newBuilder().setId(42).setName("kbd")+            .setSources(InputDevice.SOURCE_KEYBOARD).build()+        assertFalse(isGamepad(keyboard))++        assertEquals(0f, 0.05f.zeroWithin(0.1f))+        assertEquals(0f, (-0.1f).zeroWithin(0.1f))+        assertEquals(0.5f, 0.5f.zeroWithin(0.1f))+        assertEquals(-0.5f, (-0.5f).zeroWithin(0.1f))+    }++    @Test fun seatedPadKeysMotionAndRemoval() {+        val seats = mutableListOf<Triple<String, String, Boolean>>()+        val inputs = mutableListOf<ControllerInput>()+        Shadows.shadowOf(inputManager).addInputDevice(gamepad(7, "Pro Pad"))+        val direct = GamepadDirect(ctx, { id, name, present -> seats += Triple(id, name, present) }, { inputs += it })+        try {+            assertEquals(listOf(Triple("pad-7", "Pro Pad", true)), seats)+            assertEquals(setOf("pad-7"), direct.playerIds)++            // Unknown key falls through; known key seats/emits.+            assertFalse(direct.onKeyEvent(key(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_VOLUME_UP, 7)))+            assertTrue(direct.onKeyEvent(key(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BUTTON_A, 7)))+            assertEquals(1, inputs.size)+            assertEquals("pad-7", inputs.last().playerId)+            assertEquals(1L, inputs.last().seq)+            assertTrue(inputs.last().isPressed(ControllerButton.A))++            // Repeat is consumed but does not re-emit.+            assertTrue(direct.onKeyEvent(key(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BUTTON_A, 7, repeat = 1)))+            assertEquals(1, inputs.size)++            assertTrue(direct.onKeyEvent(key(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_LEFT, 7)))+            assertTrue(inputs.last().isPressed(ControllerButton.A))+            assertTrue(inputs.last().isPressed(ControllerButton.DPAD_LEFT))+            assertEquals(-1, inputs.last().hatX)+            assertTrue(direct.onKeyEvent(key(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_BUTTON_A, 7)))+            assertFalse(inputs.last().isPressed(ControllerButton.A))+            // Unmapped action type is rejected after seating check path.+            assertFalse(direct.onKeyEvent(key(99, KeyEvent.KEYCODE_BUTTON_B, 7)))++            // Motion: non-joystick source rejected, joystick sample emits axes with flat deadzone.+            val pointerProps = arrayOf(MotionEvent.PointerProperties().apply { id = 0; toolType = MotionEvent.TOOL_TYPE_FINGER })+            val coords = arrayOf(MotionEvent.PointerCoords().apply {+                setAxisValue(MotionEvent.AXIS_X, 0.05f) // inside flat -> 0+                setAxisValue(MotionEvent.AXIS_Y, -0.8f)+                setAxisValue(MotionEvent.AXIS_RTRIGGER, 0.7f)+            })+            val touch = MotionEvent.obtain(0L, 0L, MotionEvent.ACTION_MOVE, 1, pointerProps, coords, 0, 0, 1f, 1f, 7, 0, InputDevice.SOURCE_TOUCHSCREEN, 0, 0, 0)!!+            assertFalse(direct.onGenericMotionEvent(touch))+            touch.recycle()+            val stick = MotionEvent.obtain(0L, 0L, MotionEvent.ACTION_MOVE, 1, pointerProps, coords, 0, 0, 1f, 1f, 7, 0, InputDevice.SOURCE_JOYSTICK, 0, 0, 0)!!+            assertTrue(direct.onGenericMotionEvent(stick))+            stick.recycle()+            val motion = inputs.last()+            assertEquals(0f, motion.axes[AXIS_LEFT_X])+            assertEquals(-0.8f, motion.axes[AXIS_LEFT_Y])+            assertEquals(0.7f, motion.axes[AXIS_THROTTLE])+            assertEquals(-1, motion.hatY)+            assertTrue(motion.seq > inputs[inputs.size - 2].seq)+        } finally {+            direct.close()+        }+        assertTrue(seats.contains(Triple("pad-7", "", false)))+        assertEquals(emptySet(), direct.playerIds)+    }++    @Test fun unseatedAndKeyboardDevicesFallThrough() {+        val seats = mutableListOf<Triple<String, String, Boolean>>()+        val inputs = mutableListOf<ControllerInput>()+        val direct = GamepadDirect(ctx, { id, name, present -> seats += Triple(id, name, present) }, { inputs += it })+        try {+            // No device registered at all.+            assertFalse(direct.onKeyEvent(key(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BUTTON_A, 999)))+            // A keyboard device never takes a seat.+            Shadows.shadowOf(inputManager).addInputDevice(+                InputDeviceBuilder.newBuilder().setId(55).setName("kbd")+                    .setSources(InputDevice.SOURCE_KEYBOARD).build(),+            )+            assertFalse(direct.onKeyEvent(key(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BUTTON_A, 55)))+            val coords = arrayOf(MotionEvent.PointerCoords())+            val props = arrayOf(MotionEvent.PointerProperties().apply { id = 0 })+            val ev = MotionEvent.obtain(0L, 0L, MotionEvent.ACTION_MOVE, 1, props, coords, 0, 0, 1f, 1f, 55, 0, InputDevice.SOURCE_JOYSTICK, 0, 0, 0)!!+            assertFalse(direct.onGenericMotionEvent(ev))+            ev.recycle()+            assertTrue(seats.isEmpty())+            assertTrue(inputs.isEmpty())+            assertEquals(emptySet(), direct.playerIds)+        } finally {+            direct.close()+        }+    }++    @Test fun lateSeatingViaFirstKeyAndMotionFromUnknownPad() {+        val seats = mutableListOf<Triple<String, String, Boolean>>()+        val inputs = mutableListOf<ControllerInput>()+        val direct = GamepadDirect(ctx, { id, name, present -> seats += Triple(id, name, present) }, { inputs += it })+        try {+            // Device known to the system but GamepadDirect was built before it appeared;+            // the first key press seats it instead of dropping the input.+            Shadows.shadowOf(inputManager).addInputDevice(gamepad(9, "Late Pad"))+            // addInputDevice may notify the listener (seating it); either path must end seated.+            assertTrue(direct.onKeyEvent(key(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BUTTON_R1, 9)))+            assertTrue(direct.playerIds.contains("pad-9"))+            assertTrue(inputs.last().isPressed(ControllerButton.RIGHT_SHOULDER))+        } finally {+            direct.close()+        }+        assertTrue(seats.any { it.first == "pad-9" && !it.third })+    }+}
games/kart/src/test/java/com/vayunmathur/games/kart/platform/KartHostAndNativeTest.kt
diff --git a/games/kart/src/test/java/com/vayunmathur/games/kart/platform/KartHostAndNativeTest.kt b/games/kart/src/test/java/com/vayunmathur/games/kart/platform/KartHostAndNativeTest.ktnew file mode 100644index 0000000000..e5d3655da0--- /dev/null+++ b/games/kart/src/test/java/com/vayunmathur/games/kart/platform/KartHostAndNativeTest.kt@@ -0,0 +1,64 @@+package com.vayunmathur.games.kart.platform++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.games.kart.util.KartNative+import kotlinx.coroutines.runBlocking+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 KartHostAndNativeTest {++    private val ctx get() = ApplicationProvider.getApplicationContext<Context>()++    @Test fun hostLifecycleWithPairingStore() = runBlocking {+        val pairing = KartPairingStore(ctx)+        val host = KartHost(ctx, publicBundle = { null }, unsealSecret = { null }, pairingStore = pairing)+        assertEquals("kart", host.lobby.value.gameId)+        assertTrue(host.lobby.value.slots.isEmpty())+        assertTrue(host.inputs.value.isEmpty())+        assertNull(host.host)+        assertNull(host.pairingCode)+        host.start()+        // Idempotent: a second start is a no-op, not a second lobby.+        host.start()+        assertNotNull(host.host)+        assertEquals("kart", host.lobby.value.gameId)+        host.stop()+    }++    @Test fun hostLifecycleWithLegacyPrefsFallback() = runBlocking {+        val host = KartHost(ctx, publicBundle = { byteArrayOf(1) }, unsealSecret = { byteArrayOf(2) })+        host.start()+        assertNotNull(host.host)+        // Give the IO accept loop a moment to bind and advertise before teardown.+        Thread.sleep(300)+        assertEquals("kart", host.lobby.value.gameId)+        host.stop()+        // A fresh host over the same prefs reuses the minted legacy host id path without error.+        val host2 = KartHost(ctx, publicBundle = { null }, unsealSecret = { null })+        host2.start()+        assertNotNull(host2.host)+        host2.stop()+    }++    @Test fun nativeBridgeCallsAreSafe() {+        // On host JVM tests the Rust engine may be present; on Robolectric it may not.+        // Either way every guarded call must return normally and standings must be JSON-shaped.+        KartNative.startRace(listOf("p1", "p2"))+        KartNative.onDriveInput(0, 1f, 0.5f, 0f)+        KartNative.setDrift(0, true)+        KartNative.useItem(0)+        KartNative.surfaceChanged(320, 240)+        val standings = KartNative.getStandingsJson()+        assertTrue(standings.startsWith("[") && standings.endsWith("]"), standings)+        KartNative.surfaceDestroyed()+        KartNative.onDestroy()+    }+}
games/kart/src/test/java/com/vayunmathur/games/kart/platform/KartViewModelTest.kt
diff --git a/games/kart/src/test/java/com/vayunmathur/games/kart/platform/KartViewModelTest.kt b/games/kart/src/test/java/com/vayunmathur/games/kart/platform/KartViewModelTest.ktnew file mode 100644index 0000000000..b41c40f86c--- /dev/null+++ b/games/kart/src/test/java/com/vayunmathur/games/kart/platform/KartViewModelTest.kt@@ -0,0 +1,138 @@+package com.vayunmathur.games.kart.platform++import android.app.Application+import android.os.Looper+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.games.kart.util.KartNative+import com.vayunmathur.sdk.controller.ControllerButton+import com.vayunmathur.sdk.controller.ControllerInput+import java.util.concurrent.TimeUnit+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows.shadowOf+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)+class KartViewModelTest {++    private val app get() = ApplicationProvider.getApplicationContext<Application>()++    private fun pump(ms: Long) {+        if (ms > 0) shadowOf(Looper.getMainLooper()).idleFor(ms, TimeUnit.MILLISECONDS)+        else shadowOf(Looper.getMainLooper()).idle()+    }++    private fun await(desc: String, timeoutMs: Long = 15_000, cond: () -> Boolean) {+        val deadline = System.currentTimeMillis() + timeoutMs+        while (System.currentTimeMillis() < deadline) {+            pump(0)+            if (cond()) return+            Thread.sleep(10)+        }+        pump(0)+        assertTrue(cond(), "timed out waiting for: $desc")+    }++    @Test fun garageLoadsThenRaceRunsToResultsAndBack() {+        val vm = KartViewModel(app)+        await("cup loads") { vm.uiState.value.cup != null }+        assertEquals("Mushroom Cup", vm.uiState.value.cup?.name)+        assertEquals(0, vm.uiState.value.progress.currentCup)+        assertTrue(vm.racePhase.value is RacePhase.Lobby)++        // Inputs outside a race are dropped quietly; gamepad seats still register.+        vm.onLocalStick("nobody", 1f, -1f)+        vm.onGamepadInput(ControllerInput(playerId = "pad-1", seq = 1, buttons = ControllerButton.A.bit))+        vm.onGamepadSeat("pad-x", "", true)+        vm.onGamepadSeat("pad-x", "Pad", false)++        vm.startRace()+        await("countdown starts") { vm.racePhase.value is RacePhase.Countdown }+        // Starting again mid-countdown is a no-op.+        vm.startRace()+        assertTrue(vm.racePhase.value is RacePhase.Countdown)+        assertNotNull(vm.localPlayerId)++        pump(4_000)+        await("race starts") { vm.racePhase.value is RacePhase.Racing || vm.racePhase.value is RacePhase.Results }++        // Feed the local seat through the public stick path while racing (if still racing).+        if (vm.racePhase.value is RacePhase.Racing) {+            vm.onLocalStick(requireNotNull(vm.localPlayerId), 0f, -1f)+            vm.onGamepadInput(+                ControllerInput(+                    playerId = requireNotNull(vm.localPlayerId),+                    seq = 2,+                    buttons = ControllerButton.A.bit,+                    axes = listOf(0f, -1f, 0f, 0f, 0f, 0f),+                ),+            )+        }++        if (KartNative.isAvailable) {+            // The native engine owns the sim; the tick loop must at least publish a Racing+            // phase parsed from its standings JSON.+            pump(500)+            assertTrue(+                vm.racePhase.value is RacePhase.Racing || vm.racePhase.value is RacePhase.Results,+                "phase=${vm.racePhase.value}",+            )+        } else {+            // Placeholder: the AI field finishes a 3-lap race on virtual time even with+            // no human input, which banks the next cup and lands on Results.+            pump(240_000)+            await("results", 20_000) { vm.racePhase.value is RacePhase.Results }+            val results = vm.racePhase.value as RacePhase.Results+            assertTrue(results.winner in results.order)+            assertTrue(results.order.isNotEmpty())+            await("next cup banked") { vm.uiState.value.progress.currentCup == 1 }+            assertEquals("Flower Cup", vm.uiState.value.cup?.name)+            vm.backToLobby()+            assertTrue(vm.racePhase.value is RacePhase.Lobby)+        }+    }++    @Test fun placeholderRaceRunsToResultsAndBanksCup() {+        val wasAvailable = KartNative.isAvailable+        KartNative.isAvailable = false+        try {+            val vm = KartViewModel(app)+            await("cup loads") { vm.uiState.value.cup != null }+            val cupBefore = vm.uiState.value.progress.currentCup+            vm.startRace()+            pump(4_000)+            await("placeholder racing") { vm.racePhase.value is RacePhase.Racing }+            val racing = vm.racePhase.value as RacePhase.Racing+            assertEquals(3, racing.totalLaps)+            assertTrue(racing.order.isNotEmpty())+            // Drive the local seat flat-out through the public stick path.+            vm.onLocalStick(requireNotNull(vm.localPlayerId), 0f, -1f)+            // The AI field finishes a 3-lap race on virtual time even unaided.+            pump(300_000)+            await("results", 20_000) { vm.racePhase.value is RacePhase.Results }+            val results = vm.racePhase.value as RacePhase.Results+            assertTrue(results.winner in results.order)+            val expectedCup = com.vayunmathur.games.kart.domain.KartRules.nextCup(cupBefore) ?: cupBefore+            await("cup banked") { vm.uiState.value.progress.currentCup == expectedCup }+            vm.backToLobby()+            assertTrue(vm.racePhase.value is RacePhase.Lobby)+            // Starting from the lobby again works after results.+            vm.startRace()+            await("countdown again") { vm.racePhase.value is RacePhase.Countdown }+        } finally {+            KartNative.isAvailable = wasAvailable+        }+    }++    @Test fun secondViewModelSeesPersistedCupState() {+        val vm = KartViewModel(app)+        await("cup loads") { vm.uiState.value.cup != null }+        // Whatever cup a previous race banked, the garage mirrors the store exactly.+        val cupIndex = vm.uiState.value.progress.currentCup+        assertEquals(com.vayunmathur.games.kart.domain.KartRules.cupAt(cupIndex), vm.uiState.value.cup)+        assertEquals(0, vm.uiState.value.progress.racesWon)+    }+}
games/kart/src/test/java/com/vayunmathur/games/kart/ui/KartGameScreenTest.kt
diff --git a/games/kart/src/test/java/com/vayunmathur/games/kart/ui/KartGameScreenTest.kt b/games/kart/src/test/java/com/vayunmathur/games/kart/ui/KartGameScreenTest.ktnew file mode 100644index 0000000000..3f0101d707--- /dev/null+++ b/games/kart/src/test/java/com/vayunmathur/games/kart/ui/KartGameScreenTest.kt@@ -0,0 +1,135 @@+package com.vayunmathur.games.kart.ui++import androidx.compose.ui.test.assertIsDisplayed+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.kart.R+import com.vayunmathur.games.kart.data.CUPS+import com.vayunmathur.games.kart.data.KartProgress+import com.vayunmathur.games.kart.platform.KartGameActions+import com.vayunmathur.games.kart.platform.KartUiState+import com.vayunmathur.games.kart.platform.RacePhase+import com.vayunmathur.sdk.controller.LobbyState+import com.vayunmathur.sdk.controller.PlayerSlot+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.Test+import kotlin.test.assertEquals++@RunWith(RobolectricTestRunner::class)+class KartGameScreenTest {++    @get:Rule val rule = createComposeRule()+    private val ctx get() = ApplicationProvider.getApplicationContext<android.content.Context>()+    private fun str(id: Int, vararg args: Any) = ctx.getString(id, *args)++    private class RecordingActions : KartGameActions {+        var starts = 0+        var backs = 0+        override fun startRace() { starts++ }+        override fun backToLobby() { backs++ }+    }++    @Test fun lobbyLoadingWhenCupMissing() {+        rule.setContent {+            KartGameScreen(KartUiState(cup = null), RacePhase.Lobby(LobbyState(gameId = "kart")), KartGameActions.Noop)+        }+        rule.onNodeWithText(str(R.string.garage_loading)).assertIsDisplayed()+    }++    @Test fun lobbyShowsCupWinsSeatsAndStartFires() {+        val actions = RecordingActions()+        val lobby = LobbyState(+            gameId = "kart",+            slots = listOf(+                PlayerSlot("p1", "You", remote = false),+                PlayerSlot("p2", "Phone", remote = true),+            ),+        )+        rule.setContent {+            KartGameScreen(+                KartUiState(cup = CUPS[1], progress = KartProgress(currentCup = 1, racesWon = 3, bestLapMs = 10_000L)),+                RacePhase.Lobby(lobby),+                actions,+            )+        }+        rule.onNodeWithText(str(R.string.cup_title, "Flower Cup")).assertIsDisplayed()+        rule.onNodeWithText(str(R.string.cup_tracks, 4)).assertIsDisplayed()+        rule.onNodeWithText(str(R.string.races_won, 3)).assertIsDisplayed()+        rule.onNodeWithText(str(R.string.lobby_seats, 2)).assertIsDisplayed()+        rule.onNodeWithText(str(R.string.how_to_play)).assertIsDisplayed()+        rule.onNodeWithText(str(R.string.start_race)).performClick()+        assertEquals(1, actions.starts)+        assertEquals(0, actions.backs)+    }++    @Test fun lobbyWithoutWinsOrSeatsHidesThoseRows() {+        rule.setContent {+            KartGameScreen(+                KartUiState(cup = CUPS[0], progress = KartProgress()),+                RacePhase.Lobby(LobbyState(gameId = "kart")),+                KartGameActions.Noop,+            )+        }+        rule.onNodeWithText(str(R.string.start_race)).assertIsDisplayed()+        rule.onNodeWithText(str(R.string.races_won, 0)).assertDoesNotExist()+    }++    @Test fun countdownShowsNumberAndHint() {+        rule.setContent {+            KartGameScreen(KartUiState(cup = CUPS[0]), RacePhase.Countdown(2), KartGameActions.Noop)+        }+        rule.onNodeWithText("2").assertIsDisplayed()+        rule.onNodeWithText(str(R.string.countdown_hint)).assertIsDisplayed()+    }++    @Test fun racingShowsLapTimesAndStandings() {+        val phase = RacePhase.Racing(+            order = listOf("p1", "ai-0", "ai-12"),+            lapProgress = mapOf("p1" to 0.5f, "ai-0" to 0.25f),+            playerLap = 1,+            totalLaps = 3,+            lastLapMs = 83_456L,+            bestLapMs = 61_005L,+        )+        rule.setContent { KartGameScreen(KartUiState(cup = CUPS[2]), phase, KartGameActions.Noop) }+        rule.onNodeWithText(str(R.string.race_lap, 2, 3)).assertIsDisplayed()+        rule.onNodeWithText(str(R.string.race_last_lap, "1:23.456")).assertIsDisplayed()+        rule.onNodeWithText(str(R.string.race_best_lap, "1:01.005")).assertIsDisplayed()+        rule.onNodeWithText(str(R.string.race_place, 1, "You")).assertExists()+        rule.onNodeWithText(str(R.string.race_place, 2, "Rival 0")).assertExists()+        rule.onNodeWithText(str(R.string.race_place, 3, "Rival 12")).assertExists()+    }++    @Test fun racingWithoutLapTimesHidesTimeRows() {+        val phase = RacePhase.Racing(+            order = listOf("p1"),+            lapProgress = emptyMap(),+            playerLap = 0,+            totalLaps = 3,+        )+        rule.setContent { KartGameScreen(KartUiState(cup = CUPS[0]), phase, KartGameActions.Noop) }+        rule.onNodeWithText(str(R.string.race_lap, 1, 3)).assertIsDisplayed()+        rule.onNodeWithText(str(R.string.race_place, 1, "You")).assertIsDisplayed()+    }++    @Test fun resultsShowsWinnerAndBackFires() {+        val actions = RecordingActions()+        val phase = RacePhase.Results(winner = "ai-1", order = listOf("ai-1", "p1"))+        rule.setContent { KartGameScreen(KartUiState(cup = CUPS[0]), phase, actions) }+        rule.onNodeWithText(str(R.string.results_title)).assertIsDisplayed()+        rule.onNodeWithText(str(R.string.race_place, 1, "Rival 1")).assertIsDisplayed()+        rule.onNodeWithText(str(R.string.race_place, 2, "You")).assertIsDisplayed()+        rule.onNodeWithText(str(R.string.back_to_lobby)).performClick()+        assertEquals(1, actions.backs)+        assertEquals(0, actions.starts)+    }++    @Test fun noopActionsAreHarmless() {+        KartGameActions.Noop.startRace()+        KartGameActions.Noop.backToLobby()+    }+}
games/kart/src/test/java/com/vayunmathur/games/kart/ui/KartSurfaceViewTest.kt
diff --git a/games/kart/src/test/java/com/vayunmathur/games/kart/ui/KartSurfaceViewTest.kt b/games/kart/src/test/java/com/vayunmathur/games/kart/ui/KartSurfaceViewTest.ktnew file mode 100644index 0000000000..18d135cb97--- /dev/null+++ b/games/kart/src/test/java/com/vayunmathur/games/kart/ui/KartSurfaceViewTest.kt@@ -0,0 +1,27 @@+package com.vayunmathur.games.kart.ui++import android.graphics.PixelFormat+import androidx.test.core.app.ApplicationProvider+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.Test+import kotlin.test.assertNotNull++@RunWith(RobolectricTestRunner::class)+class KartSurfaceViewTest {++    private val ctx get() = ApplicationProvider.getApplicationContext<android.content.Context>()++    @Test fun surfaceCallbacksAreSafeWithoutNativeEngine() {+        val view = KartSurfaceView(ctx)+        assertNotNull(view.holder)+        // Without a live native surface (or with one that rejects a Robolectric+        // Surface) every callback must return normally; the view catches JNI errors.+        view.surfaceCreated(view.holder)+        view.surfaceChanged(view.holder, PixelFormat.RGBA_8888, 640, 480)+        view.surfaceDestroyed(view.holder)+        // A change after destroy (not ready) is also a no-op.+        view.surfaceChanged(view.holder, PixelFormat.RGBA_8888, 320, 240)+        view.surfaceDestroyed(view.holder)+    }+}