Modern Apps git

← Modern-Apps.git

maps: add slice-2 pass-2 tests for car, contacts, sheets, location and GTFS

Commit
80652f51abe12fe7caf949e668b63ef706053a50
Author
Vayun Mathur <[email protected]>
When
2026-11-07 08:12 UTC (29 days ago)
Parents
3653d99
Slice (28 files, basenames A-L outside slice-1 dirs) merged
INSTRUCTION coverage 61.6% -> 86.2% (8926/10359).

Second pass over the first pass's remainder: CarSearchScreen and
CarMapRenderer against TestCarContext (androidx.car.app:app-testing
on the host - template shape, mic permission flow both branches,
lifecycle teardown, pre-surface state holding), every CarManeuvers
lane shape, contact-picker result delivery through a fake
ActivityResultRegistry (postal row, contact fallback, address
chooser pick/dismiss, permission refusal and grant-retry), picker
launcher fallback chain and postal composition edges, the
findfamily client against a fake Messenger service (denied, dead
and non-Messenger binders, disconnect, malformed snapshots,
composable dispose), compass/no-accuracy/restart paths in
FrameworkLocationManager, BottomSheetHeader Directions routing
for both overloads and feature types plus the ViewModel sheet
body and its Departures/Wikipedia rows, the GooglePoiMapViewModel
debounce body, GTFS route colours from a zip asset path, consent
recording, and DepartureTime/departures row edges.

Untestable remainder: CarSearchScreen search/navigation bodies
(need a live SpeechRecognizer and POI archive on a head unit),
DirectionsIntent result mapping (needs map packs), the API-37
system contact picker (class absent below SDK 37), the satellite
layers row (tile source is a compile-time empty), and
GooglePoiMapViewModel pin mapping (needs a POI archive fixture).

(cherry picked from commit 6bbf1d9c2bef573913ad5e32f2e8de235e2f42b0)

Diff

