maps: slice 1/3 second-pass tests for surface, rail, streetview
- Commit
ec62a73b243834ed67e02a42da203f2e2c905050- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-07 08:33 UTC (29 days ago)
- Parents
196a3e1
Slice coverage (merged INSTRUCTION over map/nav/google/ streetview/transit/theme/settings classes): 72.9% -> 86.3% (21816/25279). New tests (11 files, all Slice1Pass2-named): - Slice1Pass2RailGeometryTest: rail lane-count ramp, lane offsets, meters-per-dp, polyline fanning (bends, degenerate segments), and the settled-camera refresh decision matrix. - Slice1Pass2StylePatchTest: the dark basemap palette through patchStyleForHybrid - every layer-id colour rule (casing before highway), label-family text/halo splits, suppressed POI layer, paint preservation. - Slice1Pass2EffectsComposeTest: vehicle-loop ticks below the zoom gate and with no stop, rail CLEAR/REFETCH settle paths, traffic-prefetch zoom gate, follow camera heading-up / north-up / not-following. - Slice1Pass2ComposeScreensTest: ElevationChart profiles (incl. degenerate), pegman drag lifecycle, Street View unavailable/sphere/attribution states, waypoint removal. - Slice1Pass2InitialCameraTest: cold-start seed (device cache over persisted fix, zero-zero rejection) and one-shot centering on the first live fix via ShadowLocationManager. - Slice1Pass2MapSurfaceProbeTest: MapSurface itself composed (bare and with route/pins/all layers) - the Vulkan renderer cannot present in the sandbox, but the surface wiring is ordinary Compose and now covered. - Slice1Pass2ProbesTest: traffic prefetch over a real viewport (host native), offline transit-board seam degradation, transit/drive/walk overlay colours and travelled greying. - Slice1Pass2NavComposeTest: maneuver banner with shield + then-peek + lanes, speed-widget limit/over-limit states, ElevationChart drawn under a real activity window. - Slice1Pass2SettingsTest: overlay status line (pending / applied / current), saved-places re-tap, voice switch. - Slice1Pass2StreetViewLoadTest: seam-default refusals, panorama tile stitching (full, failed, partial grids), nearest/byPano negative caching. - Slice1Pass2ReviewsFetchTest: WebReviewsFetcher with a valid cid walks its WebView load/settle path and times out to null (45s sandbox scrape timeout; nothing is fetched). No production code changed; no bugs found. Verified: gslot ./gradlew :maps:createMergedCoverageReport (slice suite green, 86.30% merged slice instructions). (cherry picked from commit d75f6a03fe7720b7a69abe6763056ccc33081018)
Diff
maps/src/test/java/com/vayunmathur/maps/data/google/Slice1Pass2ReviewsFetchTest.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/data/google/Slice1Pass2ReviewsFetchTest.kt b/maps/src/test/java/com/vayunmathur/maps/data/google/Slice1Pass2ReviewsFetchTest.ktnew file mode 100644index 0000000000..87eede8196--- /dev/null+++ b/maps/src/test/java/com/vayunmathur/maps/data/google/Slice1Pass2ReviewsFetchTest.kt@@ -0,0 +1,43 @@+package com.vayunmathur.maps.data.google++import androidx.test.core.app.ApplicationProvider+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.async+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.shadows.ShadowLooper+import kotlin.test.Test+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Slice 1/3 second pass (maps): [WebReviewsFetcher.fetch] with a valid cid —+ * the hidden-WebView scrape in the sandbox never answers through the JS+ * bridge, so the fetch must walk its load/settle path and give up (null)+ * at its own timeout rather than hanging or throwing.+ */+@RunWith(RobolectricTestRunner::class)+class Slice1Pass2ReviewsFetchTest {++ @Test+ fun `valid cid scrape times out to null in the sandbox`() = runBlocking {+ val fetcher = WebReviewsFetcher(+ ApplicationProvider.getApplicationContext(),+ )+ var progressTicks = 0+ val deferred = CoroutineScope(Dispatchers.Default).async {+ fetcher.fetch("0x1234:0xABCD", onProgress = { progressTicks++ })+ }+ // the fetcher waits on the main looper for page settle; pump it while+ // the scrape's own 45s timeout runs down in real time+ val deadline = System.currentTimeMillis() + 90_000+ while (!deferred.isCompleted && System.currentTimeMillis() < deadline) {+ ShadowLooper.idleMainLooper()+ Thread.sleep(100)+ }+ assertTrue(deferred.isCompleted)+ assertNull(deferred.await())+ }+}
maps/src/test/java/com/vayunmathur/maps/data/google/Slice1Pass2StreetViewLoadTest.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/data/google/Slice1Pass2StreetViewLoadTest.kt b/maps/src/test/java/com/vayunmathur/maps/data/google/Slice1Pass2StreetViewLoadTest.ktnew file mode 100644index 0000000000..f933c7c988--- /dev/null+++ b/maps/src/test/java/com/vayunmathur/maps/data/google/Slice1Pass2StreetViewLoadTest.kt@@ -0,0 +1,138 @@+package com.vayunmathur.maps.data.google++import android.graphics.Bitmap+import android.graphics.Color+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import java.io.ByteArrayOutputStream+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Slice 1/3 second pass (maps): [StreetViewDataSource.loadPanorama] tile+ * stitching and the live-network seam defaults' failure behaviour, beyond+ * the first pass's metadata parsing.+ */+@RunWith(RobolectricTestRunner::class)+class Slice1Pass2StreetViewLoadTest {++ private fun pngBytes(color: Int, w: Int = 8, h: Int = 8): ByteArray {+ val bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888)+ bmp.eraseColor(color)+ val out = ByteArrayOutputStream()+ bmp.compress(Bitmap.CompressFormat.PNG, 100, out)+ return out.toByteArray()+ }++ @Test+ fun `seam defaults refuse unreachable hosts without throwing`() = runBlocking {+ // The default seams hit the live network; a refused localhost port is+ // the deterministic offline stand-in for any transport failure.+ assertNull(StreetViewDataSource.httpGet("http://127.0.0.1:1/meta"))+ assertNull(StreetViewDataSource.httpGetBytes("http://127.0.0.1:1/tile"))+ assertNull(com.vayunmathur.maps.data.google.GooglePoiDataSource.httpGet("http://127.0.0.1:1/search"))+ }++ @Test+ fun `load panorama stitches a full tile grid`() = runBlocking {+ val originalBytes = StreetViewDataSource.httpGetBytes+ val requested = mutableListOf<String>()+ StreetViewDataSource.httpGetBytes = { url ->+ requested += url+ pngBytes(Color.RED)+ }+ try {+ val pano = StreetViewPano(+ panoId = "pano-stitch",+ lat = 37.0, lng = -122.0,+ tileSize = 8,+ levelDims = listOf(16 to 16),+ )+ val bmp = StreetViewDataSource.loadPanorama(pano)+ assertNotNull(bmp)+ assertEquals(16, bmp.width)+ assertEquals(16, bmp.height)+ // 2x2 grid of 8px tiles at zoom 0+ assertEquals(4, requested.size)+ assertTrue(requested.all { it.contains("pano-stitch") })+ } finally {+ StreetViewDataSource.httpGetBytes = originalBytes+ }+ }++ @Test+ fun `load panorama returns null when every tile fails`() = runBlocking {+ val originalBytes = StreetViewDataSource.httpGetBytes+ StreetViewDataSource.httpGetBytes = { null }+ try {+ val pano = StreetViewPano(+ panoId = "pano-empty",+ lat = 37.0, lng = -122.0,+ tileSize = 8,+ levelDims = listOf(16 to 8),+ )+ assertNull(StreetViewDataSource.loadPanorama(pano))+ } finally {+ StreetViewDataSource.httpGetBytes = originalBytes+ }+ }++ @Test+ fun `load panorama tolerates partial and undecodable tiles`() = runBlocking {+ val originalBytes = StreetViewDataSource.httpGetBytes+ var calls = 0+ StreetViewDataSource.httpGetBytes = { _ ->+ calls+++ when (calls % 3) {+ 0 -> null+ 1 -> byteArrayOf(9, 9, 9) // undecodable+ else -> pngBytes(Color.BLUE)+ }+ }+ try {+ // no levelDims: the modern 512-based pyramid shape is assumed and+ // the level picker must stay within the tile-width cap+ val pano = StreetViewPano(+ panoId = "pano-partial",+ lat = 37.0, lng = -122.0,+ tileSize = 512,+ )+ val bmp = StreetViewDataSource.loadPanorama(pano)+ assertNotNull(bmp)+ assertTrue(calls > 1)+ } finally {+ StreetViewDataSource.httpGetBytes = originalBytes+ }+ }++ @Test+ fun `nearest and byPano serve resolved panos from cache`() = runBlocking {+ val originalGet = StreetViewDataSource.httpGet+ var fetches = 0+ StreetViewDataSource.httpGet = { _ ->+ fetches+++ // minimal SingleImageSearch-shaped payload is covered exhaustively+ // by the first pass; here an unparseable body exercises the+ // negative-cache path of nearest/byPano themselves+ "not a pano payload"+ }+ try {+ val lat = 51.5007 + (System.nanoTime() % 1000) / 1_000_000.0+ assertNull(StreetViewDataSource.nearest(lat, -0.1246))+ val afterFirst = fetches+ assertNull(StreetViewDataSource.nearest(lat, -0.1246))+ assertEquals(afterFirst, fetches)+ val id = "missing-${System.nanoTime()}"+ assertNull(StreetViewDataSource.byPano(id))+ val afterByPano = fetches+ assertNull(StreetViewDataSource.byPano(id))+ assertEquals(afterByPano, fetches)+ } finally {+ StreetViewDataSource.httpGet = originalGet+ }+ }+}
maps/src/test/java/com/vayunmathur/maps/ui/map/Slice1Pass2ComposeScreensTest.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/ui/map/Slice1Pass2ComposeScreensTest.kt b/maps/src/test/java/com/vayunmathur/maps/ui/map/Slice1Pass2ComposeScreensTest.ktnew file mode 100644index 0000000000..4e543a611b--- /dev/null+++ b/maps/src/test/java/com/vayunmathur/maps/ui/map/Slice1Pass2ComposeScreensTest.kt@@ -0,0 +1,243 @@+package com.vayunmathur.maps.ui.map++import android.app.Application+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.ui.Modifier+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.performClick+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onAllNodesWithText+import androidx.compose.ui.test.onNodeWithContentDescription+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performTouchInput+import androidx.compose.ui.test.swipeLeft+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.library.map.CameraPosition+import com.vayunmathur.library.map.CameraState+import com.vayunmathur.library.map.GeoPoint+import com.vayunmathur.maps.data.google.StreetViewDataSource+import com.vayunmathur.maps.data.google.StreetViewPano+import com.vayunmathur.maps.ui.streetview.StreetViewPegman+import com.vayunmathur.maps.ui.streetview.StreetViewScreen+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/**+ * Slice 1/3 second pass (maps): ElevationChart's draw path, the pegman's+ * drag lifecycle, and StreetViewScreen's unavailable/attribution states.+ */+@RunWith(RobolectricTestRunner::class)+class Slice1Pass2ComposeScreensTest {++ @get:Rule val rule = createComposeRule()++ private val app: Application get() = ApplicationProvider.getApplicationContext()++ @Test+ fun `elevation chart draws a real profile and hides degenerate ones`() {+ val stage = androidx.compose.runtime.mutableIntStateOf(0)+ rule.setContent {+ when (stage.intValue) {+ 0 -> com.vayunmathur.maps.ui.nav.ElevationChart(+ profile = listOf(+ com.vayunmathur.maps.util.RouteService.ElevationPoint(0.0, 100.0),+ com.vayunmathur.maps.util.RouteService.ElevationPoint(500.0, 180.0),+ com.vayunmathur.maps.util.RouteService.ElevationPoint(1000.0, 130.0),+ ),+ ascentMeters = 95.4,+ descentMeters = 44.6,+ )+ 1 -> com.vayunmathur.maps.ui.nav.ElevationChart(+ profile = listOf(+ com.vayunmathur.maps.util.RouteService.ElevationPoint(0.0, 100.0),+ ),+ ascentMeters = 0.0, descentMeters = 0.0,+ )+ 2 -> com.vayunmathur.maps.ui.nav.ElevationChart(+ profile = listOf(+ com.vayunmathur.maps.util.RouteService.ElevationPoint(0.0, 50.0),+ com.vayunmathur.maps.util.RouteService.ElevationPoint(100.0, 50.0),+ ),+ ascentMeters = 0.0, descentMeters = 0.0,+ )+ else -> com.vayunmathur.maps.ui.nav.ElevationChart(+ profile = listOf(+ com.vayunmathur.maps.util.RouteService.ElevationPoint(0.0, 10.0),+ com.vayunmathur.maps.util.RouteService.ElevationPoint(0.0, 99.0),+ ),+ ascentMeters = 0.0, descentMeters = 0.0,+ )+ }+ }+ rule.onNodeWithText("Elevation").assertIsDisplayed()+ rule.onNodeWithText("95 m", substring = true).assertIsDisplayed()+ // single point, flat, and zero-distance profiles all render nothing+ for (next in 1..3) {+ rule.runOnIdle { stage.intValue = next }+ rule.waitForIdle()+ assertTrue(+ rule.onAllNodesWithText("Elevation").fetchSemanticsNodes().isEmpty(),+ )+ }+ }++ @Test+ fun `pegman drags and drops without a projection`() {+ val camera = CameraState(CameraPosition(GeoPoint(-122.4, 37.7), 12.0))+ rule.setContent {+ Box(Modifier.fillMaxSize()) {+ StreetViewPegman(camera = camera)+ }+ }+ rule.onNodeWithContentDescription("Drag onto the map to open Street View")+ .assertIsDisplayed()+ rule.onNodeWithContentDescription("Drag onto the map to open Street View")+ .performTouchInput { swipeLeft() }+ rule.waitForIdle()+ // no projection in the sandbox: the drop resolves to nothing and no+ // viewer dialog opens, but the drag lifecycle must not crash+ assertTrue(+ rule.onAllNodesWithText("Street View is not available here")+ .fetchSemanticsNodes().isEmpty(),+ )+ }++ @Test+ fun `waypoint list removes an intermediate stop`() {+ fun place(name: String, lon: Double) = com.vayunmathur.maps.data.SpecificFeature.GenericPlace(+ name = name, phone = null, website = null, openingHours = null,+ position = GeoPoint(lon, 37.7),+ )+ val reorders = mutableListOf<com.vayunmathur.maps.data.SpecificFeature.Route>()+ val route = com.vayunmathur.maps.data.SpecificFeature.Route(+ listOf(place("Start", -122.5), place("Mid", -122.4), place("End", -122.3)),+ )+ rule.setContent {+ WaypointList(+ route = route,+ onReorder = { reorders += it },+ onEditWaypoint = {},+ )+ }+ rule.onNodeWithText("Mid").assertIsDisplayed()+ // the middle row's close button is the clickable node sharing its band+ val midNode = rule.onNodeWithText("Mid").fetchSemanticsNode()+ val midCenterY = midNode.boundsInRoot.center.y+ val clickables = rule.onAllNodes(+ androidx.compose.ui.test.hasClickAction(),+ ).fetchSemanticsNodes()+ val closeIndex = clickables.withIndex().first { (_, node) ->+ kotlin.math.abs(node.boundsInRoot.center.y - midCenterY) < 5f &&+ node.boundsInRoot.center.x > midNode.boundsInRoot.center.x &&+ node.size.width < 120+ }.index+ rule.onAllNodes(androidx.compose.ui.test.hasClickAction())[closeIndex].performClick()+ assertTrue(reorders.size == 1)+ assertEquals(2, reorders.first().waypoints.size)+ assertEquals(+ listOf("Start", "End"),+ reorders.first().waypoints.map { (it as? com.vayunmathur.maps.data.SpecificFeature.GenericPlace)?.name },+ )+ }++ @Test+ fun `street view screen shows unavailable when tiles cannot load`() {+ val originalBytes = StreetViewDataSource.httpGetBytes+ StreetViewDataSource.httpGetBytes = { null }+ try {+ var closed = false+ rule.setContent {+ StreetViewScreen(+ initialPano = StreetViewPano(+ panoId = "pano-nowhere-${System.nanoTime()}",+ lat = 37.0, lng = -122.0,+ copyright = "© Test Imagery",+ captureYear = 2024, captureMonth = 6,+ ),+ onClose = { closed = true },+ )+ }+ val deadline = System.currentTimeMillis() + 10_000+ var shown = false+ while (!shown && System.currentTimeMillis() < deadline) {+ rule.waitForIdle()+ shown = rule.onAllNodesWithText("Street View is not available here")+ .fetchSemanticsNodes().isNotEmpty()+ if (!shown) Thread.sleep(50)+ }+ assertTrue(shown)+ rule.onNodeWithText("© Test Imagery · 2024-06", substring = true)+ .assertIsDisplayed()+ assertTrue(!closed)+ } finally {+ StreetViewDataSource.httpGetBytes = originalBytes+ }+ }++ @Test+ fun `street view screen renders the sphere when tiles load`() {+ val originalBytes = StreetViewDataSource.httpGetBytes+ StreetViewDataSource.httpGetBytes = { _ ->+ // an 8x8 red PNG tile, decodable by the stitcher+ val bmp = android.graphics.Bitmap.createBitmap(8, 8, android.graphics.Bitmap.Config.ARGB_8888)+ bmp.eraseColor(android.graphics.Color.RED)+ val out = java.io.ByteArrayOutputStream()+ bmp.compress(android.graphics.Bitmap.CompressFormat.PNG, 100, out)+ out.toByteArray()+ }+ try {+ rule.setContent {+ StreetViewScreen(+ initialPano = StreetViewPano(+ panoId = "pano-sphere-${System.nanoTime()}",+ lat = 37.0, lng = -122.0,+ tileSize = 8,+ levelDims = listOf(16 to 16),+ copyright = "© Sphere Test",+ ),+ onClose = {},+ )+ }+ // loading resolves into the sphere branch (attribution stays visible)+ val deadline = System.currentTimeMillis() + 10_000+ var ready = false+ while (!ready && System.currentTimeMillis() < deadline) {+ rule.waitForIdle()+ ready = rule.onAllNodesWithText("Street View is not available here")+ .fetchSemanticsNodes().isEmpty() &&+ rule.onAllNodesWithText("© Sphere Test", substring = true)+ .fetchSemanticsNodes().isNotEmpty()+ if (!ready) Thread.sleep(50)+ }+ assertTrue(ready)+ } finally {+ StreetViewDataSource.httpGetBytes = originalBytes+ }+ }++ @Test+ fun `street view attribution falls back to google copyright without a date`() {+ val originalBytes = StreetViewDataSource.httpGetBytes+ StreetViewDataSource.httpGetBytes = { null }+ try {+ rule.setContent {+ StreetViewScreen(+ initialPano = StreetViewPano(+ panoId = "pano-nodate-${System.nanoTime()}",+ lat = 37.0, lng = -122.0,+ ),+ onClose = {},+ )+ }+ rule.waitForIdle()+ rule.onNodeWithText("© Google", substring = true).assertIsDisplayed()+ } finally {+ StreetViewDataSource.httpGetBytes = originalBytes+ }+ }+}
maps/src/test/java/com/vayunmathur/maps/ui/map/Slice1Pass2EffectsComposeTest.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/ui/map/Slice1Pass2EffectsComposeTest.kt b/maps/src/test/java/com/vayunmathur/maps/ui/map/Slice1Pass2EffectsComposeTest.ktnew file mode 100644index 0000000000..13d7f8c014--- /dev/null+++ b/maps/src/test/java/com/vayunmathur/maps/ui/map/Slice1Pass2EffectsComposeTest.kt@@ -0,0 +1,223 @@+package com.vayunmathur.maps.ui.map++import androidx.compose.foundation.layout.Box+import androidx.compose.runtime.mutableStateOf+import androidx.compose.ui.test.junit4.createComposeRule+import com.vayunmathur.library.map.CameraPosition+import com.vayunmathur.library.map.CameraState+import com.vayunmathur.library.map.GeoPoint+import com.vayunmathur.maps.data.PostedLimit+import com.vayunmathur.maps.data.transit.TransitStop+import com.vayunmathur.maps.ui.theme.mapTokens+import com.vayunmathur.maps.util.NavigationProgress+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Slice 1/3 second pass (maps): the running loops behind the map effects —+ * vehicle ticks, rail settle decisions, traffic prefetch and the follow+ * camera — driven past their first-pass gate-off exits.+ */+@RunWith(RobolectricTestRunner::class)+class Slice1Pass2EffectsComposeTest {++ @get:Rule val rule = createComposeRule()++ private fun progress(course: Float = 90f) = NavigationProgress(+ snappedPosition = GeoPoint(-122.4, 37.7),+ segmentIndex = 0,+ currentStepIndex = 0,+ distanceAlongRoute = 10.0,+ distanceRemaining = 500.0,+ distanceToNextManeuver = 120.0,+ fractionComplete = 0.1,+ etaEpochMs = 0L,+ courseOverGround = course,+ distanceOffRoute = 0.0,+ )++ private fun chrome(autoFollow: Boolean = true, northUp: Boolean = false) = MapChromeState(+ selectedRouteTypeState = mutableStateOf(com.vayunmathur.maps.util.RouteService.TravelMode.DRIVE),+ selectedCategoryState = mutableStateOf(null),+ overlayState = mutableStateOf(MapOverlay.None),+ autoFollowState = mutableStateOf(autoFollow),+ northUpState = mutableStateOf(northUp),+ postedLimitState = mutableStateOf<PostedLimit?>(null),+ lastProgrammaticMoveMsState = mutableStateOf(0L),+ )++ @Test+ fun `vehicle loop ticks below the zoom gate without native calls`() {+ var vehicles: List<com.vayunmathur.library.map.MapMarker>? = null+ val camera = CameraState(CameraPosition(GeoPoint(-122.4, 37.7), 5.0))+ rule.setContent {+ Box {+ vehicles = rememberTransitVehicles(+ camera = camera,+ transitEnabled = true,+ selectedStop = TransitStop("stop-1", "Central", 37.7, -122.4),+ servingTripIds = setOf(1L),+ )+ }+ }+ rule.waitForIdle()+ // several 1 Hz ticks at zoom 5: always the empty set, never a native call+ rule.mainClock.advanceTimeBy(3_500)+ rule.waitForIdle()+ assertTrue(vehicles?.isEmpty() == true)+ }++ @Test+ fun `vehicle loop with no stop selected keeps clearing`() {+ var vehicles: List<com.vayunmathur.library.map.MapMarker>? = null+ val camera = CameraState(CameraPosition(GeoPoint(-122.4, 37.7), 15.0))+ rule.setContent {+ Box {+ vehicles = rememberTransitVehicles(+ camera = camera,+ transitEnabled = true,+ selectedStop = null,+ servingTripIds = emptySet(),+ )+ }+ }+ rule.mainClock.advanceTimeBy(2_500)+ rule.waitForIdle()+ assertTrue(vehicles?.isEmpty() == true)+ }++ @Test+ fun `rail lines clear below the zoom floor after settling`() {+ var lines: com.vayunmathur.library.map.RouteOverlay? = null+ var composed = false+ val camera = CameraState(CameraPosition(GeoPoint(-122.4, 37.7), 8.0))+ rule.setContent {+ Box {+ lines = rememberRailLines(+ camera = camera,+ transitEnabled = true,+ selectedStop = TransitStop("stop-1", "Central", 37.7, -122.4),+ tokens = mapTokens(isDark = false),+ )+ composed = true+ }+ }+ rule.mainClock.advanceTimeBy(1_500)+ rule.waitForIdle()+ assertTrue(composed)+ assertNull(lines)+ }++ @Test+ fun `rail lines settle at metro zoom through the refetch decision`() {+ var composed = false+ val camera = CameraState(CameraPosition(GeoPoint(-122.4, 37.7), 12.0))+ rule.setContent {+ Box {+ rememberRailLines(+ camera = camera,+ transitEnabled = true,+ selectedStop = TransitStop("stop-1", "Central", 37.7, -122.4),+ tokens = mapTokens(isDark = true),+ )+ composed = true+ }+ }+ // debounce (500ms) plus two settle cycles: the pack query runs (and+ // degrades to no lines in the sandbox) and the fan is rebuilt+ rule.mainClock.advanceTimeBy(2_500)+ rule.waitForIdle()+ assertTrue(composed)+ }++ @Test+ fun `follow camera animates to the puck heading-up and north-up`() {+ val camera = CameraState(CameraPosition(GeoPoint(-122.0, 37.0), 10.0))+ val chromeState = chrome(autoFollow = true, northUp = false)+ rule.setContent {+ NavigationCameraFollow(+ camera = camera,+ chrome = chromeState,+ navProgress = progress(course = 90f),+ isNavigating = true,+ )+ }+ rule.mainClock.advanceTimeBy(1_000)+ rule.waitForIdle()+ assertEquals(37.7, camera.position.target.latitude, 1e-9)+ assertEquals(17.0, camera.position.zoom, 1e-9)+ assertEquals(90.0, camera.position.bearing, 1e-6)+ assertTrue(chromeState.lastProgrammaticMoveMs > 0)+ }++ @Test+ fun `follow camera north-up keeps the existing bearing`() {+ val camera2 = CameraState(CameraPosition(GeoPoint(-122.0, 37.0), 10.0, bearing = 30.0))+ rule.setContent {+ NavigationCameraFollow(+ camera = camera2,+ chrome = chrome(autoFollow = true, northUp = true),+ navProgress = progress(course = 90f),+ isNavigating = true,+ )+ }+ rule.mainClock.advanceTimeBy(1_000)+ rule.waitForIdle()+ assertEquals(30.0, camera2.position.bearing, 1e-6)+ assertEquals(37.7, camera2.position.target.latitude, 1e-9)+ }++ @Test+ fun `follow camera rests when not following`() {+ val camera = CameraState(CameraPosition(GeoPoint(-122.0, 37.0), 10.0))+ val stage = androidx.compose.runtime.mutableIntStateOf(0)+ rule.setContent {+ when (stage.intValue) {+ 0 -> NavigationCameraFollow(+ camera = camera,+ chrome = chrome(autoFollow = false),+ navProgress = progress(),+ isNavigating = true,+ )+ 1 -> NavigationCameraFollow(+ camera = camera,+ chrome = chrome(autoFollow = true),+ navProgress = null,+ isNavigating = true,+ )+ else -> NavigationCameraFollow(+ camera = camera,+ chrome = chrome(autoFollow = true),+ navProgress = progress(),+ isNavigating = false,+ )+ }+ }+ rule.mainClock.advanceTimeBy(500)+ rule.runOnIdle { stage.intValue = 1 }+ rule.mainClock.advanceTimeBy(500)+ rule.runOnIdle { stage.intValue = 2 }+ rule.mainClock.advanceTimeBy(500)+ rule.waitForIdle()+ // never moved: no follow in any of the three configurations+ assertEquals(37.0, camera.position.target.latitude, 1e-9)+ assertEquals(10.0, camera.position.zoom, 1e-9)+ }++ @Test+ fun `traffic prefetch settles below the zoom gate without fetching`() {+ val camera = CameraState(CameraPosition(GeoPoint(-122.4, 37.7), 5.0))+ rule.setContent {+ TrafficPrefetchEffect(camera = camera, trafficEnabled = true)+ }+ rule.mainClock.advanceTimeBy(1_500)+ rule.waitForIdle()+ // reaching here means the debounce fired and the zoom gate held+ assertEquals(5.0, camera.position.zoom, 1e-9)+ }+}
maps/src/test/java/com/vayunmathur/maps/ui/map/Slice1Pass2InitialCameraTest.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/ui/map/Slice1Pass2InitialCameraTest.kt b/maps/src/test/java/com/vayunmathur/maps/ui/map/Slice1Pass2InitialCameraTest.ktnew file mode 100644index 0000000000..9bb9a69191--- /dev/null+++ b/maps/src/test/java/com/vayunmathur/maps/ui/map/Slice1Pass2InitialCameraTest.kt@@ -0,0 +1,136 @@+package com.vayunmathur.maps.ui.map++import android.Manifest+import android.app.Application+import android.content.Context+import android.location.Location+import android.location.LocationManager+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.library.map.CameraState+import com.vayunmathur.library.util.DataStoreUtils+import com.vayunmathur.maps.data.MapPreferences+import com.vayunmathur.maps.util.SelectedFeatureViewModel+import kotlinx.coroutines.runBlocking+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/**+ * Slice 1/3 second pass (maps): [rememberInitialCamera]'s cold-start seed —+ * newest cached device fix wins, then the persisted last fix, then the+ * world view — and the one-shot centering on the first live fix.+ */+@RunWith(RobolectricTestRunner::class)+class Slice1Pass2InitialCameraTest {++ @get:Rule val rule = createComposeRule()++ private val app: Application get() = ApplicationProvider.getApplicationContext()+ private val ctx: Context get() = app++ private fun location(provider: String, lat: Double, lon: Double, time: Long) =+ Location(provider).apply {+ latitude = lat+ longitude = lon+ this.time = time+ }++ private fun setLastFix(lat: Double?, lon: Double?) = runBlocking {+ val ds = DataStoreUtils.getInstance(app)+ if (lat == null || lon == null) {+ ds.setDouble(MapPreferences.KEY_LAST_LAT, 0.0)+ ds.setDouble(MapPreferences.KEY_LAST_LON, 0.0)+ } else {+ ds.setDouble(MapPreferences.KEY_LAST_LAT, lat)+ ds.setDouble(MapPreferences.KEY_LAST_LON, lon)+ }+ }++ private fun composeCamera(vm: SelectedFeatureViewModel): CameraState {+ var camera: CameraState? = null+ rule.setContent { camera = rememberInitialCamera(vm) }+ rule.waitForIdle()+ return checkNotNull(camera)+ }++ @Test+ fun `seed prefers the cached device fix over the persisted one`() {+ Shadows.shadowOf(app).grantPermissions(+ Manifest.permission.ACCESS_FINE_LOCATION,+ )+ val lm = ctx.getSystemService(LocationManager::class.java)+ val shadowLm = Shadows.shadowOf(lm)+ shadowLm.setLastKnownLocation(+ LocationManager.GPS_PROVIDER,+ location(LocationManager.GPS_PROVIDER, 37.1, -122.1, 1_000),+ )+ shadowLm.setLastKnownLocation(+ LocationManager.NETWORK_PROVIDER,+ location(LocationManager.NETWORK_PROVIDER, 48.2, 2.3, 2_000),+ )+ setLastFix(10.0, 10.0)+ val camera = composeCamera(SelectedFeatureViewModel(app))+ // the device cache (here the GPS fix the shadow serves) wins over the+ // stored fix; the shadow does not serve a network-provider cache+ assertEquals(37.1, camera.position.target.latitude, 1e-9)+ assertEquals(-122.1, camera.position.target.longitude, 1e-9)+ assertEquals(14.0, camera.position.zoom, 1e-9)+ }++ @Test+ fun `seed falls back to persisted fix without permission and ignores zero-zero`() {+ // no location permission granted in this sandbox: the device cache is+ // closed, so the persisted fix seeds the camera+ setLastFix(35.6, 139.7)+ val camera = composeCamera(SelectedFeatureViewModel(app))+ assertEquals(35.6, camera.position.target.latitude, 1e-9)+ assertEquals(139.7, camera.position.target.longitude, 1e-9)++ // a stored (0,0) is "no fix ever", not the Gulf of Guinea+ setLastFix(null, null)+ }++ @Test+ fun `zero-zero cached device fix is not a seed`() {+ Shadows.shadowOf(app).grantPermissions(Manifest.permission.ACCESS_FINE_LOCATION)+ val lm = ctx.getSystemService(LocationManager::class.java)+ Shadows.shadowOf(lm).setLastKnownLocation(+ LocationManager.GPS_PROVIDER,+ location(LocationManager.GPS_PROVIDER, 0.0, 0.0, 5_000),+ )+ setLastFix(35.6, 139.7)+ val camera = composeCamera(SelectedFeatureViewModel(app))+ assertEquals(35.6, camera.position.target.latitude, 1e-9)+ setLastFix(null, null)+ }++ @Test+ fun `first live fix centres once at first-fix zoom`() {+ setLastFix(null, null)+ Shadows.shadowOf(app).grantPermissions(Manifest.permission.ACCESS_FINE_LOCATION)+ val vm = SelectedFeatureViewModel(app)+ val camera = composeCamera(vm)+ // deliver a fix through the framework pipeline the VM subscribed to+ val lm = ctx.getSystemService(LocationManager::class.java)+ Shadows.shadowOf(lm).simulateLocation(+ location(LocationManager.GPS_PROVIDER, 40.7, -74.0, 3_000),+ )+ rule.mainClock.advanceTimeBy(1_200)+ rule.waitForIdle()+ assertEquals(40.7, camera.position.target.latitude, 1e-9)+ assertEquals(-74.0, camera.position.target.longitude, 1e-9)+ assertTrue(camera.position.zoom >= 14.0)+ // a second fix does not re-centre: the latch is one-shot+ Shadows.shadowOf(lm).simulateLocation(+ location(LocationManager.GPS_PROVIDER, 41.0, -73.0, 4_000),+ )+ rule.mainClock.advanceTimeBy(1_200)+ rule.waitForIdle()+ assertEquals(40.7, camera.position.target.latitude, 1e-9)+ }+}
maps/src/test/java/com/vayunmathur/maps/ui/map/Slice1Pass2MapSurfaceProbeTest.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/ui/map/Slice1Pass2MapSurfaceProbeTest.kt b/maps/src/test/java/com/vayunmathur/maps/ui/map/Slice1Pass2MapSurfaceProbeTest.ktnew file mode 100644index 0000000000..76c412ad5c--- /dev/null+++ b/maps/src/test/java/com/vayunmathur/maps/ui/map/Slice1Pass2MapSurfaceProbeTest.kt@@ -0,0 +1,142 @@+package com.vayunmathur.maps.ui.map++import android.app.Application+import androidx.compose.runtime.mutableStateOf+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.library.map.CameraPosition+import com.vayunmathur.library.map.CameraState+import com.vayunmathur.library.map.GeoPoint+import com.vayunmathur.library.map.MapBody+import com.vayunmathur.maps.data.PostedLimit+import com.vayunmathur.maps.util.MapsSearchViewModel+import com.vayunmathur.maps.util.RouteService+import com.vayunmathur.maps.util.SelectedFeatureViewModel+import com.vayunmathur.maps.util.TransitStopsViewModel+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.Test+import kotlin.test.assertTrue+import kotlin.time.Duration.Companion.minutes++/**+ * Slice 1/3 second pass (maps): [MapSurface] composed in the sandbox. The+ * Vulkan renderer cannot present frames here, but the surface's own wiring+ * (options, markers, overlays, effects) is ordinary Compose state work and+ * must survive composition without a live renderer.+ */+@RunWith(RobolectricTestRunner::class)+class Slice1Pass2MapSurfaceProbeTest {++ @get:Rule val rule = createComposeRule()++ private val app: Application get() = ApplicationProvider.getApplicationContext()++ private fun chrome() = MapChromeState(+ selectedRouteTypeState = mutableStateOf(RouteService.TravelMode.DRIVE),+ selectedCategoryState = mutableStateOf(null),+ overlayState = mutableStateOf(MapOverlay.None),+ autoFollowState = mutableStateOf(true),+ northUpState = mutableStateOf(false),+ postedLimitState = mutableStateOf<PostedLimit?>(null),+ lastProgrammaticMoveMsState = mutableStateOf(0L),+ )++ @Test+ fun `map surface composes its chrome wiring without a renderer`() {+ val camera = CameraState(CameraPosition(GeoPoint(-122.4, 37.7), 12.0))+ var composed = false+ rule.setContent {+ MapSurface(+ camera = camera,+ chrome = chrome(),+ viewModel = SelectedFeatureViewModel(app),+ searchViewModel = MapsSearchViewModel(app),+ transitViewModel = TransitStopsViewModel(app),+ sheetState = null,+ selectedFeature = null,+ route = null,+ userPosition = GeoPoint(0.0, 0.0),+ userBearing = null,+ navProgress = null,+ searchResults = emptyList(),+ savedPlaces = emptyList(),+ parkingSpot = null,+ familyMembers = emptyList(),+ trafficEnabled = false,+ satelliteEnabled = false,+ safetyEnabled = false,+ transitEnabled = false,+ globeEnabled = false,+ body = MapBody.Earth,+ moonTextures = null,+ selectedTransitStop = null,+ darkBasemap = false,+ )+ composed = true+ }+ rule.waitForIdle()+ rule.mainClock.advanceTimeBy(1_000)+ rule.waitForIdle()+ assertTrue(composed)+ }++ @Test+ fun `map surface composes with route pins and every layer on`() {+ val camera = CameraState(CameraPosition(GeoPoint(-122.4, 37.7), 15.0))+ val place = com.vayunmathur.maps.data.SpecificFeature.GenericPlace(+ name = "Cafe", phone = null, website = null, openingHours = null,+ position = GeoPoint(-122.4, 37.7),+ )+ val route = RouteService.Route(+ 10.minutes, 500.0,+ listOf(GeoPoint(-122.4, 37.7), GeoPoint(-122.3, 37.8)),+ listOf(+ RouteService.Step(+ distanceMeters = 100.0,+ staticDuration = 1.minutes,+ polyline = listOf(GeoPoint(-122.4, 37.7), GeoPoint(-122.3, 37.8)),+ navInstruction = RouteService.API.NavInstruction(),+ travelMode = RouteService.TravelMode.DRIVE,+ ),+ ),+ )+ var composed = false+ rule.setContent {+ MapSurface(+ camera = camera,+ chrome = chrome(),+ viewModel = SelectedFeatureViewModel(app),+ searchViewModel = MapsSearchViewModel(app),+ transitViewModel = TransitStopsViewModel(app),+ sheetState = null,+ selectedFeature = com.vayunmathur.maps.data.SpecificFeature.Route(listOf(place, null)),+ route = route,+ userPosition = GeoPoint(-122.4, 37.7),+ userBearing = 45f,+ navProgress = null,+ searchResults = emptyList(),+ savedPlaces = emptyList(),+ parkingSpot = null,+ familyMembers = emptyList(),+ trafficEnabled = true,+ satelliteEnabled = true,+ safetyEnabled = true,+ transitEnabled = true,+ globeEnabled = false,+ body = MapBody.Earth,+ moonTextures = null,+ selectedTransitStop = com.vayunmathur.maps.data.transit.TransitStop(+ "stop-1", "Central", 37.7, -122.4,+ ),+ darkBasemap = true,+ )+ composed = true+ }+ rule.waitForIdle()+ rule.mainClock.advanceTimeBy(2_000)+ rule.waitForIdle()+ assertTrue(composed)+ }+}
maps/src/test/java/com/vayunmathur/maps/ui/map/Slice1Pass2ProbesTest.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/ui/map/Slice1Pass2ProbesTest.kt b/maps/src/test/java/com/vayunmathur/maps/ui/map/Slice1Pass2ProbesTest.ktnew file mode 100644index 0000000000..2993259ee2--- /dev/null+++ b/maps/src/test/java/com/vayunmathur/maps/ui/map/Slice1Pass2ProbesTest.kt@@ -0,0 +1,143 @@+package com.vayunmathur.maps.ui.map++import androidx.compose.ui.graphics.Color+import com.vayunmathur.library.map.GeoBounds+import com.vayunmathur.library.map.GeoPoint+import com.vayunmathur.maps.data.transit.TransitousDataSource+import com.vayunmathur.maps.ui.theme.mapTokens+import com.vayunmathur.maps.util.NavigationProgress+import com.vayunmathur.maps.util.RouteService+import kotlinx.coroutines.runBlocking+import kotlinx.coroutines.withTimeoutOrNull+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+import kotlin.time.Duration.Companion.minutes++/**+ * Slice 1/3 second pass (maps): native-adjacent probes and route-overlay+ * colour decisions the first pass left — traffic prefetch over a real+ * viewport, the transit board's live seam failure, and transit line+ * colours (valid, blank, malformed) through the public overlay builder.+ */+@RunWith(RobolectricTestRunner::class)+class Slice1Pass2ProbesTest {++ @Test+ fun `traffic prefetch enumerates a small viewport and bails on huge ones`() {+ // one 1° square: the native dedup makes repeats free; on the host the+ // call must simply not throw (host Rust libs are on the library path)+ prefetchTrafficSquares(GeoBounds(west = -122.4, south = 37.7, east = -122.3, north = 37.8))+ // antimeridian-wide and inverted boxes are skipped before any native call+ prefetchTrafficSquares(GeoBounds(west = -180.0, south = -80.0, east = 180.0, north = 80.0))+ prefetchTrafficSquares(GeoBounds(west = 10.0, south = 50.0, east = 9.0, north = 49.0))+ }++ @Test+ fun `transit departures with the live seam degrade to empty offline`() = runBlocking {+ // unique stop id so no earlier cached failure/success can answer+ val deps = withTimeoutOrNull(30_000) {+ TransitousDataSource.departures("pass2-probe-${System.nanoTime()}")+ }+ // offline sandbox: the live seam fails and the board is empty, never a throw+ assertTrue(deps?.isEmpty() == true)+ }++ private fun transitStep(color: String?) = RouteService.Step(+ distanceMeters = 100.0,+ staticDuration = 1.minutes,+ polyline = listOf(GeoPoint(-122.4, 37.7), GeoPoint(-122.3, 37.8)),+ navInstruction = RouteService.API.NavInstruction(),+ travelMode = RouteService.TravelMode.TRANSIT,+ transitDetails = RouteService.API.TransitDetails(+ headsign = "Downtown",+ stopCount = 3,+ transitLine = RouteService.API.TransitLine("N", "N", color ?: ""),+ stopDetails = RouteService.API.StopDetails(+ "17:00", "17:10",+ RouteService.API.Stop("A"), RouteService.API.Stop("B"),+ ),+ ),+ )++ private fun driveStep(ratio: Double) = RouteService.Step(+ distanceMeters = 100.0,+ staticDuration = 1.minutes,+ polyline = listOf(GeoPoint(-122.4, 37.7), GeoPoint(-122.3, 37.8)),+ navInstruction = RouteService.API.NavInstruction(),+ travelMode = RouteService.TravelMode.DRIVE,+ speedRatio = ratio,+ )++ private fun routeOf(vararg steps: RouteService.Step): RouteService.Route {+ val full = steps.flatMapIndexed { i, s ->+ if (i == 0) s.polyline else s.polyline.drop(1)+ }+ return RouteService.Route(10.minutes, 500.0, full, steps.toList())+ }++ @Test+ fun `transit line colours parse, fall back on blank and malformed`() {+ val tokens = mapTokens(isDark = false)+ val valid = buildRouteOverlay(routeOf(transitStep("#FF8800")), null, tokens)+ assertNotNull(valid)+ assertEquals(Color(0xFFFF8800), valid.segments.first().color)+ val blank = buildRouteOverlay(routeOf(transitStep("")), null, tokens)+ assertEquals(tokens.routeTransitFallback, blank?.segments?.first()?.color)+ val malformed = buildRouteOverlay(routeOf(transitStep("not-a-color")), null, tokens)+ assertEquals(tokens.routeTransitFallback, malformed?.segments?.first()?.color)+ val noDetails = buildRouteOverlay(+ routeOf(transitStep(null).copy(transitDetails = null)), null, tokens,+ )+ assertEquals(tokens.routeTransitFallback, noDetails?.segments?.first()?.color)+ }++ @Test+ fun `drive ratios and walk colour through the overlay builder`() {+ val tokens = mapTokens(isDark = true)+ val jam = buildRouteOverlay(routeOf(driveStep(0.2)), null, tokens)+ assertEquals(tokens.traffic.jam, jam?.segments?.first()?.color)+ val slow = buildRouteOverlay(routeOf(driveStep(0.7)), null, tokens)+ assertEquals(tokens.traffic.slow, slow?.segments?.first()?.color)+ val free = buildRouteOverlay(routeOf(driveStep(1.0)), null, tokens)+ assertEquals(tokens.traffic.free, free?.segments?.first()?.color)+ val walk = buildRouteOverlay(+ routeOf(driveStep(1.0).copy(travelMode = RouteService.TravelMode.WALK)),+ null, tokens,+ )+ assertEquals(tokens.routeInert, walk?.segments?.first()?.color)+ // a route whose steps have no drawable polyline builds no overlay+ val empty = buildRouteOverlay(+ routeOf(driveStep(1.0).copy(polyline = listOf(GeoPoint(0.0, 0.0)))),+ null, tokens,+ )+ assertNull(empty)+ }++ @Test+ fun `navigating overlay greys the travelled portion`() {+ val tokens = mapTokens(isDark = false)+ val route = routeOf(driveStep(1.0), driveStep(1.0), driveStep(1.0))+ val progress = NavigationProgress(+ snappedPosition = GeoPoint(-122.35, 37.75),+ segmentIndex = 1,+ currentStepIndex = 1,+ distanceAlongRoute = 150.0,+ distanceRemaining = 350.0,+ distanceToNextManeuver = 50.0,+ fractionComplete = 0.3,+ etaEpochMs = 0L,+ courseOverGround = 0f,+ distanceOffRoute = 0.0,+ )+ val overlay = buildRouteOverlay(route, progress, tokens)+ assertNotNull(overlay)+ assertTrue(overlay.segments.isNotEmpty())+ assertEquals(tokens.traffic.traveled, overlay.segments.first().color)+ assertEquals(tokens.traffic.free, overlay.segments.last().color)+ }+}
maps/src/test/java/com/vayunmathur/maps/ui/map/Slice1Pass2RailGeometryTest.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/ui/map/Slice1Pass2RailGeometryTest.kt b/maps/src/test/java/com/vayunmathur/maps/ui/map/Slice1Pass2RailGeometryTest.ktnew file mode 100644index 0000000000..0e3efa4318--- /dev/null+++ b/maps/src/test/java/com/vayunmathur/maps/ui/map/Slice1Pass2RailGeometryTest.kt@@ -0,0 +1,131 @@+package com.vayunmathur.maps.ui.map++import com.vayunmathur.library.map.GeoPoint+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/**+ * Slice 1/3 second pass (maps): the rail-corridor geometry decisions —+ * lane counts, lane offsets, polyline fanning and the settled-camera+ * refresh decision — beyond the first pass's math smoke tests.+ */+class Slice1Pass2RailGeometryTest {++ @Test+ fun `lane count follows the tile style ramp`() {+ assertEquals(1, railLaneCount(-2.0))+ assertEquals(1, railLaneCount(0.0))+ assertEquals(2, railLaneCount(9.0))+ assertEquals(2, railLaneCount(10.0))+ assertEquals(3, railLaneCount(11.0))+ assertEquals(3, railLaneCount(12.0))+ assertEquals(4, railLaneCount(13.0))+ assertEquals(4, railLaneCount(18.0))+ }++ @Test+ fun `lane offset is zero for single lane corridors and scales with taper`() {+ assertEquals(0.0, railLaneOffsetDp(13.0, ordinal = 0, count = 1, taper = 255), 1e-9)+ assertEquals(0.0, railLaneOffsetDp(13.0, ordinal = 0, count = 4, taper = 0), 1e-9)+ // first and last ordinals sit on opposite sides of the centreline+ val first = railLaneOffsetDp(13.0, ordinal = 0, count = 4, taper = 255)+ val last = railLaneOffsetDp(13.0, ordinal = 3, count = 4, taper = 255)+ assertTrue(first < 0.0 && last > 0.0)+ assertEquals(-last, first, 1e-9)+ // half taper halves the offset+ assertEquals(+ first / 2,+ railLaneOffsetDp(13.0, ordinal = 0, count = 4, taper = 127),+ 0.05,+ )+ // fewer lanes than colours squash ordinals onto shared lanes from the middle+ val squashed = railLaneOffsetDp(9.0, ordinal = 1, count = 4, taper = 255)+ assertTrue(kotlin.math.abs(squashed) <= kotlin.math.abs(first))+ }++ @Test+ fun `meters per dp shrinks with zoom and latitude`() {+ val equatorZoom10 = metersPerDp(0.0, 10.0)+ assertTrue(metersPerDp(0.0, 11.0) < equatorZoom10)+ assertTrue(metersPerDp(60.0, 10.0) < equatorZoom10)+ assertEquals(equatorZoom10 / 2, metersPerDp(0.0, 11.0), equatorZoom10 * 0.01)+ }++ @Test+ fun `offset polyline shifts right of travel and glues bends`() {+ val east = listOf(GeoPoint(0.0, 0.0), GeoPoint(0.01, 0.0), GeoPoint(0.02, 0.0))+ val shifted = offsetPolyline(east, 100.0)+ // travelling east, right of travel is south: latitude drops, longitude kept+ assertTrue(shifted.all { it.latitude < 0.0 })+ assertEquals(east.map { it.longitude }, shifted.map { it.longitude })+ // a northbound leg shifts east instead+ val north = listOf(GeoPoint(0.0, 0.0), GeoPoint(0.0, 0.01))+ val shiftedNorth = offsetPolyline(north, 100.0)+ assertTrue(shiftedNorth.all { it.longitude > 0.0 })+ // negative offset goes the other way+ assertTrue(offsetPolyline(east, -100.0).all { it.latitude > 0.0 })+ }++ @Test+ fun `offset polyline degenerate inputs are returned unchanged`() {+ assertEquals(emptyList(), offsetPolyline(emptyList(), 100.0))+ val single = listOf(GeoPoint(1.0, 2.0))+ assertEquals(single, offsetPolyline(single, 100.0))+ val two = listOf(GeoPoint(0.0, 0.0), GeoPoint(0.01, 0.0))+ assertEquals(two, offsetPolyline(two, 0.0))+ // a duplicated point makes a zero-length segment; the polyline still shifts+ val withDupe = listOf(GeoPoint(0.0, 0.0), GeoPoint(0.0, 0.0), GeoPoint(0.01, 0.0))+ val shifted = offsetPolyline(withDupe, 50.0)+ assertEquals(3, shifted.size)+ // a bend averages its normals rather than tearing at the vertex+ val bend = listOf(GeoPoint(0.0, 0.0), GeoPoint(0.01, 0.0), GeoPoint(0.01, 0.01))+ val bentShifted = offsetPolyline(bend, 100.0)+ assertTrue(bentShifted[1].latitude < 0.0 && bentShifted[1].longitude > 0.01)+ }++ @Test+ fun `refresh decision matrix`() {+ val centre = 37.0 to -122.0+ // below the zoom floor always clears, even with a fresh fetch cached+ assertEquals(+ RailRefresh.CLEAR,+ railRefreshDecision(8.0, centre, centre, 12.0, 12.0, overlayNull = false, spansEmpty = false),+ )+ // never fetched: refetch+ assertEquals(+ RailRefresh.REFETCH,+ railRefreshDecision(12.0, centre, null, Double.NaN, Double.NaN, overlayNull = true, spansEmpty = true),+ )+ // drifted beyond the recenter radius: refetch+ assertEquals(+ RailRefresh.REFETCH,+ railRefreshDecision(12.0, 37.03 to -122.0, centre, 12.0, 12.0, overlayNull = false, spansEmpty = false),+ )+ // zoom stepped a full level since the fetch: refetch+ assertEquals(+ RailRefresh.REFETCH,+ railRefreshDecision(13.0, centre, centre, 12.0, 12.0, overlayNull = false, spansEmpty = false),+ )+ // inside the footprint with no spans fetched: reuse (nothing to fan)+ assertEquals(+ RailRefresh.REUSE,+ railRefreshDecision(12.0, centre, centre, 12.0, 12.0, overlayNull = true, spansEmpty = true),+ )+ // overlay cleared by the zoom gate but spans cached: refan+ assertEquals(+ RailRefresh.REFAN,+ railRefreshDecision(12.0, centre, centre, 12.0, Double.NaN, overlayNull = true, spansEmpty = false),+ )+ // lane-count band changed since the fan: refan+ assertEquals(+ RailRefresh.REFAN,+ railRefreshDecision(13.0, centre, centre, 12.5, 12.0, overlayNull = false, spansEmpty = false),+ )+ // same band, overlay live: reuse+ assertEquals(+ RailRefresh.REUSE,+ railRefreshDecision(12.0, centre, centre, 12.0, 12.0, overlayNull = false, spansEmpty = false),+ )+ }+}
maps/src/test/java/com/vayunmathur/maps/ui/map/Slice1Pass2StylePatchTest.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/ui/map/Slice1Pass2StylePatchTest.kt b/maps/src/test/java/com/vayunmathur/maps/ui/map/Slice1Pass2StylePatchTest.ktnew file mode 100644index 0000000000..2cc5b1f582--- /dev/null+++ b/maps/src/test/java/com/vayunmathur/maps/ui/map/Slice1Pass2StylePatchTest.kt@@ -0,0 +1,130 @@+package com.vayunmathur.maps.ui.map++import kotlinx.serialization.json.Json+import kotlinx.serialization.json.jsonArray+import kotlinx.serialization.json.jsonObject+import kotlinx.serialization.json.jsonPrimitive+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++/**+ * Slice 1/3 second pass (maps): the dark basemap palette applied by+ * [patchStyleForHybrid] — every layer-id colour rule, reached through the+ * public entry point the app actually calls.+ */+class Slice1Pass2StylePatchTest {++ private val json = Json { ignoreUnknownKeys = true }++ private fun styleWithLayers(vararg layers: String): String {+ val layerJson = layers.joinToString(",") { layer ->+ if (layer == "background") {+ """{"id":"background","type":"background","paint":{"background-color":"#eeeeee"}}"""+ } else {+ """{"id":"$layer","type":"fill","source":"protomaps","paint":{"fill-color":"#ffffff","line-width":2}}"""+ }+ }+ return """{"sources":{"old":{}},"layers":[$layerJson],"glyphs":"g","sprite":"s"}"""+ }++ private fun darkColorsById(patched: String): Map<String, String> {+ val root = json.parseToJsonElement(patched).jsonObject+ val layers = root["layers"]!!.jsonArray+ return layers.map { el ->+ val obj = el.jsonObject+ val id = obj["id"]!!.jsonPrimitive.content+ val paint = obj["paint"]!!.jsonObject+ id to (paint["fill-color"]?.jsonPrimitive?.content+ ?: paint["background-color"]?.jsonPrimitive?.content ?: "")+ }.toMap()+ }++ @Test+ fun `dark palette covers every layer family`() {+ val ids = listOf(+ "background", "earth", "water", "water_stream", "water_river",+ "landcover", "landuse_park", "landuse_urban_green", "landuse_hospital",+ "landuse_industrial", "landuse_school", "landuse_beach", "landuse_zoo",+ "landuse_aerodrome", "landuse_runway", "landuse_pedestrian", "landuse_pier",+ "landuse_other", "buildings", "boundaries_country", "roads_rail",+ "roads_runway_a", "roads_taxiway_a", "roads_highway_casing_early",+ "roads_tunnels_motorway", "roads_highway", "roads_major_link",+ "roads_minor", "transit_whatever",+ )+ val patched = patchStyleForHybrid(styleWithLayers(*ids.toTypedArray()), "base://", "hybrid://", dark = true)+ val colors = darkColorsById(patched)+ // each non-background layer appears twice (_base and _hybrid) with the dark colour+ assertEquals("#0d1b2a", colors["water_base"])+ assertEquals("#0d1b2a", colors["water_hybrid"])+ assertEquals("#24455f", colors["water_river_base"])+ assertEquals("#1e2b20", colors["landuse_park_base"])+ assertEquals("#1f2126", colors["landuse_other_base"])+ assertEquals("#22262c", colors["buildings_base"])+ assertEquals("#4a4f57", colors["boundaries_country_base"])+ assertEquals("#3a3e45", colors["roads_rail_base"])+ assertEquals("#2b2d33", colors["roads_runway_a_base"])+ // casing must win over the highway rule it also matches+ assertEquals("#111318", colors["roads_highway_casing_early_base"])+ assertEquals("#2b2e35", colors["roads_tunnels_motorway_base"])+ assertEquals("#464b54", colors["roads_highway_base"])+ assertEquals("#464b54", colors["roads_major_link_base"])+ assertEquals("#34383f", colors["roads_minor_base"])+ assertEquals("#26282e", colors["transit_whatever_base"])+ // background is kept as a single layer with the dark earth colour+ assertEquals("#1b1d22", colors["background"])+ assertFalse(colors.containsKey("background_base"))+ // non-colour paint keys survive untouched+ val root = json.parseToJsonElement(patched).jsonObject+ val waterPaint = root["layers"]!!.jsonArray+ .first { it.jsonObject["id"]!!.jsonPrimitive.content == "water_base" }+ .jsonObject["paint"]!!.jsonObject+ assertEquals("2", waterPaint["line-width"]!!.jsonPrimitive.content)+ }++ @Test+ fun `dark text colours split by label family`() {+ fun symbolLayer(id: String) =+ """{"id":"$id","type":"symbol","paint":{"text-color":"#000","text-halo-color":"#fff","text-size":12}}"""+ val layers = listOf(+ "places_locality", "places_country", "places_region", "places_subplace",+ "earth_label_islands", "water_label_ocean", "water_waterway_label",+ "roads_shields", "roads_labels_major", "address_label", "pois",+ )+ val style = """{"sources":{},"layers":[${layers.joinToString(",") { symbolLayer(it) }}]}"""+ val patched = patchStyleForHybrid(style, "base://", "hybrid://", dark = true)+ val root = json.parseToJsonElement(patched).jsonObject+ val byId = root["layers"]!!.jsonArray.associate { el ->+ val obj = el.jsonObject+ obj["id"]!!.jsonPrimitive.content to obj["paint"]!!.jsonObject+ }+ assertEquals("#e4e8ee", byId["places_locality_base"]!!["text-color"]!!.jsonPrimitive.content)+ assertEquals("#9aa0aa", byId["places_country_base"]!!["text-color"]!!.jsonPrimitive.content)+ assertEquals("#80868f", byId["places_region_base"]!!["text-color"]!!.jsonPrimitive.content)+ assertEquals("#6f8fce", byId["water_label_ocean_base"]!!["text-color"]!!.jsonPrimitive.content)+ assertEquals("#0d1b2a", byId["water_label_ocean_base"]!!["text-halo-color"]!!.jsonPrimitive.content)+ assertEquals("#c8ccd4", byId["roads_shields_base"]!!["text-color"]!!.jsonPrimitive.content)+ assertEquals("#b8bdc6", byId["address_label_base"]!!["text-color"]!!.jsonPrimitive.content)+ // named label families keep their own tints; halos stay near-black+ assertEquals("#9aa0aa", byId["earth_label_islands_base"]!!["text-color"]!!.jsonPrimitive.content)+ assertEquals("#101216", byId["places_locality_hybrid"]!!["text-halo-color"]!!.jsonPrimitive.content)+ assertEquals("12", byId["places_locality_base"]!!["text-size"]!!.jsonPrimitive.content)+ // the suppressed POI layer never reaches the output even in dark mode+ assertFalse(byId.keys.any { it.startsWith("pois") })+ }++ @Test+ fun `light mode keeps original paint and still splits layers`() {+ val patched = patchStyleForHybrid(styleWithLayers("water", "roads"), "b://", "h://", dark = false)+ val colors = darkColorsById(patched)+ assertEquals("#ffffff", colors["water_base"])+ assertEquals("#ffffff", colors["water_hybrid"])+ val root = json.parseToJsonElement(patched).jsonObject+ val sources = root["sources"]!!.jsonObject+ assertTrue(sources.containsKey("protomaps_base"))+ assertTrue(sources.containsKey("protomaps_hybrid"))+ // non-layer, non-source keys survive+ assertEquals("g", root["glyphs"]!!.jsonPrimitive.content)+ }+}
maps/src/test/java/com/vayunmathur/maps/ui/nav/Slice1Pass2NavComposeTest.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/ui/nav/Slice1Pass2NavComposeTest.kt b/maps/src/test/java/com/vayunmathur/maps/ui/nav/Slice1Pass2NavComposeTest.ktnew file mode 100644index 0000000000..d33b38f2c6--- /dev/null+++ b/maps/src/test/java/com/vayunmathur/maps/ui/nav/Slice1Pass2NavComposeTest.kt@@ -0,0 +1,191 @@+package com.vayunmathur.maps.ui.nav++import android.graphics.Canvas+import androidx.activity.ComponentActivity+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.AndroidComposeTestRule+import androidx.compose.ui.test.junit4.createAndroidComposeRule+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onAllNodesWithText+import androidx.compose.ui.test.onNodeWithText+import androidx.test.ext.junit.rules.ActivityScenarioRule+import com.vayunmathur.library.map.GeoPoint+import com.vayunmathur.maps.data.PostedLimit+import com.vayunmathur.maps.util.NavigationProgress+import com.vayunmathur.maps.util.RouteService+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.Test+import kotlin.test.assertTrue++/**+ * Slice 1/3 second pass (maps): the maneuver banner's full form (shield,+ * then-peek and lanes together), speed-widget limit states, and the+ * elevation chart's actual Canvas draw under a real activity window.+ */+@RunWith(RobolectricTestRunner::class)+class Slice1Pass2NavComposeTest {++ @get:Rule val rule = createComposeRule()++ private fun progress(step: Int = 0, dist: Double = 120.0) = NavigationProgress(+ snappedPosition = GeoPoint(-122.4, 37.7),+ segmentIndex = 0,+ currentStepIndex = step,+ distanceAlongRoute = 10.0,+ distanceRemaining = 500.0,+ distanceToNextManeuver = dist,+ fractionComplete = 0.1,+ etaEpochMs = 0L,+ courseOverGround = 0f,+ distanceOffRoute = 0.0,+ )++ private fun step(+ instruction: String,+ maneuver: RouteService.API.Maneuver = RouteService.API.Maneuver.TURN_LEFT,+ lanes: List<RouteService.API.Lane> = emptyList(),+ ) = RouteService.Step(+ distanceMeters = 120.0,+ staticDuration = kotlin.time.Duration.parse("1m"),+ polyline = emptyList(),+ navInstruction = RouteService.API.NavInstruction(maneuver, instruction),+ travelMode = RouteService.TravelMode.DRIVE,+ lanes = lanes,+ )++ @Test+ fun `maneuver banner shows shield then-peek and lanes together`() {+ val steps = listOf(+ step("Continue on I-280"),+ step(+ "Turn right onto US 101",+ lanes = listOf(+ RouteService.API.Lane(+ directions = listOf(+ RouteService.API.Maneuver.STRAIGHT,+ RouteService.API.Maneuver.TURN_RIGHT,+ ),+ active = true,+ ),+ RouteService.API.Lane(+ directions = listOf(RouteService.API.Maneuver.TURN_LEFT),+ active = false,+ ),+ ),+ ),+ step("Arrive at destination"),+ )+ rule.setContent { ManeuverBanner(progress = progress(), steps = steps) }+ // the banner leads with the NEXT maneuver (the current step is the+ // road being driven), peeks at the one after, and shields the ref+ rule.onNodeWithText("Turn right onto US 101").assertIsDisplayed()+ rule.onNodeWithText("US 101").assertIsDisplayed()+ rule.onNodeWithText("Arrive at destination", substring = true).assertIsDisplayed()+ }++ @Test+ fun `maneuver banner with no steps still shows the distance`() {+ rule.setContent { ManeuverBanner(progress = progress(dist = 42.0), steps = emptyList()) }+ rule.waitForIdle()+ assertTrue(+ rule.onAllNodesWithText("m", substring = true).fetchSemanticsNodes().isNotEmpty() ||+ rule.onAllNodesWithText("ft", substring = true).fetchSemanticsNodes().isNotEmpty(),+ )+ }++ @Test+ fun `speed widget shows limit and over-limit states`() {+ val stage = androidx.compose.runtime.mutableIntStateOf(0)+ rule.setContent {+ when (stage.intValue) {+ 0 -> SpeedWidget(+ speedMps = 10f,+ postedLimit = PostedLimit(kmh = 50, mph = 31, displayIsMph = false),+ defaultMph = false,+ )+ 1 -> SpeedWidget(+ speedMps = 30f, // 108 km/h, well over the 50 limit+ postedLimit = PostedLimit(kmh = 50, mph = 31, displayIsMph = false),+ defaultMph = false,+ )+ 2 -> SpeedWidget(speedMps = 10f, postedLimit = null, defaultMph = true)+ else -> SpeedWidget(+ speedMps = 0f,+ postedLimit = PostedLimit(kmh = 30, mph = 19, displayIsMph = true),+ defaultMph = false,+ darkBasemap = true,+ )+ }+ }+ rule.onNodeWithText("36").assertIsDisplayed()+ rule.onNodeWithText("50").assertIsDisplayed()+ rule.runOnIdle { stage.intValue = 1 }+ rule.onNodeWithText("108").assertIsDisplayed()+ rule.runOnIdle { stage.intValue = 2 }+ rule.onNodeWithText("22").assertIsDisplayed()+ rule.runOnIdle { stage.intValue = 3 }+ rule.onNodeWithText("19").assertIsDisplayed()+ }++ @Test+ fun `lane guidance renders nothing without lanes and cells with`() {+ val stage = androidx.compose.runtime.mutableIntStateOf(0)+ rule.setContent {+ if (stage.intValue == 0) {+ LaneGuidance(lanes = emptyList())+ } else {+ LaneGuidance(+ lanes = listOf(+ RouteService.API.Lane(+ directions = listOf(+ RouteService.API.Maneuver.STRAIGHT,+ RouteService.API.Maneuver.TURN_LEFT,+ RouteService.API.Maneuver.TURN_RIGHT,+ ),+ active = true,+ ),+ RouteService.API.Lane(+ directions = listOf(RouteService.API.Maneuver.MERGE),+ active = false,+ ),+ ),+ )+ }+ }+ rule.waitForIdle()+ rule.runOnIdle { stage.intValue = 1 }+ rule.waitForIdle()+ }+}++@RunWith(RobolectricTestRunner::class)+class Slice1Pass2ElevationDrawTest {++ @get:Rule+ val rule: AndroidComposeTestRule<ActivityScenarioRule<ComponentActivity>, ComponentActivity> =+ createAndroidComposeRule()++ @Test+ fun `elevation chart canvas actually draws under an activity`() {+ rule.setContent {+ ElevationChart(+ profile = listOf(+ RouteService.ElevationPoint(0.0, 100.0),+ RouteService.ElevationPoint(500.0, 220.0),+ RouteService.ElevationPoint(1000.0, 140.0),+ ),+ ascentMeters = 130.0,+ descentMeters = 85.0,+ )+ }+ rule.onNodeWithText("Elevation").assertIsDisplayed()+ // Force a real draw pass so the Canvas draw block executes (the+ // Robolectric compose rule alone never rasterizes).+ rule.runOnUiThread {+ rule.activity.window.decorView.draw(Canvas())+ }+ rule.waitForIdle()+ }+}
maps/src/test/java/com/vayunmathur/maps/ui/settings/Slice1Pass2SettingsTest.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/ui/settings/Slice1Pass2SettingsTest.kt b/maps/src/test/java/com/vayunmathur/maps/ui/settings/Slice1Pass2SettingsTest.ktnew file mode 100644index 0000000000..5e20758aaa--- /dev/null+++ b/maps/src/test/java/com/vayunmathur/maps/ui/settings/Slice1Pass2SettingsTest.kt@@ -0,0 +1,111 @@+package com.vayunmathur.maps.ui.settings++import android.app.Application+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.hasText+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.compose.ui.test.performScrollTo+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.library.util.DataStoreUtils+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.maps.Route+import com.vayunmathur.maps.util.MapOverlayWorker+import com.vayunmathur.maps.util.MapSettingsViewModel+import kotlinx.coroutines.runBlocking+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/**+ * Slice 1/3 second pass (maps): [MapSettingsPage]'s overlay-status line in+ * its pending/applied/current states and the saved-places re-tap behaviour,+ * beyond the first pass's render checks.+ */+@RunWith(RobolectricTestRunner::class)+class Slice1Pass2SettingsTest {++ @get:Rule val rule = createComposeRule()++ private val app: Application get() = ApplicationProvider.getApplicationContext()++ private fun setOverlay(applied: Long, pending: Long, lastCheck: Long) = runBlocking {+ val ds = DataStoreUtils.getInstance(app)+ ds.setLong(MapOverlayWorker.KEY_APPLIED_SEQ, applied)+ ds.setLong(MapOverlayWorker.KEY_PENDING_BYTES, pending)+ ds.setLong(MapOverlayWorker.KEY_LAST_CHECK, lastCheck)+ }++ private fun awaitText(text: String, timeoutMs: Long = 10_000) {+ val deadline = System.currentTimeMillis() + timeoutMs+ var found = false+ while (!found && System.currentTimeMillis() < deadline) {+ rule.waitForIdle()+ found = rule.onAllNodes(hasText(text)).fetchSemanticsNodes().isNotEmpty()+ if (!found) Thread.sleep(50)+ }+ assertTrue(found, "never saw text: $text")+ }++ @Test+ fun `overlay status line covers pending applied and current`() {+ setOverlay(applied = 7, pending = 5_000_000, lastCheck = 99)+ val vm = MapSettingsViewModel(app)+ val stack = NavBackStack(arrayOf<Route>(Route.SettingsPage))+ rule.setContent { MapSettingsPage(backStack = stack, viewModel = vm) }+ rule.waitForIdle()+ rule.onNodeWithText("Check for map updates").performScrollTo().assertIsDisplayed()+ awaitText("5 MB update downloading")++ setOverlay(applied = 7, pending = 0, lastCheck = 99)+ awaitText("Map data update 7 installed")++ setOverlay(applied = 0, pending = 0, lastCheck = 99)+ awaitText("Map data is up to date")++ // leave the shared store as found for other tests+ setOverlay(applied = 0, pending = 0, lastCheck = 0)+ }++ @Test+ fun `saved places row replaces instead of stacking`() {+ val vm = MapSettingsViewModel(app)+ val stack = NavBackStack(arrayOf<Route>(Route.SettingsPage))+ rule.setContent { MapSettingsPage(backStack = stack, viewModel = vm) }+ rule.waitForIdle()+ rule.onNodeWithText("Saved places").performScrollTo().performClick()+ assertEquals(Route.SavedPlacesPage, stack.backStack.last())+ val sizeAfterFirst = stack.backStack.size+ rule.onNodeWithText("Saved places").performClick()+ assertEquals(sizeAfterFirst, stack.backStack.size)+ assertEquals(Route.SavedPlacesPage, stack.backStack.last())+ }++ @Test+ fun `voice switch round-trips through the view model`() {+ val vm = MapSettingsViewModel(app)+ val originalVoice = vm.voiceGuidance.value+ val stack = NavBackStack(arrayOf<Route>(Route.SettingsPage))+ rule.setContent { MapSettingsPage(backStack = stack, viewModel = vm) }+ rule.waitForIdle()+ rule.onNodeWithText("Voice guidance").performScrollTo().performClick()+ // the write goes through the VM's DataStore flow, so poll for the flip+ val deadline = System.currentTimeMillis() + 10_000+ while (vm.voiceGuidance.value == originalVoice && System.currentTimeMillis() < deadline) {+ rule.waitForIdle()+ Thread.sleep(50)+ }+ assertEquals(!originalVoice, vm.voiceGuidance.value)+ vm.setVoiceGuidance(originalVoice)+ val restoreDeadline = System.currentTimeMillis() + 10_000+ while (vm.voiceGuidance.value != originalVoice && System.currentTimeMillis() < restoreDeadline) {+ rule.waitForIdle()+ Thread.sleep(50)+ }+ assertEquals(originalVoice, vm.voiceGuidance.value)+ }+}