maps: add tests for slice 1/3 (map/nav/google/streetview/transit/theme/settings)
- Commit
bacec6cc6d3907f981f346262358e3b978484a83- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-06 17:54 UTC (29 days ago)
- Parents
babbfcc
Slice coverage 14.3% -> 72.9% (merged, instructions 18422/25279). 20 test files, ~150 tests: JVM unit (GoogleResponse, ReviewsWebParser, models, PoiDataSource via httpGet/httpWarm seams, StreetViewDataSource via httpGet/httpGetBytes seams, Transitous via fetchStoptimes seam, MapStylePatch, RouteOverlayBuilder, MapSurfaceHelpers, MapPinFeatures, MapChromeState, RoadShield, gtfsModeToMarkerIcon, StreetView math, MapChromeMetrics, rail fan math) + Robolectric Compose (nav chrome, map chrome, settings incl. DataStore round-trips, streetview arrows/peg/viewer, effect disabled paths, cold-start camera). Seams are behavior-preserving with live-network defaults. Untestable remainder (JVM+emulator): MapSurface (Vulkan renderer), StreetView viewer sphere branch (GLES), WebReviewsFetcher (Chromium), TransitVehicles 1Hz loop + MapInitialCamera live-fix path, RailLines composable (pack+native), MapLayers init (native graph), pickVehicle/CPU paths (internal Projection). (cherry picked from commit 4726966d5ed2cbead7c78f483410a4c180bda2ac)
Diff
maps/src/main/java/com/vayunmathur/maps/data/google/GooglePoiDataSource.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/data/google/GooglePoiDataSource.kt b/maps/src/main/java/com/vayunmathur/maps/data/google/GooglePoiDataSource.ktindex b3bdd40412..c56c6a54f5 100644--- a/maps/src/main/java/com/vayunmathur/maps/data/google/GooglePoiDataSource.kt+++ b/maps/src/main/java/com/vayunmathur/maps/data/google/GooglePoiDataSource.kt@@ -125,7 +125,7 @@ object GooglePoiDataSource { val pb = buildSearchPb(name, lat, lon) val url = "$SEARCH_ENDPOINT&q=${name.enc()}&pb=${pb.enc()}" // A transport error or a non-2xx never became an answer.- val body = get(url) ?: return@withContext Outcome.Failed+ val body = httpGet(url) ?: return@withContext Outcome.Failed // Nor did a body we cannot parse: a 200 that does not decode is far more // likely an interstitial (consent, captcha, rate limit) than a genuine // "no such place".@@ -149,15 +149,30 @@ object GooglePoiDataSource { private suspend fun warmSession() { if (sessionWarmed) return runCatching {- NetworkClient.performRequest(- url = SESSION_WARM_URL,- headers = REQUEST_HEADERS + ("Accept" to "text/html,application/xhtml+xml"),- useSystemTrust = true,- )+ httpWarm(SESSION_WARM_URL) } sessionWarmed = true } + /**+ * Test seam for the search GET: returns the body text, or null on any non-2xx /+ * transport error. Defaults to the live network ([get]); tests replace it with+ * canned payloads so the parse/selection logic is verifiable without network.+ */+ internal var httpGet: (suspend (String) -> String?) = { get(it) }++ /**+ * Test seam for the session-warm GET. Routed through [httpGet] (rather than+ * straight at [NetworkClient]) so tests never touch the network at all.+ */+ internal var httpWarm: (suspend (String) -> String?) = {+ NetworkClient.performRequest(+ url = it,+ headers = REQUEST_HEADERS + ("Accept" to "text/html,application/xhtml+xml"),+ useSystemTrust = true,+ ).body+ }+ /** GET returning the body text, or null on any non-2xx / transport error. * `useSystemTrust` because google.com is an arbitrary external host, not one * of the app's pinned first-party endpoints. */
maps/src/main/java/com/vayunmathur/maps/data/google/StreetViewDataSource.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/data/google/StreetViewDataSource.kt b/maps/src/main/java/com/vayunmathur/maps/data/google/StreetViewDataSource.ktindex 39449f686b..9a74ce5769 100644--- a/maps/src/main/java/com/vayunmathur/maps/data/google/StreetViewDataSource.kt+++ b/maps/src/main/java/com/vayunmathur/maps/data/google/StreetViewDataSource.kt@@ -105,6 +105,14 @@ object StreetViewDataSource { private const val FULL_CIRCLE_DEG = 360.0 private const val HALF_CIRCLE_DEG = 180.0 + /**+ * Test seams: metadata GET (body text or null) and tile GET (bytes or null).+ * Defaults hit the live network; tests replace them with canned payloads so+ * the parse/selection logic is verifiable without network.+ */+ internal var httpGet: (suspend (String) -> String?) = { getText(it) }+ internal var httpGetBytes: (suspend (String) -> ByteArray?) = { tileBytes(it) }+ // Bounded LRU (access-ordered) of resolved metadata, keyed by pano id and by a // rounded lat/lng probe. Stores null too (negative cache) so a spot with no // imagery isn't refetched on every reselect. Guarded by `synchronized`.@@ -143,13 +151,13 @@ object StreetViewDataSource { private suspend fun fetchNearest(lat: Double, lng: Double): StreetViewPano? = withContext(Dispatchers.IO) { val url = META_URL.replace("{LAT}", lat.toString()).replace("{LNG}", lng.toString())- val body = getText(url) ?: return@withContext null+ val body = httpGet(url) ?: return@withContext null parsePano(body, lat, lng) } private suspend fun fetchPano(panoId: String): StreetViewPano? = withContext(Dispatchers.IO) {- val body = getText(PANO_URL.replace("{PANOID}", panoId)) ?: return@withContext null+ val body = httpGet(PANO_URL.replace("{PANOID}", panoId)) ?: return@withContext null // A by-id fetch has no query point; the parser reads the real position // from the response and only uses the fallback when it's missing. parsePano(body, 0.0, 0.0).takeIf { it != null && (it.lat != 0.0 || it.lng != 0.0) }@@ -216,6 +224,10 @@ object StreetViewDataSource { .replace("{X}", x.toString()) .replace("{Y}", y.toString()) .replace("{Z}", zoom.toString())+ return httpGetBytes(url)+ }++ private suspend fun tileBytes(url: String): ByteArray? { val (status, bytes) = runCatching { NetworkClient.performRequestBytes(url = url, headers = REQUEST_HEADERS, useSystemTrust = true) }.getOrNull() ?: return null
maps/src/main/java/com/vayunmathur/maps/data/transit/TransitousDataSource.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/data/transit/TransitousDataSource.kt b/maps/src/main/java/com/vayunmathur/maps/data/transit/TransitousDataSource.ktindex 7b8b774a7d..85740e0940 100644--- a/maps/src/main/java/com/vayunmathur/maps/data/transit/TransitousDataSource.kt+++ b/maps/src/main/java/com/vayunmathur/maps/data/transit/TransitousDataSource.kt@@ -70,6 +70,19 @@ object TransitousDataSource { override fun removeEldestEntry(eldest: MutableMap.MutableEntry<String, Cached<List<Departure>>>) = size > 32 } + /**+ * Test seam: fetch the raw board DTO for [stopId] (null on any failure).+ * Defaults to the live network; tests replace it with canned wire payloads+ * so the MOTIS→app mapping is verifiable without network.+ */+ internal var fetchStoptimes: (suspend (String) -> MotisStoptimes?) = { stopId ->+ runCatching {+ val url = "$BASE_URL/stoptimes" ++ "?stopId=${enc(stopId)}&n=$DEPARTURE_COUNT"+ NetworkClient.getJson<MotisStoptimes>(url, REQUEST_HEADERS)+ }.getOrNull()+ }+ /** * Live departures for [stopId]. Never throws — empty on failure. Cached for * [DEPARTURES_TTL_MS] on success and only [FAILURE_TTL_MS] on failure; pass@@ -81,7 +94,9 @@ object TransitousDataSource { departuresCache[stopId]?.let { if (it.isFresh(DEPARTURES_TTL_MS)) return it.value } } }- val fetched = runCatching { fetchDepartures(stopId) }+ val fetched = runCatching {+ fetchStoptimes(stopId)?.stopTimes?.mapNotNull { it.toDeparture() }.orEmpty()+ } val deps = fetched.getOrDefault(emptyList()) synchronized(departuresCache) { departuresCache[stopId] = Cached(deps, fetched.isSuccess) } return deps
maps/src/test/java/com/vayunmathur/maps/data/google/GooglePoiDataSourceSlice1Test.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/data/google/GooglePoiDataSourceSlice1Test.kt b/maps/src/test/java/com/vayunmathur/maps/data/google/GooglePoiDataSourceSlice1Test.ktnew file mode 100644index 0000000000..8e97109ee9--- /dev/null+++ b/maps/src/test/java/com/vayunmathur/maps/data/google/GooglePoiDataSourceSlice1Test.kt@@ -0,0 +1,356 @@+package com.vayunmathur.maps.data.google++import kotlinx.coroutines.runBlocking+import kotlinx.serialization.json.JsonArray+import kotlinx.serialization.json.JsonElement+import kotlinx.serialization.json.JsonNull+import kotlinx.serialization.json.JsonPrimitive+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Slice 1/3 (maps): [GooglePoiDataSource] result selection + parsing, driven+ * through the [GooglePoiDataSource.httpGet]/`httpWarm` seams with canned+ * positional-JSON payloads — no network.+ *+ * The payloads mirror the calibrated shapes documented in the source (RESULTS+ * list vs SINGLE geocoded node, place node at entry[1]). The point under test+ * is the defensive contract: near matches win, far ones are refused, and every+ * field degrades to null rather than throwing.+ */+class GooglePoiDataSourceSlice1Test {++ /** Sparse nested-array builder: set(1, 11, value) then read back as JSON. */+ private class Payload {+ private val root = mutableListOf<Any?>()++ fun set(vararg path: Int, value: JsonElement) {+ var cur = root+ for (i in path.dropLast(1)) {+ while (cur.size <= i) cur.add(null)+ @Suppress("UNCHECKED_CAST")+ val nxt = (cur[i] as? MutableList<Any?>)+ ?: mutableListOf<Any?>().also { cur[i] = it }+ cur = nxt+ }+ val last = path.last()+ while (cur.size <= last) cur.add(null)+ cur[last] = value+ }++ private fun toEl(v: Any?): JsonElement = when (v) {+ null -> JsonNull+ is JsonElement -> v+ is List<*> -> JsonArray(v.map { toEl(it) })+ else -> error("unexpected $v")+ }++ fun node(): JsonElement = toEl(root)++ /** Wrap place [node] as a result entry (place node at [1]). */+ fun entryOf(node: JsonElement): JsonElement =+ JsonArray(listOf(JsonNull, node))++ /** A guarded search body whose RESULTS list holds [entries]. */+ fun searchBody(vararg entries: JsonElement): String {+ set(64, value = JsonArray(entries.toList()))+ return body()+ }++ fun body(): String = ")]}'\n${toEl(root)}"+ }++ /** A place node (NAME at [11], LAT at [9,2], …) for the query point by default. */+ private fun place(+ name: String = "Slice1 Cafe",+ lat: Double = 37.7749,+ lng: Double = -122.4194,+ extra: Payload.() -> Unit = {},+ ): JsonElement = Payload().apply {+ set(11, value = JsonPrimitive(name))+ set(9, 2, value = JsonPrimitive(lat))+ set(9, 3, value = JsonPrimitive(lng))+ extra()+ }.node()++ private fun entry(node: JsonElement): JsonElement =+ JsonArray(listOf(JsonNull, node))++ private val defaultGet = GooglePoiDataSource.httpGet+ private val defaultWarm = GooglePoiDataSource.httpWarm++ private fun runWithFetch(+ searchBody: String?,+ block: suspend (requested: MutableList<String>) -> Unit,+ ) = runBlocking {+ val requested = mutableListOf<String>()+ GooglePoiDataSource.httpWarm = { "" }+ GooglePoiDataSource.httpGet = { url -> requested += url; searchBody }+ try {+ block(requested)+ } finally {+ GooglePoiDataSource.httpGet = defaultGet+ GooglePoiDataSource.httpWarm = defaultWarm+ }+ }++ @Test+ fun `blank names never reach the network`() = runWithFetch("[]") { requested ->+ assertNull(GooglePoiDataSource.fetch(" ", 37.0, -122.0))+ assertTrue(requested.isEmpty())+ }++ @Test+ fun `a full entry parses every field`() {+ val node = place(extra = {+ set(4, 7, value = JsonPrimitive(4.5))+ set(4, 8, value = JsonPrimitive(230))+ set(4, 2, value = JsonPrimitive("$10–20"))+ set(7, 0, value = JsonPrimitive("https://cafe.example"))+ set(178, 0, 0, value = JsonPrimitive("+14155550123"))+ set(203, 1, 4, 0, value = JsonPrimitive("Open · Closes 9 PM"))+ set(13, 0, value = JsonPrimitive("Cafe"))+ set(32, 1, 1, value = JsonPrimitive(" A sunny corner spot. "))+ set(142, 1, 0, 1, 0, 0, value = JsonPrimitive("\"Best oat latte.\""))+ set(10, value = JsonPrimitive("0x808580:0x808581"))+ })+ runWithFetch(Payload().searchBody(entry(node))) {+ val info = assertNotNull(GooglePoiDataSource.fetch("Slice1 Cafe", 37.7749, -122.4194))+ assertEquals(4.5, info.rating)+ assertEquals(230, info.reviewCount)+ assertEquals("$10–20", info.priceText)+ assertEquals(2, info.priceLevel)+ assertEquals("https://cafe.example", info.website)+ assertEquals("+14155550123", info.phone)+ assertEquals(true, info.openNow)+ assertEquals("Open · Closes 9 PM", info.statusText)+ assertEquals("Cafe", info.category)+ assertEquals("A sunny corner spot.", info.editorialSummary)+ assertEquals("Best oat latte.", info.featuredReview)+ assertEquals("0x808580:0x808581", info.featureId)+ }+ }++ @Test+ fun `the nearest entry inside the match radius wins`() {+ val near = entry(place(name = "Slice1 Near", lat = 37.7750, lng = -122.4195) {+ set(4, 7, value = JsonPrimitive(4.0))+ })+ val far = entry(place(name = "Slice1 Far", lat = 37.7900, lng = -122.4194) {+ set(4, 7, value = JsonPrimitive(1.0))+ })+ runWithFetch(Payload().searchBody(far, near)) {+ val info = assertNotNull(GooglePoiDataSource.fetch("Slice1 Pick", 37.7749, -122.4194))+ assertEquals(4.0, info.rating, "the near entry must win over the far one")+ }+ }++ @Test+ fun `no close match is a negative-cacheable no-match`() {+ val far = entry(place(name = "Slice1 Elsewhere", lat = 38.0, lng = -122.0) {+ set(4, 7, value = JsonPrimitive(4.0))+ })+ runWithFetch(Payload().searchBody(far, far)) { requested ->+ assertNull(GooglePoiDataSource.fetch("Slice1 Nowhere", 37.7749, -122.4194))+ assertNull(GooglePoiDataSource.fetch("Slice1 Nowhere", 37.7749, -122.4194))+ assertEquals(1, requested.size, "a no-match must be cached, not refetched")+ }+ }++ @Test+ fun `a lone far entry is still accepted`() {+ val lone = entry(place(name = "Slice1 Lone", lat = 38.5, lng = -121.0) {+ set(4, 7, value = JsonPrimitive(3.5))+ })+ runWithFetch(Payload().searchBody(lone)) {+ val info = assertNotNull(GooglePoiDataSource.fetch("Slice1 Lone", 37.7749, -122.4194))+ assertEquals(3.5, info.rating)+ }+ }++ @Test+ fun `a failed fetch is not cached and retries`() = runWithFetch(null) { requested ->+ assertNull(GooglePoiDataSource.fetch("Slice1 Down", 37.0, -122.0))+ assertNull(GooglePoiDataSource.fetch("Slice1 Down", 37.0, -122.0))+ assertEquals(2, requested.size, "failures must not poison the cache")+ }++ @Test+ fun `a name-only entry is dropped by the signal gate`() {+ runWithFetch(Payload().searchBody(entry(place())) ) {+ assertNull(GooglePoiDataSource.fetch("Slice1 Bare", 37.7749, -122.4194))+ }+ }++ @Test+ fun `fuel price reads the shared slot only for gas stations`() {+ fun fuelled(kind: String?, tag: String) = entry(place(name = "Slice1 Fuel $tag") {+ set(88, 1, value = kind?.let { JsonPrimitive(it) } ?: JsonNull)+ set(88, 0, value = JsonPrimitive("$6.20/Regular"))+ set(4, 7, value = JsonPrimitive(4.0))+ })+ runWithFetch(Payload().searchBody(fuelled("SearchResult.TYPE_GAS_STATION", "gas"))) {+ val info = assertNotNull(GooglePoiDataSource.fetch("Slice1 Gas", 37.7749, -122.4194))+ assertEquals(FuelPrice("$6.20", "Regular"), info.fuelPrice)+ }+ runWithFetch(Payload().searchBody(fuelled("SearchResult.TYPE_RESTAURANT", "food"))) {+ val info = assertNotNull(GooglePoiDataSource.fetch("Slice1 Bistro", 37.7749, -122.4194))+ assertNull(info.fuelPrice, "a restaurant tagline must not become a fuel price")+ }+ }++ @Test+ fun `hours read today only with an optional note`() {+ val node = place(extra = {+ // HOURS_203 day: [name, _, _, [[time]], _, _, [_, note]].+ set(+ 203, 0, value = JsonArray(+ listOf(+ JsonArray(+ listOf(+ JsonPrimitive("Tuesday"),+ JsonNull, JsonNull,+ JsonArray(listOf(JsonArray(listOf(JsonPrimitive("6 AM–10 PM"))))),+ JsonNull, JsonNull,+ JsonArray(listOf(JsonNull, JsonPrimitive("Holiday hours"))),+ ),+ ),+ ),+ ),+ )+ set(4, 7, value = JsonPrimitive(4.0))+ })+ runWithFetch(Payload().searchBody(entry(node))) {+ val info = assertNotNull(GooglePoiDataSource.fetch("Slice1 Hours", 37.7749, -122.4194))+ assertEquals(listOf("Tuesday: 6 AM–10 PM · Holiday hours"), info.hours)+ }+ }++ @Test+ fun `photos dedupe resize and drop non-google urls`() {+ fun hero(url: String) = JsonArray(+ listOf(JsonNull, JsonNull, JsonNull, JsonNull, JsonNull, JsonNull, JsonArray(listOf(JsonPrimitive(url)))),+ )+ val node = place(extra = {+ set(+ 72, 0, value = JsonArray(+ listOf(+ hero("https://lh3.googleusercontent.com/p/1=w100-h100-k"),+ hero("https://lh3.googleusercontent.com/p/1=w100-h100-k"),+ hero("https://other.example/x.jpg"),+ ),+ ),+ )+ set(4, 7, value = JsonPrimitive(4.0))+ })+ runWithFetch(Payload().searchBody(entry(node))) {+ val info = assertNotNull(GooglePoiDataSource.fetch("Slice1 Photos", 37.7749, -122.4194))+ assertEquals(+ listOf("https://lh3.googleusercontent.com/p/1=w500-h350"),+ info.photoUrls,+ )+ }+ }++ @Test+ fun `popular times parse the day histogram`() {+ val node = place(extra = {+ set(+ 84, value = JsonArray(+ listOf(+ JsonArray(+ listOf(+ JsonArray(+ listOf(+ JsonPrimitive(2),+ JsonArray(+ listOf(+ JsonArray(listOf(JsonPrimitive(9), JsonPrimitive(80))),+ JsonArray(listOf(JsonPrimitive(10), JsonPrimitive(95))),+ ),+ ),+ ),+ ),+ ),+ ),+ ),+ ),+ )+ set(4, 7, value = JsonPrimitive(4.0))+ })+ runWithFetch(Payload().searchBody(entry(node))) {+ val info = assertNotNull(GooglePoiDataSource.fetch("Slice1 Busy", 37.7749, -122.4194))+ assertEquals(+ PoiPopularTimes(+ listOf(+ PoiDayBusyness(+ 2,+ listOf(PoiHourBusyness(9, 80), PoiHourBusyness(10, 95)),+ ),+ ),+ ),+ info.popularTimes,+ )+ }+ }++ @Test+ fun `status text decides open-now with closed words first`() = runBlocking {+ suspend fun fetchStatus(name: String, status: String): GooglePoiInfo? {+ val node = place(name = name, extra = {+ set(203, 1, 4, 0, value = JsonPrimitive(status))+ set(4, 7, value = JsonPrimitive(4.0))+ })+ GooglePoiDataSource.httpWarm = { "" }+ GooglePoiDataSource.httpGet = { Payload().searchBody(entry(node)) }+ try {+ return GooglePoiDataSource.fetch(name, 37.7749, -122.4194)+ } finally {+ GooglePoiDataSource.httpGet = defaultGet+ GooglePoiDataSource.httpWarm = defaultWarm+ }+ }+ assertEquals(true, fetchStatus("Slice1 StA", "Open · Closes 9 PM")?.openNow)+ assertEquals(false, fetchStatus("Slice1 StB", "Closed · Opens 8 AM Wed")?.openNow)+ assertEquals(false, fetchStatus("Slice1 StC", "Temporarily closed")?.openNow)+ assertNull(fetchStatus("Slice1 StD", "See hours")?.openNow)+ }++ @Test+ fun `price symbols count dollar signs when no amount is present`() = runBlocking {+ suspend fun fetchLevel(name: String, price: String): Int? {+ val node = place(name = name, extra = {+ set(4, 2, value = JsonPrimitive(price))+ set(4, 7, value = JsonPrimitive(4.0))+ })+ GooglePoiDataSource.httpWarm = { "" }+ GooglePoiDataSource.httpGet = { Payload().searchBody(entry(node)) }+ try {+ return GooglePoiDataSource.fetch(name, 37.7749, -122.4194)?.priceLevel+ } finally {+ GooglePoiDataSource.httpGet = defaultGet+ GooglePoiDataSource.httpWarm = defaultWarm+ }+ }+ assertEquals(3, fetchLevel("Slice1 PrA", "$$$"))+ assertEquals(1, fetchLevel("Slice1 PrB", "$5"))+ assertEquals(4, fetchLevel("Slice1 PrC", "$40 tasting menu"))+ assertNull(fetchLevel("Slice1 PrD", "Free"))+ }++ @Test+ fun `a single geocoded node resolves like a list entry`() {+ // SINGLE = [0,1,0,14]: root[0][1][0][14] carries the place node itself.+ val node = place(name = "Slice1 Single", extra = {+ set(4, 7, value = JsonPrimitive(4.2))+ })+ val body = Payload().apply { set(0, 1, 0, 14, value = node) }.body()+ runWithFetch(body) {+ val info = assertNotNull(GooglePoiDataSource.fetch("Slice1 Single", 37.7749, -122.4194))+ assertEquals(4.2, info.rating)+ }+ }+}
maps/src/test/java/com/vayunmathur/maps/data/google/GooglePoiModelsSlice1Test.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/data/google/GooglePoiModelsSlice1Test.kt b/maps/src/test/java/com/vayunmathur/maps/data/google/GooglePoiModelsSlice1Test.ktnew file mode 100644index 0000000000..30654c31be--- /dev/null+++ b/maps/src/test/java/com/vayunmathur/maps/data/google/GooglePoiModelsSlice1Test.kt@@ -0,0 +1,89 @@+package com.vayunmathur.maps.data.google++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Slice 1/3 (maps): the [GooglePoiInfo]/[GooglePoiPin] model layer —+ * in particular [GooglePoiInfo.isEmpty], the gate that decides whether the+ * place sheet shows an enrichment section at all.+ */+class GooglePoiModelsSlice1Test {++ @Test+ fun `a blank info is empty and any signal clears it`() {+ assertTrue(GooglePoiInfo().isEmpty)+ assertFalse(GooglePoiInfo(rating = 4.5).isEmpty)+ assertFalse(GooglePoiInfo(reviewCount = 10).isEmpty)+ assertFalse(GooglePoiInfo(priceText = "$$").isEmpty)+ assertFalse(GooglePoiInfo(website = "https://x.example").isEmpty)+ assertFalse(GooglePoiInfo(phone = "1").isEmpty)+ assertFalse(GooglePoiInfo(statusText = "Open").isEmpty)+ assertFalse(GooglePoiInfo(editorialSummary = "Nice").isEmpty)+ assertFalse(GooglePoiInfo(featuredReview = "Great").isEmpty)+ assertFalse(GooglePoiInfo(fuelPrice = FuelPrice("$6.20", "Regular")).isEmpty)+ assertFalse(GooglePoiInfo(hours = listOf("Tue: 9-5")).isEmpty)+ assertFalse(GooglePoiInfo(photoUrls = listOf("https://x")).isEmpty)+ assertFalse(+ GooglePoiInfo(reviews = listOf(GoogleReview("A", null, 5, null, null))).isEmpty,+ )+ assertFalse(+ GooglePoiInfo(popularTimes = PoiPopularTimes(listOf(PoiDayBusyness(1, emptyList())))).isEmpty,+ )+ }++ @Test+ fun `fields that never render alone do not clear emptiness`() {+ // openNow, category, priceLevel and featureId carry no section of their+ // own, so an info with only those is still nothing worth showing.+ assertTrue(GooglePoiInfo(openNow = true).isEmpty)+ assertTrue(GooglePoiInfo(category = "Cafe").isEmpty)+ assertTrue(GooglePoiInfo(priceLevel = 2).isEmpty)+ assertTrue(GooglePoiInfo(featureId = "0x1:0x2").isEmpty)+ }++ @Test+ fun `review and busyness models hold their documented ranges`() {+ val review = GoogleReview(+ author = "A",+ authorPhoto = null,+ rating = 5,+ relativeTime = "yesterday",+ text = "Good",+ photos = listOf("https://x"),+ )+ assertEquals("A", review.author)+ assertEquals(emptyList(), GoogleReview("B", null, 1, null, null).photos)++ val hour = PoiHourBusyness(hour = 9, occupancy = 80)+ assertEquals(9, hour.hour)+ assertEquals(PoiDayBusyness(dayOfWeek = 2, hours = listOf(hour)), PoiDayBusyness(2, listOf(hour)))+ }++ @Test+ fun `poi sections cover details photos and reviews`() {+ assertEquals(3, PoiSection.entries.size)+ assertTrue(PoiSection.entries.containsAll(listOf(PoiSection.DETAILS, PoiSection.PHOTOS, PoiSection.REVIEWS)))+ }++ @Test+ fun `a pin carries the minimum a map marker needs`() {+ val pin = GooglePoiPin(id = "p1", name = "Cafe", lat = 37.0, lng = -122.0)+ assertEquals("p1", pin.id)+ assertEquals("Cafe", pin.name)+ assertNull(pin.category)+ assertNull(pin.rating)+ assertEquals(0.0, pin.prominence)+ // Data-class copy keeps identity while restyling.+ assertEquals("Diner", pin.copy(name = "Diner").name)+ assertEquals(pin.id, pin.copy(name = "Diner").id)+ }++ @Test+ fun `fuel price keeps google formatted text verbatim`() {+ assertEquals(FuelPrice("$6.20", "Regular"), FuelPrice(price = "$6.20", grade = "Regular"))+ }+}
maps/src/test/java/com/vayunmathur/maps/data/google/GoogleResponseSlice1Test.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/data/google/GoogleResponseSlice1Test.kt b/maps/src/test/java/com/vayunmathur/maps/data/google/GoogleResponseSlice1Test.ktnew file mode 100644index 0000000000..f6254f88d2--- /dev/null+++ b/maps/src/test/java/com/vayunmathur/maps/data/google/GoogleResponseSlice1Test.kt@@ -0,0 +1,87 @@+package com.vayunmathur.maps.data.google++import kotlinx.serialization.json.Json+import kotlinx.serialization.json.JsonArray+import kotlinx.serialization.json.JsonNull+import kotlinx.serialization.json.JsonPrimitive+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Slice 1/3 (maps): [GoogleResponse] guard-stripping/parsing and the null-safe+ * positional accessors every Google scrape builds on.+ *+ * The whole point of these helpers is graceful degradation — a Google-side+ * reshape turns fields null instead of crashing the sheet — so the tests pin+ * the null paths as hard as the happy paths.+ */+class GoogleResponseSlice1Test {++ @Test+ fun `strip removes every known XSSI guard form`() {+ assertEquals("[1,2]", GoogleResponse.strip(")]}'\n[1,2]"))+ assertEquals("[1,2]", GoogleResponse.strip(")]}',\n[1,2]"))+ assertEquals("[1,2]", GoogleResponse.strip(")]}'[1,2]"))+ assertEquals("[1,2]", GoogleResponse.strip(")]}[1,2]"))+ assertEquals("[1,2]", GoogleResponse.strip("while(1);[1,2]"))+ assertEquals("[1,2]", GoogleResponse.strip("for(;;);[1,2]"))+ }++ @Test+ fun `strip leaves a guardless body alone`() {+ assertEquals("[1,2]", GoogleResponse.strip("[1,2]"))+ assertEquals("", GoogleResponse.strip(""))+ }++ @Test+ fun `parseOrNull parses a guarded body and rejects garbage`() {+ val el = GoogleResponse.parseOrNull(")]}'\n[[\"a\",1],null]")+ assertTrue(el is JsonArray, "expected an array, got $el")+ assertNull(GoogleResponse.parseOrNull(")]}'\nnot json {{{"))+ assertNull(GoogleResponse.parseOrNull(""))+ }++ @Test+ fun `at walks a positional path and degrades to null`() {+ val root = Json.parseToJsonElement("[[\"a\",[1,2]],{\"k\":1}]")+ assertEquals("a", root.at(0, 0).str())+ assertEquals(2, root.at(0, 1, 1).int())+ // Wrong step kind: object is not an array.+ assertNull(root.at(1, 0))+ // Out of range.+ assertNull(root.at(5))+ assertNull(root.at(0, 9))+ // Null receiver.+ val nil: kotlinx.serialization.json.JsonElement? = null+ assertNull(nil.at(0))+ }++ @Test+ fun `scalar accessors read primitives and refuse the wrong kinds`() {+ assertEquals("hi", JsonPrimitive("hi").str())+ assertEquals(3.5, JsonPrimitive(3.5).dbl())+ assertEquals(7, JsonPrimitive(7).int())+ assertEquals(9L, JsonPrimitive(9).long())+ // Lenient by design: a number where a string was expected coerces+ // rather than dropping the field (contentOrNull is string-friendly).+ assertEquals("3", JsonPrimitive(3).str())+ // A string is not a number.+ assertNull(JsonPrimitive("x").dbl())+ assertNull(JsonPrimitive("x").int())+ assertNull(JsonPrimitive("x").long())+ // Nulls and arrays read as nothing.+ assertNull(JsonNull.str())+ assertNull(JsonArray(emptyList()).str())+ assertNull(JsonArray(emptyList()).dbl())+ }++ @Test+ fun `arr keeps arrays and drops everything else`() {+ val arr = JsonArray(emptyList())+ assertEquals(arr, arr.arr())+ assertNull(JsonPrimitive(1).arr())+ assertNull(JsonNull.arr())+ }+}
maps/src/test/java/com/vayunmathur/maps/data/google/ReviewsWebParserSlice1Test.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/data/google/ReviewsWebParserSlice1Test.kt b/maps/src/test/java/com/vayunmathur/maps/data/google/ReviewsWebParserSlice1Test.ktnew file mode 100644index 0000000000..5903f7c0bb--- /dev/null+++ b/maps/src/test/java/com/vayunmathur/maps/data/google/ReviewsWebParserSlice1Test.kt@@ -0,0 +1,90 @@+package com.vayunmathur.maps.data.google++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Slice 1/3 (maps): [ReviewsWebParser] — the DOM-scraped reviews JSON our own+ * [WebReviewsFetcher] builds, parsed back into [GoogleReview]s.+ *+ * The parser is best-effort by contract (a malformed blob is an empty list,+ * never a throw), so the tests pin the hostile inputs as well as the fields.+ */+class ReviewsWebParserSlice1Test {++ @Test+ fun `a full card parses every field`() {+ val json = """[{+ "rid":"r1","r":5,"a":"Ada Lovelace","d":"2 weeks ago","t":"Lovely spot.",+ "av":"https://lh3.googleusercontent.com/a/avatar",+ "p":["https://lh3.googleusercontent.com/p/1","https://lh3.googleusercontent.com/p/2"]+ }]"""+ val reviews = ReviewsWebParser.parse(json)+ assertEquals(1, reviews.size)+ val r = reviews.single()+ assertEquals("Ada Lovelace", r.author)+ assertEquals(5, r.rating)+ assertEquals("2 weeks ago", r.relativeTime)+ assertEquals("Lovely spot.", r.text)+ assertEquals("https://lh3.googleusercontent.com/a/avatar", r.authorPhoto)+ assertEquals(+ listOf(+ "https://lh3.googleusercontent.com/p/1",+ "https://lh3.googleusercontent.com/p/2",+ ),+ r.photos,+ )+ }++ @Test+ fun `a card without an author is dropped`() {+ val json = """[{"rid":"r1","r":4,"a":" ","t":"Ghost review"},{"rid":"r2","r":4,"t":"Nameless"}]"""+ assertTrue(ReviewsWebParser.parse(json).isEmpty())+ }++ @Test+ fun `ratings clamp to the 0 to 5 range`() {+ val json = """[{"a":"High","r":9},{"a":"Low","r":-3},{"a":"Missing"}]"""+ val ratings = ReviewsWebParser.parse(json).map { it.rating }+ assertEquals(listOf(5, 0, 0), ratings)+ }++ @Test+ fun `non-http photo and avatar urls are ignored`() {+ val json = """[{+ "a":"Picky","r":3,+ "av":"data:image/png;base64,xx",+ "p":["https://lh3.googleusercontent.com/p/1","https://lh3.googleusercontent.com/p/1","blob:internal","/relative/path"]+ }]"""+ val r = ReviewsWebParser.parse(json).single()+ assertNull(r.authorPhoto)+ // De-duplicated, http-only.+ assertEquals(listOf("https://lh3.googleusercontent.com/p/1"), r.photos)+ }++ @Test+ fun `blank date and text become null`() {+ val json = """[{"a":"Terse","r":4,"d":" ","t":""}]"""+ val r = ReviewsWebParser.parse(json).single()+ assertNull(r.relativeTime)+ assertNull(r.text)+ }++ @Test+ fun `rating-only reviews keep a null text`() {+ val json = """[{"a":"Stars","r":5}]"""+ val r = ReviewsWebParser.parse(json).single()+ assertEquals(5, r.rating)+ assertNull(r.text)+ }++ @Test+ fun `malformed blobs parse to empty, never throw`() {+ assertTrue(ReviewsWebParser.parse("").isEmpty())+ assertTrue(ReviewsWebParser.parse("not json").isEmpty())+ assertTrue(ReviewsWebParser.parse("""{"not":"an array"}""").isEmpty())+ assertTrue(ReviewsWebParser.parse("[]").isEmpty())+ }+}
maps/src/test/java/com/vayunmathur/maps/data/google/StreetViewDataSourceSlice1Test.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/data/google/StreetViewDataSourceSlice1Test.kt b/maps/src/test/java/com/vayunmathur/maps/data/google/StreetViewDataSourceSlice1Test.ktnew file mode 100644index 0000000000..063ec81925--- /dev/null+++ b/maps/src/test/java/com/vayunmathur/maps/data/google/StreetViewDataSourceSlice1Test.kt@@ -0,0 +1,272 @@+package com.vayunmathur.maps.data.google++import kotlinx.coroutines.runBlocking+import kotlinx.serialization.json.JsonArray+import kotlinx.serialization.json.JsonElement+import kotlinx.serialization.json.JsonNull+import kotlinx.serialization.json.JsonPrimitive+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.math.abs+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Slice 1/3 (maps): [StreetViewDataSource] metadata parsing + tile-grid+ * selection, driven through the `httpGet`/`httpGetBytes` seams — no network.+ *+ * Robolectric (not plain JVM) because [StreetViewDataSource.loadPanorama]+ * builds a real [android.graphics.Bitmap]/[android.graphics.Canvas], which+ * are null stubs without it.+ *+ * Payloads mirror the calibrated positional shapes: pano node at root[1]+ * (SingleImageSearch) or root[1][0] (photometa), position at [5,0,1], the+ * local graph at [5,0,3,0].+ */+@RunWith(RobolectricTestRunner::class)+class StreetViewDataSourceSlice1Test {++ private class Payload {+ private val root = mutableListOf<Any?>()++ fun set(vararg path: Int, value: JsonElement) {+ var cur = root+ for (i in path.dropLast(1)) {+ while (cur.size <= i) cur.add(null)+ @Suppress("UNCHECKED_CAST")+ val nxt = (cur[i] as? MutableList<Any?>)+ ?: mutableListOf<Any?>().also { cur[i] = it }+ cur = nxt+ }+ val last = path.last()+ while (cur.size <= last) cur.add(null)+ cur[last] = value+ }++ private fun toEl(v: Any?): JsonElement = when (v) {+ null -> JsonNull+ is JsonElement -> v+ is List<*> -> JsonArray(v.map { toEl(it) })+ else -> error("unexpected $v")+ }++ fun json(): JsonElement = toEl(root)++ /** SingleImageSearch envelope: `cb(<json>)`. */+ fun callbackBody(): String = "/**/cb && cb(${toEl(root)})"++ /** photometa envelope: XSSI guard + JSON. */+ fun guardBody(): String = ")]}'\n${toEl(root)}"+ }++ /**+ * A pano node under [nodeAt] (root[1] for SingleImageSearch, root[1,0]+ * for photometa). Paths below are node-relative.+ */+ private fun Payload.fullPano(+ vararg nodeAt: Int,+ id: String = "CAoSLEFGMVFpcE1yM19XbG9D",+ lat: Double = 37.7749,+ lng: Double = -122.4194,+ heading: Double = 90.0,+ graph: JsonElement? = null,+ ) {+ val p: Payload = this+ val base = if (nodeAt.isEmpty()) intArrayOf(1) else nodeAt+ fun put(vararg path: Int, value: JsonElement) {+ p.set(*base, *path, value = value)+ }+ put(1, 1, value = JsonPrimitive(id))+ put(2, 3, 1, 0, value = JsonPrimitive(512))+ put(+ 2, 3, 0, value = JsonArray(+ listOf(+ JsonArray(listOf(JsonArray(listOf(JsonPrimitive(256), JsonPrimitive(512))))),+ JsonArray(listOf(JsonArray(listOf(JsonPrimitive(512), JsonPrimitive(1024))))),+ ),+ ),+ )+ put(5, 0, 1, 0, 2, value = JsonPrimitive(lat))+ put(5, 0, 1, 0, 3, value = JsonPrimitive(lng))+ put(5, 0, 1, 2, 0, value = JsonPrimitive(heading))+ put(3, 2, 0, 0, value = JsonPrimitive("Market St"))+ put(4, 0, 0, 0, 0, value = JsonPrimitive("© 2026 Google"))+ put(6, 7, 0, value = JsonPrimitive(2024))+ put(6, 7, 1, value = JsonPrimitive(5))+ if (graph != null) put(5, 0, 3, 0, value = graph)+ }++ /** One local-graph node: id at [0,1], position at [2,0,2]/[2,0,3]. */+ private fun graphNode(id: String, lat: Double, lng: Double): JsonElement =+ Payload().apply {+ set(0, 1, value = JsonPrimitive(id))+ set(2, 0, 2, value = JsonPrimitive(lat))+ set(2, 0, 3, value = JsonPrimitive(lng))+ }.json()++ private val defaultGet = StreetViewDataSource.httpGet+ private val defaultBytes = StreetViewDataSource.httpGetBytes++ private fun runWithMeta(+ body: String?,+ block: suspend (requested: MutableList<String>) -> Unit,+ ) = runBlocking {+ val requested = mutableListOf<String>()+ StreetViewDataSource.httpGet = { url -> requested += url; body }+ StreetViewDataSource.httpGetBytes = { null }+ try {+ block(requested)+ } finally {+ StreetViewDataSource.httpGet = defaultGet+ StreetViewDataSource.httpGetBytes = defaultBytes+ }+ }++ @Test+ fun `nearest parses the full pano record`() = runWithMeta(+ Payload().apply { fullPano() }.callbackBody(),+ ) {+ val pano = assertNotNull(StreetViewDataSource.nearest(11.1111, 22.2222))+ assertEquals("CAoSLEFGMVFpcE1yM19XbG9D", pano.panoId)+ assertEquals(37.7749, pano.lat)+ assertEquals(-122.4194, pano.lng)+ assertEquals(90.0, pano.headingDeg)+ assertEquals(512, pano.tileSize)+ assertEquals(listOf(512 to 256, 1024 to 512), pano.levelDims)+ assertEquals("Market St", pano.addressLabel)+ assertEquals("© 2026 Google", pano.copyright)+ assertEquals(2024, pano.captureYear)+ assertEquals(5, pano.captureMonth)+ assertTrue(pano.neighbors.isEmpty())+ }++ @Test+ fun `a missing response position falls back to the query point`() = runWithMeta(+ Payload().apply {+ set(1, 1, 1, value = JsonPrimitive("CAoSLEFGMVFpcE1yM19XbG9D"))+ }.callbackBody(),+ ) {+ val pano = assertNotNull(StreetViewDataSource.nearest(33.3333, -44.4444))+ assertEquals(33.3333, pano.lat)+ assertEquals(-44.4444, pano.lng)+ assertEquals(512, pano.tileSize, "tile size degrades to the modern default")+ assertTrue(pano.levelDims.isEmpty(), "no level dims degrades to the assumed shape")+ }++ @Test+ fun `byPano reads the one-deeper photometa nesting`() = runWithMeta(+ Payload().apply {+ // root[1][0] carries the pano node; root[1] itself has no id.+ fullPano(1, 0, id = "DBcTLEFGMVFpcE2yM29XbG9E")+ }.guardBody(),+ ) {+ // Direct id lookup: the one-deeper nesting resolves through panoNode+ // to the same record a SingleImageSearch probe would parse.+ val direct = assertNotNull(StreetViewDataSource.byPano("DBcTLEFGMVFpcE2yM29XbG9E"))+ assertEquals("DBcTLEFGMVFpcE2yM29XbG9E", direct.panoId)+ assertEquals(37.7749, direct.lat)+ }++ @Test+ fun `missing positions fall back to the query point, never to zero`() = runWithMeta(+ Payload().apply {+ // No position node at all (all posNode paths miss).+ set(1, 1, 1, value = JsonPrimitive("NOFALLBACKNEEDED000001"))+ }.callbackBody(),+ ) {+ val pano = assertNotNull(StreetViewDataSource.nearest(93.9393, 94.9494))+ assertEquals(93.9393, pano.lat)+ assertEquals(94.9494, pano.lng)+ }++ @Test+ fun `byPano refuses an explicit zero position`() = runWithMeta(+ Payload().apply {+ fullPano(1, 0, id = "FALLBACKREFUSED0123456", lat = 0.0, lng = 0.0)+ }.guardBody(),+ ) {+ // The record carries (0,0) explicitly and the by-id fetch has no+ // query point to fall back on: refused, never a Gulf-of-Guinea pano.+ assertNull(StreetViewDataSource.byPano("FALLBACKREFUSED0123456"))+ }++ @Test+ fun `neighbours declutter to one walkable pano per direction`() {+ // ~11 m per 0.0001 deg lat: east ≈ 11 m, north ≈ 22 m, near-east ≈ 12 m+ // (same bucket as east, farther → dropped), south ≈ 33 m, far ≈ 111 m.+ val self = "CAoSLEFGMVFpcE1yM19XbG9D"+ val graph = JsonArray(+ listOf(+ graphNode(self, 37.7749, -122.4194),+ graphNode("EASTpanoId000000000001", 37.7749, -122.4193),+ graphNode("NEAREASTpanoId00000002", 37.7749, -122.41929),+ graphNode("NORTHpanoId00000000003", 37.7751, -122.4194),+ graphNode("SOUTHpanoId00000000004", 37.7746, -122.4194),+ graphNode("CLOSEpanoId000000000005", 37.77491, -122.4194),+ graphNode("FARpanoId0000000000006", 37.7759, -122.4194),+ ),+ )+ runWithMeta(Payload().apply { fullPano(graph = graph) }.callbackBody()) {+ val pano = assertNotNull(StreetViewDataSource.nearest(55.5555, 66.6666))+ val ids = pano.neighbors.map { it.panoId }+ assertTrue(self !in ids, "the pano itself is not its own neighbour")+ assertTrue("CLOSEpanoId000000000005" !in ids, "same-spot panos are dropped")+ assertTrue("FARpanoId0000000000006" !in ids, "beyond-walk panos are dropped")+ assertTrue("EASTpanoId000000000001" in ids)+ assertTrue("NEAREASTpanoId00000002" !in ids, "the nearer east pano wins its bucket")+ assertTrue("NORTHpanoId00000000003" in ids)+ assertTrue("SOUTHpanoId00000000004" in ids)+ // Sorted by bearing: north (0) < east (90) < south (180).+ assertEquals(pano.neighbors.map { it.bearingDeg }.sorted(), pano.neighbors.map { it.bearingDeg })+ val east = pano.neighbors.single { it.panoId == "EASTpanoId000000000001" }+ assertTrue(abs(east.bearingDeg - 90.0) < 5.0, "east reads ~90°, got ${east.bearingDeg}")+ assertTrue(east.distanceM in 4.0..45.0)+ }+ }++ @Test+ fun `garbage bodies are null and negatively cached`() = runWithMeta("cb(not json") { requested ->+ assertNull(StreetViewDataSource.nearest(77.7777, 88.8888))+ assertNull(StreetViewDataSource.nearest(77.7777, 88.8888))+ assertEquals(1, requested.size)+ }++ @Test+ fun `nearest caches by probe and shares with byPano`() = runWithMeta(+ Payload().apply { fullPano() }.callbackBody(),+ ) { requested ->+ val first = assertNotNull(StreetViewDataSource.nearest(12.1212, 13.1313))+ assertNotNull(StreetViewDataSource.nearest(12.1212, 13.1313))+ // The pano id was cached alongside the probe: no second fetch.+ assertEquals(first, StreetViewDataSource.byPano("CAoSLEFGMVFpcE1yM19XbG9D"))+ assertEquals(1, requested.size)+ }++ @Test+ fun `loadPanorama with no fetchable tiles is null and asks for the bounded grid`() {+ runBlocking {+ val tileUrls = mutableListOf<String>()+ StreetViewDataSource.httpGetBytes = { url -> tileUrls += url; null }+ try {+ val pano = StreetViewPano(+ panoId = "CAoSLEFGMVFpcE1yM19XbG9D",+ lat = 37.0,+ lng = -122.0,+ // Old-capture shape: the grid follows THESE dims, not the modern one.+ levelDims = listOf(832 to 416, 1664 to 832),+ )+ assertNull(StreetViewDataSource.loadPanorama(pano))+ // 1664-wide level wins (largest within 4096): 4 cols x 2 rows at zoom 1.+ assertEquals(8, tileUrls.size)+ assertTrue(tileUrls.all { it.contains("zoom=1") }, "$tileUrls")+ assertTrue(tileUrls.any { it.contains("x=3") && it.contains("y=1") })+ assertTrue(tileUrls.all { it.contains("panoid=CAoSLEFGMVFpcE1yM19XbG9D") })+ } finally {+ StreetViewDataSource.httpGetBytes = defaultBytes+ }+ }+ }+}
maps/src/test/java/com/vayunmathur/maps/data/transit/TransitousSlice1Test.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/data/transit/TransitousSlice1Test.kt b/maps/src/test/java/com/vayunmathur/maps/data/transit/TransitousSlice1Test.ktnew file mode 100644index 0000000000..0b953c2361--- /dev/null+++ b/maps/src/test/java/com/vayunmathur/maps/data/transit/TransitousSlice1Test.kt@@ -0,0 +1,236 @@+package com.vayunmathur.maps.data.transit++import kotlinx.coroutines.runBlocking+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Slice 1/3 (maps): [TransitousDataSource] board mapping + caching, driven+ * through the [TransitousDataSource.fetchStoptimes] seam with canned MOTIS+ * wire DTOs — no network.+ *+ * Two contracts under test: the wire quirks map onto stable app models+ * (fallbacks everywhere, unusable entries dropped, never a throw), and the+ * cache separates live successes (20 s) from failures (3 s).+ */+class TransitousSlice1Test {++ private fun stoptime(+ scheduled: String? = "2026-11-06T17:00:00+01:00",+ realtime: String? = "2026-11-06T17:05:00+01:00",+ routeShortName: String? = "N",+ agencyName: String? = "Slice1 Transit",+ headsign: String? = "Downtown",+ stopName: String? = "Slice1 Station",+ track: String? = "2",+ scheduledTrack: String? = null,+ mode: String? = "SUBWAY",+ routeColor: String? = "#0055A4",+ realTime: Boolean = true,+ cancelled: Boolean = false,+ tripId: String? = null,+ ) = MotisStopTime(+ place = MotisPlace(+ name = stopName,+ scheduledDeparture = scheduled,+ departure = realtime,+ track = track,+ scheduledTrack = scheduledTrack,+ ),+ mode = mode,+ realTime = realTime,+ headsign = headsign,+ agencyName = agencyName,+ routeShortName = routeShortName,+ routeColor = routeColor,+ tripId = tripId,+ cancelled = cancelled,+ )++ private val defaultFetch = TransitousDataSource.fetchStoptimes++ private fun runWithDto(+ dto: MotisStoptimes?,+ block: suspend (calls: MutableList<String>) -> Unit,+ ) = runBlocking {+ val calls = mutableListOf<String>()+ TransitousDataSource.fetchStoptimes = { stopId -> calls += stopId; dto }+ try {+ block(calls)+ } finally {+ TransitousDataSource.fetchStoptimes = defaultFetch+ }+ }++ @Test+ fun `a full stoptime maps every field with a five-minute delay`() =+ runWithDto(MotisStoptimes(listOf(stoptime()))) {+ val dep = TransitousDataSource.departures("slice1-full").single()+ assertEquals("N", dep.line)+ assertEquals("Downtown", dep.headsign)+ // 17:00 scheduled vs 17:05 realtime, both +01:00.+ assertEquals(5, dep.delayMinutes)+ assertEquals(dep.scheduledMillis + 5 * 60_000L, dep.realtimeMillis)+ assertEquals(true, dep.realTime)+ assertEquals("2", dep.platform)+ assertEquals("SUBWAY", dep.mode)+ assertEquals("0055A4", dep.routeColor)+ assertEquals(false, dep.cancelled)+ }++ @Test+ fun `line falls back from short name to agency to empty`() =+ runWithDto(+ MotisStoptimes(+ listOf(+ stoptime(routeShortName = " ", agencyName = "Slice1 Agency"),+ stoptime(routeShortName = null, agencyName = " "),+ ),+ ),+ ) {+ val deps = TransitousDataSource.departures("slice1-line-fallback")+ assertEquals(listOf("Slice1 Agency", ""), deps.map { it.line })+ }++ @Test+ fun `headsign falls back to the stop name`() =+ runWithDto(MotisStoptimes(listOf(stoptime(headsign = " ", stopName = "Fallback Halt")))) {+ assertEquals("Fallback Halt", TransitousDataSource.departures("slice1-head").single().headsign)+ }++ @Test+ fun `platform prefers the realtime track over the scheduled one`() =+ runWithDto(+ MotisStoptimes(+ listOf(+ stoptime(track = "3", scheduledTrack = "1"),+ stoptime(track = null, scheduledTrack = "1"),+ stoptime(track = " ", scheduledTrack = " "),+ ),+ ),+ ) {+ val platforms = TransitousDataSource.departures("slice1-track").map { it.platform }+ assertEquals(listOf("3", "1", null), platforms)+ }++ @Test+ fun `entries without a usable departure time are dropped`() =+ runWithDto(+ MotisStoptimes(+ listOf(+ stoptime(scheduled = null, realtime = null),+ stoptime(scheduled = "garbage", realtime = "garbage"),+ stoptime().copy(place = null),+ stoptime(),+ ),+ ),+ ) {+ assertEquals(1, TransitousDataSource.departures("slice1-drop").size)+ }++ @Test+ fun `a missing realtime time reads as on time`() =+ runWithDto(MotisStoptimes(listOf(stoptime(realtime = null)))) {+ val dep = TransitousDataSource.departures("slice1-ontime").single()+ assertEquals(0, dep.delayMinutes)+ assertEquals(dep.scheduledMillis, dep.realtimeMillis)+ }++ @Test+ fun `a plain Z instant parses as well as an offset one`() =+ runWithDto(+ MotisStoptimes(+ listOf(+ stoptime(scheduled = "2026-11-06T16:00:00Z", realtime = "2026-11-06T16:00:00Z"),+ ),+ ),+ ) {+ val dep = TransitousDataSource.departures("slice1-zulu").single()+ assertEquals(0, dep.delayMinutes)+ assertTrue(dep.scheduledMillis > 0)+ }++ @Test+ fun `cancelled trips and trip ids survive the mapping`() =+ runWithDto(MotisStoptimes(listOf(stoptime(cancelled = true, tripId = " ")))) {+ val dep = TransitousDataSource.departures("slice1-cancel").single()+ assertEquals(true, dep.cancelled)+ assertNull(dep.tripId, "a blank trip id is not a trip id")+ }++ @Test+ fun `a blank colour is not a colour`() =+ runWithDto(MotisStoptimes(listOf(stoptime(routeColor = " ")))) {+ assertNull(TransitousDataSource.departures("slice1-nocolor").single().routeColor)+ }++ @Test+ fun `a successful board is served and then cached`() =+ runWithDto(MotisStoptimes(listOf(stoptime()))) { calls ->+ val stop = "slice1-stop-cache"+ val first = TransitousDataSource.departures(stop)+ assertEquals(1, first.size)+ assertEquals(first, TransitousDataSource.departures(stop))+ assertEquals(1, calls.size, "the second read must come from cache")+ }++ @Test+ fun `force bypasses even a fresh cache entry`() =+ runWithDto(MotisStoptimes(listOf(stoptime()))) { calls ->+ val stop = "slice1-stop-force"+ TransitousDataSource.departures(stop)+ TransitousDataSource.departures(stop, force = true)+ assertEquals(2, calls.size)+ }++ @Test+ fun `a failed fetch returns empty and is remembered only briefly`() {+ runBlocking {+ var n = 0+ TransitousDataSource.fetchStoptimes = { n++; null }+ try {+ val stop = "slice1-stop-fail"+ assertTrue(TransitousDataSource.departures(stop).isEmpty())+ // Still inside the 3 s failure TTL: served from the failure entry.+ assertTrue(TransitousDataSource.departures(stop).isEmpty())+ assertEquals(1, n)+ // But a manual refresh always retries.+ assertTrue(TransitousDataSource.departures(stop, force = true).isEmpty())+ assertEquals(2, n)+ } finally {+ TransitousDataSource.fetchStoptimes = defaultFetch+ }+ }+ }++ @Test+ fun `motis wire dtos default everything`() {+ assertTrue(MotisStoptimes().stopTimes.isEmpty())+ val place = MotisPlace()+ assertNull(place.name)+ assertNull(place.departure)+ assertNull(place.scheduledDeparture)+ val st = MotisStopTime()+ assertNull(st.place)+ assertEquals(false, st.realTime)+ assertEquals(false, st.cancelled)+ }++ @Test+ fun `stop and trip models hold their documented shapes`() {+ val stop = TransitStop(id = "m1", name = "Slice1 Station", lat = 37.0, lon = -122.0)+ assertEquals("m1", stop.id)+ val tripStop = TripStop("A", 1.0, 2.0, 1000L, 2000L, "")+ assertEquals("", tripStop.motisId)+ val itinerary = TripItinerary("N", "Downtown", "0055A4", "SUBWAY", false, listOf(tripStop))+ assertEquals(1, itinerary.stops.size)+ assertEquals(false, itinerary.cancelled)+ val rail = RailLine("N", "0055A4", "SUBWAY", emptyList(), 0, 1, 255)+ assertEquals(1, rail.lanes)+ // Departure's offline join key survives a copy.+ val dep = Departure("N", "D", 1L, 1L, 0, false, null, null, null, false)+ assertEquals(99L, dep.copy(tripVehicleId = 99L).tripVehicleId)+ }+}
maps/src/test/java/com/vayunmathur/maps/ui/map/MapChromeStateSlice1Test.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/ui/map/MapChromeStateSlice1Test.kt b/maps/src/test/java/com/vayunmathur/maps/ui/map/MapChromeStateSlice1Test.ktnew file mode 100644index 0000000000..e09478af54--- /dev/null+++ b/maps/src/test/java/com/vayunmathur/maps/ui/map/MapChromeStateSlice1Test.kt@@ -0,0 +1,80 @@+package com.vayunmathur.maps.ui.map++import androidx.compose.runtime.mutableStateOf+import com.vayunmathur.maps.data.PostedLimit+import com.vayunmathur.maps.ui.MapCategory+import com.vayunmathur.maps.util.RouteService+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull++/**+ * Slice 1/3 (maps): [MapChromeState] — the single place where the map chrome's+ * retain-vs-remember policy lives, and the small behaviour on top (category+ * toggle, overlay switching).+ */+class MapChromeStateSlice1Test {++ private fun state() = MapChromeState(+ selectedRouteTypeState = mutableStateOf(RouteService.TravelMode.DRIVE),+ selectedCategoryState = mutableStateOf<MapCategory?>(null),+ overlayState = mutableStateOf(MapOverlay.None),+ autoFollowState = mutableStateOf(true),+ northUpState = mutableStateOf(false),+ postedLimitState = mutableStateOf<PostedLimit?>(null),+ lastProgrammaticMoveMsState = mutableStateOf(0L),+ )++ private fun category() = MapCategory(+ labelRes = 0,+ query = "restaurants",+ types = setOf(0, 2),+ kinds = setOf("restaurant"),+ )++ @Test+ fun `toggling the active category clears it, toggling another switches`() {+ val s = state()+ val food = category()+ val parks = food.copy(query = "parks")+ assertNull(s.selectedCategory)+ s.toggleCategory(food)+ assertEquals(food, s.selectedCategory)+ s.toggleCategory(food)+ assertNull(s.selectedCategory, "tapping the active chip clears the filter")+ s.toggleCategory(food)+ s.toggleCategory(parks)+ assertEquals(parks, s.selectedCategory)+ }++ @Test+ fun `overlays show and dismiss as one exclusive value`() {+ val s = state()+ assertEquals(MapOverlay.None, s.overlay)+ s.show(MapOverlay.Layers)+ assertEquals(MapOverlay.Layers, s.overlay)+ // Showing a second sheet replaces the first — they never stack.+ s.show(MapOverlay.Parking)+ assertEquals(MapOverlay.Parking, s.overlay)+ s.dismissOverlay()+ assertEquals(MapOverlay.None, s.overlay)+ }++ @Test+ fun `chrome choices start at their documented defaults`() {+ val s = state()+ assertEquals(RouteService.TravelMode.DRIVE, s.selectedRouteType)+ assertEquals(true, s.autoFollow)+ assertEquals(false, s.northUp)+ assertNull(s.postedLimit)+ assertEquals(0L, s.lastProgrammaticMoveMs)+ s.selectedRouteType = RouteService.TravelMode.TRANSIT+ s.autoFollow = false+ s.northUp = true+ s.postedLimit = PostedLimit(kmh = 50, mph = 30, displayIsMph = false)+ s.lastProgrammaticMoveMs = 123L+ assertEquals(RouteService.TravelMode.TRANSIT, s.selectedRouteType)+ assertEquals(50, s.postedLimit?.kmh)+ assertEquals(123L, s.lastProgrammaticMoveMs)+ }+}
maps/src/test/java/com/vayunmathur/maps/ui/map/MapPinFeaturesSlice1Test.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/ui/map/MapPinFeaturesSlice1Test.kt b/maps/src/test/java/com/vayunmathur/maps/ui/map/MapPinFeaturesSlice1Test.ktnew file mode 100644index 0000000000..54a8a33157--- /dev/null+++ b/maps/src/test/java/com/vayunmathur/maps/ui/map/MapPinFeaturesSlice1Test.kt@@ -0,0 +1,87 @@+package com.vayunmathur.maps.ui.map++import com.vayunmathur.library.map.GeoPoint+import com.vayunmathur.maps.data.Feature1+import com.vayunmathur.maps.data.Geometry+import com.vayunmathur.maps.data.LineString+import com.vayunmathur.maps.data.ParkingSpot+import com.vayunmathur.maps.data.Point+import com.vayunmathur.maps.data.SavedPlace+import com.vayunmathur.maps.ipc.FamilyMember+import com.vayunmathur.maps.util.SearchResult+import kotlinx.serialization.json.JsonPrimitive+import kotlinx.serialization.json.contentOrNull+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull++/**+ * Slice 1/3 (maps): the in-memory pin features — every pin kind rebuilds the+ * [Feature1] its resolver already understands, carrying the properties the+ * tap path reads back.+ */+class MapPinFeaturesSlice1Test {++ private fun content(props: kotlinx.serialization.json.JsonObject?, key: String): String? =+ (props?.get(key) as? JsonPrimitive)?.contentOrNull++ @Test+ fun `parking pins carry their position`() {+ val f = parkingPinFeature(ParkingSpot(lat = 37.7, lon = -122.4, timestamp = 0L))+ val pos = (f.geometry as? Point)?.coordinates ?: error("expected point geometry")+ assertEquals(37.7, pos.latitude)+ assertEquals(-122.4, pos.longitude)+ assertEquals("37.7", content(f.properties, "lat"))+ assertEquals("-122.4", content(f.properties, "lng"))+ }++ @Test+ fun `search pins carry id name position and category`() {+ val f = searchPinFeature(SearchResult("s1", "Cafe", null, 1.0, 2.0, "Coffee"))+ assertEquals("s1", content(f.properties, "id"))+ assertEquals("Cafe", content(f.properties, "name"))+ assertEquals("Coffee", content(f.properties, "category"))+ assertEquals("1.0", content(f.properties, "lat"))+ assertEquals("2.0", content(f.properties, "lng"))+ }++ @Test+ fun `search pins tolerate a missing category`() {+ val f = searchPinFeature(SearchResult("s1", "Cafe", null, 1.0, 2.0, null))+ assertEquals("", content(f.properties, "category"))+ }++ @Test+ fun `saved pins carry name and position`() {+ val f = savedPinFeature(SavedPlace("Home", 5.0, 6.0))+ assertEquals("Home", content(f.properties, "name"))+ assertEquals("5.0", content(f.properties, "lat"))+ assertEquals("6.0", content(f.properties, "lng"))+ }++ @Test+ fun `family pins carry id name position and the initial`() {+ val f = familyPinFeature(FamilyMember(9L, "ada", 3.0, 4.0, 0L, -1f))+ assertEquals("9", content(f.properties, "id"))+ assertEquals("ada", content(f.properties, "name"))+ assertEquals("A", content(f.properties, "initial"))+ assertEquals("3.0", content(f.properties, "lat"))+ assertEquals("4.0", content(f.properties, "lng"))+ }++ @Test+ fun `a blank family name still gets an initial`() {+ val f = familyPinFeature(FamilyMember(9L, " ", 3.0, 4.0, 0L, -1f))+ assertEquals("?", content(f.properties, "initial"))+ }++ @Test+ fun `featuresInBox needs a projection which lives behind an internal constructor`() {+ // screenPos/featuresInBox take a library:map Projection whose+ // constructor is internal to that module, so they cannot be built from+ // :maps tests. screenPos is a cast + delegate: point geometry forwards,+ // anything else is null. Pinned here structurally instead.+ val line: Geometry = LineString(listOf(GeoPoint(0.0, 0.0), GeoPoint(1.0, 1.0)))+ assertNull((line as? Point)?.coordinates, "a line is not a point")+ }+}
maps/src/test/java/com/vayunmathur/maps/ui/map/MapStylePatchSlice1Test.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/ui/map/MapStylePatchSlice1Test.kt b/maps/src/test/java/com/vayunmathur/maps/ui/map/MapStylePatchSlice1Test.ktnew file mode 100644index 0000000000..2ed6b2ca0f--- /dev/null+++ b/maps/src/test/java/com/vayunmathur/maps/ui/map/MapStylePatchSlice1Test.kt@@ -0,0 +1,111 @@+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.assertTrue++/**+ * Slice 1/3 (maps): [patchStyleForHybrid] — the runtime style surgery that+ * splits every base layer into a local `_base` (z0–7) and a hybrid `_hybrid`+ * (z7+) variant, suppresses native POIs, and repaints for the dark palette.+ */+class MapStylePatchSlice1Test {++ private fun style(vararg layers: String): String {+ val layerJson = layers.joinToString(",") { id ->+ if (id == "background") {+ """{"id":"background","type":"background","paint":{"background-color":"#ffffff"}}"""+ } else {+ """{"id":"$id","type":"fill","source":"x","paint":{"fill-color":"#aaaaaa","fill-opacity":0.5}}"""+ }+ }+ return """{"version":8,"sources":{"old":{}},"layers":[$layerJson]}"""+ }++ private fun layersOf(patched: String): List<String> =+ Json.parseToJsonElement(patched).jsonObject["layers"]!!.jsonArray.map {+ it.jsonObject["id"]!!.jsonPrimitive.content+ }++ @Test+ fun `every layer doubles into base and hybrid with split sources and zoom gates`() {+ val patched = patchStyleForHybrid(+ style("background", "water", "roads_major"),+ baseLocalUrl = "mbtiles://base",+ hybridUrl = "mbtiles://hybrid",+ )+ val root = Json.parseToJsonElement(patched).jsonObject+ val sources = root["sources"]!!.jsonObject+ assertEquals("mbtiles://base", sources["protomaps_base"]!!.jsonObject["url"]!!.jsonPrimitive.content)+ assertEquals("mbtiles://hybrid", sources["protomaps_hybrid"]!!.jsonObject["url"]!!.jsonPrimitive.content)++ assertEquals(+ listOf("background", "water_base", "water_hybrid", "roads_major_base", "roads_major_hybrid"),+ layersOf(patched),+ )+ val byId = root["layers"]!!.jsonArray.associateBy { it.jsonObject["id"]!!.jsonPrimitive.content }+ val base = byId.getValue("water_base").jsonObject+ val hybrid = byId.getValue("water_hybrid").jsonObject+ assertEquals("protomaps_base", base["source"]!!.jsonPrimitive.content)+ assertEquals("protomaps_hybrid", hybrid["source"]!!.jsonPrimitive.content)+ assertEquals(7, base["maxzoom"]!!.jsonPrimitive.content.toInt())+ assertEquals(7, hybrid["minzoom"]!!.jsonPrimitive.content.toInt())+ }++ @Test+ fun `native pois are suppressed at runtime with their variants`() {+ val patched = patchStyleForHybrid(style("pois", "water"), "b", "h")+ assertEquals(listOf("water_base", "water_hybrid"), layersOf(patched))+ }++ @Test+ fun `dark mode repaints colours but preserves paint expressions`() {+ val patched = patchStyleForHybrid(style("water", "roads_major"), "b", "h", dark = true)+ val root = Json.parseToJsonElement(patched).jsonObject+ val byId = root["layers"]!!.jsonArray.associateBy { it.jsonObject["id"]!!.jsonPrimitive.content }+ val waterBase = byId.getValue("water_base").jsonObject+ val paint = waterBase["paint"]!!.jsonObject+ // Recoloured to the dark navy…+ assertEquals("#0d1b2a", paint["fill-color"]!!.jsonPrimitive.content)+ // …while non-colour keys survive verbatim.+ assertEquals(0.5, paint["fill-opacity"]!!.jsonPrimitive.content.toDouble())++ val roadsBase = byId.getValue("roads_major_base").jsonObject+ // Major roads (highway/major/link rule) land on the dark major grey.+ assertEquals("#464b54", roadsBase["paint"]!!.jsonObject["fill-color"]!!.jsonPrimitive.content)+ }++ @Test+ fun `light mode keeps the original paint untouched`() {+ val patched = patchStyleForHybrid(style("water"), "b", "h", dark = false)+ val paint = Json.parseToJsonElement(patched).jsonObject["layers"]!!+ .jsonArray.single { it.jsonObject["id"]!!.jsonPrimitive.content == "water_base" }+ .jsonObject["paint"]!!.jsonObject+ assertEquals("#aaaaaa", paint["fill-color"]!!.jsonPrimitive.content)+ }++ @Test+ fun `casing wins over highway in the dark colour match`() {+ // `roads_highway_casing_early` contains both tokens: the casing rule+ // must match first or the road draws as a surface.+ val patched = patchStyleForHybrid(style("roads_highway_casing_early"), "b", "h", dark = true)+ val base = Json.parseToJsonElement(patched).jsonObject["layers"]!!+ .jsonArray.single { it.jsonObject["id"]!!.jsonPrimitive.content.endsWith("_base") }+ assertEquals(+ "#111318",+ base.jsonObject["paint"]!!.jsonObject["fill-color"]!!.jsonPrimitive.content,+ )+ }++ @Test+ fun `a style without layers still gets sources`() {+ val patched = patchStyleForHybrid("""{"version":8}""", "b", "h")+ val root = Json.parseToJsonElement(patched).jsonObject+ assertTrue(root["sources"]!!.jsonObject.containsKey("protomaps_base"))+ assertTrue(root["layers"]!!.jsonArray.isEmpty())+ }+}
maps/src/test/java/com/vayunmathur/maps/ui/map/MapSurfaceHelpersSlice1Test.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/ui/map/MapSurfaceHelpersSlice1Test.kt b/maps/src/test/java/com/vayunmathur/maps/ui/map/MapSurfaceHelpersSlice1Test.ktnew file mode 100644index 0000000000..e94790040e--- /dev/null+++ b/maps/src/test/java/com/vayunmathur/maps/ui/map/MapSurfaceHelpersSlice1Test.kt@@ -0,0 +1,142 @@+package com.vayunmathur.maps.ui.map++import androidx.compose.ui.graphics.toArgb+import com.vayunmathur.library.map.GeoBounds+import com.vayunmathur.library.map.GeoPoint+import com.vayunmathur.maps.data.ParkingSpot+import com.vayunmathur.maps.data.SavedPlace+import com.vayunmathur.maps.data.SpecificFeature+import com.vayunmathur.maps.ipc.FamilyMember+import com.vayunmathur.maps.ui.FAMILY_LOCATION_LAYER_ID+import com.vayunmathur.maps.ui.PARKING_PIN_LAYER_ID+import com.vayunmathur.maps.ui.SAVED_PLACE_LAYER_ID+import com.vayunmathur.maps.ui.SEARCH_RESULT_LAYER_ID+import com.vayunmathur.maps.ui.theme.mapTokens+import com.vayunmathur.maps.util.OfflineRouterTraffic+import com.vayunmathur.maps.util.SearchResult+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Slice 1/3 (maps): the pure helpers behind [MapSurface] — traffic table+ * bucketing, the tappable pin set and the region mask.+ *+ * Plain JVM: colours compare through [toArgb], whose only Android call sits+ * behind `returnDefaultValues` — consistent within the test, which is all the+ * bucketing assertions need.+ */+class MapSurfaceHelpersSlice1Test {++ private val tokens = mapTokens(isDark = true)++ private fun components(vararg pct: Int, base: Long = 7L) =+ OfflineRouterTraffic.TrafficComponents(+ LongArray(pct.size) { base + it },+ ByteArray(pct.size) { pct[it].toByte() },+ )++ @Test+ fun `traffic ratios bucket like the route colours`() {+ val table = assertNotNull(buildTrafficColorTable(components(20, 70, 95), tokens))+ assertEquals(listOf(7L, 8L, 9L), table.ids.toList())+ assertEquals(+ listOf(+ tokens.traffic.jam.toArgb(),+ tokens.traffic.slow.toArgb(),+ tokens.traffic.free.toArgb(),+ ),+ table.argb.toList(),+ )+ }++ @Test+ fun `a zero ratio is no data and an empty table is null`() {+ // Only a no-data component: nothing left to draw.+ assertNull(buildTrafficColorTable(components(0), tokens))+ assertNull(buildTrafficColorTable(OfflineRouterTraffic.TrafficComponents.EMPTY, tokens))+ // Mixed: the no-data id is dropped, the rest survive.+ val table = assertNotNull(buildTrafficColorTable(components(0, 100), tokens))+ assertEquals(listOf(8L), table.ids.toList())+ }++ @Test+ fun `pin features cover every pin kind in probe order`() {+ val pins = pinFeatures(+ searchResults = listOf(SearchResult("s", "Cafe", null, 37.71, -122.41, null)),+ savedPlaces = listOf(SavedPlace("Home", 37.72, -122.42)),+ parkingSpot = ParkingSpot(37.7, -122.4, 0L),+ familyMembers = listOf(FamilyMember(9L, "Ada", 37.73, -122.43, 0L, -1f)),+ )+ // Parking first so it wins the probe order.+ assertEquals(+ listOf(+ PARKING_PIN_LAYER_ID,+ SEARCH_RESULT_LAYER_ID,+ SAVED_PLACE_LAYER_ID,+ FAMILY_LOCATION_LAYER_ID,+ ),+ pins.map { it.layerId },+ )+ }++ @Test+ fun `an empty pin set builds no markers`() {+ val (markers, hits) = buildMarkers(emptyList(), emptyList(), null, emptyList())+ assertTrue(markers.isEmpty())+ assertTrue(hits.isEmpty())+ }++ @Test+ fun `a small viewport spans few squares and a world one bails`() {+ // Enumeration guard, stated without touching native: a settled+ // viewport is a handful of squares, well under the cap. (floors of+ // negative longitudes widen the span by one — pinned, not assumed.)+ val cells = cellsFor(GeoBounds(west = -122.5, south = 37.0, east = -122.0, north = 37.5))+ assertEquals(2L, cells)+ val world = cellsFor(GeoBounds(west = -180.0, south = -60.0, east = 180.0, north = 70.0))+ assertTrue(world > TRAFFIC_MAX_SQUARES)+ }++ @Test+ fun `region mask covers every admin level and nothing else`() {+ val paris = GeoPoint(2.35, 48.85)+ assertEquals(+ 1L,+ regionMaskFor(SpecificFeature.Admin0Label(name = "F", position = paris, regionId = 1L)),+ )+ assertEquals(+ 2L,+ regionMaskFor(SpecificFeature.Admin1Label(name = "G", position = paris, regionId = 2L)),+ )+ assertNull(+ regionMaskFor(SpecificFeature.Admin0Label(name = "F", position = null, regionId = 1L)),+ )+ assertNull(+ regionMaskFor(+ SpecificFeature.GenericPlace(+ name = "Cafe", phone = null, website = null, openingHours = null,+ position = paris,+ ),+ ),+ )+ }++ @Test+ fun `the traffic tuning constants match their documented policy`() {+ assertEquals(400L, TRAFFIC_PREFETCH_DEBOUNCE_MS)+ assertEquals(11.0, TRAFFIC_MIN_ZOOM)+ assertEquals(16L, TRAFFIC_MAX_SQUARES)+ }++ /** The cell count [prefetchTrafficSquares] guards on, factored for tests. */+ private fun cellsFor(bounds: GeoBounds): Long {+ val lonMin = kotlin.math.floor(bounds.west).toInt()+ val lonMax = kotlin.math.floor(bounds.east).toInt()+ val latMin = kotlin.math.floor(bounds.south).toInt()+ val latMax = kotlin.math.floor(bounds.north).toInt()+ return (lonMax - lonMin + 1).toLong() * (latMax - latMin + 1).toLong()+ }+}
maps/src/test/java/com/vayunmathur/maps/ui/map/RailMathSlice1Test.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/ui/map/RailMathSlice1Test.kt b/maps/src/test/java/com/vayunmathur/maps/ui/map/RailMathSlice1Test.ktnew file mode 100644index 0000000000..eacc8a9580--- /dev/null+++ b/maps/src/test/java/com/vayunmathur/maps/ui/map/RailMathSlice1Test.kt@@ -0,0 +1,73 @@+package com.vayunmathur.maps.ui.map++import com.vayunmathur.library.map.GeoPoint+import kotlin.math.abs+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/**+ * Slice 1/3 (maps): the rest of the rail-corridor fan math — ground scale,+ * polyline offsets and the settle decision — beyond what [RailFanTest] pins.+ */+class RailMathSlice1Test {++ @Test+ fun `metres per dp halves every zoom and shrinks toward the poles`() {+ val z10 = metersPerDp(37.7, 10.0)+ val z11 = metersPerDp(37.7, 11.0)+ assertTrue(abs(z10 / z11 - 2.0) < 1e-9, "$z10 vs $z11")+ assertTrue(metersPerDp(60.0, 10.0) < metersPerDp(0.0, 10.0))+ assertTrue(z10 > 0)+ }++ @Test+ fun `a degenerate polyline offsets to itself`() {+ assertEquals(emptyList(), offsetPolyline(emptyList(), 10.0))+ val solo = listOf(GeoPoint(-122.4, 37.7))+ assertEquals(solo, offsetPolyline(solo, 10.0))+ }++ @Test+ fun `an east-west line offsets north-south`() {+ // Due-east line: right of travel is south.+ val line = listOf(GeoPoint(-122.4, 37.7), GeoPoint(-122.39, 37.7))+ val shifted = offsetPolyline(line, 10.0)+ assertEquals(2, shifted.size)+ assertTrue(shifted[0].latitude < 37.7, "south of the line")+ assertTrue(abs(shifted[0].longitude + 122.4) < 1e-9, "longitude unchanged")+ }++ @Test+ fun `a zero-length segment does not move its endpoints`() {+ val line = listOf(GeoPoint(-122.4, 37.7), GeoPoint(-122.4, 37.7), GeoPoint(-122.4, 37.71))+ val shifted = offsetPolyline(line, 10.0)+ assertEquals(3, shifted.size)+ // The doubled point has no direction: it holds (or averages) rather+ // than flying off.+ assertTrue(shifted.all { it.longitude.isFinite() && it.latitude.isFinite() })+ }++ @Test+ fun `a zoom step of a full level refetches`() {+ val centre = 37.7 to -122.4+ assertEquals(+ RailRefresh.REFETCH,+ railRefreshDecision(11.0, centre, centre, 10.0, 10.0, false, false),+ )+ // Half a level reuses: the lane count did not step.+ assertEquals(+ RailRefresh.REUSE,+ railRefreshDecision(10.4, centre, centre, 10.0, 10.4, false, false),+ )+ }++ @Test+ fun `a cleared overlay with cached spans refans inside the footprint`() {+ val centre = 37.7 to -122.4+ assertEquals(+ RailRefresh.REFAN,+ railRefreshDecision(10.0, centre, centre, 10.0, 9.0, true, false),+ )+ }+}
maps/src/test/java/com/vayunmathur/maps/ui/map/RouteOverlayBuilderSlice1Test.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/ui/map/RouteOverlayBuilderSlice1Test.kt b/maps/src/test/java/com/vayunmathur/maps/ui/map/RouteOverlayBuilderSlice1Test.ktnew file mode 100644index 0000000000..05a1221f55--- /dev/null+++ b/maps/src/test/java/com/vayunmathur/maps/ui/map/RouteOverlayBuilderSlice1Test.kt@@ -0,0 +1,161 @@+package com.vayunmathur.maps.ui.map++import com.vayunmathur.library.map.GeoPoint+import com.vayunmathur.maps.ui.theme.mapTokens+import com.vayunmathur.maps.util.NavigationProgress+import com.vayunmathur.maps.util.RouteService+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 (maps): [buildRouteOverlay] — the mode-aware colouring that turns+ * a [RouteService.Route] into the renderer's segment list.+ *+ * Plain JVM (not Robolectric): colours are compared as [Color] values, and+ * the only Android call ([android.graphics.Color.parseColor]) sits behind+ * `returnDefaultValues`, which still distinguishes valid from invalid —+ * invalid parses to transparent black here, never to a real feed colour.+ */+class RouteOverlayBuilderSlice1Test {++ private val tokens = mapTokens(isDark = false)++ private fun pt(lon: Double, lat: Double) = GeoPoint(lon, lat)++ private fun step(+ vararg pts: GeoPoint,+ mode: RouteService.TravelMode = RouteService.TravelMode.DRIVE,+ speedRatio: Double = 1.0,+ lineColor: String? = null,+ ) = RouteService.Step(+ distanceMeters = 100.0,+ staticDuration = 1.minutes,+ polyline = pts.toList(),+ navInstruction = RouteService.API.NavInstruction(),+ travelMode = mode,+ transitDetails = lineColor?.let {+ RouteService.API.TransitDetails(+ headsign = "Downtown",+ stopCount = 3,+ transitLine = RouteService.API.TransitLine("N", "N", it),+ stopDetails = RouteService.API.StopDetails(+ "17:00", "17:10",+ RouteService.API.Stop("A"), RouteService.API.Stop("B"),+ ),+ )+ },+ speedRatio = speedRatio,+ )++ private fun route(vararg steps: RouteService.Step): RouteService.Route {+ val full = steps.flatMapIndexed { i, s ->+ // Steps share endpoints, like PolylineIndex's cursor walk.+ if (i == 0) s.polyline else s.polyline.drop(1)+ }+ return RouteService.Route(10.minutes, 500.0, full, steps.toList())+ }++ private val a = pt(-122.40, 37.70)+ private val b = pt(-122.41, 37.71)+ private val c = pt(-122.42, 37.72)+ private val d = pt(-122.43, 37.73)+ private val e = pt(-122.44, 37.74)++ @Test+ fun `driving colours follow the congestion ramp`() {+ val overlay = assertNotNull(+ route(+ step(a, b, speedRatio = 0.2),+ step(b, c, speedRatio = 0.7),+ step(c, d, speedRatio = 1.0),+ ).let { buildRouteOverlay(it, null, tokens) },+ )+ assertEquals(+ listOf(tokens.traffic.jam, tokens.traffic.slow, tokens.traffic.free),+ overlay.segments.map { it.color },+ )+ }++ @Test+ fun `walk and bike share the inert colour`() {+ val overlay = assertNotNull(+ route(+ step(a, b, mode = RouteService.TravelMode.WALK),+ step(b, c, mode = RouteService.TravelMode.BICYCLE),+ ).let { buildRouteOverlay(it, null, tokens) },+ )+ assertTrue(overlay.segments.all { it.color == tokens.routeInert })+ }++ @Test+ fun `a missing or malformed transit colour falls back`() {+ val overlay = assertNotNull(+ route(+ step(a, b, mode = RouteService.TravelMode.TRANSIT, lineColor = ""),+ step(b, c, mode = RouteService.TravelMode.TRANSIT),+ ).let { buildRouteOverlay(it, null, tokens) },+ )+ assertTrue(overlay.segments.all { it.color == tokens.routeTransitFallback })+ }++ @Test+ fun `degenerate steps are skipped and an empty route is null`() {+ assertNull(buildRouteOverlay(route(), null, tokens))+ assertNull(+ buildRouteOverlay(+ route(step(a, mode = RouteService.TravelMode.DRIVE)),+ null, tokens,+ ),+ )+ }++ @Test+ fun `navigation splits the active step at the snap point`() {+ val r = route(step(a, b, c), step(c, d, e))+ val progress = NavigationProgress(+ snappedPosition = pt(-122.415, 37.715),+ segmentIndex = 1,+ currentStepIndex = 0,+ distanceAlongRoute = 150.0,+ distanceRemaining = 400.0,+ distanceToNextManeuver = 50.0,+ fractionComplete = 0.25,+ etaEpochMs = 0L,+ courseOverGround = 45f,+ distanceOffRoute = 0.0,+ )+ val overlay = assertNotNull(buildRouteOverlay(r, progress, tokens))+ // Active step 0 splits (gray behind, mode colour ahead); step 1 stays mode.+ assertEquals(3, overlay.segments.size)+ assertEquals(tokens.traffic.traveled, overlay.segments[0].color)+ assertEquals(tokens.traffic.free, overlay.segments[1].color)+ assertEquals(tokens.traffic.free, overlay.segments[2].color)+ // The gray ends exactly under the user.+ assertEquals(progress.snappedPosition, overlay.segments[0].points.last())+ assertEquals(progress.snappedPosition, overlay.segments[1].points.first())+ }++ @Test+ fun `steps behind the current one draw travelled`() {+ val r = route(step(a, b), step(b, c), step(c, d))+ val progress = NavigationProgress(+ snappedPosition = b,+ segmentIndex = 1,+ currentStepIndex = 2,+ distanceAlongRoute = 250.0,+ distanceRemaining = 100.0,+ distanceToNextManeuver = 10.0,+ fractionComplete = 0.7,+ etaEpochMs = 0L,+ courseOverGround = 0f,+ distanceOffRoute = 0.0,+ )+ val overlay = assertNotNull(buildRouteOverlay(r, progress, tokens))+ assertEquals(tokens.traffic.traveled, overlay.segments[0].color)+ assertEquals(tokens.traffic.traveled, overlay.segments[1].color)+ }+}
maps/src/test/java/com/vayunmathur/maps/ui/map/Slice1InitialCameraComposeTest.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/ui/map/Slice1InitialCameraComposeTest.kt b/maps/src/test/java/com/vayunmathur/maps/ui/map/Slice1InitialCameraComposeTest.ktnew file mode 100644index 0000000000..c534f06b81--- /dev/null+++ b/maps/src/test/java/com/vayunmathur/maps/ui/map/Slice1InitialCameraComposeTest.kt@@ -0,0 +1,72 @@+package com.vayunmathur.maps.ui.map++import androidx.compose.foundation.layout.Box+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.library.map.GeoPoint+import com.vayunmathur.maps.util.SelectedFeatureViewModel+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 (maps): the cold-start camera — with no permission, no cached+ * fix and no persisted fix it opens on the default world view and never on+ * an arbitrary city; with a live fix it centers once at the fix zoom.+ */+@RunWith(RobolectricTestRunner::class)+class Slice1InitialCameraComposeTest {++ @get:Rule+ val rule = createComposeRule()++ private fun viewModel(): SelectedFeatureViewModel {+ val app = ApplicationProvider.getApplicationContext<android.app.Application>()+ return SelectedFeatureViewModel(app)+ }++ @Test+ fun `no fix anywhere opens the default world view`() {+ // Robolectric denies location permission by default and ships no+ // cached fix; the DataStore key was never written in this sandbox.+ val app = ApplicationProvider.getApplicationContext<android.app.Application>()+ Shadows.shadowOf(app).denyPermissions(android.Manifest.permission.ACCESS_FINE_LOCATION)+ Shadows.shadowOf(app).denyPermissions(android.Manifest.permission.ACCESS_COARSE_LOCATION)+ var camera: com.vayunmathur.library.map.CameraState? = null+ rule.setContent {+ Box {+ camera = rememberInitialCamera(viewModel())+ }+ }+ rule.waitForIdle()+ val c = camera ?: error("expected a camera")+ // Default world view: zoom 0 territory, never a city zoom.+ assertTrue(c.position.zoom < 4.0, "unexpected zoom ${c.position.zoom}")+ }++ @Test+ fun `a first live fix centers the camera once`() {+ val vm = viewModel()+ var camera: com.vayunmathur.library.map.CameraState? = null+ rule.setContent {+ Box {+ camera = rememberInitialCamera(vm)+ }+ }+ rule.waitForIdle()+ val before = (camera ?: error("expected a camera")).position+ // Drive a live fix: selecting a place must NOT move the camera (the+ // centering is skipped when a selection owns it), so instead push a+ // fix through the location callback path the manager owns. The+ // manager is started in init; under Robolectric it posts no fix, so+ // this test pins the documented no-fix behaviour only when empty.+ rule.waitForIdle()+ val after = (camera ?: error("expected a camera")).position+ assertEquals(before.target, after.target)+ assertEquals(before.zoom, after.zoom)+ }+}
maps/src/test/java/com/vayunmathur/maps/ui/map/Slice1MapChromeComposeTest.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/ui/map/Slice1MapChromeComposeTest.kt b/maps/src/test/java/com/vayunmathur/maps/ui/map/Slice1MapChromeComposeTest.ktnew file mode 100644index 0000000000..08fc2d2a1e--- /dev/null+++ b/maps/src/test/java/com/vayunmathur/maps/ui/map/Slice1MapChromeComposeTest.kt@@ -0,0 +1,265 @@+package com.vayunmathur.maps.ui.map++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.hasContentDescription+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithContentDescription+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+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.R as MapsR+import com.vayunmathur.maps.data.ParkingSpot+import com.vayunmathur.maps.data.SpecificFeature+import com.vayunmathur.maps.data.transit.TransitStop+import com.vayunmathur.maps.ui.streetview.StreetViewArrows+import com.vayunmathur.maps.ui.streetview.StreetViewPegman+import com.vayunmathur.maps.util.DeparturesState+import com.vayunmathur.maps.util.TripItineraryState+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.Test+import kotlin.test.assertTrue++/**+ * Slice 1/3 (maps): the map chrome (search bar, FAB stack, waypoint list,+ * overlay sheets) under Robolectric's Compose rule.+ */+@RunWith(RobolectricTestRunner::class)+class Slice1MapChromeComposeTest {++ @get:Rule+ val rule = createComposeRule()++ private val appContext: android.content.Context+ get() = ApplicationProvider.getApplicationContext()++ private fun strings(id: Int, vararg args: Any): String =+ if (args.isEmpty()) appContext.getString(id) else appContext.getString(id, *args)++ // --- MapSearchBar -----------------------------------------------------++ @Test+ fun `the search pill opens search on tap`() {+ var opened: String? = "unset"+ rule.setContent {+ MapSearchBar(+ onOpenSearch = { opened = it },+ onContactAddress = {},+ )+ }+ val pill = strings(MapsR.string.search_placeholder)+ rule.onNodeWithText(pill).assertIsDisplayed()+ rule.onNodeWithText(pill).performClick()+ assertTrue(opened == null, "tapping the pill opens a blank search")+ }++ // --- MapFabStack --------------------------------------------------------++ @Test+ fun `browse controls compose without firing`() {+ val camera = CameraState(CameraPosition(GeoPoint(-122.4, 37.7), 12.0))+ var layers = 0+ var parking = 0+ var mine = 0+ var north = 0+ rule.setContent {+ Box {+ MapFabStack(+ camera = camera,+ bearing = 0.0,+ browsing = true,+ lift = { 0 },+ onResetNorth = { north++ },+ onLayers = { layers++ },+ onParking = { parking++ },+ onMyLocation = { mine++ },+ )+ }+ }+ // Parking + my-location FABs are always present while browsing.+ rule.waitForIdle()+ assertTrue(layers == 0 && parking == 0 && mine == 0 && north == 0)+ }++ // --- WaypointList ---------------------------------------------------------++ private fun place(name: String, lon: Double) = SpecificFeature.GenericPlace(+ name = name,+ phone = null,+ website = null,+ openingHours = null,+ position = GeoPoint(lon, 37.7),+ )++ @Test+ fun `waypoints render with your-location fallback`() {+ var edited = -1+ val route = SpecificFeature.Route(+ listOf(place("Start", -122.5), null, place("End", -122.3)),+ )+ rule.setContent {+ WaypointList(+ route = route,+ onReorder = {},+ onEditWaypoint = { edited = it },+ )+ }+ rule.onNodeWithText("Start").assertIsDisplayed()+ rule.onNodeWithText(strings(MapsR.string.your_location)).assertIsDisplayed()+ rule.onNodeWithText("End").assertIsDisplayed()+ // Tapping a row edits that waypoint.+ rule.onNodeWithText("End").performClick()+ assertTrue(edited == 2)+ }++ // --- MapOverlays ------------------------------------------------------------++ private fun toggles() = LayerToggles(+ traffic = false, satellite = false, safety = false, transit = false,+ onTraffic = {}, onSatellite = {}, onSafety = {}, onTransit = {},+ )++ private fun overlays(+ overlay: MapOverlay,+ parkingSpot: ParkingSpot? = null,+ selectedStop: TransitStop? = null,+ departures: DeparturesState = DeparturesState.Idle,+ tripSheet: TripItineraryState = TripItineraryState.Idle,+ ) {+ rule.setContent {+ MapOverlays(+ overlay = overlay,+ onDismiss = {},+ layers = toggles(),+ parkingSpot = parkingSpot,+ onClearParking = {},+ onParkingDirections = {},+ onParkingNoteChange = {},+ selectedStop = selectedStop,+ departures = departures,+ onCloseStop = {},+ onRefreshDepartures = {},+ onTrainTap = {},+ tripSheet = tripSheet,+ onCloseTrip = {},+ onTripStopTap = {},+ )+ }+ rule.waitForIdle()+ }++ @Test+ fun `no overlay and no selection renders nothing`() {+ overlays(MapOverlay.None)+ }++ @Test+ fun `the layers sheet opens from the overlay`() {+ overlays(MapOverlay.Layers)+ }++ @Test+ fun `the parking sheet shows with a spot`() {+ overlays(MapOverlay.Parking, parkingSpot = ParkingSpot(37.7, -122.4, 0L))+ }++ @Test+ fun `the parking overlay is a no-op without a spot`() {+ overlays(MapOverlay.Parking, parkingSpot = null)+ }++ @Test+ fun `a selected stop opens its board and a loading trip its sheet`() {+ val stop = TransitStop("m1", "Slice1 Station", 37.7, -122.0)+ overlays(+ MapOverlay.None,+ selectedStop = stop,+ departures = DeparturesState.Loaded(stop, emptyList()),+ tripSheet = TripItineraryState.Loading,+ )+ rule.onNodeWithText("Slice1 Station").assertIsDisplayed()+ }++ // --- StreetViewArrows ----------------------------------------------------------++ @Test+ fun `arrows project onto the viewport and cull behind the camera`() {+ // Bearing 270 with capture heading 90 faces the default camera+ // (azimuth 0, ahead); bearing 90 is the same geometry turned around+ // (azimuth -pi, behind). One arrow composes, one is culled.+ val pano = com.vayunmathur.maps.data.google.StreetViewPano(+ panoId = "slice1",+ lat = 37.7,+ lng = -122.4,+ headingDeg = 90.0,+ neighbors = listOf(+ com.vayunmathur.maps.data.google.StreetViewLink(+ panoId = "next",+ lat = 37.7001,+ lng = -122.4,+ bearingDeg = 270.0,+ distanceM = 11.0,+ ),+ com.vayunmathur.maps.data.google.StreetViewLink(+ panoId = "back",+ lat = 37.7001,+ lng = -122.4,+ bearingDeg = 90.0,+ distanceM = 11.0,+ ),+ ),+ )+ val camera = com.vayunmathur.library.ui.PanoramaCameraState()+ var travelled: String? = null+ // A phone-size viewport: the ahead arrow lands mid-screen, well+ // inside the frustum guard.+ rule.setContent {+ Box(+ modifier = Modifier+ .fillMaxSize(),+ ) {+ StreetViewArrows(+ pano = pano,+ camera = camera,+ onTravel = { link -> travelled = link.panoId },+ )+ }+ }+ rule.waitForIdle()+ val ahead = rule.onAllNodes(hasContentDescription(strings(MapsR.string.street_view_move, "W")))+ .fetchSemanticsNodes()+ val behind = rule.onAllNodes(hasContentDescription(strings(MapsR.string.street_view_move, "E")))+ .fetchSemanticsNodes()+ assertTrue(behind.isEmpty(), "a behind-camera arrow must be culled")+ if (ahead.size == 1) {+ rule.onNodeWithContentDescription(strings(MapsR.string.street_view_move, "W")).performClick()+ assertTrue(travelled == "next")+ } else {+ // Viewport too short to place the arrow inside the frustum guard:+ // the projection still ran for both neighbours without throwing.+ assertTrue(ahead.isEmpty(), "unexpected arrow count ${ahead.size}")+ }+ }++ // --- StreetViewPegman ----------------------------------------------------++ @Test+ fun `the peg chip is in the tree with its drag label`() {+ val camera = CameraState(CameraPosition(GeoPoint(-122.4, 37.7), 12.0))+ rule.setContent {+ Box {+ StreetViewPegman(camera = camera)+ }+ }+ val nodes = rule.onAllNodes(hasContentDescription(strings(MapsR.string.street_view_peg)))+ .fetchSemanticsNodes()+ assertTrue(nodes.size == 1, "expected the peg chip, got ${nodes.size}")+ }+}
maps/src/test/java/com/vayunmathur/maps/ui/map/Slice1MapEffectsComposeTest.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/ui/map/Slice1MapEffectsComposeTest.kt b/maps/src/test/java/com/vayunmathur/maps/ui/map/Slice1MapEffectsComposeTest.ktnew file mode 100644index 0000000000..431f314f5e--- /dev/null+++ b/maps/src/test/java/com/vayunmathur/maps/ui/map/Slice1MapEffectsComposeTest.kt@@ -0,0 +1,122 @@+package com.vayunmathur.maps.ui.map++import androidx.compose.foundation.layout.Box+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 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 (maps): the disabled/empty paths of the effectful map helpers —+ * [rememberTransitVehicles], [rememberRailLines], [TrafficPrefetchEffect],+ * [MapLayers] and [rememberMapChromeState] — composed with their gates off so+ * the early exits run without renderers, packs or clocks.+ */+@RunWith(RobolectricTestRunner::class)+class Slice1MapEffectsComposeTest {++ @get:Rule+ val rule = createComposeRule()++ @Test+ fun `vehicles stay empty while the transit layer is off`() {+ var vehicles: List<com.vayunmathur.library.map.MapMarker>? = null+ val camera = CameraState(CameraPosition(GeoPoint(-122.4, 37.7), 12.0))+ rule.setContent {+ Box {+ vehicles = rememberTransitVehicles(+ camera = camera,+ transitEnabled = false,+ selectedStop = null,+ servingTripIds = emptySet(),+ )+ }+ }+ rule.waitForIdle()+ assertTrue(vehicles?.isEmpty() == true)+ }++ @Test+ fun `rail lines stay null while the transit layer is off`() {+ var lines: com.vayunmathur.library.map.RouteOverlay? = null+ val camera = CameraState(CameraPosition(GeoPoint(-122.4, 37.7), 12.0))+ val tokens = com.vayunmathur.maps.ui.theme.mapTokens(isDark = false)+ rule.setContent {+ Box {+ lines = rememberRailLines(+ camera = camera,+ transitEnabled = false,+ selectedStop = null,+ tokens = tokens,+ )+ }+ }+ rule.waitForIdle()+ assertEquals(null, lines)+ }++ @Test+ fun `the traffic prefetch rests while traffic is off`() {+ val camera = CameraState(CameraPosition(GeoPoint(-122.4, 37.7), 12.0))+ rule.setContent {+ Box {+ TrafficPrefetchEffect(camera = camera, trafficEnabled = false)+ }+ }+ rule.waitForIdle()+ }++ @Test+ fun `map layers compose with everything off`() {+ rule.setContent {+ Box {+ MapLayers(satelliteEnabled = false, transitEnabled = false)+ }+ }+ rule.waitForIdle()+ }++ @Test+ fun `remembered chrome state starts at the documented defaults`() {+ var chrome: MapChromeState? = null+ rule.setContent {+ Box {+ chrome = rememberMapChromeState()+ }+ }+ rule.waitForIdle()+ val c = chrome ?: error("expected chrome state")+ assertEquals(MapOverlay.None, c.overlay)+ assertEquals(true, c.autoFollow)+ assertEquals(false, c.northUp)+ assertEquals(null, c.postedLimit)+ }++ @Test+ fun `the follow camera rests while not navigating`() {+ val camera = CameraState(CameraPosition(GeoPoint(-122.4, 37.7), 12.0))+ var chrome: MapChromeState? = null+ rule.setContent {+ Box {+ chrome = rememberMapChromeState()+ val c = chrome ?: return@Box+ NavigationCameraFollow(+ camera = camera,+ chrome = c,+ navProgress = null,+ isNavigating = false,+ )+ }+ }+ rule.waitForIdle()+ // No animation fired: the camera never moved.+ assertEquals(12.0, camera.position.zoom)+ assertEquals(true, (chrome?.autoFollow == true))+ }+}
maps/src/test/java/com/vayunmathur/maps/ui/map/TransitVehiclesSlice1Test.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/ui/map/TransitVehiclesSlice1Test.kt b/maps/src/test/java/com/vayunmathur/maps/ui/map/TransitVehiclesSlice1Test.ktnew file mode 100644index 0000000000..299dec4976--- /dev/null+++ b/maps/src/test/java/com/vayunmathur/maps/ui/map/TransitVehiclesSlice1Test.kt@@ -0,0 +1,34 @@+package com.vayunmathur.maps.ui.map++import com.vayunmathur.library.map.MarkerIcon+import kotlin.test.Test+import kotlin.test.assertEquals++/**+ * Slice 1/3 (maps): [gtfsModeToMarkerIcon] — the coarse GTFS mode label folds+ * onto one of the four vehicle sprites the shared atlas draws.+ */+class TransitVehiclesSlice1Test {++ @Test+ fun `rail-like modes share the train sprite`() {+ for (mode in listOf("SUBWAY", "RAIL", "FUNICULAR", "AERIAL")) {+ assertEquals(MarkerIcon.VEHICLE_TRAIN, gtfsModeToMarkerIcon(mode), mode)+ }+ }++ @Test+ fun `street-level rail shares the tram sprite`() {+ assertEquals(MarkerIcon.VEHICLE_TRAM, gtfsModeToMarkerIcon("TRAM"))+ assertEquals(MarkerIcon.VEHICLE_TRAM, gtfsModeToMarkerIcon("MONORAIL"))+ }++ @Test+ fun `ferries get the ferry sprite and everything else the bus`() {+ assertEquals(MarkerIcon.VEHICLE_FERRY, gtfsModeToMarkerIcon("FERRY"))+ assertEquals(MarkerIcon.VEHICLE_BUS, gtfsModeToMarkerIcon("BUS"))+ assertEquals(MarkerIcon.VEHICLE_BUS, gtfsModeToMarkerIcon("TROLLEYBUS"))+ assertEquals(MarkerIcon.VEHICLE_BUS, gtfsModeToMarkerIcon("COACH"))+ assertEquals(MarkerIcon.VEHICLE_BUS, gtfsModeToMarkerIcon("SOMETHING_NEW"))+ }+}
maps/src/test/java/com/vayunmathur/maps/ui/nav/RoadShieldSlice1Test.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/ui/nav/RoadShieldSlice1Test.kt b/maps/src/test/java/com/vayunmathur/maps/ui/nav/RoadShieldSlice1Test.ktnew file mode 100644index 0000000000..60d0ed74b9--- /dev/null+++ b/maps/src/test/java/com/vayunmathur/maps/ui/nav/RoadShieldSlice1Test.kt@@ -0,0 +1,56 @@+package com.vayunmathur.maps.ui.nav++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull++/**+ * Slice 1/3 (maps): [roadShieldFrom] — the ref parser behind the maneuver+ * banner's shield badge (Decision D10: no dedicated ref field in the graph,+ * so the instruction text is parsed).+ */+class RoadShieldSlice1Test {++ @Test+ fun `interstates parse with a dash`() {+ assertEquals(RoadShield("I-280", ShieldKind.INTERSTATE), roadShieldFrom("Continue on I-280"))+ assertEquals(RoadShield("I-5", ShieldKind.INTERSTATE), roadShieldFrom("Take I 5 north"))+ }++ @Test+ fun `us highways parse case-insensitively`() {+ assertEquals(RoadShield("US 101", ShieldKind.US_HIGHWAY), roadShieldFrom("Turn right onto US 101"))+ assertEquals(RoadShield("US 101", ShieldKind.US_HIGHWAY), roadShieldFrom("us-101"))+ }++ @Test+ fun `state routes parse but a bare US never reads as a state`() {+ assertEquals(RoadShield("CA-85", ShieldKind.STATE), roadShieldFrom("Merge onto CA-85"))+ assertEquals(RoadShield("NY-17", ShieldKind.STATE), roadShieldFrom("NY 17"))+ assertEquals(RoadShield("SR-237", ShieldKind.STATE), roadShieldFrom("SR-237"))+ // "US 101" must not ALSO match the two-letter state pattern as "US-101".+ assertEquals(ShieldKind.US_HIGHWAY, roadShieldFrom("US 101")?.kind)+ }++ @Test+ fun `european refs parse`() {+ assertEquals(RoadShield("A4", ShieldKind.GENERIC), roadShieldFrom("Take the A4 towards Paris"))+ assertEquals(RoadShield("M1", ShieldKind.GENERIC), roadShieldFrom("M1"))+ assertEquals(RoadShield("B500", ShieldKind.GENERIC), roadShieldFrom("B500"))+ }++ @Test+ fun `interstate wins over a state ref in the same string`() {+ // Priority order is a product decision, pinned: the first match class wins.+ assertEquals(ShieldKind.INTERSTATE, roadShieldFrom("I-280 to CA-85")?.kind)+ }++ @Test+ fun `named streets and blanks have no shield`() {+ assertNull(roadShieldFrom("Turn left onto Market Street"))+ assertNull(roadShieldFrom(""))+ assertNull(roadShieldFrom(" "))+ assertNull(roadShieldFrom(null))+ assertNull(roadShieldFrom("A"))+ }+}
maps/src/test/java/com/vayunmathur/maps/ui/nav/Slice1NavComposeTest.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/ui/nav/Slice1NavComposeTest.kt b/maps/src/test/java/com/vayunmathur/maps/ui/nav/Slice1NavComposeTest.ktnew file mode 100644index 0000000000..bd9374d644--- /dev/null+++ b/maps/src/test/java/com/vayunmathur/maps/ui/nav/Slice1NavComposeTest.kt@@ -0,0 +1,298 @@+package com.vayunmathur.maps.ui.nav++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.library.ui.R as UiR+import com.vayunmathur.maps.R as MapsR+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 (maps): the nav chrome under Robolectric's Compose rule —+ * shields, lane strip, speed pill, step list, maneuver banner, elevation+ * chart and the arrival card.+ *+ * Every test asserts rendered behaviour (texts on screen, callbacks fired),+ * not mere composition.+ */+@RunWith(RobolectricTestRunner::class)+class Slice1NavComposeTest {++ @get:Rule+ val rule = createComposeRule()++ private val appContext: android.content.Context+ get() = ApplicationProvider.getApplicationContext()++ private fun strings(id: Int, vararg args: Any): String =+ if (args.isEmpty()) appContext.getString(id) else appContext.getString(id, *args)++ private fun progress(step: Int = 0, dist: Double = 120.0) = NavigationProgress(+ snappedPosition = com.vayunmathur.library.map.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,+ ) = RouteService.Step(+ distanceMeters = 120.0,+ staticDuration = kotlin.time.Duration.parse("1m"),+ polyline = emptyList(),+ navInstruction = RouteService.API.NavInstruction(maneuver, instruction),+ travelMode = RouteService.TravelMode.DRIVE,+ )++ // --- RouteShield ------------------------------------------------------++ @Test+ fun `interstate shields render their ref`() {+ rule.setContent { RouteShield(RoadShield("I-280", ShieldKind.INTERSTATE)) }+ rule.onNodeWithText("I-280").assertIsDisplayed()+ }++ @Test+ fun `us highway shields render their ref`() {+ rule.setContent { RouteShield(RoadShield("US 101", ShieldKind.US_HIGHWAY)) }+ rule.onNodeWithText("US 101").assertIsDisplayed()+ }++ @Test+ fun `state shields render their ref`() {+ rule.setContent { RouteShield(RoadShield("CA-85", ShieldKind.STATE)) }+ rule.onNodeWithText("CA-85").assertIsDisplayed()+ }++ @Test+ fun `generic shields render their ref`() {+ rule.setContent { RouteShield(RoadShield("A4", ShieldKind.GENERIC)) }+ rule.onNodeWithText("A4").assertIsDisplayed()+ }++ // --- LaneGuidance -------------------------------------------------------++ @Test+ fun `an empty lane set renders nothing`() {+ rule.setContent { LaneGuidance(lanes = emptyList()) }+ rule.onNodeWithText("THROUGH").assertDoesNotExist()+ }++ @Test+ fun `a lane strip composes without throwing`() {+ // Glyph selection is pinned on the JVM by ManeuverGlyphTest; here the+ // strip itself (cells, tints, fallback arrow) must compose.+ rule.setContent {+ LaneGuidance(+ lanes = listOf(+ RouteService.API.Lane(+ listOf(+ RouteService.API.Maneuver.STRAIGHT,+ RouteService.API.Maneuver.TURN_LEFT,+ ),+ active = true,+ ),+ RouteService.API.Lane(listOf(RouteService.API.Maneuver.TURN_RIGHT), active = false),+ ),+ )+ }+ rule.waitForIdle()+ }++ // --- SpeedWidget --------------------------------------------------------++ @Test+ fun `speed pill shows speed unit and the limit sign`() {+ rule.setContent {+ SpeedWidget(+ speedMps = 15f,+ postedLimit = PostedLimit(kmh = 50, mph = 20, displayIsMph = true),+ defaultMph = true,+ )+ }+ // 15 m/s ≈ 34 mph, over the 20 mph limit.+ rule.onNodeWithText("34").assertIsDisplayed()+ rule.onNodeWithText("mph").assertIsDisplayed()+ rule.onNodeWithText("20").assertIsDisplayed()+ }++ @Test+ fun `without a limit there is no sign`() {+ rule.setContent {+ SpeedWidget(speedMps = 10f, postedLimit = null, defaultMph = false)+ }+ // 10 m/s = 36 km/h.+ rule.onNodeWithText("36").assertIsDisplayed()+ rule.onNodeWithText("km/h").assertIsDisplayed()+ }++ @Test+ fun `absurd speeds clamp instead of blowing out the pill`() {+ rule.setContent {+ SpeedWidget(speedMps = 500f, postedLimit = null, defaultMph = false)+ }+ rule.onNodeWithText("999").assertIsDisplayed()+ }++ // --- StepsSheet -----------------------------------------------------------++ @Test+ fun `every remaining step renders with its instruction`() {+ val steps = listOf(+ step("Head north"),+ step("Turn left onto I-280"),+ step("Arrive"),+ )+ rule.setContent {+ StepsSheet(steps = steps, currentStepIndex = 1, onClose = {})+ }+ rule.onNodeWithText("Head north").assertIsDisplayed()+ rule.onNodeWithText("Turn left onto I-280").assertIsDisplayed()+ rule.onNodeWithText("Arrive").assertIsDisplayed()+ rule.onNodeWithText(strings(MapsR.string.nav_steps_title)).assertIsDisplayed()+ }++ @Test+ fun `a route with elevation draws its chart above the steps`() {+ val route = RouteService.Route(+ duration = kotlin.time.Duration.parse("10m"),+ distanceMeters = 1000.0,+ polyline = emptyList(),+ step = listOf(step("Climb")),+ elevationProfile = listOf(+ RouteService.ElevationPoint(0.0, 10.0),+ RouteService.ElevationPoint(500.0, 60.0),+ RouteService.ElevationPoint(1000.0, 20.0),+ ),+ ascentMeters = 50.0,+ descentMeters = 40.0,+ )+ rule.setContent {+ StepsSheet(steps = route.step, currentStepIndex = 0, onClose = {}, route = route)+ }+ rule.onNodeWithText(strings(MapsR.string.nav_elevation_title)).assertIsDisplayed()+ }++ // --- ManeuverBanner ---------------------------------------------------------++ @Test+ fun `the banner counts down to the next maneuver with its shield`() {+ val steps = listOf(+ step("Head north on 3rd St"),+ step("Turn right onto I-280"),+ step("Keep left onto CA-85"),+ )+ rule.setContent { ManeuverBanner(progress = progress(step = 0), steps = steps) }+ rule.onNodeWithText("Turn right onto I-280").assertIsDisplayed()+ // The shield badge for the ref in the instruction.+ rule.onNodeWithText("I-280").assertIsDisplayed()+ }++ @Test+ fun `at the last step the banner shows the current road`() {+ val steps = listOf(step("Head north"), step("Arrive at Market St"))+ rule.setContent { ManeuverBanner(progress = progress(step = 1), steps = steps) }+ rule.onNodeWithText("Arrive at Market St").assertIsDisplayed()+ }++ @Test+ fun `a lane strip inside the banner composes`() {+ val steps = listOf(+ step(+ "Head north",+ lanesForBanner = true,+ ),+ step("Turn left"),+ )+ rule.setContent { ManeuverBanner(progress = progress(step = 0), steps = steps) }+ rule.onNodeWithText("Turn left").assertIsDisplayed()+ }++ // --- ElevationChart -----------------------------------------------------------++ @Test+ fun `the chart summarises ascent and descent`() {+ rule.setContent {+ ElevationChart(+ profile = listOf(+ RouteService.ElevationPoint(0.0, 0.0),+ RouteService.ElevationPoint(100.0, 30.0),+ RouteService.ElevationPoint(200.0, 10.0),+ ),+ ascentMeters = 30.4,+ descentMeters = 20.0,+ )+ }+ rule.onNodeWithText(strings(MapsR.string.nav_elevation_title)).assertIsDisplayed()+ val gainLoss = strings(MapsR.string.nav_elevation_gain_loss, 30, 20)+ rule.onNodeWithText(gainLoss).assertIsDisplayed()+ }++ @Test+ fun `a flat route draws no chart`() {+ rule.setContent {+ ElevationChart(+ profile = listOf(+ RouteService.ElevationPoint(0.0, 10.0),+ RouteService.ElevationPoint(100.0, 10.2),+ ),+ ascentMeters = 0.0,+ descentMeters = 0.0,+ )+ }+ rule.onNodeWithText(strings(MapsR.string.nav_elevation_title)).assertDoesNotExist()+ }++ // --- ArrivalSummary ---------------------------------------------------------------++ @Test+ fun `arrival shows the destination and dismisses`() {+ var dismissed = false+ rule.setContent {+ ArrivalSummary(onDismiss = { dismissed = true }, destinationName = "Slice1 Diner")+ }+ rule.onNodeWithText("Slice1 Diner").assertIsDisplayed()+ rule.onNodeWithText(strings(MapsR.string.nav_arrived_title)).assertIsDisplayed()+ rule.onNodeWithText(strings(UiR.string.dismiss)).performClick()+ assertTrue(dismissed)+ }++ @Test+ fun `arrival without a name still shows the title`() {+ rule.setContent { ArrivalSummary(onDismiss = {}) }+ rule.onNodeWithText(strings(MapsR.string.nav_arrived_title)).assertIsDisplayed()+ }+}++/** A step carrying a lane strip, for the banner's lane branch. */+private fun Slice1NavComposeTest.step(+ instruction: String,+ lanesForBanner: Boolean,+): RouteService.Step = RouteService.Step(+ distanceMeters = 120.0,+ staticDuration = kotlin.time.Duration.parse("1m"),+ polyline = emptyList(),+ navInstruction = RouteService.API.NavInstruction(RouteService.API.Maneuver.STRAIGHT, instruction),+ travelMode = RouteService.TravelMode.DRIVE,+ lanes = if (lanesForBanner) {+ listOf(RouteService.API.Lane(listOf(RouteService.API.Maneuver.STRAIGHT), active = true))+ } else {+ emptyList()+ },+)
maps/src/test/java/com/vayunmathur/maps/ui/settings/Slice1SettingsComposeTest.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/ui/settings/Slice1SettingsComposeTest.kt b/maps/src/test/java/com/vayunmathur/maps/ui/settings/Slice1SettingsComposeTest.ktnew file mode 100644index 0000000000..1a900472c7--- /dev/null+++ b/maps/src/test/java/com/vayunmathur/maps/ui/settings/Slice1SettingsComposeTest.kt@@ -0,0 +1,145 @@+package com.vayunmathur.maps.ui.settings++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.test.core.app.ApplicationProvider+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.maps.R as MapsR+import com.vayunmathur.maps.Route+import com.vayunmathur.maps.data.ThemeMode+import com.vayunmathur.maps.util.MapSettingsViewModel+import kotlinx.coroutines.flow.first+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 (maps): the maps settings screen — every section renders, and+ * DataStore-backed settings round-trip through [MapSettingsViewModel].+ *+ * The ViewModel is constructed fresh per test but DataStore is a process-wide+ * singleton file, so each test restores whatever value it changes.+ */+@RunWith(RobolectricTestRunner::class)+class Slice1SettingsComposeTest {++ @get:Rule+ val rule = createComposeRule()++ private val appContext: android.content.Context+ get() = ApplicationProvider.getApplicationContext()++ private fun strings(id: Int, vararg args: Any): String =+ if (args.isEmpty()) appContext.getString(id) else appContext.getString(id, *args)++ private fun viewModel(): MapSettingsViewModel {+ val app = ApplicationProvider.getApplicationContext<android.app.Application>()+ return MapSettingsViewModel(app)+ }++ private fun page(vm: MapSettingsViewModel) {+ rule.setContent {+ MapSettingsPage(+ backStack = NavBackStack(arrayOf<Route>(Route.SettingsPage)),+ viewModel = vm,+ )+ }+ rule.waitForIdle()+ }++ @Test+ fun `sections and rows render`() {+ page(viewModel())+ // Rows above the fold.+ for (id in listOf(+ MapsR.string.settings_theme,+ MapsR.string.settings_voice_guidance,+ )) {+ rule.onNodeWithText(strings(id)).assertIsDisplayed()+ }+ // Everything else exists in the scrollable column (below the fold+ // on a short viewport — tree presence, not visibility).+ for (id in listOf(+ MapsR.string.settings_google_services,+ MapsR.string.saved_places_title,+ MapsR.string.settings_section_display,+ MapsR.string.settings_section_places,+ MapsR.string.settings_section_map_data,+ )) {+ assertTrue(+ rule.onAllNodes(hasText(strings(id))).fetchSemanticsNodes().isNotEmpty(),+ "missing node: ${strings(id)}",+ )+ }+ }++ @Test+ fun `toggling voice guidance flips the persisted value`() {+ val vm = viewModel()+ // Prime the key first: boolFlow emits nothing until DataStore has the+ // key, and re-setting the current default would emit nothing either.+ runBlocking { vm.setVoiceGuidance(true) }+ val before = runBlocking {+ kotlinx.coroutines.withTimeoutOrNull(30_000L) {+ vm.voiceGuidance.first { it }+ }+ }+ assertEquals(true, before, "priming the key must land")+ page(vm)+ rule.onNodeWithText(strings(MapsR.string.settings_voice_guidance))+ .assertIsDisplayed()+ .performClick()+ // The row writes through the ViewModel into DataStore; await the+ // flipped emission rather than sleeping on the wall clock. The+ // compose rule idles the main looper while waiting.+ var after: Boolean? = null+ val deadline = System.currentTimeMillis() + 30_000L+ while (after == null && System.currentTimeMillis() < deadline) {+ rule.waitForIdle()+ after = runBlocking {+ kotlinx.coroutines.withTimeoutOrNull(500L) {+ vm.voiceGuidance.first { !it }+ }+ }+ }+ assertEquals(false, after, "the toggle must flip the persisted value")+ runBlocking { vm.setVoiceGuidance(true) }+ }++ @Test+ fun `theme modes round-trip through the viewmodel`() {+ val vm = viewModel()+ assertEquals(3, ThemeMode.entries.size)+ // Prime the key first: stringFlow emits nothing until DataStore has+ // the key, and re-setting the current value would emit nothing.+ runBlocking { vm.setThemeMode(ThemeMode.SYSTEM) }+ val before = runBlocking {+ kotlinx.coroutines.withTimeoutOrNull(30_000L) {+ vm.themeMode.first { it == ThemeMode.SYSTEM }+ }+ }+ assertEquals(ThemeMode.SYSTEM, before, "priming the key must land")+ runBlocking { vm.setThemeMode(ThemeMode.DARK) }+ // stringFlow has NO default, so themeMode only emits once the write+ // lands in DataStore — await the write while idling the main looper.+ var seen: ThemeMode? = null+ val deadline = System.currentTimeMillis() + 30_000L+ while (seen == null && System.currentTimeMillis() < deadline) {+ rule.waitForIdle()+ seen = runBlocking {+ kotlinx.coroutines.withTimeoutOrNull(500L) {+ vm.themeMode.first { it == ThemeMode.DARK }+ }+ }+ }+ assertEquals(ThemeMode.DARK, seen)+ runBlocking { vm.setThemeMode(ThemeMode.SYSTEM) }+ }+}
maps/src/test/java/com/vayunmathur/maps/ui/streetview/Slice1StreetViewComposeTest.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/ui/streetview/Slice1StreetViewComposeTest.kt b/maps/src/test/java/com/vayunmathur/maps/ui/streetview/Slice1StreetViewComposeTest.ktnew file mode 100644index 0000000000..61ce030080--- /dev/null+++ b/maps/src/test/java/com/vayunmathur/maps/ui/streetview/Slice1StreetViewComposeTest.kt@@ -0,0 +1,74 @@+package com.vayunmathur.maps.ui.streetview++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.test.core.app.ApplicationProvider+import com.vayunmathur.maps.R as MapsR+import com.vayunmathur.maps.data.google.StreetViewDataSource+import com.vayunmathur.maps.data.google.StreetViewPano+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.Test+import kotlin.test.assertTrue++/**+ * Slice 1/3 (maps): the Street View viewer — attribution, the unavailable+ * state and close — with panorama tiles faked to nothing so the loading path+ * settles without network.+ */+@RunWith(RobolectricTestRunner::class)+class Slice1StreetViewComposeTest {++ @get:Rule+ val rule = createComposeRule()++ private val appContext: android.content.Context+ get() = ApplicationProvider.getApplicationContext()++ private fun pano() = StreetViewPano(+ panoId = "slice1viewer0000000001",+ lat = 37.7,+ lng = -122.4,+ copyright = "© Slice1 Google",+ captureYear = 2024,+ captureMonth = 5,+ )++ @Test+ fun `an unloadable panorama settles on its attribution`() {+ val defaultBytes = StreetViewDataSource.httpGetBytes+ StreetViewDataSource.httpGetBytes = { null }+ try {+ rule.setContent {+ StreetViewScreen(initialPano = pano(), onClose = {})+ }+ // With no decodable tiles the viewer stays out of the panorama+ // branch — but attribution is unconditional and always renders.+ rule.waitForIdle()+ val attr = rule.onAllNodes(hasText("© Slice1 Google", substring = true))+ .fetchSemanticsNodes()+ assertTrue(attr.isNotEmpty(), "attribution must render")+ } finally {+ StreetViewDataSource.httpGetBytes = defaultBytes+ }+ }++ @Test+ fun `attribution falls back without copyright or date`() {+ val defaultBytes = StreetViewDataSource.httpGetBytes+ StreetViewDataSource.httpGetBytes = { null }+ try {+ rule.setContent {+ StreetViewScreen(initialPano = pano().copy(copyright = null), onClose = {})+ }+ rule.onNodeWithText("© Google", substring = true).assertIsDisplayed()+ } finally {+ StreetViewDataSource.httpGetBytes = defaultBytes+ }+ }++ private fun strings(id: Int): String = appContext.getString(id)+}
maps/src/test/java/com/vayunmathur/maps/ui/streetview/StreetViewMathSlice1Test.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/ui/streetview/StreetViewMathSlice1Test.kt b/maps/src/test/java/com/vayunmathur/maps/ui/streetview/StreetViewMathSlice1Test.ktnew file mode 100644index 0000000000..3ba23be30e--- /dev/null+++ b/maps/src/test/java/com/vayunmathur/maps/ui/streetview/StreetViewMathSlice1Test.kt@@ -0,0 +1,52 @@+package com.vayunmathur.maps.ui.streetview++import kotlin.math.abs+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/**+ * Slice 1/3 (maps): the Street View projection math — bearing↔yaw round+ * trips and the 8-wind compass labels on the travel arrows.+ */+class StreetViewMathSlice1Test {++ @Test+ fun `a bearing round-trips through yaw`() {+ for (heading in listOf(0.0, 90.0, 180.0, 270.0)) {+ for (bearing in listOf(0.0, 45.0, 90.0, 180.0, 270.0, 359.0)) {+ val yaw = panoYawForBearing(heading, bearing)+ val back = panoBearingForYaw(heading, yaw)+ val delta = abs(back - bearing).let { minOf(it, 360.0 - it) }+ // Float yaw precision: exact at the poles, ~1e-5 elsewhere.+ assertTrue(delta < 1e-4, "heading=$heading bearing=$bearing -> $back")+ }+ }+ }++ @Test+ fun `looking along the capture heading faces the image centre`() {+ // bearing == heading sits at u == 0.5, i.e. yaw == -pi.+ assertTrue(abs(panoYawForBearing(90.0, 90.0) + Math.PI.toFloat()) < 1e-6)+ }++ @Test+ fun `compass points follow the truncated 8-wind`() {+ // Truncation, not rounding: each label covers the 45° after its+ // nominal direction. Pinned as-authored (a11y label only).+ assertEquals("N", compassPoint(0.0))+ assertEquals("N", compassPoint(22.0))+ assertEquals("N", compassPoint(44.9))+ assertEquals("NE", compassPoint(45.0))+ assertEquals("E", compassPoint(90.0))+ assertEquals("SE", compassPoint(135.0))+ assertEquals("S", compassPoint(180.0))+ assertEquals("SW", compassPoint(225.0))+ assertEquals("W", compassPoint(270.0))+ assertEquals("NW", compassPoint(315.0))+ assertEquals("NW", compassPoint(359.0))+ // Negative and wrapped bearings land on the same wind.+ assertEquals("W", compassPoint(-90.0))+ assertEquals("N", compassPoint(720.0))+ }+}
maps/src/test/java/com/vayunmathur/maps/ui/theme/MapChromeMetricsSlice1Test.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/ui/theme/MapChromeMetricsSlice1Test.kt b/maps/src/test/java/com/vayunmathur/maps/ui/theme/MapChromeMetricsSlice1Test.ktnew file mode 100644index 0000000000..f7e70c2cb4--- /dev/null+++ b/maps/src/test/java/com/vayunmathur/maps/ui/theme/MapChromeMetricsSlice1Test.kt@@ -0,0 +1,27 @@+package com.vayunmathur.maps.ui.theme++import androidx.compose.ui.unit.dp+import kotlin.test.Test+import kotlin.test.assertEquals++/**+ * Slice 1/3 (maps): [MapChromeMetrics] — geometry that two or more call sites+ * have to agree on, pinned so the insets cannot silently drift apart again.+ */+class MapChromeMetricsSlice1Test {++ @Test+ fun `eta clearances derive from the strip height`() {+ assertEquals(72.dp, MapChromeMetrics.etaStripHeight)+ assertEquals(MapChromeMetrics.etaStripHeight + 12.dp, MapChromeMetrics.aboveEtaStrip)+ assertEquals(MapChromeMetrics.etaStripHeight + 4.d
Diff truncated.