maps/build.gradle.kts
diff --git a/maps/build.gradle.kts b/maps/build.gradle.ktsindex aa6eb8e920..a88036cffc 100644--- a/maps/build.gradle.kts+++ b/maps/build.gradle.kts@@ -49,6 +49,9 @@ dependencies {     // code path — the phone UI is untouched.     implementation(libs.androidx.car.app)     implementation(libs.androidx.car.app.projected)+    // Host-side car screens (CarSearchScreen/CarMapRenderer) run against+    // TestCarContext under Robolectric; the real head unit is DHU-only.+    testImplementation(libs.androidx.car.app.testing)      // Car-view store-listing screenshots render through the shared host renderer.     add("screenshotTestImplementation", project(":library:carhost"))
maps/src/test/java/com/vayunmathur/maps/car/CarManeuversLanesSlice2Test.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/car/CarManeuversLanesSlice2Test.kt b/maps/src/test/java/com/vayunmathur/maps/car/CarManeuversLanesSlice2Test.ktnew file mode 100644index 0000000000..c3558c03d4--- /dev/null+++ b/maps/src/test/java/com/vayunmathur/maps/car/CarManeuversLanesSlice2Test.kt@@ -0,0 +1,74 @@+package com.vayunmathur.maps.car++import androidx.car.app.navigation.model.LaneDirection+import com.vayunmathur.maps.util.RouteService+import kotlin.test.Test+import kotlin.test.assertEquals+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner++/**+ * Every lane shape the maneuver translation can produce, through the public+ * `lanes` entry point.+ * Slice-2 coverage for maps (basename C, outside the slice-1 dirs).+ */+@RunWith(RobolectricTestRunner::class)+class CarManeuversLanesSlice2Test {++    private fun lane(+        directions: List<RouteService.API.Maneuver>,+        active: Boolean = false,+    ) = RouteService.API.Lane(directions = directions, active = active)++    private fun shapes(maneuver: RouteService.API.Maneuver): List<Int> =+        CarManeuvers.lanes(listOf(lane(listOf(maneuver))))+            .single()+            .directions+            .map { it.shape }++    @Test fun `every maneuver maps to its lane shape`() {+        val expected = mapOf(+            RouteService.API.Maneuver.TURN_SLIGHT_LEFT to LaneDirection.SHAPE_SLIGHT_LEFT,+            RouteService.API.Maneuver.FORK_LEFT to LaneDirection.SHAPE_SLIGHT_LEFT,+            RouteService.API.Maneuver.RAMP_LEFT to LaneDirection.SHAPE_SLIGHT_LEFT,+            RouteService.API.Maneuver.TURN_SLIGHT_RIGHT to LaneDirection.SHAPE_SLIGHT_RIGHT,+            RouteService.API.Maneuver.FORK_RIGHT to LaneDirection.SHAPE_SLIGHT_RIGHT,+            RouteService.API.Maneuver.RAMP_RIGHT to LaneDirection.SHAPE_SLIGHT_RIGHT,+            RouteService.API.Maneuver.TURN_LEFT to LaneDirection.SHAPE_NORMAL_LEFT,+            RouteService.API.Maneuver.ROUNDABOUT_LEFT to LaneDirection.SHAPE_NORMAL_LEFT,+            RouteService.API.Maneuver.TURN_RIGHT to LaneDirection.SHAPE_NORMAL_RIGHT,+            RouteService.API.Maneuver.ROUNDABOUT_RIGHT to LaneDirection.SHAPE_NORMAL_RIGHT,+            RouteService.API.Maneuver.TURN_SHARP_LEFT to LaneDirection.SHAPE_SHARP_LEFT,+            RouteService.API.Maneuver.TURN_SHARP_RIGHT to LaneDirection.SHAPE_SHARP_RIGHT,+            RouteService.API.Maneuver.UTURN_LEFT to LaneDirection.SHAPE_U_TURN_LEFT,+            RouteService.API.Maneuver.UTURN_RIGHT to LaneDirection.SHAPE_U_TURN_RIGHT,+            RouteService.API.Maneuver.STRAIGHT to LaneDirection.SHAPE_STRAIGHT,+        )+        for ((maneuver, shape) in expected) {+            assertEquals(listOf(shape), shapes(maneuver), maneuver.name)+        }+        // Anything unrecognised also goes straight.+        assertEquals(+            listOf(LaneDirection.SHAPE_STRAIGHT),+            shapes(RouteService.API.Maneuver.DEPART),+        )+    }++    @Test fun `empty directions default to straight and active is carried`() {+        val lanes = CarManeuvers.lanes(+            listOf(+                lane(emptyList(), active = true),+                lane(listOf(RouteService.API.Maneuver.TURN_LEFT, RouteService.API.Maneuver.STRAIGHT)),+            ),+        )+        assertEquals(2, lanes.size)+        // No highlight accessor in this car-app alpha: equality is the+        // observable that carries the active flag.+        assertEquals(+            LaneDirection.create(LaneDirection.SHAPE_STRAIGHT, true),+            lanes[0].directions.single(),+        )+        assertEquals(2, lanes[1].directions.size)+        assertEquals(emptyList(), CarManeuvers.lanes(emptyList()))+    }+}
maps/src/test/java/com/vayunmathur/maps/car/CarSearchScreenSlice2Test.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/car/CarSearchScreenSlice2Test.kt b/maps/src/test/java/com/vayunmathur/maps/car/CarSearchScreenSlice2Test.ktnew file mode 100644index 0000000000..6accab6c99--- /dev/null+++ b/maps/src/test/java/com/vayunmathur/maps/car/CarSearchScreenSlice2Test.kt@@ -0,0 +1,133 @@+package com.vayunmathur.maps.car++import android.Manifest+import android.app.Application+import androidx.car.app.model.ListTemplate+import androidx.car.app.navigation.model.MapWithContentTemplate+import androidx.car.app.testing.TestCarContext+import androidx.lifecycle.Lifecycle+import androidx.lifecycle.LifecycleRegistry+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.maps.R+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNotNull+import kotlin.test.assertTrue+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows.shadowOf++/**+ * The Android Auto search screen against [TestCarContext]: the template it+ * builds, the voice-search action's permission flow, and lifecycle teardown.+ * The real head unit (template rendering, speech, routing) is DHU-only.+ * Slice-2 coverage for maps (basename C, outside the slice-1 dirs).+ */+@RunWith(RobolectricTestRunner::class)+class CarSearchScreenSlice2Test {++    private val app get() = ApplicationProvider.getApplicationContext<Application>()++    private fun clickAction(action: androidx.car.app.model.Action) {+        action.onClickDelegate!!.sendClick(+            object : androidx.car.app.OnDoneCallback {+                override fun onSuccess(response: androidx.car.app.serialization.Bundleable?) {}+                override fun onFailure(response: androidx.car.app.serialization.Bundleable) {}+            },+        )+    }++    private fun newScreen(): Pair<TestCarContext, CarSearchScreen> {+        val carContext = TestCarContext.createCarContext(app)+        return carContext to CarSearchScreen(carContext)+    }++    @Test fun `the template is a map with a search list and the voice hint`() {+        val (carContext, screen) = newScreen()+        val template = screen.onGetTemplate()+        assertTrue(template is MapWithContentTemplate, "was ${template.javaClass}")+        val list = (template as MapWithContentTemplate).contentTemplate as ListTemplate+        assertFalse(list.isLoading)+        val items = list.singleList+        assertNotNull(items)+        // No results yet: the list carries the voice hint as its empty message.+        assertEquals(+            carContext.getString(R.string.car_voice_hint),+            items.noItemsMessage?.toString(),+        )+        assertTrue(items.items.isEmpty())+        // Header + the voice search action are both present.+        assertNotNull(list.header)+        assertEquals(1, list.actionStrip?.actions?.size)+    }++    @Test fun `the search action asks for the microphone first`() {+        val (carContext, screen) = newScreen()+        val list = (screen.onGetTemplate() as MapWithContentTemplate).contentTemplate as ListTemplate+        val action = list.actionStrip!!.actions.single()+        clickAction(action)+        // Without RECORD_AUDIO the screen requests it through the car context+        // instead of listening.+        val request = carContext.lastPermissionRequestInfo+        assertNotNull(request)+        assertTrue(request.permissionsRequested.contains(Manifest.permission.RECORD_AUDIO))+    }++    @Test fun `with the microphone granted the action tries to listen`() {+        shadowOf(app).grantPermissions(Manifest.permission.RECORD_AUDIO)+        val (_, screen) = newScreen()+        val list = (screen.onGetTemplate() as MapWithContentTemplate).contentTemplate as ListTemplate+        // Robolectric has no recognition service, so listening is a quiet+        // no-op rather than a crash — the point is the granted branch runs.+        clickAction(list.actionStrip!!.actions.single())+    }++    @Test fun `granting through the permission callback also listens`() {+        val (carContext, screen) = newScreen()+        val list = (screen.onGetTemplate() as MapWithContentTemplate).contentTemplate as ListTemplate+        clickAction(list.actionStrip!!.actions.single())+        val request = carContext.lastPermissionRequestInfo+        assertNotNull(request)+        // The host grants the mic: the callback re-enters the listen path.+        request.listener.onRequestPermissionsResult(+            listOf(Manifest.permission.RECORD_AUDIO),+            emptyList(),+        )+    }++    @Test fun `destroying the screen tears down its scope and recognizer`() {+        val (_, screen) = newScreen()+        val registry = screen.lifecycle as LifecycleRegistry+        registry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE)+        registry.handleLifecycleEvent(Lifecycle.Event.ON_DESTROY)+        assertEquals(Lifecycle.State.DESTROYED, registry.currentState)+        // A template after destroy still builds (the host may ask once more).+        assertNotNull(screen.onGetTemplate())+    }++    @Test fun `the renderer holds state before any surface and tears down cleanly`() {+        val carContext = TestCarContext.createCarContext(app)+        val renderer = CarMapRenderer(carContext, darkMap = true)+        // State primed before the surface exists is held, not dropped.+        renderer.setCamera(com.vayunmathur.library.map.GeoPoint(-122.4, 37.8), zoom = 12.0, bearing = 90.0)+        renderer.setPuck(com.vayunmathur.library.map.GeoPoint(-122.4, 37.8), bearing = 45f)+        renderer.setPuck(null, null)+        renderer.setRoute(+            listOf(+                com.vayunmathur.library.map.GeoPoint(-122.4, 37.8),+                com.vayunmathur.library.map.GeoPoint(-122.3, 37.9),+            ),+        )+        renderer.setRoute(null)+        // Surface callbacks with nothing usable to draw on are no-ops.+        renderer.onSurfaceAvailable(+            androidx.car.app.SurfaceContainer(null, 0, 0, 160),+        )+        renderer.onSurfaceDestroyed(+            androidx.car.app.SurfaceContainer(null, 0, 0, 160),+        )+        renderer.destroy()+        renderer.destroy()+    }+}
maps/src/test/java/com/vayunmathur/maps/ipc/FamilyLocationBinderSlice2Test.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/ipc/FamilyLocationBinderSlice2Test.kt b/maps/src/test/java/com/vayunmathur/maps/ipc/FamilyLocationBinderSlice2Test.ktnew file mode 100644index 0000000000..f84421d18f--- /dev/null+++ b/maps/src/test/java/com/vayunmathur/maps/ipc/FamilyLocationBinderSlice2Test.kt@@ -0,0 +1,110 @@+package com.vayunmathur.maps.ipc++import android.app.Application+import android.content.ComponentName+import android.content.Intent+import android.content.pm.ResolveInfo+import android.content.pm.ServiceInfo+import android.os.Binder+import android.os.Bundle+import android.os.Handler+import android.os.Looper+import android.os.Message+import android.os.Messenger+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.setValue+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import kotlin.test.Test+import kotlin.test.assertEquals+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.Shadows.shadowOf++/**+ * The findfamily client against a binder that is not a Messenger at all+ * (register/unregister fail as RemoteExceptions), an unbind the framework+ * rejects, and the composable receiving a real push.+ * Slice-2 coverage for maps (basename F, outside the slice-1 dirs).+ */+@RunWith(AndroidJUnit4::class)+class FamilyLocationBinderSlice2Test {++    @get:Rule+    val rule = createComposeRule()++    private val app get() = ApplicationProvider.getApplicationContext<Application>()+    private val component = ComponentName("com.vayunmathur.findfamily", ".FamilyService")++    private fun installService(binder: android.os.IBinder) {+        val resolve = ResolveInfo().apply {+            serviceInfo = ServiceInfo().apply {+                packageName = component.packageName+                name = component.className+            }+        }+        shadowOf(app.packageManager).addResolveInfoForIntent(Intent(FamilyLocationProtocol.ACTION), resolve)+        shadowOf(app).setComponentNameAndServiceForBindService(component, binder)+    }++    private fun pump() = shadowOf(Looper.getMainLooper()).idle()++    @Test fun `a non-messenger binder fails registration quietly`() {+        installService(Binder())+        val client = FamilyLocationClient(app) {}+        client.bind()+        pump()+        // Unregistering against the same dead target is equally quiet, and a+        // framework that says "never bound" is swallowed too.+        shadowOf(app).setUnbindServiceShouldThrowIllegalArgument(true)+        client.unbind()+        pump()+        client.unbind()+        pump()+    }++    @Test fun `the composable receives a push and clears it on dispose`() {+        val received = mutableListOf<Int>()+        var replyTo: Messenger? = null+        val service = Messenger(+            Handler(Looper.getMainLooper()) { msg ->+                received.add(msg.what)+                if (msg.what == FamilyLocationProtocol.MSG_REGISTER) replyTo = msg.replyTo+                true+            },+        )+        installService(service.binder)++        var show by mutableStateOf(true)+        var seen: List<FamilyMember>? = null+        rule.setContent {+            if (show) {+                val members = rememberFamilyMembers()+                seen = members.value+            }+        }+        rule.waitForIdle()+        pump()+        assertEquals(listOf(FamilyLocationProtocol.MSG_REGISTER), received)++        val push = Message.obtain(null, FamilyLocationProtocol.MSG_LOCATIONS)+        push.data = Bundle().apply {+            putLongArray(FamilyLocationProtocol.KEY_IDS, longArrayOf(7L))+            putStringArray(FamilyLocationProtocol.KEY_NAMES, arrayOf("Ada"))+            putDoubleArray(FamilyLocationProtocol.KEY_LATS, doubleArrayOf(37.1))+            putDoubleArray(FamilyLocationProtocol.KEY_LNGS, doubleArrayOf(-122.1))+            putLongArray(FamilyLocationProtocol.KEY_TIMESTAMPS, longArrayOf(100L))+        }+        replyTo?.send(push)+        rule.waitForIdle()+        pump()+        assertEquals(listOf(FamilyMember(7L, "Ada", 37.1, -122.1, 100L, -1f)), seen)++        show = false+        rule.waitForIdle()+        pump()+        assertEquals(FamilyLocationProtocol.MSG_UNREGISTER, received.last())+    }+}
maps/src/test/java/com/vayunmathur/maps/ipc/FamilyLocationEdgesSlice2Test.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/ipc/FamilyLocationEdgesSlice2Test.kt b/maps/src/test/java/com/vayunmathur/maps/ipc/FamilyLocationEdgesSlice2Test.ktnew file mode 100644index 0000000000..d8aae944e5--- /dev/null+++ b/maps/src/test/java/com/vayunmathur/maps/ipc/FamilyLocationEdgesSlice2Test.kt@@ -0,0 +1,168 @@+package com.vayunmathur.maps.ipc++import android.app.Application+import android.content.ComponentName+import android.content.Intent+import android.content.pm.ResolveInfo+import android.content.pm.ServiceInfo+import android.os.Bundle+import android.os.Handler+import android.os.HandlerThread+import android.os.Looper+import android.os.Message+import android.os.Messenger+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.setValue+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.Shadows.shadowOf++/**+ * The findfamily client's failure edges: a denied bind, a service that is+ * already dead at registration, disconnect delivery, malformed snapshots,+ * and the composable's dispose path.+ * Slice-2 coverage for maps (basename F, outside the slice-1 dirs).+ */+@RunWith(AndroidJUnit4::class)+class FamilyLocationEdgesSlice2Test {++    @get:Rule+    val rule = createComposeRule()++    private val app get() = ApplicationProvider.getApplicationContext<Application>()+    private val component = ComponentName("com.vayunmathur.findfamily", ".FamilyService")++    private class FakeService {+        val received = mutableListOf<Int>()+        var replyTo: Messenger? = null+        val messenger = Messenger(+            Handler(Looper.getMainLooper()) { msg ->+                received.add(msg.what)+                if (msg.what == FamilyLocationProtocol.MSG_REGISTER) replyTo = msg.replyTo+                true+            },+        )+        fun push(bundle: Bundle?) {+            val msg = Message.obtain(null, FamilyLocationProtocol.MSG_LOCATIONS)+            msg.data = bundle+            replyTo?.send(msg)+        }+    }++    private fun installService(binder: android.os.IBinder) {+        val resolve = ResolveInfo().apply {+            serviceInfo = ServiceInfo().apply {+                packageName = component.packageName+                name = component.className+            }+        }+        shadowOf(app.packageManager).addResolveInfoForIntent(Intent(FamilyLocationProtocol.ACTION), resolve)+        shadowOf(app).setComponentNameAndServiceForBindService(component, binder)+    }++    private fun pump() = shadowOf(Looper.getMainLooper()).idle()++    private fun fullSnapshot(): Bundle = Bundle().apply {+        putLongArray(FamilyLocationProtocol.KEY_IDS, longArrayOf(1L, 2L))+        putStringArray(FamilyLocationProtocol.KEY_NAMES, arrayOf("Ada", "Bo"))+        putDoubleArray(FamilyLocationProtocol.KEY_LATS, doubleArrayOf(37.1, 37.2))+        putDoubleArray(FamilyLocationProtocol.KEY_LNGS, doubleArrayOf(-122.1, -122.2))+        putLongArray(FamilyLocationProtocol.KEY_TIMESTAMPS, longArrayOf(100L, 200L))+        putFloatArray(FamilyLocationProtocol.KEY_BATTERIES, floatArrayOf(0.5f))+    }++    @Test fun `a denied bind is silent and unbind stays silent`() {+        installService(FakeService().messenger.binder)+        shadowOf(app).setThrowInBindService(SecurityException("not co-signed"))+        val updates = mutableListOf<List<FamilyMember>>()+        val client = FamilyLocationClient(app) { updates.add(it) }+        client.bind()+        client.unbind()+        pump()+        assertTrue(updates.isEmpty())+    }++    @Test fun `registering with a dead service is swallowed`() {+        val thread = HandlerThread("dead-service").apply { start() }+        val deadMessenger = Messenger(Handler(thread.looper))+        thread.quit()+        thread.join()+        installService(deadMessenger.binder)+        val client = FamilyLocationClient(app) {}+        // onServiceConnected tries to register; the target is gone, which the+        // client treats as "nothing to stream" rather than a crash.+        client.bind()+        pump()+        client.unbind()+        pump()+    }++    @Test fun `malformed snapshots read as nobody and short batteries default`() {+        val service = FakeService()+        installService(service.messenger.binder)+        val updates = mutableListOf<List<FamilyMember>>()+        val client = FamilyLocationClient(app) { updates.add(it) }+        client.bind()+        pump()++        // Short battery array: the second member falls back to the sentinel.+        service.push(fullSnapshot())+        pump()+        assertEquals(2, updates.last().size)+        assertEquals(0.5f, updates.last()[0].battery)+        assertEquals(-1f, updates.last()[1].battery)++        // Each required array missing in turn reads as an empty snapshot.+        for (key in listOf(+            FamilyLocationProtocol.KEY_IDS,+            FamilyLocationProtocol.KEY_LATS,+            FamilyLocationProtocol.KEY_LNGS,+            FamilyLocationProtocol.KEY_TIMESTAMPS,+        )) {+            val broken = fullSnapshot()+            broken.remove(key)+            service.push(broken)+            pump()+            assertEquals(emptyList(), updates.last(), "missing $key")+        }++        // No payload at all.+        service.push(null)+        pump()+        assertEquals(emptyList(), updates.last())+        client.unbind()+        pump()+    }++    @Test fun `disconnect on unbind and dispose both tear down quietly`() {+        val service = FakeService()+        installService(service.messenger.binder)+        shadowOf(app).setUnbindServiceCallsOnServiceDisconnected(true)++        var show by mutableStateOf(true)+        var seen: List<FamilyMember>? = null+        rule.setContent {+            if (show) {+                val members = rememberFamilyMembers()+                seen = members.value+            }+        }+        rule.waitForIdle()+        pump()+        assertEquals(emptyList(), seen)+        assertEquals(listOf(FamilyLocationProtocol.MSG_REGISTER), service.received)++        // Leaving the composition unbinds and clears.+        show = false+        rule.waitForIdle()+        pump()+        assertEquals(FamilyLocationProtocol.MSG_UNREGISTER, service.received.last())+    }+}
maps/src/test/java/com/vayunmathur/maps/ipc/FamilyLocationServiceSlice2Test.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/ipc/FamilyLocationServiceSlice2Test.kt b/maps/src/test/java/com/vayunmathur/maps/ipc/FamilyLocationServiceSlice2Test.ktnew file mode 100644index 0000000000..fc28e3c8c1--- /dev/null+++ b/maps/src/test/java/com/vayunmathur/maps/ipc/FamilyLocationServiceSlice2Test.kt@@ -0,0 +1,131 @@+package com.vayunmathur.maps.ipc++import android.app.Application+import android.content.ComponentName+import android.content.Intent+import android.content.pm.ResolveInfo+import android.content.pm.ServiceInfo+import android.os.Bundle+import android.os.Handler+import android.os.Looper+import android.os.Message+import android.os.Messenger+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue+import org.junit.runner.RunWith+import org.robolectric.Shadows.shadowOf++/**+ * The findfamily channel with a fake service on the other end of the+ * Messenger: registration, snapshot parsing through the real handler,+ * and unregistration.+ * Slice-2 coverage for maps (basename F, outside the slice-1 dirs).+ */+@RunWith(AndroidJUnit4::class)+class FamilyLocationServiceSlice2Test {++    private val app get() = ApplicationProvider.getApplicationContext<Application>()++    private class FakeService {+        val received = mutableListOf<Int>()+        var replyTo: Messenger? = null+        val messenger = Messenger(+            Handler(Looper.getMainLooper()) { msg ->+                received.add(msg.what)+                if (msg.what == FamilyLocationProtocol.MSG_REGISTER) replyTo = msg.replyTo+                true+            },+        )++        fun push(bundle: Bundle?, what: Int = FamilyLocationProtocol.MSG_LOCATIONS) {+            val msg = Message.obtain(null, what)+            msg.data = bundle+            replyTo?.send(msg)+        }+    }++    private fun snapshot(+        ids: LongArray = longArrayOf(1L, 2L),+        names: Array<String> = arrayOf("Ada", "Bo"),+        lats: DoubleArray = doubleArrayOf(37.1, 37.2),+        lngs: DoubleArray = doubleArrayOf(-122.1, -122.2),+        timestamps: LongArray = longArrayOf(100L, 200L),+        batteries: FloatArray? = floatArrayOf(0.5f, 0.9f),+    ): Bundle = Bundle().apply {+        putLongArray(FamilyLocationProtocol.KEY_IDS, ids)+        putStringArray(FamilyLocationProtocol.KEY_NAMES, names)+        putDoubleArray(FamilyLocationProtocol.KEY_LATS, lats)+        putDoubleArray(FamilyLocationProtocol.KEY_LNGS, lngs)+        putLongArray(FamilyLocationProtocol.KEY_TIMESTAMPS, timestamps)+        if (batteries != null) putFloatArray(FamilyLocationProtocol.KEY_BATTERIES, batteries)+    }++    private fun pump() = shadowOf(Looper.getMainLooper()).idle()++    @Test fun `bind registers and snapshots parse through the handler`() {+        val service = FakeService()+        val component = ComponentName("com.vayunmathur.findfamily", ".FamilyService")+        val resolve = ResolveInfo().apply {+            serviceInfo = ServiceInfo().apply {+                packageName = component.packageName+                name = component.className+            }+        }+        shadowOf(app.packageManager).addResolveInfoForIntent(Intent(FamilyLocationProtocol.ACTION), resolve)+        shadowOf(app).setComponentNameAndServiceForBindService(component, service.messenger.binder)++        val updates = mutableListOf<List<FamilyMember>>()+        val client = FamilyLocationClient(app) { updates.add(it) }+        client.bind()+        client.bind() // already bound: no second registration+        pump()+        assertEquals(listOf(FamilyLocationProtocol.MSG_REGISTER), service.received)++        // A well-formed snapshot with batteries.+        service.push(snapshot())+        pump()+        assertEquals(1, updates.size)+        assertEquals(+            FamilyMember(1L, "Ada", 37.1, -122.1, 100L, 0.5f),+            updates.last()[0],+        )+        assertEquals(0.9f, updates.last()[1].battery)++        // Without a battery array the sentinel stands in.+        service.push(snapshot(batteries = null))+        pump()+        assertEquals(-1f, updates.last()[0].battery)++        // Mismatched arrays truncate to the length they agree on.+        service.push(snapshot(names = arrayOf("Only")))+        pump()+        assertEquals(1, updates.last().size)+        assertEquals("Only", updates.last()[0].name)++        // A snapshot missing a required array reads as nobody.+        val broken = snapshot()+        broken.remove(FamilyLocationProtocol.KEY_NAMES)+        service.push(broken)+        pump()+        assertEquals(emptyList(), updates.last())++        // An unrelated message is not a snapshot.+        val before = updates.size+        service.push(snapshot(), what = 99)+        pump()+        assertEquals(before, updates.size)++        // Unbind unregisters exactly once.+        client.unbind()+        pump()+        assertEquals(FamilyLocationProtocol.MSG_UNREGISTER, service.received.last())+        val count = service.received.count { it == FamilyLocationProtocol.MSG_UNREGISTER }+        client.unbind()+        pump()+        assertEquals(count, service.received.count { it == FamilyLocationProtocol.MSG_UNREGISTER })+        assertTrue(service.received.contains(FamilyLocationProtocol.MSG_REGISTER))+    }+}
maps/src/test/java/com/vayunmathur/maps/ui/BottomSheetClicksSlice2Test.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/ui/BottomSheetClicksSlice2Test.kt b/maps/src/test/java/com/vayunmathur/maps/ui/BottomSheetClicksSlice2Test.ktnew file mode 100644index 0000000000..15a7c9e4d1--- /dev/null+++ b/maps/src/test/java/com/vayunmathur/maps/ui/BottomSheetClicksSlice2Test.kt@@ -0,0 +1,114 @@+package com.vayunmathur.maps.ui++import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.library.map.GeoPoint+import com.vayunmathur.maps.data.SpecificFeature+import com.vayunmathur.maps.util.PlacePanelActions+import com.vayunmathur.maps.util.PlacePanelState+import com.vayunmathur.maps.util.RouteService+import com.vayunmathur.maps.util.SavedPlacesViewModel+import com.vayunmathur.maps.util.SelectedFeatureViewModel+import com.vayunmathur.maps.util.TransitStopsViewModel+import kotlin.test.Test+import kotlin.test.assertEquals+import org.junit.Rule+import org.junit.runner.RunWith++/**+ * Clickable rows inside the sheet body: the Wikipedia button on an admin+ * label, and the Departures row a transit-stop place carries.+ * Slice-2 coverage for maps (basename B, outside the slice-1 dirs).+ */+@RunWith(AndroidJUnit4::class)+class BottomSheetClicksSlice2Test {++    @get:Rule+    val rule = createComposeRule()++    private val app get() = ApplicationProvider.getApplicationContext<android.app.Application>()++    @Test fun `the wikipedia button on a label is tappable`() {+        rule.setContent {+            BottomSheetContent(+                panelState = PlacePanelState(),+                panelActions = PlacePanelActions.Noop,+                selectedFeature = SpecificFeature.Admin1Label(+                    name = "California",+                    wikipedia = "https://en.wikipedia.org/wiki/California",+                ),+                route = emptyMap(),+                selectedRouteType = RouteService.TravelMode.DRIVE,+                setSelectedRouteType = {},+            )+        }+        rule.onNodeWithText("Wikipedia").assertIsDisplayed()+        // Opens the article through the external-intent path; under+        // Robolectric that is a recorded VIEW intent, not a crash.+        rule.onNodeWithText("Wikipedia").performClick()+        rule.onNodeWithText("California").assertIsDisplayed()+    }++    @Test fun `a transit stop departures row asks for the nearest stop at its own coordinates`() {+        var opened: Pair<Double, Double>? = null+        val actions = object : PlacePanelActions by PlacePanelActions.Noop {+            override fun openNearestStop(lat: Double, lon: Double) {+                opened = lat to lon+            }+        }+        val stop = SpecificFeature.GenericPlace(+            name = "Ferry Terminal",+            phone = null,+            website = null,+            openingHours = null,+            position = GeoPoint(-122.39, 37.79),+            poiType = 50,+        )+        rule.setContent {+            BottomSheetContent(+                panelState = PlacePanelState(),+                panelActions = actions,+                selectedFeature = stop,+                route = emptyMap(),+                selectedRouteType = RouteService.TravelMode.DRIVE,+                setSelectedRouteType = {},+            )+        }+        rule.onNodeWithText("Departures").assertIsDisplayed()+        rule.onNodeWithText("Departures").performClick()+        assertEquals(37.79 to -122.39, opened)+    }++    @Test fun `the viewmodel body departures row drives the transit viewmodel`() {+        val stop = SpecificFeature.GenericPlace(+            name = "Ferry Terminal",+            phone = null,+            website = null,+            openingHours = null,+            position = GeoPoint(-122.39, 37.79),+            poiType = 50,+        )+        rule.setContent {+            BottomSheetContent(+                viewModel = SelectedFeatureViewModel(app),+                selectedFeature = stop,+                route = emptyMap(),+                selectedRouteType = RouteService.TravelMode.DRIVE,+                setSelectedRouteType = {},+                savedPlacesViewModel = SavedPlacesViewModel(app),+                transitViewModel = TransitStopsViewModel(app),+            )+        }+        rule.onNodeWithText("Departures").assertIsDisplayed()+        // Drives TransitStopsViewModel.openNearestStop for the stop's own+        // coordinates; the board state leaving Idle is the observable effect+        // (asserted through the sheet still rendering afterwards).+        rule.onNodeWithText("Departures").performClick()+        rule.waitForIdle()+        rule.onNodeWithText("Departures").assertIsDisplayed()+    }+}
maps/src/test/java/com/vayunmathur/maps/ui/BottomSheetContentVmSlice2Test.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/ui/BottomSheetContentVmSlice2Test.kt b/maps/src/test/java/com/vayunmathur/maps/ui/BottomSheetContentVmSlice2Test.ktnew file mode 100644index 0000000000..f16faf7143--- /dev/null+++ b/maps/src/test/java/com/vayunmathur/maps/ui/BottomSheetContentVmSlice2Test.kt@@ -0,0 +1,106 @@+package com.vayunmathur.maps.ui++import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.library.map.GeoPoint+import com.vayunmathur.maps.data.SpecificFeature+import com.vayunmathur.maps.util.PlacePanelActions+import com.vayunmathur.maps.util.PlacePanelState+import com.vayunmathur.maps.util.RouteService+import com.vayunmathur.maps.util.SavedPlacesViewModel+import com.vayunmathur.maps.util.SelectedFeatureViewModel+import com.vayunmathur.maps.util.TransitStopsViewModel+import kotlin.test.Test+import org.junit.Rule+import org.junit.runner.RunWith++/**+ * The ViewModel-backed bottom-sheet body (the overload the map page actually+ * calls), plus the stateless branches the first pass did not render: a+ * restaurant and a transit-stop place.+ * Slice-2 coverage for maps (basename B, outside the slice-1 dirs).+ */+@RunWith(AndroidJUnit4::class)+class BottomSheetContentVmSlice2Test {++    @get:Rule+    val rule = createComposeRule()++    private val app get() = ApplicationProvider.getApplicationContext<android.app.Application>()++    private val cafe = SpecificFeature.Restaurant(+        name = "Blue Bottle",+        phone = null,+        website = null,+        menu = "https://example.com/menu",+        openingHours = null,+        position = GeoPoint(-122.4, 37.8),+    )+    private val place = SpecificFeature.GenericPlace(+        name = "Ferry Building",+        phone = null,+        website = null,+        openingHours = null,+        position = GeoPoint(-122.39, 37.79),+        address = "1 Ferry Plaza, San Francisco",+    )++    private fun vmContent(feature: SpecificFeature?, route: Map<RouteService.TravelMode, RouteService.RouteType?>? = emptyMap()) {+        rule.setContent {+            BottomSheetContent(+                viewModel = SelectedFeatureViewModel(app),+                selectedFeature = feature,+                route = route,+                selectedRouteType = RouteService.TravelMode.DRIVE,+                setSelectedRouteType = {},+                savedPlacesViewModel = SavedPlacesViewModel(app),+                transitViewModel = TransitStopsViewModel(app),+            )+        }+    }++    @Test fun `the viewmodel body renders a place panel`() {+        // The name lives in the header slot; the body shows the place's rows.+        vmContent(place)+        rule.onNodeWithText("1 Ferry Plaza, San Francisco").assertIsDisplayed()+    }++    @Test fun `the viewmodel body renders a restaurant panel`() {+        vmContent(cafe)+        rule.onNodeWithText("Menu").assertIsDisplayed()+    }++    @Test fun `the viewmodel body renders an admin label`() {+        vmContent(SpecificFeature.Admin1Label(name = "California", wikipedia = null))+        rule.onNodeWithText("California").assertIsDisplayed()+    }++    @Test fun `the viewmodel body says generating while a route is planned`() {+        vmContent(SpecificFeature.Route(listOf(null, place)), route = null)+        rule.onNodeWithText("Generating Route…").assertIsDisplayed()+    }++    @Test fun `the viewmodel body renders nothing with no selection`() {+        vmContent(null)+        rule.onNodeWithText("Ferry Building").assertDoesNotExist()+        rule.onNodeWithText("Generating Route…").assertDoesNotExist()+    }++    @Test fun `a transit stop place renders its panel with departures wiring`() {+        rule.setContent {+            BottomSheetContent(+                panelState = PlacePanelState(),+                panelActions = PlacePanelActions.Noop,+                selectedFeature = place.copy(poiType = 50),+                route = emptyMap(),+                selectedRouteType = RouteService.TravelMode.DRIVE,+                setSelectedRouteType = {},+            )+        }+        // The transit-stop place gets a Departures row in its panel.+        rule.onNodeWithText("Departures").assertIsDisplayed()+    }+}
maps/src/test/java/com/vayunmathur/maps/ui/BottomSheetHeaderDirectionsSlice2Test.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/ui/BottomSheetHeaderDirectionsSlice2Test.kt b/maps/src/test/java/com/vayunmathur/maps/ui/BottomSheetHeaderDirectionsSlice2Test.ktnew file mode 100644index 0000000000..49bd26917b--- /dev/null+++ b/maps/src/test/java/com/vayunmathur/maps/ui/BottomSheetHeaderDirectionsSlice2Test.kt@@ -0,0 +1,148 @@+package com.vayunmathur.maps.ui++import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.library.map.GeoPoint+import com.vayunmathur.maps.data.SpecificFeature+import com.vayunmathur.maps.util.PlacePanelActions+import com.vayunmathur.maps.util.PlacePanelState+import com.vayunmathur.maps.util.SavedPlacesViewModel+import com.vayunmathur.maps.util.SelectedFeatureViewModel+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull+import org.junit.Rule+import org.junit.runner.RunWith++/**+ * The bottom-sheet header's Directions action: [routeTo] starting a fresh+ * route and appending to an inactive one, through both header overloads+ * and both routable feature types.+ * Slice-2 coverage for maps (basename B, outside the slice-1 dirs).+ */+@RunWith(AndroidJUnit4::class)+class BottomSheetHeaderDirectionsSlice2Test {++    @get:Rule+    val rule = createComposeRule()++    private val app get() = ApplicationProvider.getApplicationContext<android.app.Application>()++    private val cafe = SpecificFeature.Restaurant(+        name = "Blue Bottle",+        phone = null,+        website = null,+        menu = null,+        openingHours = null,+        position = GeoPoint(-122.4, 37.8),+    )+    private val place = SpecificFeature.GenericPlace(+        name = "Ferry Building",+        phone = null,+        website = null,+        openingHours = null,+        position = GeoPoint(-122.39, 37.79),+    )++    @Test fun `stateless restaurant header directions starts a fresh route`() {+        var selected: SpecificFeature? = null+        rule.setContent {+            BottomSheetHeader(+                panelState = PlacePanelState(),+                panelActions = PlacePanelActions.Noop,+                selectedFeature = cafe,+                setSelectedFeature = { selected = it },+                inactiveNavigation = null,+            )+        }+        rule.onNodeWithText("Blue Bottle").assertIsDisplayed()+        rule.onNodeWithText("Directions").performClick()+        val route = selected as? SpecificFeature.Route+        assertEquals(listOf(null, cafe), route?.waypoints)+    }++    @Test fun `stateless place header directions appends to the inactive route`() {+        var selected: SpecificFeature? = null+        val inactive = SpecificFeature.Route(listOf(null, cafe))+        rule.setContent {+            BottomSheetHeader(+                panelState = PlacePanelState(),+                panelActions = PlacePanelActions.Noop,+                selectedFeature = place,+                setSelectedFeature = { selected = it },+                inactiveNavigation = inactive,+            )+        }+        rule.onNodeWithText("Add Stop to Route").performClick()+        val route = selected as? SpecificFeature.Route+        assertEquals(listOf(null, cafe, place), route?.waypoints)+    }++    @Test fun `viewmodel restaurant header directions starts a fresh route`() {+        var selected: SpecificFeature? = null+        rule.setContent {+            BottomSheetHeader(+                viewModel = SelectedFeatureViewModel(app),+                selectedFeature = cafe,+                setSelectedFeature = { selected = it },+                inactiveNavigation = null,+                savedPlacesViewModel = SavedPlacesViewModel(app),+            )+        }+        rule.onNodeWithText("Blue Bottle").assertIsDisplayed()+        rule.onNodeWithText("Directions").performClick()+        assertEquals(listOf(null, cafe), (selected as? SpecificFeature.Route)?.waypoints)+    }++    @Test fun `viewmodel place header directions appends to the inactive route`() {+        var selected: SpecificFeature? = null+        val inactive = SpecificFeature.Route(listOf(place))+        rule.setContent {+            BottomSheetHeader(+                viewModel = SelectedFeatureViewModel(app),+                selectedFeature = place,+                setSelectedFeature = { selected = it },+                inactiveNavigation = inactive,+                savedPlacesViewModel = SavedPlacesViewModel(app),+            )+        }+        rule.onNodeWithText("Directions").assertDoesNotExist()+        rule.onNodeWithText("Add Stop to Route").performClick()+        assertEquals(listOf(place, place), (selected as? SpecificFeature.Route)?.waypoints)+    }++    @Test fun `a stateless non-place selection renders no header`() {+        var selected: SpecificFeature? = null+        rule.setContent {+            BottomSheetHeader(+                panelState = PlacePanelState(),+                panelActions = PlacePanelActions.Noop,+                selectedFeature = SpecificFeature.Admin0Label(name = "France", wikipedia = null),+                setSelectedFeature = { selected = it },+                inactiveNavigation = null,+            )+        }+        rule.onNodeWithText("France").assertDoesNotExist()+        rule.onNodeWithText("Directions").assertDoesNotExist()+        assertNull(selected)+    }++    @Test fun `a viewmodel header with nothing selected renders nothing`() {+        var selected: SpecificFeature? = null+        rule.setContent {+            BottomSheetHeader(+                viewModel = SelectedFeatureViewModel(app),+                selectedFeature = null,+                setSelectedFeature = { selected = it },+                inactiveNavigation = null,+                savedPlacesViewModel = SavedPlacesViewModel(app),+            )+        }+        rule.onNodeWithText("Directions").assertDoesNotExist()+        assertNull(selected)+    }+}
maps/src/test/java/com/vayunmathur/maps/ui/ContactAddressButtonResultsSlice2Test.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/ui/ContactAddressButtonResultsSlice2Test.kt b/maps/src/test/java/com/vayunmathur/maps/ui/ContactAddressButtonResultsSlice2Test.ktnew file mode 100644index 0000000000..4e0f126f80--- /dev/null+++ b/maps/src/test/java/com/vayunmathur/maps/ui/ContactAddressButtonResultsSlice2Test.kt@@ -0,0 +1,344 @@+package com.vayunmathur.maps.ui++import android.app.Activity+import android.content.ContentProvider+import android.content.ContentValues+import android.content.Intent+import android.database.Cursor+import android.net.Uri+import android.provider.ContactsContract+import androidx.activity.compose.LocalActivityResultRegistryOwner+import androidx.activity.result.ActivityResultRegistry+import androidx.activity.result.ActivityResultRegistryOwner+import androidx.activity.result.contract.ActivityResultContract+import androidx.activity.result.contract.ActivityResultContracts+import androidx.compose.runtime.CompositionLocalProvider+import androidx.compose.ui.test.assertIsDisplayed+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.core.app.ActivityOptionsCompat+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.maps.util.ContactLookupProvidersSlice2Test+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.Robolectric++/**+ * The contact-address button with picker results actually delivered: a fake+ * activity-result registry answers each launch with a canned result, and the+ * fake contacts provider serves the rows behind the returned URIs.+ * Slice-2 coverage for maps (basename C, outside the slice-1 dirs).+ */+@RunWith(AndroidJUnit4::class)+class ContactAddressButtonResultsSlice2Test {++    @get:Rule+    val rule = createComposeRule()++    /** Answers every launch immediately with [responder]'s result. */+    private class FakeRegistry(+        var responder: (contract: ActivityResultContract<*, *>, input: Any?) -> Pair<Int, Intent?>,+    ) : ActivityResultRegistry() {+        val launches = mutableListOf<String>()+        override fun <I, O> onLaunch(+            requestCode: Int,+            contract: ActivityResultContract<I, O>,+            input: I,+            options: ActivityOptionsCompat?,+        ) {+            launches += contract.javaClass.simpleName+            val (code, data) = responder(contract, input)+            dispatchResult(requestCode, code, data)+        }+    }++    private class ThrowingContactsProvider : ContentProvider() {+        override fun onCreate(): Boolean = true+        override fun query(+            uri: Uri,+            projection: Array<String>?,+            selection: String?,+            selectionArgs: Array<String>?,+            sortOrder: String?,+        ): Cursor = throw SecurityException("no READ_CONTACTS")+        override fun getType(uri: Uri): String? = null+        override fun insert(uri: Uri, values: ContentValues?): Uri? = null+        override fun delete(uri: Uri, selection: String?, selectionArgs: Array<String>?): Int = 0+        override fun update(uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array<String>?): Int = 0+    }++    private val rowUri = Uri.parse("content://com.android.contacts/data/7")+    private val contactUri = Uri.parse("content://com.android.contacts/contacts/9")++    private fun providerWith(rows: Map<String, List<Array<Any?>>>) {+        val provider = Robolectric.setupContentProvider(+            ContactLookupProvidersSlice2Test.FakeContactsProvider::class.java,+            "com.android.contacts",+        )+        provider.tables = rows+    }++    private fun postalRow(formatted: String?): Array<Any?> =+        arrayOf(+            ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE,+            formatted, null, null, null, null, null, "9",+        )++    private fun setUpButton(registry: FakeRegistry, picked: MutableList<String>) {+        val owner = object : ActivityResultRegistryOwner {+            override val activityResultRegistry: ActivityResultRegistry = registry+        }+        rule.setContent {+            CompositionLocalProvider(LocalActivityResultRegistryOwner provides owner) {+                ContactAddressButton(onAddress = { picked += it })+            }+        }+    }++    private fun dataIntent(uri: Uri?) = Intent().apply { data = uri }++    @Test fun `a picked postal row delivers its address`() {+        providerWith(mapOf(rowUri.toString() to listOf(postalRow("1 Ferry Building\nSan Francisco, CA 94111"))))+        val registry = FakeRegistry { _, _ -> Activity.RESULT_OK to dataIntent(rowUri) }+        val picked = mutableListOf<String>()+        setUpButton(registry, picked)+        rule.onNodeWithContentDescription("Contacts").performClick()+        rule.waitForIdle()+        assertEquals(listOf("1 Ferry Building, San Francisco, CA 94111"), picked)+    }++    @Test fun `a cancelled pick delivers nothing`() {+        providerWith(emptyMap())+        val registry = FakeRegistry { _, _ -> Activity.RESULT_CANCELED to null }+        val picked = mutableListOf<String>()+        setUpButton(registry, picked)+        rule.onNodeWithContentDescription("Contacts").performClick()+        rule.waitForIdle()+        assertEquals(emptyList(), picked)+        rule.onNodeWithText("Choose an address").assertDoesNotExist()+    }++    @Test fun `an empty postal row falls back to the contact picker and a single address delivers`() {+        providerWith(+            mapOf(+                rowUri.toString() to listOf(postalRow(null)),+                contactUri.toString() to listOf(arrayOf<Any?>("9", null, null, null, null, null, null, "9")),+                ContactsContract.Data.CONTENT_URI.toString() to listOf(postalRow("2 Mission St, San Francisco")),+            ),+        )+        val registry = FakeRegistry { contract, _ ->+            if (contract is ActivityResultContracts.PickContact) {+                Activity.RESULT_OK to dataIntent(contactUri)+            } else {+                Activity.RESULT_OK to dataIntent(rowUri)+            }+        }+        val picked = mutableListOf<String>()+        setUpButton(registry, picked)+        rule.onNodeWithContentDescription("Contacts").performClick()+        rule.waitForIdle()+        assertEquals(listOf("2 Mission St, San Francisco"), picked)+        assertTrue(registry.launches.size >= 2, "postal then contact: ${registry.launches}")+    }++    @Test fun `several contact addresses open the chooser and tapping one delivers it`() {+        providerWith(+            mapOf(+                rowUri.toString() to listOf(postalRow(null)),+                contactUri.toString() to listOf(arrayOf<Any?>("9", null, null, null, null, null, null, "9")),+                ContactsContract.Data.CONTENT_URI.toString() to listOf(+                    postalRow("Home: 1 First St"),+                    postalRow("Work: 2 Second Ave"),+                ),+            ),+        )+        val registry = FakeRegistry { contract, _ ->+            if (contract is ActivityResultContracts.PickContact) {+                Activity.RESULT_OK to dataIntent(contactUri)+            } else {+                Activity.RESULT_OK to dataIntent(rowUri)+            }+        }+        val picked = mutableListOf<String>()+        setUpButton(registry, picked)+        rule.onNodeWithContentDescription("Contacts").performClick()+        rule.waitForIdle()+        rule.onNodeWithText("Choose an address").assertIsDisplayed()+        assertEquals(emptyList(), picked)+        rule.onNodeWithText("Work: 2 Second Ave").performClick()+        rule.waitForIdle()+        assertEquals(listOf("Work: 2 Second Ave"), picked)+        rule.onNodeWithText("Choose an address").assertDoesNotExist()+    }++    @Test fun `dismissing the chooser delivers nothing`() {+        providerWith(+            mapOf(+                rowUri.toString() to listOf(postalRow(null)),+                contactUri.toString() to listOf(arrayOf<Any?>("9", null, null, null, null, null, null, "9")),+                ContactsContract.Data.CONTENT_URI.toString() to listOf(+                    postalRow("Home: 1 First St"),+                    postalRow("Work: 2 Second Ave"),+                ),+            ),+        )+        val registry = FakeRegistry { contract, _ ->+            if (contract is ActivityResultContracts.PickContact) {+                Activity.RESULT_OK to dataIntent(contactUri)+            } else {+                Activity.RESULT_OK to dataIntent(rowUri)+            }+        }+        val picked = mutableListOf<String>()+        setUpButton(registry, picked)+        rule.onNodeWithContentDescription("Contacts").performClick()+        rule.waitForIdle()+        rule.onNodeWithText("Choose an address").assertIsDisplayed()+        rule.onNodeWithText("Cancel").performClick()+        rule.waitForIdle()+        assertEquals(emptyList(), picked)+        rule.onNodeWithText("Choose an address").assertDoesNotExist()+    }++    @Test fun `an ok pick with no data delivers nothing`() {+        providerWith(emptyMap())+        val registry = FakeRegistry { _, _ -> Activity.RESULT_OK to Intent() }+        val picked = mutableListOf<String>()+        setUpButton(registry, picked)+        rule.onNodeWithContentDescription("Contacts").performClick()+        rule.waitForIdle()+        assertEquals(emptyList(), picked)+    }++    @Test fun `a contact with no postal addresses delivers nothing and shows no chooser`() {+        providerWith(+            mapOf(+                rowUri.toString() to listOf(postalRow(null)),+                contactUri.toString() to listOf(arrayOf<Any?>("9", null, null, null, null, null, null, "9")),+                ContactsContract.Data.CONTENT_URI.toString() to emptyList(),+            ),+        )+        val registry = FakeRegistry { contract, _ ->+            if (contract is ActivityResultContracts.PickContact) {+                Activity.RESULT_OK to dataIntent(contactUri)+            } else {+                Activity.RESULT_OK to dataIntent(rowUri)+            }+        }+        val picked = mutableListOf<String>()+        setUpButton(registry, picked)+        rule.onNodeWithContentDescription("Contacts").performClick()+        rule.waitForIdle()+        assertEquals(emptyList(), picked)+        rule.onNodeWithText("Choose an address").assertDoesNotExist()+    }++    /** Refuses every query until [refuse] flips, then serves one postal row. */+    private class FlakyContactsProvider : ContentProvider() {+        override fun onCreate(): Boolean = true+        override fun query(+            uri: Uri,+            projection: Array<String>?,+            selection: String?,+            selectionArgs: Array<String>?,+            sortOrder: String?,+        ): Cursor {+            if (refuse) throw SecurityException("no READ_CONTACTS yet")+            val cursor = android.database.MatrixCursor(+                arrayOf(+                    ContactsContract.Data.MIMETYPE,+                    ContactsContract.CommonDataKinds.StructuredPostal.FORMATTED_ADDRESS,+                    ContactsContract.CommonDataKinds.StructuredPostal.STREET,+                    ContactsContract.CommonDataKinds.StructuredPostal.CITY,+                    ContactsContract.CommonDataKinds.StructuredPostal.REGION,+                    ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE,+                    ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY,+                    ContactsContract.Contacts._ID,+                ),+            )+            cursor.addRow(+                arrayOf<Any?>(+                    ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE,+                    "3 Third St, Springfield", null, null, null, null, null, "9",+                ),+            )+            return cursor+        }+        override fun getType(uri: Uri): String? = null+        override fun insert(uri: Uri, values: ContentValues?): Uri? = null+        override fun delete(uri: Uri, selection: String?, selectionArgs: Array<String>?): Int = 0+        override fun update(uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array<String>?): Int = 0++        companion object {+            var refuse = true+        }+    }++    @Test fun `a granted permission retries the refused contact read`() {+        FlakyContactsProvider.refuse = true+        Robolectric.setupContentProvider(FlakyContactsProvider::class.java, "com.android.contacts")+        val registry = FakeRegistry { contract, _ ->+            when (contract) {+                is ActivityResultContracts.PickContact -> Activity.RESULT_OK to dataIntent(contactUri)+                is ActivityResultContracts.RequestPermission -> {+                    FlakyContactsProvider.refuse = false+                    Activity.RESULT_OK to Intent().putExtra(+                        "androidx.activity.result.contract.extra.PERMISSION_GRANT_RESULTS",+                        intArrayOf(android.content.pm.PackageManager.PERMISSION_GRANTED),+                    )+                }+                else -> Activity.RESULT_OK to dataIntent(rowUri)+            }+        }+        val picked = mutableListOf<String>()+        setUpButton(registry, picked)+        rule.onNodeWithContentDescription("Contacts").performClick()+        rule.waitForIdle()+        assertEquals(listOf("3 Third St, Springfield"), picked)+    }++    @Test fun `a cancelled contact pick after an empty postal row delivers nothing`() {+        providerWith(mapOf(rowUri.toString() to listOf(postalRow(null))))+        val registry = FakeRegistry { contract, _ ->+            if (contract is ActivityResultContracts.PickContact) {+                Activity.RESULT_CANCELED to null+            } else {+                Activity.RESULT_OK to dataIntent(rowUri)+            }+        }+        val picked = mutableListOf<String>()+        setUpButton(registry, picked)+        rule.onNodeWithContentDescription("Contacts").performClick()+        rule.waitForIdle()+        assertEquals(emptyList(), picked)+        rule.onNodeWithText("Choose an address").assertDoesNotExist()+    }++    @Test fun `a refused contact read asks for permission and a denial delivers nothing`() {+        Robolectric.setupContentProvider(ThrowingContactsProvider::class.java, "com.android.contacts")+        val registry = FakeRegistry { contract, _ ->+            when (contract) {+                is ActivityResultContracts.PickContact -> Activity.RESULT_OK to dataIntent(contactUri)+                is ActivityResultContracts.RequestPermission -> Activity.RESULT_OK to Intent()+                else -> Activity.RESULT_OK to dataIntent(rowUri)+            }+        }+        val picked = mutableListOf<String>()+        setUpButton(registry, picked)+        rule.onNodeWithContentDescription("Contacts").performClick()+        rule.waitForIdle()+        // Postal read was refused too, so the flow fell back to the contact+        // picker, whose read was refused again: permission was requested and+        // the (empty-intent) answer counts as denied.+        assertEquals(emptyList(), picked)+        assertTrue(+            registry.launches.any { it.contains("RequestPermission") },+            "permission requested: ${registry.launches}",+        )+    }+}
maps/src/test/java/com/vayunmathur/maps/ui/DepartureTimeEdgesSlice2Test.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/ui/DepartureTimeEdgesSlice2Test.kt b/maps/src/test/java/com/vayunmathur/maps/ui/DepartureTimeEdgesSlice2Test.ktnew file mode 100644index 0000000000..489e1f3032--- /dev/null+++ b/maps/src/test/java/com/vayunmathur/maps/ui/DepartureTimeEdgesSlice2Test.kt@@ -0,0 +1,82 @@+package com.vayunmathur.maps.ui++import java.time.ZoneId+import java.util.Locale+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++/**+ * The departure-time label edges the board tests cannot all reach: the+ * default clock entry point, symmetric rounding, and the scroll index at+ * its extremes.+ * Slice-2 coverage for maps (basename D, outside the slice-1 dirs).+ */+class DepartureTimeEdgesSlice2Test {++    private val now = 1_700_000_000_000L+    private val utc: ZoneId = ZoneId.of("UTC")++    @Test fun `the default clock entry point formats like the explicit one`() {+        assertEquals(+            DepartureTime.clock(now, ZoneId.systemDefault(), Locale.getDefault()),+            DepartureTime.clock(now),+        )+        assertTrue(DepartureTime.clock(now, utc, Locale.US).isNotBlank())+    }++    @Test fun `labels switch from countdown to clock past ten minutes`() {+        assertEquals(+            DepartureTime.Label.InMinutes(10),+            DepartureTime.label(now + 10 * 60_000L, now, utc, Locale.US),+        )+        assertTrue(+            DepartureTime.label(now + 11 * 60_000L, now, utc, Locale.US) is DepartureTime.Label.Clock,+        )+        assertEquals(+            DepartureTime.Label.MinutesAgo(10),+            DepartureTime.label(now - 10 * 60_000L, now, utc, Locale.US),+        )+        assertTrue(+            DepartureTime.label(now - 11 * 60_000L, now, utc, Locale.US) is DepartureTime.Label.Clock,+        )+    }++    @Test fun `ninety seconds rounds the same in both directions`() {+        assertEquals(+            DepartureTime.Label.InMinutes(2),+            DepartureTime.label(now + 90_000L, now, utc, Locale.US),+        )+        assertEquals(+            DepartureTime.Label.MinutesAgo(2),+            DepartureTime.label(now - 90_000L, now, utc, Locale.US),+        )+        assertEquals(+            DepartureTime.Label.Now,+            DepartureTime.label(now + 20_000L, now, utc, Locale.US),+        )+        assertEquals(+            DepartureTime.Label.Now,+            DepartureTime.label(now - 20_000L, now, utc, Locale.US),+        )+    }++    @Test fun `the window is a day either side inclusive`() {+        val dayMs = 24L * 60 * 60_000L+        assertTrue(DepartureTime.withinWindow(now + dayMs, now))+        assertTrue(DepartureTime.withinWindow(now - dayMs, now))+        assertFalse(DepartureTime.withinWindow(now + dayMs + 1, now))+        assertFalse(DepartureTime.withinWindow(now - dayMs - 1, now))+    }++    @Test fun `first upcoming at the extremes`() {+        assertEquals(0, DepartureTime.firstUpcoming(emptyList(), now))+        assertEquals(0, DepartureTime.firstUpcoming(listOf(now + 1, now + 2), now))+        // Everything gone: the index is the size, scrolling to the end.+        assertEquals(2, DepartureTime.firstUpcoming(listOf(now - 2, now - 1), now))+        assertEquals(1, DepartureTime.firstUpcoming(listOf(now - 1, now + 1), now))+        // A departure exactly now counts as upcoming.+        assertEquals(0, DepartureTime.firstUpcoming(listOf(now), now))+    }+}
maps/src/test/java/com/vayunmathur/maps/ui/DeparturesExtraSlice2Test.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/ui/DeparturesExtraSlice2Test.kt b/maps/src/test/java/com/vayunmathur/maps/ui/DeparturesExtraSlice2Test.ktnew file mode 100644index 0000000000..30ec913923--- /dev/null+++ b/maps/src/test/java/com/vayunmathur/maps/ui/DeparturesExtraSlice2Test.kt@@ -0,0 +1,99 @@+package com.vayunmathur.maps.ui++import androidx.compose.ui.test.assertIsDisplayed+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.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.maps.data.transit.Departure+import com.vayunmathur.maps.data.transit.TransitStop+import com.vayunmathur.maps.util.DeparturesState+import kotlin.test.Test+import kotlin.test.assertEquals+import org.junit.Rule+import org.junit.runner.RunWith++/**+ * Departure-board rows the first pass did not render: already-departed+ * (minutes-ago wording, dimmed), far-future (clock wording), the delay+ * colour bands, a scheduled-only row, the refresh action, and dismissal.+ * Slice-2 coverage for maps (basename D, outside the slice-1 dirs).+ */+@RunWith(AndroidJUnit4::class)+class DeparturesExtraSlice2Test {++    @get:Rule+    val rule = createComposeRule()++    private val stop = TransitStop(id = "s1", name = "Ferry Terminal", lat = 37.8, lon = -122.4)++    private fun departure(+        line: String = "N",+        headsign: String = "Ocean Beach",+        inMinutes: Long = 5,+        delayMinutes: Int = 0,+        realTime: Boolean = true,+        cancelled: Boolean = false,+    ): Departure {+        val now = System.currentTimeMillis()+        return Departure(+            line = line,+            headsign = headsign,+            scheduledMillis = now + inMinutes * 60_000L,+            realtimeMillis = now + inMinutes * 60_000L,+            delayMinutes = delayMinutes,+            realTime = realTime,+            platform = null,+            mode = "tram",+            routeColor = null,+            cancelled = cancelled,+            tripVehicleId = null,+        )+    }++    private fun board(departures: List<Departure>, onRefresh: () -> Unit = {}, onDismiss: () -> Unit = {}) {+        rule.setContent {+            DeparturesSheet(+                state = DeparturesState.Loaded(stop, departures),+                onDismiss = onDismiss,+                onRefresh = onRefresh,+            )+        }+    }++    @Test fun `a departed train reads minutes ago`() {+        board(listOf(departure(inMinutes = -5)))+        rule.onNodeWithText("Ferry Terminal").assertIsDisplayed()+        rule.onNodeWithText("5 min ago").assertIsDisplayed()+    }++    @Test fun `a train beyond the countdown window reads as a clock time`() {+        board(listOf(departure(inMinutes = 120)))+        // Clock wording is locale-formatted; the row itself must render with+        // its line and destination rather than a minute count.+        rule.onNodeWithText("Ocean Beach").assertIsDisplayed()+    }++    @Test fun `delay bands and a scheduled only row all render`() {+        board(+            listOf(+                departure(line = "N", headsign = "On Time", inMinutes = 3, delayMinutes = 0),+                departure(line = "L", headsign = "Slightly Late", inMinutes = 6, delayMinutes = 3),+                departure(line = "M", headsign = "Very Late", inMinutes = 9, delayMinutes = 12),+                departure(line = "K", headsign = "Scheduled Only", inMinutes = 15, realTime = false),+                departure(line = "J", headsign = "Early Bird", inMinutes = 20, delayMinutes = -4),+            ),+        )+        rule.onNodeWithText("On Time").assertIsDisplayed()+        rule.onNodeWithText("Scheduled Only").assertIsDisplayed()+    }++    @Test fun `refresh fires from the board header`() {+        var refreshes = 0+        board(listOf(departure()), onRefresh = { refreshes++ })+        rule.onNodeWithText("Ferry Terminal").assertIsDisplayed()+        rule.onNodeWithContentDescription("Refresh").performClick()+        assertEquals(1, refreshes)+    }+}
maps/src/test/java/com/vayunmathur/maps/ui/DeparturesRowsSlice2Test.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/ui/DeparturesRowsSlice2Test.kt b/maps/src/test/java/com/vayunmathur/maps/ui/DeparturesRowsSlice2Test.ktnew file mode 100644index 0000000000..0b18ea0746--- /dev/null+++ b/maps/src/test/java/com/vayunmathur/maps/ui/DeparturesRowsSlice2Test.kt@@ -0,0 +1,113 @@+package com.vayunmathur.maps.ui++import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.assertCountEquals+import androidx.compose.ui.test.onAllNodesWithText+import androidx.compose.ui.test.onNodeWithText+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.maps.data.transit.Departure+import com.vayunmathur.maps.data.transit.TransitStop+import com.vayunmathur.maps.util.DeparturesState+import kotlin.test.Test+import org.junit.Rule+import org.junit.runner.RunWith++/**+ * Departure rows with the remaining field combinations: a blank headsign,+ * platform and route colour present, a loaded board whose trains all fall+ * outside the display window, and a loading board with no stop yet.+ * Slice-2 coverage for maps (basename D, outside the slice-1 dirs).+ */+@RunWith(AndroidJUnit4::class)+class DeparturesRowsSlice2Test {++    @get:Rule+    val rule = createComposeRule()++    private val stop = TransitStop(id = "s1", name = "Ferry Terminal", lat = 37.8, lon = -122.4)++    private fun departure(+        line: String = "N",+        headsign: String = "Ocean Beach",+        inMinutes: Long = 5,+        platform: String? = null,+        routeColor: String? = null,+        cancelled: Boolean = false,+    ): Departure {+        val now = System.currentTimeMillis()+        return Departure(+            line = line,+            headsign = headsign,+            scheduledMillis = now + inMinutes * 60_000L,+            realtimeMillis = now + inMinutes * 60_000L,+            delayMinutes = 0,+            realTime = true,+            platform = platform,+            mode = "tram",+            routeColor = routeColor,+            cancelled = cancelled,+            tripVehicleId = null,+        )+    }++    @Test fun `a blank headsign shows the dash placeholder`() {+        rule.setContent {+            DeparturesSheet(+                state = DeparturesState.Loaded(stop, listOf(departure(headsign = ""))),+                onDismiss = {},+                onRefresh = {},+            )+        }+        rule.onNodeWithText("—").assertIsDisplayed()+    }++    @Test fun `platform and colour and cancellation all render on one row`() {+        rule.setContent {+            DeparturesSheet(+                state = DeparturesState.Loaded(+                    stop,+                    listOf(departure(platform = "2", routeColor = "#FF0000", cancelled = true)),+                ),+                onDismiss = {},+                onRefresh = {},+            )+        }+        rule.onNodeWithText("Ocean Beach").assertIsDisplayed()+        rule.onNodeWithText("Platform 2").assertIsDisplayed()+    }++    @Test fun `trains outside the window leave an empty list under the header`() {+        rule.setContent {+            DeparturesSheet(+                state = DeparturesState.Loaded(stop, listOf(departure(inMinutes = 30 * 60))),+                onDismiss = {},+                onRefresh = {},+            )+        }+        rule.onNodeWithText("Ferry Terminal").assertIsDisplayed()+        rule.onNodeWithText("Ocean Beach").assertDoesNotExist()+    }++    @Test fun `a loading board shows its fetching message`() {+        rule.setContent {+            DeparturesSheet(+                state = DeparturesState.Loading(stop),+                onDismiss = {},+                onRefresh = {},+            )+        }+        rule.onNodeWithText("Ferry Terminal").assertIsDisplayed()+    }++    @Test fun `an idle board shows only the generic header`() {+        rule.setContent {+            DeparturesSheet(+                state = DeparturesState.Idle,+                onDismiss = {},+                onRefresh = {},+            )+        }+        rule.onAllNodesWithText("Departures").assertCountEquals(2)+    }+}
maps/src/test/java/com/vayunmathur/maps/ui/GoogleConsentRecordSlice2Test.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/ui/GoogleConsentRecordSlice2Test.kt b/maps/src/test/java/com/vayunmathur/maps/ui/GoogleConsentRecordSlice2Test.ktnew file mode 100644index 0000000000..66eba55ed8--- /dev/null+++ b/maps/src/test/java/com/vayunmathur/maps/ui/GoogleConsentRecordSlice2Test.kt@@ -0,0 +1,44 @@+package com.vayunmathur.maps.ui++import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.library.util.DataStoreUtils+import kotlin.test.Test+import kotlin.test.assertFalse+import kotlin.test.assertTrue+import org.junit.runner.RunWith++/**+ * Recording a consent choice directly (the non-ViewModel path): the write+ * lands on DataStore's IO threads, so the test polls the synchronous gates+ * with a bounded deadline instead of sleeping a fixed duration.+ * Slice-2 coverage for maps (basename G, outside the slice-1 dirs).+ */+@RunWith(AndroidJUnit4::class)+class GoogleConsentRecordSlice2Test {++    private val context get() = ApplicationProvider.getApplicationContext<android.content.Context>()++    private fun await(desc: String, cond: () -> Boolean) {+        val deadline = System.currentTimeMillis() + 15_000+        while (System.currentTimeMillis() < deadline) {+            if (cond()) return+            Thread.sleep(25)+        }+        assertTrue(cond(), "timed out waiting for: $desc")+    }++    @Test fun `recording a choice flips both gates`() {+        val ds = DataStoreUtils.getInstance(context)+        recordGoogleConsent(ds, enabled = true)+        await("consent asked") { !shouldShowGoogleConsent(ds) }+        await("services enabled") { googleServicesEnabled(ds) }+        assertFalse(shouldShowGoogleConsent(ds))+        assertTrue(googleServicesEnabled(ds))++        recordGoogleConsent(ds, enabled = false)+        await("services disabled") { !googleServicesEnabled(ds) }+        assertFalse(googleServicesEnabled(ds))+        assertFalse(shouldShowGoogleConsent(ds))+    }+}
maps/src/test/java/com/vayunmathur/maps/util/ContactLookupLaunchersSlice2Test.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/util/ContactLookupLaunchersSlice2Test.kt b/maps/src/test/java/com/vayunmathur/maps/util/ContactLookupLaunchersSlice2Test.ktindex 098354e00a..02e77ca9d0 100644--- a/maps/src/test/java/com/vayunmathur/maps/util/ContactLookupLaunchersSlice2Test.kt+++ b/maps/src/test/java/com/vayunmathur/maps/util/ContactLookupLaunchersSlice2Test.kt@@ -1,98 +1,142 @@ package com.vayunmathur.maps.util +import android.app.Application import android.content.ActivityNotFoundException+import android.content.ContentProvider+import android.content.ContentValues+import android.content.Context import android.content.Intent+import android.database.Cursor+import android.database.MatrixCursor+import android.net.Uri+import android.provider.ContactsContract+import android.provider.ContactsContract.CommonDataKinds.StructuredPostal import androidx.activity.result.ActivityResultLauncher-import androidx.activity.result.contract.ActivityResultContracts+import androidx.activity.result.contract.ActivityResultContract import androidx.core.app.ActivityOptionsCompat import androidx.test.core.app.ApplicationProvider-import androidx.test.ext.junit.runners.AndroidJUnit4 import kotlin.test.Test import kotlin.test.assertEquals-import kotlin.test.assertTrue+import kotlin.test.assertNull import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.RobolectricTestRunner  /**- * The postal-picker fallback chain: postal row first, whole-contact second,- * quiet no-op when the device has neither.+ * The picker fallback chain with fake launchers (postal refused → contact+ * picker → give up), and session reads over a cursor that carries no+ * mimetype column at all.  * Slice-2 coverage for maps (basename C, outside the slice-1 dirs).  */-@RunWith(AndroidJUnit4::class)+@RunWith(RobolectricTestRunner::class) class ContactLookupLaunchersSlice2Test { -    private class RecordingLauncher<I>(-        private val behaviour: (I) -> Unit = {},-    ) : ActivityResultLauncher<I>() {-        val launched = mutableListOf<I>()-        override val contract: androidx.activity.result.contract.ActivityResultContract<I, *>-            get() = throw UnsupportedOperationException("test fake")+    private val context: Context get() = ApplicationProvider.getApplicationContext() +    private class FakeLauncher<I>(+        override val contract: ActivityResultContract<I, *>,+        private val fails: Boolean = false,+    ) : ActivityResultLauncher<I>() {+        val launchedInputs = mutableListOf<I?>()         override fun launch(input: I, options: ActivityOptionsCompat?) {-            launched.add(input)-            behaviour(input)+            launchedInputs += input+            if (fails) throw ActivityNotFoundException("no handler")         }-         override fun unregister() {}     } -    @Test-    fun `the postal picker is tried first`() {-        val postal = RecordingLauncher<Intent>()-        val contact = RecordingLauncher<Void?>()+    /** Serves postal rows with NO mimetype column in the cursor. */+    private class NoMimeProvider : ContentProvider() {+        override fun onCreate(): Boolean = true+        override fun query(+            uri: Uri,+            projection: Array<String>?,+            selection: String?,+            selectionArgs: Array<String>?,+            sortOrder: String?,+        ): Cursor {+            val cursor = MatrixCursor(+                arrayOf(+                    StructuredPostal.FORMATTED_ADDRESS,+                    StructuredPostal.STREET,+                    StructuredPostal.CITY,+                    StructuredPostal.REGION,+                    StructuredPostal.POSTCODE,+                    StructuredPostal.COUNTRY,+                ),+            )+            cursor.addRow(arrayOf<Any?>("9 Elm St\nSpringfield", null, null, null, null, null))+            return cursor+        }+        override fun getType(uri: Uri): String? = null+        override fun insert(uri: Uri, values: ContentValues?): Uri? = null+        override fun delete(uri: Uri, selection: String?, selectionArgs: Array<String>?): Int = 0+        override fun update(uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array<String>?): Int = 0+    }++    @Test fun `the postal picker launches a postal pick intent`() {+        val postal = FakeLauncher(androidx.activity.result.contract.ActivityResultContracts.StartActivityForResult())+        val contact = FakeLauncher(androidx.activity.result.contract.ActivityResultContracts.PickContact())         var noPicker = 0-        launchPostalPicker(postal, contact, onNoPicker = { noPicker++ })-        assertEquals(1, postal.launched.size)-        assertEquals(0, contact.launched.size)+        launchPostalPicker(postal, contact) { noPicker++ }+        assertEquals(1, postal.launchedInputs.size)+        assertEquals(StructuredPostal.CONTENT_TYPE, postal.launchedInputs.first()?.type)+        assertEquals(0, contact.launchedInputs.size)         assertEquals(0, noPicker)-        // Typed to the postal content type.-        assertEquals(-            android.provider.ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_TYPE,-            postal.launched[0].type,-        )-        assertEquals(Intent.ACTION_PICK, postal.launched[0].action)     } -    @Test-    fun `no postal picker falls back to the whole-contact picker`() {-        val postal = RecordingLauncher<Intent> { throw ActivityNotFoundException() }-        val contact = RecordingLauncher<Void?>()+    @Test fun `a refused postal picker falls back to the contact picker`() {+        val postal = FakeLauncher(+            androidx.activity.result.contract.ActivityResultContracts.StartActivityForResult(),+            fails = true,+        )+        val contact = FakeLauncher(androidx.activity.result.contract.ActivityResultContracts.PickContact())         var noPicker = 0-        launchPostalPicker(postal, contact, onNoPicker = { noPicker++ })-        assertEquals(1, postal.launched.size)-        assertEquals(1, contact.launched.size)+        launchPostalPicker(postal, contact) { noPicker++ }+        assertEquals(1, contact.launchedInputs.size)+        assertNull(contact.launchedInputs.first())         assertEquals(0, noPicker)     } -    @Test-    fun `no picker at all reports through onNoPicker`() {-        val contact = RecordingLauncher<Void?> { throw ActivityNotFoundException() }+    @Test fun `when even the contact picker is refused the caller is told`() {+        val postal = FakeLauncher(+            androidx.activity.result.contract.ActivityResultContracts.StartActivityForResult(),+            fails = true,+        )+        val contact = FakeLauncher(+            androidx.activity.result.contract.ActivityResultContracts.PickContact(),+            fails = true,+        )         var noPicker = 0-        launchContactPicker(contact, onNoPicker = { noPicker++ })-        assertEquals(1, contact.launched.size)+        launchPostalPicker(postal, contact) { noPicker++ }         assertEquals(1, noPicker)     } -    @Test-    fun `a working contact picker stays quiet`() {-        val contact = RecordingLauncher<Void?>()+    @Test fun `the contact picker alone reports refusal the same way`() {+        val contact = FakeLauncher(+            androidx.activity.result.contract.ActivityResultContracts.PickContact(),+            fails = true,+        )         var noPicker = 0-        launchContactPicker(contact, onNoPicker = { noPicker++ })-        assertEquals(1, contact.launched.size)-        assertEquals(0, noPicker)+        launchContactPicker(contact) { noPicker++ }+        assertEquals(1, noPicker)     } -    @Test-    fun `double fallback reaches onNoPicker`() {-        val postal = RecordingLauncher<Intent> { throw ActivityNotFoundException() }-        val contact = RecordingLauncher<Void?> { throw ActivityNotFoundException() }-        var noPicker = 0-        launchPostalPicker(postal, contact, onNoPicker = { noPicker++ })-        assertEquals(1, noPicker)+    @Test fun `a session cursor without a mimetype column still reads its rows`() {+        Robolectric.setupContentProvider(NoMimeProvider::class.java, "com.android.contacts")+        val uri = Uri.parse("content://com.android.contacts/session/42")+        assertEquals(+            listOf("9 Elm St, Springfield"),+            readSessionAddresses(context, uri),+        )     } -    @Test-    fun `the system picker intent is only built on android 17`() {-        // Robolectric runs SDK 34 here, below CINNAMON_BUN — document the gate.-        assertTrue(android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.CINNAMON_BUN)+    @Test fun `a contact uri that no longer resolves reads empty`() {+        Robolectric.setupContentProvider(+            ContactLookupProvidersSlice2Test.FakeContactsProvider::class.java,+            "com.android.contacts",+        )+        val uri = Uri.parse("content://com.android.contacts/contacts/404")+        assertEquals(emptyList(), readContactAddresses(context, uri))     } }
maps/src/test/java/com/vayunmathur/maps/util/ContactLookupNullCursorSlice2Test.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/util/ContactLookupNullCursorSlice2Test.kt b/maps/src/test/java/com/vayunmathur/maps/util/ContactLookupNullCursorSlice2Test.ktnew file mode 100644index 0000000000..d052d797e7--- /dev/null+++ b/maps/src/test/java/com/vayunmathur/maps/util/ContactLookupNullCursorSlice2Test.kt@@ -0,0 +1,50 @@+package com.vayunmathur.maps.util++import android.content.ContentProvider+import android.content.ContentValues+import android.content.Context+import android.database.Cursor+import android.net.Uri+import androidx.test.core.app.ApplicationProvider+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.RobolectricTestRunner++/**+ * Contacts reads when the provider answers with no cursor at all (an OEM+ * provider mid-teardown does this): every read degrades to empty/null.+ * Slice-2 coverage for maps (basename C, outside the slice-1 dirs).+ */+@RunWith(RobolectricTestRunner::class)+class ContactLookupNullCursorSlice2Test {++    private class NullCursorProvider : ContentProvider() {+        override fun onCreate(): Boolean = true+        override fun query(+            uri: Uri,+            projection: Array<String>?,+            selection: String?,+            selectionArgs: Array<String>?,+            sortOrder: String?,+        ): Cursor? = null+        override fun getType(uri: Uri): String? = null+        override fun insert(uri: Uri, values: ContentValues?): Uri? = null+        override fun delete(uri: Uri, selection: String?, selectionArgs: Array<String>?): Int = 0+        override fun update(uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array<String>?): Int = 0+    }++    private val context: Context get() = ApplicationProvider.getApplicationContext()++    @Test fun `null cursors read as empty everywhere`() {+        Robolectric.setupContentProvider(NullCursorProvider::class.java, "com.android.contacts")+        val session = Uri.parse("content://com.android.contacts/session/1")+        val row = Uri.parse("content://com.android.contacts/data/7")+        val contact = Uri.parse("content://com.android.contacts/contacts/9")+        assertEquals(emptyList(), readSessionAddresses(context, session))+        assertNull(readAddress(context, row))+        assertEquals(emptyList(), readContactAddresses(context, contact))+    }+}
maps/src/test/java/com/vayunmathur/maps/util/ContactLookupPostalSlice2Test.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/util/ContactLookupPostalSlice2Test.kt b/maps/src/test/java/com/vayunmathur/maps/util/ContactLookupPostalSlice2Test.ktnew file mode 100644index 0000000000..d708d35077--- /dev/null+++ b/maps/src/test/java/com/vayunmathur/maps/util/ContactLookupPostalSlice2Test.kt@@ -0,0 +1,70 @@+package com.vayunmathur.maps.util++import android.content.Context+import android.net.Uri+import android.provider.ContactsContract.CommonDataKinds.StructuredPostal+import androidx.test.core.app.ApplicationProvider+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.RobolectricTestRunner++/**+ * Postal-row composition edges: a null mimetype counts as postal, a blank+ * formatted address falls back to components, and whitespace-only rows+ * read as no address.+ * Slice-2 coverage for maps (basename C, outside the slice-1 dirs).+ */+@RunWith(RobolectricTestRunner::class)+class ContactLookupPostalSlice2Test {++    private val context: Context get() = ApplicationProvider.getApplicationContext()+    private val sessionUri = Uri.parse("content://com.android.contacts/session/3")+    private val rowUri = Uri.parse("content://com.android.contacts/data/11")++    private fun setUp(rows: Map<String, List<Array<Any?>>>) {+        val provider = Robolectric.setupContentProvider(+            ContactLookupProvidersSlice2Test.FakeContactsProvider::class.java,+            "com.android.contacts",+        )+        provider.tables = rows+    }++    private fun row(+        formatted: String? = null,+        street: String? = null,+        city: String? = null,+        region: String? = null,+        postcode: String? = null,+        country: String? = null,+        mime: String? = StructuredPostal.CONTENT_ITEM_TYPE,+    ): Array<Any?> = arrayOf(mime, formatted, street, city, region, postcode, country, "9")++    @Test fun `a session row with a null mimetype counts as postal`() {+        setUp(mapOf(sessionUri.toString() to listOf(row(formatted = "1 Main St", mime = null))))+        assertEquals(listOf("1 Main St"), readSessionAddresses(context, sessionUri))+    }++    @Test fun `a blank formatted address falls back to its components`() {+        setUp(+            mapOf(+                rowUri.toString() to listOf(+                    row(formatted = "   ", street = "2 Oak Ave", city = "Springfield"),+                ),+            ),+        )+        assertEquals("2 Oak Ave, Springfield", readAddress(context, rowUri))+    }++    @Test fun `a whitespace only address reads as no address`() {+        setUp(mapOf(rowUri.toString() to listOf(row(formatted = "\n  \n"))))+        assertNull(readAddress(context, rowUri))+    }++    @Test fun `a multiline formatted address collapses blank lines and runs of spaces`() {+        setUp(mapOf(rowUri.toString() to listOf(row(formatted = "3  Pine   St\n\nSpringfield,  IL"))))+        assertEquals("3 Pine St, Springfield, IL", readAddress(context, rowUri))+    }+}
maps/src/test/java/com/vayunmathur/maps/util/FrameworkLocationNoAccuracySlice2Test.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/util/FrameworkLocationNoAccuracySlice2Test.kt b/maps/src/test/java/com/vayunmathur/maps/util/FrameworkLocationNoAccuracySlice2Test.ktnew file mode 100644index 0000000000..1c6022a0b8--- /dev/null+++ b/maps/src/test/java/com/vayunmathur/maps/util/FrameworkLocationNoAccuracySlice2Test.kt@@ -0,0 +1,86 @@+package com.vayunmathur.maps.util++import android.Manifest+import android.app.Application+import android.content.Context+import android.location.Location+import android.location.LocationManager+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.library.map.GeoPoint+import kotlin.test.Test+import kotlin.test.assertEquals+import org.junit.runner.RunWith+import org.robolectric.Shadows.shadowOf++/**+ * Fixes with no accuracy and seeds with a bearing: the fallback branches of+ * the acceptance conversion in the framework location feed.+ * Slice-2 coverage for maps (basename F, outside the slice-1 dirs).+ */+@RunWith(AndroidJUnit4::class)+class FrameworkLocationNoAccuracySlice2Test {++    private val context: Context get() = ApplicationProvider.getApplicationContext()++    private fun bareFix(+        provider: String = LocationManager.GPS_PROVIDER,+        lat: Double = 37.8,+        lon: Double = -122.4,+        bearing: Float? = null,+        timeNanos: Long = 1_000_000_000L,+    ): Location = Location(provider).apply {+        latitude = lat+        longitude = lon+        if (bearing != null) this.bearing = bearing+        elapsedRealtimeNanos = timeNanos+        // Deliberately no accuracy: hasAccuracy() stays false.+    }++    @Test fun `a last-known seed with a bearing uses it and needs no accuracy`() {+        shadowOf(context as Application).grantPermissions(+            Manifest.permission.ACCESS_FINE_LOCATION,+            Manifest.permission.ACCESS_COARSE_LOCATION,+        )+        val lm = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager+        shadowOf(lm).setProviderEnabled(LocationManager.GPS_PROVIDER, true)+        shadowOf(lm).setLastKnownLocation(+            LocationManager.GPS_PROVIDER,+            bareFix(bearing = 45f),+        )+        val manager = FrameworkLocationManager(context)+        val updates = mutableListOf<Pair<GeoPoint, Float?>>()+        manager.startUpdates(onUpdateReceived = { point, heading -> updates.add(point to heading) })+        manager.stop()+        assertEquals(1, updates.size)+        assertEquals(45f, updates[0].second)+    }++    @Test fun `live fixes without accuracy still emit and gate by provider`() {+        shadowOf(context as Application).grantPermissions(+            Manifest.permission.ACCESS_FINE_LOCATION,+            Manifest.permission.ACCESS_COARSE_LOCATION,+        )+        val lm = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager+        shadowOf(lm).setProviderEnabled(LocationManager.GPS_PROVIDER, true)+        shadowOf(lm).setProviderEnabled(LocationManager.NETWORK_PROVIDER, true)+        val manager = FrameworkLocationManager(context)+        val points = mutableListOf<GeoPoint>()+        manager.startUpdates(onUpdateReceived = { point, _ -> points.add(point) })+        val live = shadowOf(lm).requestLocationUpdateListeners+        live.forEach { it.onLocationChanged(bareFix(timeNanos = 1_000_000_000L)) }+        // A network fix with no accuracy stated cannot displace fresh GPS:+        // "provider declined to say" is not evidence of being better.+        live.forEach {+            it.onLocationChanged(+                bareFix(+                    provider = LocationManager.NETWORK_PROVIDER,+                    lat = 37.9,+                    timeNanos = 2_000_000_000L,+                ),+            )+        }+        assertEquals(1, points.size)+        manager.stop()+    }+}
maps/src/test/java/com/vayunmathur/maps/util/FrameworkLocationSensorSlice2Test.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/util/FrameworkLocationSensorSlice2Test.kt b/maps/src/test/java/com/vayunmathur/maps/util/FrameworkLocationSensorSlice2Test.ktnew file mode 100644index 0000000000..28ab61d3c8--- /dev/null+++ b/maps/src/test/java/com/vayunmathur/maps/util/FrameworkLocationSensorSlice2Test.kt@@ -0,0 +1,176 @@+package com.vayunmathur.maps.util++import android.Manifest+import android.app.Application+import android.content.Context+import android.hardware.Sensor+import android.hardware.SensorManager+import android.location.Location+import android.location.LocationManager+import android.os.Looper+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.library.map.GeoPoint+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue+import org.junit.runner.RunWith+import org.robolectric.Shadows.shadowOf+import org.robolectric.shadows.SensorEventBuilder+import org.robolectric.shadows.ShadowSensor++/**+ * The compass half of the framework location feed, plus provider-off and+ * restart behaviour the live-fix suite does not reach.+ * Slice-2 coverage for maps (basename F, outside the slice-1 dirs).+ */+@RunWith(AndroidJUnit4::class)+class FrameworkLocationSensorSlice2Test {++    private val context: Context get() = ApplicationProvider.getApplicationContext()++    private fun grantLocation() {+        shadowOf(context as Application).grantPermissions(+            Manifest.permission.ACCESS_FINE_LOCATION,+            Manifest.permission.ACCESS_COARSE_LOCATION,+        )+    }++    private fun fix(+        provider: String = LocationManager.GPS_PROVIDER,+        lat: Double = 37.8,+        lon: Double = -122.4,+        timeNanos: Long = 1_000_000_000L,+    ): Location = Location(provider).apply {+        latitude = lat+        longitude = lon+        accuracy = 5f+        elapsedRealtimeNanos = timeNanos+    }++    private fun sensorEvent(type: Int, values: FloatArray) =+        SensorEventBuilder.newBuilder()+            .setSensor(ShadowSensor.newInstance(type))+            .setValues(values)+            .build()++    @Test fun `compass emits once a location exists and only on real turns`() {+        grantLocation()+        val lm = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager+        shadowOf(lm).setProviderEnabled(LocationManager.GPS_PROVIDER, true)+        val sm = context.getSystemService(Context.SENSOR_SERVICE) as SensorManager+        shadowOf(sm).addSensor(ShadowSensor.newInstance(Sensor.TYPE_ACCELEROMETER))+        shadowOf(sm).addSensor(ShadowSensor.newInstance(Sensor.TYPE_MAGNETIC_FIELD))++        val manager = FrameworkLocationManager(context)+        val updates = mutableListOf<Pair<GeoPoint, Float?>>()+        val accuracies = mutableListOf<Int>()+        manager.startUpdates(+            onUpdateReceived = { point, heading -> updates.add(point to heading) },+            onAccuracyReceived = { accuracies.add(it) },+        )+        assertTrue(shadowOf(sm).hasListener(manager), "compass listeners registered")++        // No location yet: sensor samples alone never emit a position.+        manager.onSensorChanged(sensorEvent(Sensor.TYPE_ACCELEROMETER, floatArrayOf(0f, 0f, 9.81f)))+        manager.onSensorChanged(sensorEvent(Sensor.TYPE_MAGNETIC_FIELD, floatArrayOf(0f, 25f, -40f)))+        assertEquals(0, updates.size)++        // A fix without bearing opens the gate for the compass path.+        shadowOf(lm).requestLocationUpdateListeners.forEach { it.onLocationChanged(fix()) }+        assertEquals(1, updates.size)++        // First compass sample after the fix always emits (no prior heading).+        manager.onSensorChanged(sensorEvent(Sensor.TYPE_MAGNETIC_FIELD, floatArrayOf(0f, 25f, -40f)))+        assertTrue(updates.size >= 2, "first heading emits: $updates")+        val settled = updates.size+        // The same heading again is sub-degree movement: gated out.+        manager.onSensorChanged(sensorEvent(Sensor.TYPE_MAGNETIC_FIELD, floatArrayOf(0f, 25f, -40f)))+        manager.onSensorChanged(sensorEvent(Sensor.TYPE_ACCELEROMETER, floatArrayOf(0f, 0f, 9.81f)))+        assertEquals(settled, updates.size)+        // A real turn (field rotated ~90 degrees) emits again.+        manager.onSensorChanged(sensorEvent(Sensor.TYPE_MAGNETIC_FIELD, floatArrayOf(-25f, 0f, -40f)))+        assertTrue(updates.size > settled, "turn emits: $updates")+        assertTrue(updates.last().second != null)++        // Only magnetometer accuracy is a calibration signal.+        manager.onAccuracyChanged(ShadowSensor.newInstance(Sensor.TYPE_MAGNETIC_FIELD), 1)+        manager.onAccuracyChanged(ShadowSensor.newInstance(Sensor.TYPE_ACCELEROMETER), 3)+        manager.onAccuracyChanged(null, 2)+        assertEquals(listOf(1), accuracies)+        manager.stop()+        assertTrue(!shadowOf(sm).hasListener(manager))+    }++    @Test fun `with every provider off nothing registers and nothing emits`() {+        grantLocation()+        val lm = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager+        shadowOf(lm).setProviderEnabled(LocationManager.GPS_PROVIDER, false)+        shadowOf(lm).setProviderEnabled(LocationManager.NETWORK_PROVIDER, false)+        shadowOf(lm).setLastKnownLocation(LocationManager.GPS_PROVIDER, fix())+        val manager = FrameworkLocationManager(context)+        val updates = mutableListOf<Pair<GeoPoint, Float?>>()+        manager.startUpdates(onUpdateReceived = { point, heading -> updates.add(point to heading) })+        assertTrue(shadowOf(lm).requestLocationUpdateListeners.isEmpty())+        assertEquals(0, updates.size)+        manager.stop()+    }++    @Test fun `a network last-known seeds when gps is off`() {+        grantLocation()+        val lm = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager+        shadowOf(lm).setProviderEnabled(LocationManager.GPS_PROVIDER, false)+        shadowOf(lm).setProviderEnabled(LocationManager.NETWORK_PROVIDER, true)+        shadowOf(lm).setLastKnownLocation(+            LocationManager.NETWORK_PROVIDER,+            fix(provider = LocationManager.NETWORK_PROVIDER, lat = 37.25),+        )+        val manager = FrameworkLocationManager(context)+        val points = mutableListOf<GeoPoint>()+        manager.startUpdates(onUpdateReceived = { point, _ -> points.add(point) })+        manager.stop()+        assertEquals(1, points.size)+        assertEquals(37.25, points[0].latitude)+    }++    @Test fun `a restart forgets the previous fix and heading gate`() {+        grantLocation()+        val lm = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager+        shadowOf(lm).setProviderEnabled(LocationManager.GPS_PROVIDER, true)+        val manager = FrameworkLocationManager(context)+        val points = mutableListOf<GeoPoint>()+        manager.startUpdates(onUpdateReceived = { point, _ -> points.add(point) })+        shadowOf(lm).requestLocationUpdateListeners.forEach { it.onLocationChanged(fix()) }+        manager.stop()+        // Same fix again in a fresh session: it must emit, not be rejected as stale.+        manager.startUpdates(onUpdateReceived = { point, _ -> points.add(point) })+        shadowOf(lm).requestLocationUpdateListeners.forEach { it.onLocationChanged(fix()) }+        manager.stop()+        assertEquals(2, points.size)+        shadowOf(Looper.getMainLooper()).idle()+    }++    @Test fun `a stale network fix can displace gps and a much tighter one can too`() {+        grantLocation()+        val lm = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager+        shadowOf(lm).setProviderEnabled(LocationManager.GPS_PROVIDER, true)+        shadowOf(lm).setProviderEnabled(LocationManager.NETWORK_PROVIDER, true)+        val manager = FrameworkLocationManager(context)+        val points = mutableListOf<GeoPoint>()+        manager.startUpdates(onUpdateReceived = { point, _ -> points.add(point) })+        val live = shadowOf(lm).requestLocationUpdateListeners+        // GPS at t=1s, then a network fix 11 s later (GPS stale) far away: taken.+        live.forEach { it.onLocationChanged(fix(timeNanos = 1_000_000_000L)) }+        live.forEach {+            it.onLocationChanged(+                Location(LocationManager.NETWORK_PROVIDER).apply {+                    latitude = 37.9; longitude = -122.5; accuracy = 5f+                    elapsedRealtimeNanos = 12_000_000_000L+                },+            )+        }+        assertEquals(2, points.size)+        assertEquals(37.9, points.last().latitude)+        manager.stop()+    }+}
maps/src/test/java/com/vayunmathur/maps/util/FrameworkLocationStopSlice2Test.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/util/FrameworkLocationStopSlice2Test.kt b/maps/src/test/java/com/vayunmathur/maps/util/FrameworkLocationStopSlice2Test.ktnew file mode 100644index 0000000000..7860d92c4f--- /dev/null+++ b/maps/src/test/java/com/vayunmathur/maps/util/FrameworkLocationStopSlice2Test.kt@@ -0,0 +1,101 @@+package com.vayunmathur.maps.util++import android.Manifest+import android.app.Application+import android.content.Context+import android.hardware.Sensor+import android.location.Location+import android.location.LocationManager+import android.os.Bundle+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.library.map.GeoPoint+import kotlin.test.Test+import kotlin.test.assertEquals+import org.junit.runner.RunWith+import org.robolectric.Shadows.shadowOf+import org.robolectric.shadows.SensorEventBuilder+import org.robolectric.shadows.ShadowSensor++/**+ * Lifecycle edges of the framework location feed: stopping before/without+ * starting, the deprecated status callback, and sensor samples that cannot+ * produce a heading.+ * Slice-2 coverage for maps (basename F, outside the slice-1 dirs).+ */+@RunWith(AndroidJUnit4::class)+class FrameworkLocationStopSlice2Test {++    private val context: Context get() = ApplicationProvider.getApplicationContext()++    private fun fix(): Location = Location(LocationManager.GPS_PROVIDER).apply {+        latitude = 37.8+        longitude = -122.4+        accuracy = 5f+        elapsedRealtimeNanos = 1_000_000_000L+    }++    @Test fun `stop before start and double stop are silent`() {+        val manager = FrameworkLocationManager(context)+        manager.stop()+        manager.stop()+        // Sensor callbacks with nothing registered are also silent.+        manager.onAccuracyChanged(null, 1)+        manager.onSensorChanged(+            SensorEventBuilder.newBuilder()+                .setSensor(ShadowSensor.newInstance(Sensor.TYPE_ROTATION_VECTOR))+                .setValues(floatArrayOf(0f, 0f, 0f, 1f))+                .build(),+        )+    }++    @Test fun `the status callback is a no-op and updates resume after it`() {+        shadowOf(context as Application).grantPermissions(+            Manifest.permission.ACCESS_FINE_LOCATION,+            Manifest.permission.ACCESS_COARSE_LOCATION,+        )+        val lm = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager+        shadowOf(lm).setProviderEnabled(LocationManager.GPS_PROVIDER, true)+        val manager = FrameworkLocationManager(context)+        val points = mutableListOf<GeoPoint>()+        val listener = manager.startUpdates(onUpdateReceived = { point, _ -> points.add(point) })+        @Suppress("DEPRECATION")+        listener.onStatusChanged(LocationManager.GPS_PROVIDER, 2, Bundle())+        listener.onLocationChanged(fix())+        assertEquals(1, points.size)+        manager.stop()+        // Fixes after stop go nowhere: the listener list is unregistered, and+        // a stale direct call still reaches the (now null) callback quietly.+        listener.onLocationChanged(fix().apply { latitude = 38.0; elapsedRealtimeNanos = 5_000_000_000L })+        assertEquals(1, points.size)+    }++    @Test fun `zero readings produce no heading emit`() {+        shadowOf(context as Application).grantPermissions(+            Manifest.permission.ACCESS_FINE_LOCATION,+            Manifest.permission.ACCESS_COARSE_LOCATION,+        )+        val lm = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager+        shadowOf(lm).setProviderEnabled(LocationManager.GPS_PROVIDER, true)+        val manager = FrameworkLocationManager(context)+        val updates = mutableListOf<Pair<GeoPoint, Float?>>()+        manager.startUpdates(onUpdateReceived = { point, heading -> updates.add(point to heading) })+        shadowOf(lm).requestLocationUpdateListeners.forEach { it.onLocationChanged(fix()) }+        assertEquals(1, updates.size)+        // All-zero accel/mag readings cannot form a rotation matrix.+        manager.onSensorChanged(+            SensorEventBuilder.newBuilder()+                .setSensor(ShadowSensor.newInstance(Sensor.TYPE_ACCELEROMETER))+                .setValues(floatArrayOf(0f, 0f, 0f))+                .build(),+        )+        manager.onSensorChanged(+            SensorEventBuilder.newBuilder()+                .setSensor(ShadowSensor.newInstance(Sensor.TYPE_MAGNETIC_FIELD))+                .setValues(floatArrayOf(0f, 0f, 0f))+                .build(),+        )+        assertEquals(1, updates.size)+        manager.stop()+    }+}
maps/src/test/java/com/vayunmathur/maps/util/GTFSColorsSlice2Test.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/util/GTFSColorsSlice2Test.kt b/maps/src/test/java/com/vayunmathur/maps/util/GTFSColorsSlice2Test.ktnew file mode 100644index 0000000000..b7a8304937--- /dev/null+++ b/maps/src/test/java/com/vayunmathur/maps/util/GTFSColorsSlice2Test.kt@@ -0,0 +1,84 @@+package com.vayunmathur.maps.util++import android.content.Context+import android.content.res.AssetManager+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import java.nio.file.Files+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull+import org.junit.runner.RunWith++/**+ * The GTFS route-colour lookup against a real `routes.txt`: header mapping,+ * short/long name matching, quoted commas, caching and absent rows.+ * Slice-2 coverage for maps (basename G, outside the slice-1 dirs).+ *+ * The feed lives in a temp dir registered as an extra asset path on the+ * application's AssetManager.+ */+@RunWith(AndroidJUnit4::class)+class GTFSColorsSlice2Test {++    private val app get() = ApplicationProvider.getApplicationContext<android.content.Context>()++    private fun contextWithRoutes(feed: String, routesTxt: String): Context {+        // Pack the feed as a zip with an assets/ root and register it as an+        // extra asset path on the app's own AssetManager (the addAssetPath+        // the platform itself uses for overlays); feed names are unique per+        // test, so nothing collides.+        val zip = Files.createTempFile("gtfs-feed", ".zip").toFile()+        java.util.zip.ZipOutputStream(zip.outputStream()).use { out ->+            out.putNextEntry(java.util.zip.ZipEntry("assets/$feed/routes.txt"))+            out.write(routesTxt.encodeToByteArray())+            out.closeEntry()+        }+        AssetManager::class.java.getMethod("addAssetPath", String::class.java)+            .invoke(app.assets, zip.absolutePath)+        return app+    }++    private val routes = """+        route_id,route_short_name,route_long_name,route_type,route_color+        R1,N,"Judah, Ocean Beach",3,0000FF+        R2,38,Geary,3,FF0000+        R3,L,,3,+        """.trimIndent() + "\n"++    @Test fun `short and long names resolve to their colours`() {+        val context = contextWithRoutes("feed-a", routes)+        assertEquals("#0000FF", GTFSProvider.getRouteColor(context, "feed-a", "N"))+        assertEquals("#FF0000", GTFSProvider.getRouteColor(context, "feed-a", "38"))+        // The quoted long name with its comma intact is also a key.+        assertEquals("#0000FF", GTFSProvider.getRouteColor(context, "feed-a", "Judah, Ocean Beach"))+    }++    @Test fun `a cached colour survives the feed disappearing`() {+        val context = contextWithRoutes("feed-b", routes)+        assertEquals("#FF0000", GTFSProvider.getRouteColor(context, "feed-b", "Geary"))+        // Second lookup is served from the cache: even a context whose assets+        // are gone (the base app, no such feed) returns the colour.+        assertEquals("#FF0000", GTFSProvider.getRouteColor(app, "feed-b", "Geary"))+    }++    @Test fun `unknown routes and empty colours read null`() {+        val context = contextWithRoutes("feed-c", routes)+        assertNull(GTFSProvider.getRouteColor(context, "feed-c", "ZZZ"))+        // Row exists but its colour cell is empty.+        assertNull(GTFSProvider.getRouteColor(context, "feed-c", "L"))+    }++    @Test fun `a feed without a colour column reads null`() {+        val context = contextWithRoutes(+            "feed-d",+            "route_id,route_short_name,route_long_name\nR1,N,Judah\n",+        )+        assertNull(GTFSProvider.getRouteColor(context, "feed-d", "N"))+    }++    @Test fun `an empty feed file reads null`() {+        val context = contextWithRoutes("feed-e", "")+        assertNull(GTFSProvider.getRouteColor(context, "feed-e", "N"))+    }+}
maps/src/test/java/com/vayunmathur/maps/util/GooglePoiViewportSlice2Test.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/util/GooglePoiViewportSlice2Test.kt b/maps/src/test/java/com/vayunmathur/maps/util/GooglePoiViewportSlice2Test.ktnew file mode 100644index 0000000000..593fc79d30--- /dev/null+++ b/maps/src/test/java/com/vayunmathur/maps/util/GooglePoiViewportSlice2Test.kt@@ -0,0 +1,62 @@+package com.vayunmathur.maps.util++import android.app.Application+import android.os.Looper+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import java.util.concurrent.TimeUnit+import kotlin.test.Test+import kotlin.test.assertEquals+import org.junit.runner.RunWith+import org.robolectric.Shadows.shadowOf++/**+ * The ambient POI driver's debounced lookup body: a narrow viewport runs it+ * (on the ViewModel scope plus Dispatchers.IO), and with no offline index on+ * the test device the previous pins are kept — the no-clear contract.+ * Slice-2 coverage for maps (basename G, outside the slice-1 dirs).+ */+@RunWith(AndroidJUnit4::class)+class GooglePoiViewportSlice2Test {++    private val app get() = ApplicationProvider.getApplicationContext<Application>()++    /** Advance the paused main looper past the debounce, then give the IO+     *  lookup a bounded window to land before asserting. */+    private fun settle(vm: GooglePoiMapViewModel) {+        shadowOf(Looper.getMainLooper()).idleFor(1, TimeUnit.SECONDS)+        val deadline = System.currentTimeMillis() + 10_000+        while (System.currentTimeMillis() < deadline) {+            shadowOf(Looper.getMainLooper()).idle()+            Thread.sleep(20)+            // The lookup publishes only non-empty results; with no index the+            // pins staying empty is the settled state once IO has had time.+            if (System.currentTimeMillis() > deadline - 9_000) break+        }+        shadowOf(Looper.getMainLooper()).idleFor(1, TimeUnit.SECONDS)+    }++    @Test fun `a narrow viewport runs the lookup and keeps pins when the index is empty`() {+        val vm = GooglePoiMapViewModel(app)+        vm.onViewportOffline(north = 37.85, east = -122.35, south = 37.75, west = -122.45)+        settle(vm)+        assertEquals(emptyList(), vm.pins.value)+    }++    @Test fun `rapid viewport changes debounce to the last one`() {+        val vm = GooglePoiMapViewModel(app)+        vm.onViewportOffline(north = 37.85, east = -122.35, south = 37.75, west = -122.45)+        vm.onViewport(north = 37.86, east = -122.34, south = 37.76, west = -122.44)+        vm.onViewportOffline(north = 37.87, east = -122.33, south = 37.77, west = -122.43)+        settle(vm)+        assertEquals(emptyList(), vm.pins.value)+    }++    @Test fun `a wide viewport after a narrow one still keeps the pins`() {+        val vm = GooglePoiMapViewModel(app)+        vm.onViewportOffline(north = 37.85, east = -122.35, south = 37.75, west = -122.45)+        vm.onViewportOffline(north = 40.0, east = -120.0, south = 36.0, west = -124.0)+        settle(vm)+        assertEquals(emptyList(), vm.pins.value)+    }+}