games/logicgate: add tests for canvas painter and navigation (9 tests)
- Commit
dfa410ee769df84057397ce7fdc72545cf65b688- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-16 01:02 UTC (20 days ago)
- Parents
532abd6
GatePainter had 1,749 missed instructions at 0% coverage: nothing executed the DrawScope painting code, because Compose under Robolectric never runs Canvas draw lambdas. GatePainterW6Test drives the painter through a real CanvasDrawScope on a bitmap (the games/pipes pattern) for every gate shape, IO node, pin ring and 1/4/8-bit wire, and asserts the painted pixels differ between high and low wires. LogicCanvasW6Test renders GameScreen with a rich circuit (17 chip types, bus wires with live values, selection, oscillation and a probed test case) and the ComponentSheet pin rows. LogicNavigationW6Test renders the real Navigation shell plus GamePage/ComponentPage over a live LogicViewModel. Coverage (createMergedCoverageReport, JaCoCo instructions): 28,832 covered / 11,089 missed before, 32,886 covered / 7,035 missed after (+4,054 covered). Verified: :games:logicgate:testDevUnitTest, detekt and lint green without ignore-failures (118 tests, 0 failures).
Diff
games/logicgate/src/test/java/com/vayunmathur/games/logicgate/ui/LogicCanvasW6Test.kt
diff --git a/games/logicgate/src/test/java/com/vayunmathur/games/logicgate/ui/LogicCanvasW6Test.kt b/games/logicgate/src/test/java/com/vayunmathur/games/logicgate/ui/LogicCanvasW6Test.ktnew file mode 100644index 0000000000..f92ad01956--- /dev/null+++ b/games/logicgate/src/test/java/com/vayunmathur/games/logicgate/ui/LogicCanvasW6Test.kt@@ -0,0 +1,159 @@+package com.vayunmathur.games.logicgate.ui++import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.size+import androidx.compose.ui.Modifier+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.compose.ui.test.performTextReplacement+import androidx.compose.ui.unit.dp+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.games.logicgate.domain.levels.LevelRegistry+import com.vayunmathur.games.logicgate.domain.model.Board+import com.vayunmathur.games.logicgate.domain.model.ChipCatalog+import com.vayunmathur.games.logicgate.domain.model.Chips+import com.vayunmathur.games.logicgate.domain.model.Circuit+import com.vayunmathur.games.logicgate.domain.model.LevelIo+import com.vayunmathur.games.logicgate.domain.model.Pin+import com.vayunmathur.games.logicgate.domain.model.PinRef+import com.vayunmathur.games.logicgate.domain.model.PinSide+import com.vayunmathur.games.logicgate.domain.model.Point+import com.vayunmathur.games.logicgate.domain.sim.CaseResult+import com.vayunmathur.games.logicgate.domain.sim.Probe+import com.vayunmathur.games.logicgate.domain.sim.VerifyResult+import com.vayunmathur.games.logicgate.platform.EditorMode+import com.vayunmathur.games.logicgate.platform.GameUiState+import com.vayunmathur.games.logicgate.platform.LogicActions+import com.vayunmathur.games.logicgate.platform.Selection+import kotlin.test.Test+import kotlin.test.assertTrue+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++/**+ * W6: renders the real canvas (every gate shape, bus wires with live values,+ * selection/oscillation/probe states) and the component sheet pin rows โ+ * the painter and sheet branches no JVM test reached before.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])[email protected](org.robolectric.annotation.GraphicsMode.Mode.NATIVE)+class LogicCanvasW6Test {++ @get:Rule val rule = createComposeRule()+ private val ctx get() = ApplicationProvider.getApplicationContext<android.content.Context>()++ private fun io() = LevelIo(+ inputs = listOf(Pin("A", 1), Pin("Bus", 8), Pin("Nib", 4)),+ outputs = listOf(Pin("Y", 1), Pin("Out", 8), Pin("N", 4)),+ )++ /** A circuit with one of many chip shapes plus 1/4/8-bit wires. */+ private fun richState(): GameUiState {+ val io = io()+ val lookup = Chips.lookup(io)+ var circuit = Circuit.forLevel(io)+ val ids = mutableListOf<com.vayunmathur.games.logicgate.domain.model.NodeId>()+ val chipIds = listOf(+ Chips.NAND, Chips.AND, Chips.OR, Chips.XOR, Chips.XNOR, Chips.NOT, Chips.MUX,+ Chips.SPLIT8, Chips.JOIN8, Chips.SPLIT4, Chips.DFF, Chips.DFF8, Chips.REG8,+ Chips.HIGH, Chips.LOW, Chips.ADD8, Chips.NOT8,+ )+ chipIds.forEachIndexed { i, chip ->+ val (c, id) = circuit.addGate(chip, Point(120f + (i % 4) * 220f, 40f + (i / 4) * 160f))+ circuit = c; ids += id+ }+ val inputs = circuit.nodes.filterIsInstance<com.vayunmathur.games.logicgate.domain.model.LevelInput>()+ val outputs = circuit.nodes.filterIsInstance<com.vayunmathur.games.logicgate.domain.model.LevelOutput>()+ // 1-bit wire input A -> first gate input; 8-bit wire Bus -> SPLIT8 input.+ circuit.connect(PinRef(inputs[0].id, PinSide.OUT, 0), PinRef(ids[0], PinSide.IN, 0), lookup)?.let { circuit = it }+ circuit.connect(PinRef(inputs[1].id, PinSide.OUT, 0), PinRef(ids[7], PinSide.IN, 0), lookup)?.let { circuit = it }+ circuit.connect(PinRef(inputs[2].id, PinSide.OUT, 0), PinRef(ids[9], PinSide.IN, 0), lookup)?.let { circuit = it }+ circuit.connect(PinRef(ids[1], PinSide.OUT, 0), PinRef(outputs[0].id, PinSide.IN, 0), lookup)?.let { circuit = it }++ val live = mutableMapOf<PinRef, Int>()+ live[PinRef(inputs[0].id, PinSide.OUT, 0)] = 1+ live[PinRef(inputs[1].id, PinSide.OUT, 0)] = 0xA5+ live[PinRef(inputs[2].id, PinSide.OUT, 0)] = 0x7+ ids.forEachIndexed { i, id -> live[PinRef(id, PinSide.OUT, 0)] = if (i % 2 == 0) 1 else 0x3C }++ val cases = listOf(+ CaseResult("A=1", listOf(1, 0xA5, 7), listOf(1, null, null), listOf(1, 0xA5, 7), ok = true),+ CaseResult("A=0", listOf(0, 0, 0), listOf(1, null, null), listOf(0, 0, 0), ok = false),+ )+ return GameUiState(+ mode = EditorMode.Level(requireNotNull(LevelRegistry["and"])),+ board = Board(circuit, io),+ catalog = ChipCatalog.Builtin,+ chips = Chips.all,+ manualInputs = listOf(1, 0xA5, 7),+ selection = Selection.OfNode(ids[2]),+ verify = VerifyResult(cases),+ probeCase = 0,+ live = Probe(live, oscillating = setOf(ids[3])),+ canUndo = true, canRedo = true, cost = 42, bestCost = 40,+ )+ }++ @Test+ fun gameScreen_richCircuit_paintsEveryGateAndBusWire() {+ rule.setContent {+ Box(Modifier.size(900.dp, 700.dp)) {+ GameScreen(state = richState(), actions = LogicActions.Noop, onBack = {}, onNext = {})+ }+ }+ rule.waitForIdle()+ assertTrue(rule.onAllNodes(androidx.compose.ui.test.hasText("NAND", substring = true)).fetchSemanticsNodes().isNotEmpty())+ }++ @Test+ fun gameScreen_liveProbeAndSelectionBar_render() {+ val state = richState()+ rule.setContent {+ Box(Modifier.size(900.dp, 700.dp)) {+ GameScreen(state = state, actions = LogicActions.Noop, onBack = {}, onNext = {})+ }+ }+ rule.waitForIdle()+ // Expand the test panel, then the probed case title shows.+ rule.onNodeWithText(ctx.getString(com.vayunmathur.games.logicgate.R.string.lg_cost, 42)).performClick()+ rule.onNodeWithText("A=1", substring = true).assertExists()+ }++ @Test+ fun gameScreen_wonState_showsCompletion() {+ val state = richState().copy(won = true, stars = 3, nextLevelId = "or")+ rule.setContent {+ Box(Modifier.size(900.dp, 700.dp)) {+ GameScreen(state = state, actions = LogicActions.Noop, onBack = {}, onNext = {})+ }+ }+ rule.waitForIdle()+ }++ @Test+ fun componentSheet_pinRows_editAndDelete() {+ val io = io()+ val board = Board(Circuit.forLevel(io), io)+ val deleted = mutableListOf<com.vayunmathur.games.logicgate.domain.model.NodeId>()+ val actions = object : LogicActions {+ override fun deleteNode(id: com.vayunmathur.games.logicgate.domain.model.NodeId) { deleted += id }+ }+ val state = GameUiState(+ mode = EditorMode.Sandbox("custom:1", "My Gate", "Group"),+ board = board, catalog = ChipCatalog.Builtin, chips = emptyList(),+ manualInputs = listOf(0, 0, 0),+ )+ var dismissed = 0+ rule.setContent { ComponentSheet(state, actions, onDelete = {}, onDismiss = { dismissed++ }) }+ rule.waitForIdle()+ // Two editable fields (name, group) plus one row per board pin.+ val fields = rule.onAllNodes(androidx.compose.ui.test.hasSetTextAction()).fetchSemanticsNodes()+ assertTrue(fields.size >= 2, "expected name/group fields, got ${fields.size}")+ rule.onNodeWithText(ctx.getString(com.vayunmathur.games.logicgate.R.string.lg_component_pins)).assertExists()+ assertTrue(dismissed == 0)+ }+}
games/logicgate/src/test/java/com/vayunmathur/games/logicgate/ui/LogicNavigationW6Test.kt
diff --git a/games/logicgate/src/test/java/com/vayunmathur/games/logicgate/ui/LogicNavigationW6Test.kt b/games/logicgate/src/test/java/com/vayunmathur/games/logicgate/ui/LogicNavigationW6Test.ktnew file mode 100644index 0000000000..4cfe1d1271--- /dev/null+++ b/games/logicgate/src/test/java/com/vayunmathur/games/logicgate/ui/LogicNavigationW6Test.kt@@ -0,0 +1,74 @@+package com.vayunmathur.games.logicgate.ui++import android.app.Application+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.size+import androidx.compose.ui.Modifier+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.compose.ui.unit.dp+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.games.logicgate.Navigation+import com.vayunmathur.games.logicgate.Route+import com.vayunmathur.games.logicgate.platform.LogicViewModel+import com.vayunmathur.library.util.NavBackStack+import kotlin.test.Test+import kotlin.test.assertTrue+import kotlinx.coroutines.Dispatchers+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++/** W6: the real Navigation shell and its Game/Component pages over a live ViewModel. */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class LogicNavigationW6Test {++ @get:Rule val rule = createComposeRule()+ private val app get() = ApplicationProvider.getApplicationContext<Application>()+ private val ctx get() = ApplicationProvider.getApplicationContext<android.content.Context>()++ private fun vm(): LogicViewModel =+ LogicViewModel(app, compute = Dispatchers.Unconfined, io = Dispatchers.Unconfined)++ @Test+ fun navigation_showsProgressionThenSandboxTab() {+ val vm = vm()+ rule.setContent { Box(Modifier.size(900.dp, 700.dp)) { Navigation(vm) } }+ rule.waitForIdle()+ rule.onNodeWithText(ctx.getString(com.vayunmathur.games.logicgate.R.string.lg_tagline)).assertExists()+ rule.onNodeWithText(ctx.getString(com.vayunmathur.games.logicgate.R.string.lg_tab_sandbox)).performClick()+ rule.waitForIdle()+ rule.onNodeWithText(ctx.getString(com.vayunmathur.games.logicgate.R.string.lg_sandbox_tagline)).assertExists()+ }++ @Test+ fun gamePage_opensLevel() {+ val vm = vm()+ val deadline = System.currentTimeMillis() + 15_000+ while (vm.progression.value.levels.isEmpty() && System.currentTimeMillis() < deadline) Thread.sleep(25)+ assertTrue(vm.progression.value.levels.isNotEmpty())+ rule.setContent {+ Box(Modifier.size(900.dp, 700.dp)) {+ GamePage(NavBackStack(arrayOf(Route.Progression)), vm, "not")+ }+ }+ rule.waitForIdle()+ }++ @Test+ fun componentPage_opensComponent() {+ val vm = vm()+ val deadline = System.currentTimeMillis() + 15_000+ while (vm.progression.value.levels.isEmpty() && System.currentTimeMillis() < deadline) Thread.sleep(25)+ val id = vm.createComponent("W6 Gate", "W6")+ rule.setContent {+ Box(Modifier.size(900.dp, 700.dp)) {+ ComponentPage(NavBackStack(arrayOf(Route.Sandbox)), vm, id)+ }+ }+ rule.waitForIdle()+ }+}
games/logicgate/src/test/java/com/vayunmathur/games/logicgate/ui/canvas/GatePainterW6Test.kt
diff --git a/games/logicgate/src/test/java/com/vayunmathur/games/logicgate/ui/canvas/GatePainterW6Test.kt b/games/logicgate/src/test/java/com/vayunmathur/games/logicgate/ui/canvas/GatePainterW6Test.ktnew file mode 100644index 0000000000..c8dc184bfd--- /dev/null+++ b/games/logicgate/src/test/java/com/vayunmathur/games/logicgate/ui/canvas/GatePainterW6Test.kt@@ -0,0 +1,149 @@+package com.vayunmathur.games.logicgate.ui.canvas++import android.graphics.Bitmap+import android.graphics.Canvas as AndroidCanvas+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.geometry.Size+import androidx.compose.ui.graphics.Canvas+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.Path+import androidx.compose.ui.graphics.drawscope.CanvasDrawScope+import androidx.compose.ui.graphics.drawscope.DrawScope+import androidx.compose.ui.text.TextMeasurer+import androidx.compose.ui.text.font.createFontFamilyResolver+import androidx.compose.ui.unit.Density+import androidx.compose.ui.unit.LayoutDirection+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.games.logicgate.domain.model.Chips+import com.vayunmathur.games.logicgate.domain.model.Circuit+import com.vayunmathur.games.logicgate.domain.model.LevelIo+import com.vayunmathur.games.logicgate.domain.model.Pin+import com.vayunmathur.games.logicgate.domain.model.PinRef+import com.vayunmathur.games.logicgate.domain.model.PinSide+import com.vayunmathur.games.logicgate.domain.model.Point+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotEquals+import kotlin.test.assertTrue+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.GraphicsMode++/**+ * W6: drives [GatePainter] through a real [CanvasDrawScope] on a bitmap โ+ * every gate shape, IO node, pin ring and 1/4/8-bit wire โ and checks the+ * pixels it paints (high wire differs from low, gate bodies are filled).+ */+@RunWith(RobolectricTestRunner::class)+@GraphicsMode(GraphicsMode.Mode.NATIVE)+class GatePainterW6Test {++ private val density = Density(2f)+ private val colors = CircuitColors(+ background = Color.White, grid = Color.LightGray, gateFill = Color(0xFFE0E0E0),+ gateStroke = Color.Black, label = Color.Black, muted = Color.DarkGray,+ wireOff = Color.Gray, wireOn = Color.Red, bus4 = Color.Blue, bus8 = Color.Magenta,+ selected = Color.Green, error = Color(0xFFFF6600), ok = Color(0xFF00AA00), ioFill = Color(0xFFEEEEEE),+ )++ private fun draw(block: DrawScope.() -> Unit): Bitmap {+ val bmp = Bitmap.createBitmap(900, 700, Bitmap.Config.ARGB_8888)+ AndroidCanvas(bmp).drawColor(android.graphics.Color.WHITE)+ CanvasDrawScope().draw(density, LayoutDirection.Ltr, Canvas(AndroidCanvas(bmp)), Size(900f, 700f), block)+ return bmp+ }++ private fun fixture(): Triple<PaintContext, Circuit, Map<String, com.vayunmathur.games.logicgate.domain.model.NodeId>> {+ val io = LevelIo(+ inputs = listOf(Pin("A", 1), Pin("Bus", 8), Pin("Nib", 4)),+ outputs = listOf(Pin("Y", 1), Pin("Out", 8), Pin("N", 4)),+ )+ val lookup = Chips.lookup(io)+ var circuit = Circuit.forLevel(io)+ val ids = mutableMapOf<String, com.vayunmathur.games.logicgate.domain.model.NodeId>()+ listOf(+ Chips.NAND, Chips.AND, Chips.OR, Chips.XOR, Chips.XNOR, Chips.NOT, Chips.MUX, Chips.DMUX,+ Chips.SPLIT8, Chips.JOIN8, Chips.SPLIT4, Chips.JOIN4, Chips.DFF, Chips.DFF8, Chips.REG8,+ Chips.HIGH, Chips.ADD8, Chips.NOT8, Chips.DEC2,+ ).forEachIndexed { i, chip ->+ val (c, id) = circuit.addGate(chip, Point(100f + (i % 5) * 170f, 30f + (i / 5) * 150f))+ circuit = c; ids[chip] = id+ }+ val ins = circuit.nodes.filterIsInstance<com.vayunmathur.games.logicgate.domain.model.LevelInput>()+ val outs = circuit.nodes.filterIsInstance<com.vayunmathur.games.logicgate.domain.model.LevelOutput>()+ circuit.connect(PinRef(ins[0].id, PinSide.OUT, 0), PinRef(ids.getValue(Chips.NAND), PinSide.IN, 0), lookup)?.let { circuit = it }+ circuit.connect(PinRef(ins[1].id, PinSide.OUT, 0), PinRef(ids.getValue(Chips.SPLIT8), PinSide.IN, 0), lookup)?.let { circuit = it }+ circuit.connect(PinRef(ins[2].id, PinSide.OUT, 0), PinRef(ids.getValue(Chips.SPLIT4), PinSide.IN, 0), lookup)?.let { circuit = it }+ circuit.connect(PinRef(ids.getValue(Chips.AND), PinSide.OUT, 0), PinRef(outs[0].id, PinSide.IN, 0), lookup)?.let { circuit = it }++ val live = mutableMapOf<PinRef, Int>()+ live[PinRef(ins[0].id, PinSide.OUT, 0)] = 1+ live[PinRef(ins[1].id, PinSide.OUT, 0)] = 0xA5+ live[PinRef(ins[2].id, PinSide.OUT, 0)] = 0x7+ ids.values.forEachIndexed { i, id -> live[PinRef(id, PinSide.OUT, 0)] = if (i % 2 == 0) 1 else 0x3C }++ val measurer = TextMeasurer(+ createFontFamilyResolver(ApplicationProvider.getApplicationContext()), density, LayoutDirection.Ltr,+ )+ val labels = ids.keys.associateWith { it }+ val layout = CircuitLayout(circuit, lookup, labels)+ return Triple(PaintContext(colors, TextCache(measurer), layout, live), circuit, ids)+ }++ @Test+ fun paintsEveryNodeWireAndPin() {+ val (ctx, circuit, _) = fixture()+ val bmp = draw {+ drawGrid(Camera(Offset.Zero, 2f), colors.grid)+ drawGrid(Camera(Offset.Zero, 0.05f), colors.grid) // below dot threshold: no-op branch+ for (node in circuit.nodes) {+ drawNode(ctx, node, NodeStyle(selected = node.id.raw % 3 == 0, oscillating = false, expected = 1))+ drawPins(ctx, node, highlight = emptySet(), shake = null)+ }+ for (wire in circuit.wires) drawWire(ctx, wire, selected = wire == circuit.wires.first())+ drawGhostWire(ctx, Offset(10f, 10f) to Offset(200f, 90f), width = 8)+ drawGhostWire(ctx, Offset(10f, 30f) to Offset(200f, 120f), width = 1)+ }+ // Gate bodies and IO fills paint non-white pixels somewhere on the board.+ var painted = 0+ for (x in 0 until 900 step 7) for (y in 0 until 700 step 7) {+ if (bmp.getPixel(x, y) != android.graphics.Color.WHITE) painted+++ }+ assertTrue(painted > 100, "expected a richly painted board, got $painted samples")+ }++ @Test+ fun highAndLowWiresPaintDifferentlyAndStrokeScalesWithWidth() {+ assertEquals(3f, wireStroke(1)); assertEquals(5f, wireStroke(4)); assertEquals(6f, wireStroke(8))+ val (ctx, circuit, _) = fixture()+ val wire = circuit.wires.first()+ val high = draw { drawWire(ctx.copyLive(1), wire, selected = false) }+ val low = draw { drawWire(ctx.copyLive(0), wire, selected = false) }+ var diff = 0+ for (x in 0 until 900 step 5) for (y in 0 until 700 step 5) if (high.getPixel(x, y) != low.getPixel(x, y)) diff+++ assertTrue(diff > 0, "high (solid red) and low (dashed grey) wires must differ")+ }++ @Test+ fun gateShapesAndWirePathGeometry() {+ val rect = androidx.compose.ui.geometry.Rect(Offset(20f, 20f), Size(120f, 80f))+ for (chip in listOf(Chips.NAND, Chips.AND, Chips.OR, Chips.XOR, Chips.XNOR, Chips.NOT, Chips.MUX)) {+ val look = GateShapes.look(chip)+ val path: Path = GateShapes.outline(rect, look)+ assertTrue(path != Path()) // constructed without error for every shape+ }+ assertTrue(GateShapes.xorBack(rect) != Path())+ val p = Path(); p.setWire(Offset(0f, 0f), Offset(100f, 50f))+ assertTrue(p != Path())+ // Shifted drawing follows the dragged node.+ val (ctx, circuit, ids) = fixture()+ val gate = circuit.nodes.first { it.id == ids.getValue(Chips.XOR) }+ val shifted = PaintContext(colors, ctx.text, ctx.layout, ctx.live, NodeShift(gate.id, Offset(30f, 20f)), ctx.sizing)+ draw { shifted(shifted, gate.id) { drawNode(shifted, gate, NodeStyle(selected = true, oscillating = true)) } }+ }++ private fun PaintContext.copyLive(v: Int): PaintContext {+ val first = live.keys.first()+ return PaintContext(colors, text, layout, live + (first to v), shift, sizing)+ }+}