Modern Apps git

← Modern-Apps.git

networklocation: add tests for provider, geocoder, stores and UI

Commit
d8b0374c284afb7a4f51371e6c3f0786ead4b24a
Author
Vayun Mathur <[email protected]>
When
2026-11-07 07:01 UTC (29 days ago)
Parents
43b6333
Coverage 3.8% -> 91.7% (merged, 4991/5443 instructions; unit tests 9 -> 83, all passing).

New Robolectric/JVM tests cover: OfflineDatabases presence/header/prune/open semantics, PositioningData and Route serialization, the native bridges and position solver (empty, single, agreeing and non-finite beacons), OfflineBeaconStore over real WPSDB2 fixtures built in-test (wifi/cell hits, unknown accuracy/altitude, randomized and malformed BSSIDs, late-arriving and truncated stores), GeocodeService provider callbacks over a real minimal v5 geocoder.db fixture (reverse, structured forward, name search, unavailable and late-arriving database), DatabaseStatusProvider caller gating, NearbyCells/NearbyWifi shadow scans including sentinel identities, LocationReportingTask end-to-end fixes, LocationFeeds flows and the pre-Tiramisu geocoder branch, and Compose coverage of Setup/Status/LiveLocation/Navigation including the Found/Failed/Looking geocode states and the download button.

Test-only production changes: GeocodeService.provider is now internal, and LiveLocationSection takes an injectable geocodeLookup defaulting to the existing system-Geocoder path, so its result states can be driven without a backend. Test deps add the compile-only locationprovider stubs and WorkManager runtime to the unit-test classpath only.

Untestable remainder: LocationProviderImpl and NetworkLocationService.onCreate (the compile-only ProviderPropertiesUnbundled.create stub throws on the JVM and the real unbundled provider classes are absent from the emulator image), GeocodeService.onBind (stub binder throws), and the Geocoder listener onError path.

Verified: gslot ./gradlew :networklocation:createMergedCoverageReport, :networklocation:detekt (3 pre-existing UndocumentedPublicClass warnings in untouched files), :networklocation:lint, :networklocation:compileDevKotlin.
(cherry picked from commit 83fd5a6813752197870cbe7f350689c6d42bf8a7)

Diff

networklocation/build.gradle.kts
diff --git a/networklocation/build.gradle.kts b/networklocation/build.gradle.ktsindex 51b7639931..ea161d7a76 100644--- a/networklocation/build.gradle.kts+++ b/networklocation/build.gradle.kts@@ -41,6 +41,12 @@ dependencies {     // Resumable, checksummed, unmetered-only fetch of the offline databases, which are no     // longer bundled (see OfflineDatabases). Also supplies the progress UI on the status screen.     implementation(project(":library:downloadservice"))+    // The provider stubs are compile-only in production (the framework supplies them+    // at runtime), but unit tests exercise GeocodeService's provider callbacks on the+    // JVM, so the stub signatures must be on the test runtime classpath too.+    testImplementation(project(":library:locationprovider"))+    // For initializing WorkManager when a test taps the offline-database download button.+    testImplementation(libs.androidx.work.runtime.ktx)     // The offline geocoder search runs natively (Rust/ruzstd) over geocoder.db; there is no     // Kotlin-side DB code, so no zstd-jni / serialization deps are needed here. }
networklocation/src/main/java/com/vayunmathur/networklocation/GeocodeService.kt
diff --git a/networklocation/src/main/java/com/vayunmathur/networklocation/GeocodeService.kt b/networklocation/src/main/java/com/vayunmathur/networklocation/GeocodeService.ktindex 9eade6bc52..4eef03a845 100644--- a/networklocation/src/main/java/com/vayunmathur/networklocation/GeocodeService.kt+++ b/networklocation/src/main/java/com/vayunmathur/networklocation/GeocodeService.kt@@ -23,7 +23,7 @@ class GeocodeService : Service() {     private var pfd: ParcelFileDescriptor? = null     private var handle: Long = 0L -    private val provider: GeocodeProvider by lazy {+    internal val provider: GeocodeProvider by lazy {         object : GeocodeProvider() {             override fun onGetFromLocation(                 latitude: Double,
networklocation/src/main/java/com/vayunmathur/networklocation/ui/LiveLocationSection.kt
diff --git a/networklocation/src/main/java/com/vayunmathur/networklocation/ui/LiveLocationSection.kt b/networklocation/src/main/java/com/vayunmathur/networklocation/ui/LiveLocationSection.ktindex 175da72d1a..316a571b2e 100644--- a/networklocation/src/main/java/com/vayunmathur/networklocation/ui/LiveLocationSection.kt+++ b/networklocation/src/main/java/com/vayunmathur/networklocation/ui/LiveLocationSection.kt@@ -1,5 +1,6 @@ package com.vayunmathur.networklocation.ui +import android.content.Context import android.location.Address import android.location.Location import android.location.LocationManager@@ -46,7 +47,13 @@ private sealed interface GeocodeState {  * the geocoder is judged against a position that does not depend on the beacon stores.  */ @Composable-fun LiveLocationSection(modifier: Modifier = Modifier) {+fun LiveLocationSection(+    modifier: Modifier = Modifier,+    // Injectable so tests can drive the Found/Failed states without a geocoder backend;+    // production always uses the system Geocoder through this app's own GeocodeService.+    geocodeLookup: suspend (Context, Double, Double) -> Result<Address?> =+        { context, lat, lon -> reverseGeocode(context, lat, lon) },+) {     val context = LocalContext.current     if (!hasFineLocation(context)) {         Text(@@ -80,7 +87,7 @@ fun LiveLocationSection(modifier: Modifier = Modifier) {     LaunchedEffect(anchor) {         val fix = anchor ?: return@LaunchedEffect         geocode = GeocodeState.Looking-        geocode = reverseGeocode(context, fix.latitude, fix.longitude).fold(+        geocode = geocodeLookup(context, fix.latitude, fix.longitude).fold(             onSuccess = { a -> a?.let { GeocodeState.Found(it, fix) } ?: GeocodeState.NoMatch },             onFailure = { GeocodeState.Failed(it.message ?: it.javaClass.simpleName) },         )
networklocation/src/test/java/com/vayunmathur/networklocation/GeocodeServiceTest.kt
diff --git a/networklocation/src/test/java/com/vayunmathur/networklocation/GeocodeServiceTest.kt b/networklocation/src/test/java/com/vayunmathur/networklocation/GeocodeServiceTest.ktnew file mode 100644index 0000000000..59f72f1d9c--- /dev/null+++ b/networklocation/src/test/java/com/vayunmathur/networklocation/GeocodeServiceTest.kt@@ -0,0 +1,188 @@+package com.vayunmathur.networklocation++import android.content.Context+import android.location.Address+import android.location.GeocoderParams+import androidx.test.core.app.ApplicationProvider+import java.util.Locale+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.RobolectricTestRunner++@RunWith(RobolectricTestRunner::class)+class GeocodeServiceTest {++    private val context: Context get() = ApplicationProvider.getApplicationContext()++    /** The framework's GeocoderParams constructors are hidden from the SDK stub. */+    private fun params(): GeocoderParams {+        val ctor = GeocoderParams::class.java+            .getConstructor(Context::class.java, Locale::class.java)+        return ctor.newInstance(context, Locale.US)+    }++    private fun clearDb() {+        OfflineDatabases.file(context, OfflineDatabases.GEOCODER).delete()+    }++    private fun installDb() {+        writeGeocoderDb(OfflineDatabases.file(context, OfflineDatabases.GEOCODER))+    }++    @Test+    fun `without the database every query reports unavailable`() {+        clearDb()+        val controller = Robolectric.buildService(GeocodeService::class.java).create()+        val service = controller.get()+        val addrs = mutableListOf<Address>()+        assertEquals(+            "geocoder database unavailable",+            service.provider.onGetFromLocation(37.4215, -122.084, 1, params(), addrs),+        )+        assertEquals(+            "geocoder database unavailable",+            service.provider.onGetFromLocationName("Main St", 0.0, 0.0, 0.0, 0.0, 5, params(), addrs),+        )+        assertTrue(addrs.isEmpty())+        controller.destroy()+    }++    @Test+    fun `reverse geocode maps the flat native result onto an address`() {+        installDb()+        val controller = Robolectric.buildService(GeocodeService::class.java).create()+        val service = controller.get()+        val addrs = mutableListOf<Address>()+        val err = service.provider.onGetFromLocation(37.4215, -122.084, 1, params(), addrs)+        assertNull(err)+        assertEquals(1, addrs.size)+        val a = addrs[0]+        assertEquals(37.4215, a.latitude, 1e-6)+        assertEquals(-122.084, a.longitude, 1e-6)+        assertEquals("Test Cafe", a.getAddressLine(0), "a named feature leads the address line")+        assertEquals("Test Cafe", a.featureName)+        assertEquals("Main St", a.thoroughfare)+        assertEquals("Springfield", a.locality)+        assertEquals("CA", a.adminArea)+        assertEquals("12345", a.postalCode)+        assertEquals("US", a.countryCode)+        controller.destroy()+    }++    @Test+    fun `reverse geocode far from any record adds nothing and succeeds`() {+        installDb()+        val controller = Robolectric.buildService(GeocodeService::class.java).create()+        val addrs = mutableListOf<Address>()+        val err = controller.get().provider.onGetFromLocation(0.0, 0.0, 1, params(), addrs)+        assertNull(err)+        assertTrue(addrs.isEmpty())+        controller.destroy()+    }++    @Test+    fun `structured name query uses the forward index and honours max results`() {+        installDb()+        val controller = Robolectric.buildService(GeocodeService::class.java).create()+        val service = controller.get()+        val addrs = mutableListOf<Address>()+        val err = service.provider.onGetFromLocationName(+            "Main St, Springfield, CA, US", 0.0, 0.0, 0.0, 0.0, 10, params(), addrs,+        )+        assertNull(err)+        assertEquals(2, addrs.size)+        // First result is the named cafe; the second is a plain "<number> <street>" address.+        assertEquals("Test Cafe", addrs[0].getAddressLine(0))+        assertEquals("124 Main St", addrs[1].getAddressLine(0))+        assertEquals("124", addrs[1].featureName)++        val one = mutableListOf<Address>()+        service.provider.onGetFromLocationName(+            "Main St, Springfield, CA, US", 0.0, 0.0, 0.0, 0.0, 1, params(), one,+        )+        assertEquals(1, one.size, "maxResults caps the appended addresses")+        controller.destroy()+    }++    @Test+    fun `unstructured name query uses the name index`() {+        installDb()+        val controller = Robolectric.buildService(GeocodeService::class.java).create()+        val service = controller.get()+        val addrs = mutableListOf<Address>()+        val err = service.provider.onGetFromLocationName(+            "Test Cafe", 0.0, 0.0, 0.0, 0.0, 10, params(), addrs,+        )+        assertNull(err)+        assertEquals(1, addrs.size)+        assertEquals("Test Cafe", addrs[0].featureName)++        val none = mutableListOf<Address>()+        val err2 = service.provider.onGetFromLocationName(+            "No Such Place", 0.0, 0.0, 0.0, 0.0, 10, params(), none,+        )+        assertNull(err2)+        assertTrue(none.isEmpty())+        controller.destroy()+    }++    @Test+    fun `structured query for an unknown street adds nothing`() {+        installDb()+        val controller = Robolectric.buildService(GeocodeService::class.java).create()+        val addrs = mutableListOf<Address>()+        val err = controller.get().provider.onGetFromLocationName(+            "Nowhere Road, Springfield, CA, US", 0.0, 0.0, 0.0, 0.0, 10, params(), addrs,+        )+        assertNull(err)+        assertTrue(addrs.isEmpty())+        controller.destroy()+    }++    @Test+    fun `a database arriving after create is opened on the next query`() {+        clearDb()+        val controller = Robolectric.buildService(GeocodeService::class.java).create()+        val service = controller.get()+        val addrs = mutableListOf<Address>()+        assertEquals(+            "geocoder database unavailable",+            service.provider.onGetFromLocation(37.4215, -122.084, 1, params(), addrs),+        )+        installDb()+        assertNull(service.provider.onGetFromLocation(37.4215, -122.084, 1, params(), addrs))+        assertEquals(1, addrs.size)+        // Reopening explicitly while open releases and reopens the handle.+        service.openDatabase()+        val again = mutableListOf<Address>()+        assertNull(service.provider.onGetFromLocation(37.4215, -122.084, 1, params(), again))+        assertEquals(1, again.size)+        controller.destroy()+    }++    @Test+    fun `blank name query falls back to the raw name and finds nothing`() {+        installDb()+        val controller = Robolectric.buildService(GeocodeService::class.java).create()+        val addrs = mutableListOf<Address>()+        val err = controller.get().provider.onGetFromLocationName(+            " , , ", 0.0, 0.0, 0.0, 0.0, 10, params(), addrs,+        )+        assertNull(err)+        assertTrue(addrs.isEmpty())+        controller.destroy()+    }++    @Test+    fun `service can be created and destroyed without a database`() {+        clearDb()+        val controller = Robolectric.buildService(GeocodeService::class.java).create()+        assertNotNull(controller.get())+        controller.destroy()+    }+}
networklocation/src/test/java/com/vayunmathur/networklocation/NativeBridgesTest.kt
diff --git a/networklocation/src/test/java/com/vayunmathur/networklocation/NativeBridgesTest.kt b/networklocation/src/test/java/com/vayunmathur/networklocation/NativeBridgesTest.ktnew file mode 100644index 0000000000..9c7bde3ee9--- /dev/null+++ b/networklocation/src/test/java/com/vayunmathur/networklocation/NativeBridgesTest.kt@@ -0,0 +1,100 @@+package com.vayunmathur.networklocation++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner++@RunWith(RobolectricTestRunner::class)+class NativeBridgesTest {++    @Test+    fun `geocoder field layout constants`() {+        assertEquals(10, GeocoderNative.FIELDS_PER_RESULT)+        assertEquals(0, GeocoderNative.F_LAT)+        assertEquals(1, GeocoderNative.F_LON)+        assertEquals(2, GeocoderNative.F_NAME)+        assertEquals(3, GeocoderNative.F_HOUSE)+        assertEquals(4, GeocoderNative.F_STREET)+        assertEquals(5, GeocoderNative.F_CITY)+        assertEquals(6, GeocoderNative.F_STATE)+        assertEquals(7, GeocoderNative.F_COUNTRY)+        assertEquals(8, GeocoderNative.F_POSTCODE)+        assertEquals(9, GeocoderNative.F_KIND)+        assertEquals(1, GeocoderNative.KIND_ADDRESS)+        assertEquals(2, GeocoderNative.KIND_STREET)+        assertEquals(3, GeocoderNative.KIND_POI)+        assertEquals(4, GeocoderNative.KIND_PLACE)+    }++    @Test+    fun `native libraries load on the host`() {+        assertTrue(WpsStoreNative.available)+        assertTrue(GeocoderNative.available)+        assertTrue(NetworkLocationNative.available)+    }++    @Test+    fun `closing a zero handle is a no-op for both stores`() {+        WpsStoreNative.close(0L)+        GeocoderNative.close(0L)+    }++    @Test+    fun `opening a bad descriptor yields a zero handle`() {+        assertEquals(0L, WpsStoreNative.open(-1, 0L, 0L))+        assertEquals(0L, GeocoderNative.open(-1, 0L, 0L))+    }++    @Test+    fun `a single beacon positions at that beacon`() {+        val pos = NetworkLocationNative.estimatePosition(doubleArrayOf(37.4215, -122.084, 25.0))+        assertNotNull(pos)+        assertEquals(3, pos.size)+        assertEquals(37.4215, pos[0], 1e-4)+        assertEquals(-122.084, pos[1], 1e-4)+        assertTrue(pos[2] > 0.0, "accuracy must be positive, was ${pos[2]}")+    }++    @Test+    fun `agreeing beacons position between them`() {+        val pos = NetworkLocationNative.estimatePosition(+            doubleArrayOf(+                37.4215, -122.084, 20.0,+                37.4216, -122.0841, 20.0,+                37.4214, -122.0839, 20.0,+            ),+        )+        assertNotNull(pos)+        assertEquals(37.4215, pos[0], 5e-4)+        assertEquals(-122.084, pos[1], 5e-4)+    }++    @Test+    fun `no usable beacons yields null`() {+        assertNull(NetworkLocationNative.estimatePosition(doubleArrayOf()))+        assertNull(NetworkLocationNative.estimatePosition(doubleArrayOf(37.0)))+        assertNull(NetworkLocationNative.estimatePosition(doubleArrayOf(37.0, -122.0)))+        assertNull(+            NetworkLocationNative.estimatePosition(+                doubleArrayOf(Double.NaN, Double.NaN, Double.NaN),+            ),+        )+    }++    @Test+    fun `non-finite beacons are ignored rather than poisoning the fix`() {+        val pos = NetworkLocationNative.estimatePosition(+            doubleArrayOf(+                Double.NaN, Double.NaN, Double.NaN,+                37.4215, -122.084, 25.0,+            ),+        )+        assertNotNull(pos)+        assertEquals(37.4215, pos[0], 1e-4)+        assertEquals(-122.084, pos[1], 1e-4)+    }+}
networklocation/src/test/java/com/vayunmathur/networklocation/OfflineDatabasesTest.kt
diff --git a/networklocation/src/test/java/com/vayunmathur/networklocation/OfflineDatabasesTest.kt b/networklocation/src/test/java/com/vayunmathur/networklocation/OfflineDatabasesTest.ktnew file mode 100644index 0000000000..d6ecea499f--- /dev/null+++ b/networklocation/src/test/java/com/vayunmathur/networklocation/OfflineDatabasesTest.kt@@ -0,0 +1,143 @@+package com.vayunmathur.networklocation++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import java.io.File+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner++@RunWith(RobolectricTestRunner::class)+class OfflineDatabasesTest {++    private val context: Context get() = ApplicationProvider.getApplicationContext()++    private fun clearAll() {+        val names = listOf(+            OfflineDatabases.GEOCODER, OfflineDatabases.WIFI, OfflineDatabases.CELL,+            "geocoder.geodb", "geocoder-v3.geodb", "wifi.wpsdb", "cells.wpsdb",+            "wifi-v2.wpsdb", "cells-v2.wpsdb", "unrelated.txt",+        )+        for (n in names) OfflineDatabases.file(context, n).delete()+    }++    private fun writeGeocoderHeader(magic: Int, version: Int, size: Int = 16) {+        val f = OfflineDatabases.file(context, OfflineDatabases.GEOCODER)+        val bytes = ByteArray(size)+        fun put(at: Int, v: Int) {+            for (i in 0 until 4) bytes[at + i] = (v ushr (24 - 8 * i)).toByte()+        }+        put(0, magic)+        put(4, version)+        f.writeBytes(bytes)+    }++    @Test+    fun `names urls and hashes are the published ones`() {+        assertEquals("geocoder.db", OfflineDatabases.GEOCODER)+        assertEquals("wifi-v3.wpsdb", OfflineDatabases.WIFI)+        assertEquals("cells-v3.wpsdb", OfflineDatabases.CELL)+        assertEquals(+            "https://data.maproj.org/geocoder/geocoder.db",+            OfflineDatabases.urlFor(OfflineDatabases.GEOCODER),+        )+        assertEquals(+            "https://data.maproj.org/wps/wifi-v3.wpsdb",+            OfflineDatabases.urlFor(OfflineDatabases.WIFI),+        )+        assertEquals(+            "https://data.maproj.org/wps/cells-v3.wpsdb",+            OfflineDatabases.urlFor(OfflineDatabases.CELL),+        )+        assertEquals("https://data.maproj.org/wps/other.bin", OfflineDatabases.urlFor("other.bin"))+        assertEquals(64, OfflineDatabases.sha256For(OfflineDatabases.GEOCODER)?.length)+        assertEquals(64, OfflineDatabases.sha256For(OfflineDatabases.WIFI)?.length)+        assertEquals(64, OfflineDatabases.sha256For(OfflineDatabases.CELL)?.length)+        assertNull(OfflineDatabases.sha256For("other.bin"))+        assertNull(OfflineDatabases.sha256For(""))+    }++    @Test+    fun `file lives in device protected files dir`() {+        clearAll()+        val f = OfflineDatabases.file(context, OfflineDatabases.WIFI)+        assertEquals(OfflineDatabases.WIFI, f.name)+        assertEquals(OfflineDatabases.dir(context), f.parentFile)+        assertTrue(OfflineDatabases.dir(context).path.endsWith("files"))+    }++    @Test+    fun `absent and empty stores are not present`() {+        clearAll()+        assertFalse(OfflineDatabases.isPresent(context, OfflineDatabases.WIFI))+        assertFalse(OfflineDatabases.allPresent(context))+        OfflineDatabases.file(context, OfflineDatabases.WIFI).writeBytes(ByteArray(0))+        assertFalse(OfflineDatabases.isPresent(context, OfflineDatabases.WIFI))+        assertFalse(OfflineDatabases.allPresent(context))+    }++    @Test+    fun `non-geocoder stores are present when non-empty`() {+        clearAll()+        OfflineDatabases.file(context, OfflineDatabases.WIFI).writeBytes(byteArrayOf(1, 2, 3))+        OfflineDatabases.file(context, OfflineDatabases.CELL).writeBytes(byteArrayOf(9))+        assertTrue(OfflineDatabases.isPresent(context, OfflineDatabases.WIFI))+        assertTrue(OfflineDatabases.isPresent(context, OfflineDatabases.CELL))+        assertFalse(OfflineDatabases.allPresent(context), "geocoder still missing")+        writeGeocoderHeader(0x4D414745, 5)+        assertTrue(OfflineDatabases.allPresent(context))+    }++    @Test+    fun `geocoder needs the current magic and version`() {+        clearAll()+        writeGeocoderHeader(0x4D414745, 5)+        assertTrue(OfflineDatabases.isPresent(context, OfflineDatabases.GEOCODER))+        writeGeocoderHeader(0x4D414745, 4)+        assertFalse(OfflineDatabases.isPresent(context, OfflineDatabases.GEOCODER), "old version counts absent")+        writeGeocoderHeader(0x12345678, 5)+        assertFalse(OfflineDatabases.isPresent(context, OfflineDatabases.GEOCODER))+        // Too short to hold a header at all.+        OfflineDatabases.file(context, OfflineDatabases.GEOCODER).writeBytes(byteArrayOf(0x4D, 0x41))+        assertFalse(OfflineDatabases.isPresent(context, OfflineDatabases.GEOCODER))+    }++    @Test+    fun `prune stale deletes superseded names only and is repeatable`() {+        clearAll()+        val superseded = listOf(+            "geocoder.geodb", "geocoder-v3.geodb", "wifi.wpsdb", "cells.wpsdb",+            "wifi-v2.wpsdb", "cells-v2.wpsdb",+        )+        for (n in superseded) OfflineDatabases.file(context, n).writeBytes(byteArrayOf(1))+        OfflineDatabases.file(context, OfflineDatabases.WIFI).writeBytes(byteArrayOf(1))+        OfflineDatabases.file(context, "unrelated.txt").writeBytes(byteArrayOf(1))+        OfflineDatabases.pruneStale(context)+        for (n in superseded) {+            assertFalse(OfflineDatabases.file(context, n).exists(), "$n should be pruned")+        }+        assertTrue(OfflineDatabases.file(context, OfflineDatabases.WIFI).exists())+        assertTrue(OfflineDatabases.file(context, "unrelated.txt").exists())+        OfflineDatabases.pruneStale(context) // second call is a no-op, not an error+        assertTrue(OfflineDatabases.file(context, OfflineDatabases.WIFI).exists())+    }++    @Test+    fun `open read only returns null for missing or empty and a descriptor otherwise`() {+        clearAll()+        assertNull(OfflineDatabases.openReadOnly(context, OfflineDatabases.WIFI))+        val f = OfflineDatabases.file(context, OfflineDatabases.WIFI)+        f.writeBytes(ByteArray(0))+        assertNull(OfflineDatabases.openReadOnly(context, OfflineDatabases.WIFI))+        f.writeBytes(byteArrayOf(7, 8, 9, 10))+        val pfd = OfflineDatabases.openReadOnly(context, OfflineDatabases.WIFI)+        assertNotNull(pfd)+        assertEquals(4L, pfd.statSize)+        pfd.close()+    }+}
networklocation/src/test/java/com/vayunmathur/networklocation/PositioningDataTest.kt
diff --git a/networklocation/src/test/java/com/vayunmathur/networklocation/PositioningDataTest.kt b/networklocation/src/test/java/com/vayunmathur/networklocation/PositioningDataTest.ktnew file mode 100644index 0000000000..00213fff1b--- /dev/null+++ b/networklocation/src/test/java/com/vayunmathur/networklocation/PositioningDataTest.kt@@ -0,0 +1,87 @@+package com.vayunmathur.networklocation++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue++class PositioningDataTest {++    @Test+    fun `radio wire values match the store protocol`() {+        assertEquals(1, RadioType.GSM.wire)+        assertEquals(2, RadioType.UMTS.wire)+        assertEquals(3, RadioType.LTE.wire)+        assertEquals(4, RadioType.NR.wire)+        assertEquals(+            listOf(RadioType.GSM, RadioType.UMTS, RadioType.LTE, RadioType.NR),+            RadioType.entries,+        )+        assertEquals(RadioType.LTE, RadioType.valueOf("LTE"))+    }++    @Test+    fun `beacon ids are value types`() {+        val wifi = BeaconId.Wifi("00:11:22:33:44:55")+        assertEquals(wifi, BeaconId.Wifi("00:11:22:33:44:55"))+        assertEquals(wifi.hashCode(), BeaconId.Wifi("00:11:22:33:44:55").hashCode())+        assertNotEquals(wifi, BeaconId.Wifi("00:11:22:33:44:56"))+        assertTrue(wifi.toString().contains("00:11:22:33:44:55"))++        val cell = BeaconId.Cell(310, 260, RadioType.NR, 0xFFFFFFFFFL, 0xFFFFFF)+        assertEquals(310, cell.mcc)+        assertEquals(260, cell.mnc)+        assertEquals(RadioType.NR, cell.radio)+        assertEquals(0xFFFFFFFFFL, cell.cellId, "36-bit NCI must not truncate")+        assertEquals(0xFFFFFF, cell.tacOrLac)+        assertEquals(cell, cell.copy())+        assertNotEquals(cell, cell.copy(radio = RadioType.LTE))+        // A wifi id never equals a cell id.+        assertNotEquals<BeaconId>(wifi, cell)+        val renamed = wifi.copy(bssid = "00:11:22:33:44:56")+        assertEquals("00:11:22:33:44:56", renamed.bssid)+        assertEquals("00:11:22:33:44:55", wifi.component1())+    }++    @Test+    fun `beacon fix defaults altitude to unknown`() {+        val id = BeaconId.Wifi("aa:bb:cc:dd:ee:ff")+        val fix = BeaconFix(id, 37.0, -122.0, 30.0)+        assertEquals(id, fix.id)+        assertEquals(37.0, fix.latitude)+        assertEquals(-122.0, fix.longitude)+        assertEquals(30.0, fix.accuracyMeters)+        assertNull(fix.altitudeMeters)+        val withAlt = fix.copy(altitudeMeters = 15.5)+        assertEquals(15.5, withAlt.altitudeMeters)+        assertNotEquals(fix, withAlt)+    }++    @Test+    fun `device position is a value type`() {+        val pos = DevicePosition(37.4215, -122.084, 12.0)+        assertEquals(pos, DevicePosition(37.4215, -122.084, 12.0))+        assertEquals(37.4215, pos.latitude)+        assertEquals(-122.084, pos.longitude)+        assertEquals(12.0, pos.accuracyMeters)+        assertNotEquals(pos, pos.copy(accuracyMeters = 13.0))+    }++    @Test+    fun `routes are distinct nav keys`() {+        assertNotEquals<Route>(Route.Setup, Route.Status)+        assertEquals(Route.Setup, Route.Setup)+        assertEquals(Route.Status, Route.Status)+    }++    @Test+    fun `routes serialize through their generated serializer`() {+        val json = kotlinx.serialization.json.Json+        val setup = json.encodeToString(Route.serializer(), Route.Setup)+        val status = json.encodeToString(Route.serializer(), Route.Status)+        assertNotEquals(setup, status)+        assertEquals(Route.Setup, json.decodeFromString(Route.serializer(), setup))+        assertEquals(Route.Status, json.decodeFromString(Route.serializer(), status))+    }+}
networklocation/src/test/java/com/vayunmathur/networklocation/ServicesAndNavigationTest.kt
diff --git a/networklocation/src/test/java/com/vayunmathur/networklocation/ServicesAndNavigationTest.kt b/networklocation/src/test/java/com/vayunmathur/networklocation/ServicesAndNavigationTest.ktnew file mode 100644index 0000000000..dee45609a8--- /dev/null+++ b/networklocation/src/test/java/com/vayunmathur/networklocation/ServicesAndNavigationTest.kt@@ -0,0 +1,72 @@+package com.vayunmathur.networklocation++import android.content.Context+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 kotlin.test.Test+import kotlin.test.assertNull+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.Robolectric++@RunWith(AndroidJUnit4::class)+class ServicesAndNavigationTest {++    @get:Rule+    val rule = createComposeRule()++    private val context: Context get() = ApplicationProvider.getApplicationContext()++    private fun clearDbs() {+        for (n in listOf(OfflineDatabases.GEOCODER, OfflineDatabases.WIFI, OfflineDatabases.CELL)) {+            OfflineDatabases.file(context, n).delete()+        }+    }++    private fun installAllDbs() {+        writeGeocoderDb(OfflineDatabases.file(context, OfflineDatabases.GEOCODER))+        OfflineDatabases.file(context, OfflineDatabases.WIFI).writeBytes(byteArrayOf(1))+        OfflineDatabases.file(context, OfflineDatabases.CELL).writeBytes(byteArrayOf(1))+    }++    @Test+    fun `network location service binds to nothing before create and destroys cleanly`() {+        val service = NetworkLocationService()+        assertNull(service.onBind(null), "no provider exists until onCreate runs")+        service.onDestroy()+    }++    @Test+    fun `navigation starts on setup while databases are missing`() {+        clearDbs()+        rule.setContent { Navigation() }+        rule.onNodeWithText("Offline databases").assertIsDisplayed()+        rule.onNodeWithText("Download offline databases").assertExists()+    }++    @Test+    fun `navigation starts on status once databases are installed`() {+        installAllDbs()+        rule.setContent { Navigation() }+        rule.onNodeWithText("Offline databases").assertIsDisplayed()+        rule.onNodeWithText(+            "All offline databases are installed. Positioning and geocoding work without " ++                "a network connection.",+        ).assertIsDisplayed()+    }++    @Test+    fun `main activity creates its content`() {+        clearDbs()+        val controller = Robolectric.buildActivity(MainActivity::class.java).create()+        val activity = controller.get()+        org.junit.Assert.assertEquals(+            "com.vayunmathur.networklocation.MainActivity",+            activity.javaClass.name,+        )+        controller.destroy()+    }+}
networklocation/src/test/java/com/vayunmathur/networklocation/TestFixtures.kt
diff --git a/networklocation/src/test/java/com/vayunmathur/networklocation/TestFixtures.kt b/networklocation/src/test/java/com/vayunmathur/networklocation/TestFixtures.ktnew file mode 100644index 0000000000..1259ea1e56--- /dev/null+++ b/networklocation/src/test/java/com/vayunmathur/networklocation/TestFixtures.kt@@ -0,0 +1,333 @@+package com.vayunmathur.networklocation++import java.io.ByteArrayOutputStream+import java.io.File++/** Bit writer matching the Rust WPSDB2 fixture writer (LSB-first within each byte). */+internal class BitWriter {+    private val backing = mutableListOf<Byte>()+    var bits: Long = 0+        private set++    fun push(v: Long, nbits: Int) {+        for (k in 0 until nbits) {+            while (backing.size <= (bits / 8).toInt()) backing.add(0)+            if (((v ushr k) and 1L) == 1L) {+                val idx = (bits / 8).toInt()+                backing[idx] = (backing[idx].toInt() or (1 shl (bits % 8).toInt())).toByte()+            }+            bits+++        }+    }++    fun pushBit(set: Boolean) = push(if (set) 1L else 0L, 1)++    fun bytes(): ByteArray = ByteArray(backing.size) { backing[it] }+}++internal data class WpsRec(+    val keyHi: Long,+    val keyLo: Long,+    val latE8: Long,+    val lonE8: Long,+    val acc: Long,+    val altMeters: Long?,+)++private fun wpsKeyOf(r: WpsRec) = java.math.BigInteger.valueOf(r.keyHi).shiftLeft(64)+    .add(+        java.math.BigInteger.valueOf(r.keyLo)+            .and(java.math.BigInteger.ONE.shiftLeft(64).subtract(java.math.BigInteger.ONE)),+    )++private fun wpsChooseL(universeBits: Int, n: Int): Int {+    if (n == 0) return minOf(universeBits, 64)+    var cand = 0+    val u = java.math.BigInteger.ONE.shiftLeft(universeBits)+    while (cand < 64 && u.shiftRight(cand + 1) >= java.math.BigInteger.valueOf(n.toLong())) cand+++    return cand+}++private fun wpsHigh(sorted: List<WpsRec>, l: Int, universeBits: Int): BitWriter {+    val high = BitWriter()+    var prevBucket = java.math.BigInteger.ZERO+    for (r in sorted) {+        val bucket = wpsKeyOf(r).shiftRight(l)+        var b = prevBucket+        while (b < bucket) {+            high.pushBit(false)+            b = b.add(java.math.BigInteger.ONE)+        }+        high.pushBit(true)+        prevBucket = bucket+    }+    val buckets = java.math.BigInteger.ONE.shiftLeft(universeBits - l)+    var b = prevBucket+    while (b < buckets) {+        high.pushBit(false)+        b = b.add(java.math.BigInteger.ONE)+    }+    return high+}++private fun wpsZeros(highBytes: ByteArray, highLenBits: Long, sampleLog2: Int): ByteArray {+    val zeros = mutableListOf(0L)+    var count = 0L+    for (p in 0 until highLenBits) {+        val byte = highBytes[(p / 8).toInt()].toInt()+        if (((byte ushr (p % 8).toInt()) and 1) == 0) count+++        if ((p + 1) and ((1L shl sampleLog2) - 1) == 0L) zeros.add(count)+    }+    val out = ByteArrayOutputStream()+    for (z in zeros) for (i in 0 until 8) out.write((z ushr (8 * i)).toInt() and 0xFF)+    return out.toByteArray()+}++private fun wpsLow(sorted: List<WpsRec>, l: Int): ByteArray {+    val low = BitWriter()+    if (l > 0) {+        val mask = java.math.BigInteger.ONE.shiftLeft(l).subtract(java.math.BigInteger.ONE)+        for (r in sorted) low.push(wpsKeyOf(r).and(mask).toLong(), l)+    }+    return low.bytes()+}++private fun wpsPayload(sorted: List<WpsRec>): ByteArray {+    val payload = BitWriter()+    for (r in sorted) {+        payload.push(r.latE8 + 9_000_000_000L, 35)+        payload.push(r.lonE8 + 18_000_000_000L, 36)+        payload.push(r.acc, 16)+        payload.push((r.altMeters ?: -32768L) + 32768L, 16)+    }+    return payload.bytes()+}++private fun ByteArrayOutputStream.u64le(v: Long) {+    for (i in 0 until 8) write((v ushr (8 * i)).toInt() and 0xFF)+}++/** Writes a valid WPSDB2 store (payload kind 2) holding [records], mirroring wpsdb_part2.rs. */+internal fun writeWpsStore(file: File, universeBits: Int, records: List<WpsRec>) {+    val sorted = records.sortedWith(compareBy({ it.keyHi.toULong() }, { it.keyLo.toULong() }))+        .distinctBy { it.keyHi to it.keyLo }+    val sampleLog2 = 6+    val l = wpsChooseL(universeBits, sorted.size)+    val high = wpsHigh(sorted, l, universeBits)+    val highBytes = high.bytes()+    val out = ByteArrayOutputStream()+    out.write("WPSDB2\u0000\u0000".toByteArray(Charsets.US_ASCII))+    out.write(1)+    out.write(universeBits)+    out.write(2) // payload kind 2+    out.write(l)+    out.write(sampleLog2)+    out.write(byteArrayOf(0, 0, 0))+    out.u64le(sorted.size.toLong())+    out.u64le(high.bits)+    out.u64le(highBytes.size.toLong())+    out.write(highBytes)+    val zerosBytes = wpsZeros(highBytes, high.bits, sampleLog2)+    out.u64le(zerosBytes.size.toLong())+    out.write(zerosBytes)+    val lowBytes = wpsLow(sorted, l)+    out.u64le(lowBytes.size.toLong())+    out.write(lowBytes)+    val payloadBytes = wpsPayload(sorted)+    out.u64le(payloadBytes.size.toLong())+    out.write(payloadBytes)+    file.parentFile?.mkdirs()+    file.writeBytes(out.toByteArray())+}++/** Minimal zstd frame holding [data] in raw (uncompressed) blocks, which ruzstd decodes. */+internal fun zstdRaw(data: ByteArray): ByteArray {+    val out = ByteArrayOutputStream()+    out.write(byteArrayOf(0x28, 0xB5.toByte(), 0x2F, 0xFD.toByte()))+    out.write(0xA0) // single-segment, 4-byte frame content size+    for (i in 0 until 4) out.write((data.size ushr (8 * i)) and 0xFF)+    if (data.isEmpty()) {+        out.write(byteArrayOf(1, 0, 0)) // last, raw, size 0+    } else {+        var off = 0+        while (off < data.size) {+            val chunk = minOf(data.size - off, 100_000)+            val last = if (off + chunk == data.size) 1 else 0+            val header = (chunk shl 3) or last+            for (i in 0 until 3) out.write((header ushr (8 * i)) and 0xFF)+            out.write(data, off, chunk)+            off += chunk+        }+    }+    return out.toByteArray()+}++private fun be32(out: ByteArrayOutputStream, v: Int) {+    for (i in 3 downTo 0) out.write((v ushr (8 * i)) and 0xFF)+}++private fun be64(out: ByteArrayOutputStream, v: Long) {+    for (i in 7 downTo 0) out.write(((v ushr (8 * i)) and 0xFF).toInt())+}++private fun zigzag(v: Int): Long = (((v shl 1) xor (v shr 31)).toLong()) and 0xFFFFFFFFL++private fun varint(out: ByteArrayOutputStream, value: Long) {+    var v = value+    while (true) {+        val b = (v and 0x7F).toInt()+        v = v ushr 7+        if (v == 0L) {+            out.write(b)+            return+        }+        out.write(b or 0x80)+    }+}++private fun geocoderColumn(values: IntArray, delta: Boolean): ByteArray {+    val raw = ByteArrayOutputStream()+    var prev = 0+    for ((i, v) in values.withIndex()) {+        val dv = if (delta && i > 0) v - prev else v+        varint(raw, zigzag(dv))+        prev = v+    }+    val comp = zstdRaw(raw.toByteArray())+    val out = ByteArrayOutputStream()+    be32(out, values.size)+    be32(out, 1)+    be32(out, raw.size())+    be32(out, comp.size)+    out.write(comp)+    return out.toByteArray()+}++private fun geocoderDict(strings: List<String>): ByteArray {+    val per = maxOf(strings.size, 1)+    val blocks = if (strings.isEmpty()) 0 else (strings.size + per - 1) / per+    val out = ByteArrayOutputStream()+    be32(out, strings.size)+    be32(out, per)+    be32(out, blocks)+    // first-string table: first string of each block, cumulative ends+    val firsts = ByteArrayOutputStream()+    var end = 0+    for (blk in 0 until blocks) {+        val s = strings[blk * per].toByteArray(Charsets.UTF_8)+        firsts.write(s)+        end += s.size+        be32(out, end)+    }+    out.write(firsts.toByteArray())+    // blocks: raw encoding [be32 len][utf8] per string, zstd-wrapped+    val blockData = ByteArrayOutputStream()+    var compEnd = 0+    val ends = mutableListOf<Int>()+    for (blk in 0 until blocks) {+        val rawBlk = ByteArrayOutputStream()+        val from = blk * per+        val to = minOf(from + per, strings.size)+        for (i in from until to) {+            val s = strings[i].toByteArray(Charsets.UTF_8)+            be32(rawBlk, s.size)+            rawBlk.write(s)+        }+        val comp = zstdRaw(rawBlk.toByteArray())+        blockData.write(comp)+        compEnd += comp.size+        ends.add(compEnd)+    }+    for (e in ends) be32(out, e)+    out.write(blockData.toByteArray())+    return out.toByteArray()+}++internal data class GeoRec(+    val latE5: Int,+    val lonE5: Int,+    val nameId: Int,+    val houseId: Int,+    val streetId: Int,+    val cityId: Int,+    val stateId: Int,+    val countryId: Int,+    val postcodeId: Int,+    val kind: Int,+)++/** Dictionary contents shared by [writeGeocoderDb] records, in dict order. */+internal val GEO_DICTS: List<List<String>> = listOf(+    listOf("", "Test Cafe"), // name+    listOf("123", "124"), // house+    listOf("Main St"), // street+    listOf("Springfield"), // city+    listOf("CA"), // state+    listOf("US"), // country+    listOf("12345"), // postcode+)++internal val GEO_RECORDS: List<GeoRec> = listOf(+    GeoRec(3_742_150, -12_208_400, 1, 0, 0, 0, 0, 0, 0, 1),+    GeoRec(3_742_250, -12_208_300, -1, 1, 0, 0, 0, 0, 0, 1),+)++/** Writes a minimal but valid v5 geocoder.db holding [GEO_RECORDS]. */+internal fun writeGeocoderDb(file: File) {+    val cellOf = { r: GeoRec ->+        val row = (r.latE5.toLong() + 9_000_000L) / 5_000L+        val col = (r.lonE5.toLong() + 18_000_000L) / 5_000L+        row * 7_200L + col+    }+    val ordered = GEO_RECORDS.sortedBy(cellOf)+    val grid = mutableListOf<Pair<Long, Int>>()+    ordered.forEachIndexed { idx, r ->+        val c = cellOf(r)+        if (grid.none { it.first == c }) grid.add(c to idx)+    }+    grid.sortBy { it.first }++    val dictSections = GEO_DICTS.map { geocoderDict(it) }+    val colValues: List<IntArray> = listOf(+        ordered.map { it.latE5 }.toIntArray(),+        ordered.map { it.lonE5 }.toIntArray(),+        ordered.map { it.nameId }.toIntArray(),+        ordered.map { it.houseId }.toIntArray(),+        ordered.map { it.streetId }.toIntArray(),+        ordered.map { it.cityId }.toIntArray(),+        ordered.map { it.stateId }.toIntArray(),+        ordered.map { it.countryId }.toIntArray(),+        ordered.map { it.postcodeId }.toIntArray(),+        ordered.map { it.kind }.toIntArray(),+    )+    val deltaCols = booleanArrayOf(true, true, false, false, false, false, false, false, false, false)+    val colSections = colValues.mapIndexed { i, v -> geocoderColumn(v, deltaCols[i]) }++    val gridBody = ByteArrayOutputStream()+    be32(gridBody, grid.size)+    for ((cell, start) in grid) {+        be64(gridBody, cell)+        be32(gridBody, start)+    }++    val fwdRecs = ordered.indices.filter { ordered[it].streetId >= 0 }+    val fwd = geocoderColumn(fwdRecs.toIntArray(), delta = true)+    val nmPairs = ordered.indices+        .filter { ordered[it].nameId >= 0 }+        .map { ordered[it].nameId to it }+        .sortedBy { it.first }+    val nmName = geocoderColumn(nmPairs.map { it.first }.toIntArray(), delta = true)+    val nmRec = geocoderColumn(nmPairs.map { it.second }.toIntArray(), delta = false)++    val sections = dictSections + colSections + listOf(gridBody.toByteArray(), fwd, nmName, nmRec)+    val out = ByteArrayOutputStream()+    be32(out, 0x4D414745)+    be32(out, 5)+    be32(out, ordered.size)+    for (s in sections) {+        be32(out, s.size)+        out.write(s)+    }+    file.parentFile?.mkdirs()+    file.writeBytes(out.toByteArray())+}
networklocation/src/test/java/com/vayunmathur/networklocation/cell/NearbyCellsTest.kt
diff --git a/networklocation/src/test/java/com/vayunmathur/networklocation/cell/NearbyCellsTest.kt b/networklocation/src/test/java/com/vayunmathur/networklocation/cell/NearbyCellsTest.ktnew file mode 100644index 0000000000..bc0d01c506--- /dev/null+++ b/networklocation/src/test/java/com/vayunmathur/networklocation/cell/NearbyCellsTest.kt@@ -0,0 +1,136 @@+package com.vayunmathur.networklocation.cell++import android.content.Context+import android.telephony.TelephonyManager+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.networklocation.BeaconId+import com.vayunmathur.networklocation.RadioType+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows.shadowOf+import org.robolectric.shadows.CellIdentityGsmBuilder+import org.robolectric.shadows.CellIdentityLteBuilder+import org.robolectric.shadows.CellIdentityNrBuilder+import org.robolectric.shadows.CellIdentityWcdmaBuilder+import org.robolectric.shadows.CellInfoGsmBuilder+import org.robolectric.shadows.CellInfoLteBuilder+import org.robolectric.shadows.CellInfoNrBuilder+import org.robolectric.shadows.CellInfoWcdmaBuilder++@RunWith(RobolectricTestRunner::class)+class NearbyCellsTest {++    private val context: Context get() = ApplicationProvider.getApplicationContext()++    private fun setCells(cells: List<android.telephony.CellInfo>) {+        val tm = context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager+        shadowOf(tm).setAllCellInfo(cells)+    }++    private fun lte(mcc: String? = "310", mnc: String? = "260", ci: Int = 4242, tac: Int = 1234) =+        CellInfoLteBuilder.newBuilder()+            .setCellIdentity(+                CellIdentityLteBuilder.newBuilder()+                    .setMcc(mcc).setMnc(mnc).setCi(ci).setTac(tac).build(),+            ).build()++    @Test+    fun `lte gsm wcdma and nr cells all map to beacon ids`() {+        val gsm = CellInfoGsmBuilder.newBuilder()+            .setCellIdentity(+                CellIdentityGsmBuilder.newBuilder()+                    .setMcc("234").setMnc("15").setCid(777).setLac(99).build(),+            ).build()+        val wcdma = CellInfoWcdmaBuilder.newBuilder()+            .setCellIdentity(+                CellIdentityWcdmaBuilder.newBuilder()+                    .setMcc("234").setMnc("15").setCid(888).setLac(98).build(),+            ).build()+        val nr = CellInfoNrBuilder.newBuilder()+            .setCellIdentity(+                CellIdentityNrBuilder.newBuilder()+                    .setMcc("505").setMnc("01").setNci(0xFFFFFFFFFL).setTac(0xFFFFFF).build(),+            ).build()+        setCells(listOf(lte(), gsm, wcdma, nr))+        assertEquals(+            listOf(+                BeaconId.Cell(310, 260, RadioType.LTE, 4242, 1234),+                BeaconId.Cell(234, 15, RadioType.GSM, 777, 99),+                BeaconId.Cell(234, 15, RadioType.UMTS, 888, 98),+                BeaconId.Cell(505, 1, RadioType.NR, 0xFFFFFFFFFL, 0xFFFFFF),+            ),+            NearbyCells(context).scan(),+        )+    }++    @Test+    fun `duplicate cells are returned once`() {+        setCells(listOf(lte(), lte()))+        assertEquals(+            listOf(BeaconId.Cell(310, 260, RadioType.LTE, 4242, 1234)),+            NearbyCells(context).scan(),+        )+    }++    @Test+    fun `cells with missing or sentinel identity are dropped`() {+        setCells(+            listOf(+                lte(mcc = null),+                lte(mnc = null),+                lte(mcc = "not-a-number"),+                lte(ci = Int.MAX_VALUE), // CellInfo.UNAVAILABLE+                lte(ci = 0),+                lte(tac = Int.MAX_VALUE), // CellInfo.UNAVAILABLE+                lte(),+            ),+        )+        assertEquals(+            listOf(BeaconId.Cell(310, 260, RadioType.LTE, 4242, 1234)),+            NearbyCells(context).scan(),+            "only the fully-identified cell survives",+        )+    }++    @Test+    fun `gsm wcdma and nr cells with sentinel or missing identity are dropped`() {+        val gsmNoMcc = CellInfoGsmBuilder.newBuilder()+            .setCellIdentity(+                CellIdentityGsmBuilder.newBuilder().setCid(777).setLac(99).build(),+            ).build()+        val gsmBadCid = CellInfoGsmBuilder.newBuilder()+            .setCellIdentity(+                CellIdentityGsmBuilder.newBuilder()+                    .setMcc("234").setMnc("15").setCid(Int.MAX_VALUE).setLac(99).build(),+            ).build()+        val wcdmaBadLac = CellInfoWcdmaBuilder.newBuilder()+            .setCellIdentity(+                CellIdentityWcdmaBuilder.newBuilder()+                    .setMcc("234").setMnc("15").setCid(888).setLac(Int.MAX_VALUE).build(),+            ).build()+        val nrUnavailable = CellInfoNrBuilder.newBuilder()+            .setCellIdentity(+                CellIdentityNrBuilder.newBuilder()+                    .setMcc("505").setMnc("01").setNci(Long.MAX_VALUE).setTac(55).build(),+            ).build()+        val nrZero = CellInfoNrBuilder.newBuilder()+            .setCellIdentity(+                CellIdentityNrBuilder.newBuilder()+                    .setMcc("505").setMnc("01").setNci(0L).setTac(55).build(),+            ).build()+        setCells(listOf(gsmNoMcc, gsmBadCid, wcdmaBadLac, nrUnavailable, nrZero, lte()))+        assertEquals(+            listOf(BeaconId.Cell(310, 260, RadioType.LTE, 4242, 1234)),+            NearbyCells(context).scan(),+        )+    }++    @Test+    fun `no cell info yields an empty list`() {+        setCells(emptyList())+        assertTrue(NearbyCells(context).scan().isEmpty())+    }+}
networklocation/src/test/java/com/vayunmathur/networklocation/platform/LocationFeedsLegacySdkTest.kt
diff --git a/networklocation/src/test/java/com/vayunmathur/networklocation/platform/LocationFeedsLegacySdkTest.kt b/networklocation/src/test/java/com/vayunmathur/networklocation/platform/LocationFeedsLegacySdkTest.ktnew file mode 100644index 0000000000..fb4a8f9072--- /dev/null+++ b/networklocation/src/test/java/com/vayunmathur/networklocation/platform/LocationFeedsLegacySdkTest.kt@@ -0,0 +1,26 @@+package com.vayunmathur.networklocation.platform++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import kotlin.test.Test+import kotlin.test.assertNull+import kotlin.test.assertTrue+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++/** The pre-Tiramisu branch of [reverseGeocode] uses the deprecated synchronous Geocoder API. */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [33])+class LocationFeedsLegacySdkTest {++    private val context: Context get() = ApplicationProvider.getApplicationContext()++    @Test+    fun `reverse geocode on sdk 33 succeeds with null when nothing matches`() = runBlocking {+        val result = reverseGeocode(context, 37.4215, -122.084)+        assertTrue(result.isSuccess)+        assertNull(result.getOrNull())+    }+}
networklocation/src/test/java/com/vayunmathur/networklocation/platform/LocationFeedsTest.kt
diff --git a/networklocation/src/test/java/com/vayunmathur/networklocation/platform/LocationFeedsTest.kt b/networklocation/src/test/java/com/vayunmathur/networklocation/platform/LocationFeedsTest.ktnew file mode 100644index 0000000000..cedbb62283--- /dev/null+++ b/networklocation/src/test/java/com/vayunmathur/networklocation/platform/LocationFeedsTest.kt@@ -0,0 +1,103 @@+package com.vayunmathur.networklocation.platform++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 kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.flow.toList+import kotlinx.coroutines.launch+import kotlinx.coroutines.runBlocking+import kotlinx.coroutines.yield+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows.shadowOf++@RunWith(RobolectricTestRunner::class)+class LocationFeedsTest {++    private val context: Context get() = ApplicationProvider.getApplicationContext()++    private fun grant() {+        shadowOf(context as Application).grantPermissions(Manifest.permission.ACCESS_FINE_LOCATION)+    }++    private fun fix(provider: String, lat: Double = 37.4215): Location = Location(provider).apply {+        latitude = lat+        longitude = -122.084+        accuracy = 5f+        elapsedRealtimeNanos = 1_000_000_000L+    }++    @Test+    fun `hasFineLocation reflects the grant`() {+        assertFalse(hasFineLocation(context))+        grant()+        assertTrue(hasFineLocation(context))+    }++    @Test+    fun `location updates emits nothing without permission`() = runBlocking {+        val lm = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager+        shadowOf(lm).setProviderEnabled(LocationManager.GPS_PROVIDER, true)+        val got = mutableListOf<Location>()+        val job = launch { locationUpdates(context, LocationManager.GPS_PROVIDER).toList(got) }+        yield()+        shadowOf(context as Application).denyPermissions(Manifest.permission.ACCESS_FINE_LOCATION)+        job.cancel()+        assertTrue(got.isEmpty())+    }++    @Test+    fun `location updates emits nothing for an unknown provider`() = runBlocking {+        grant()+        val got = mutableListOf<Location>()+        val job = launch { locationUpdates(context, "no-such-provider").toList(got) }+        yield()+        job.cancel()+        assertTrue(got.isEmpty())+    }++    @Test+    fun `location updates seeds with the last known fix and follows live fixes`() = runBlocking {+        grant()+        val lm = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager+        val shadow = shadowOf(lm)+        shadow.setProviderEnabled(LocationManager.GPS_PROVIDER, true)+        shadow.setLastKnownLocation(LocationManager.GPS_PROVIDER, fix(LocationManager.GPS_PROVIDER, 37.0))++        val flow = locationUpdates(context, LocationManager.GPS_PROVIDER)+        val first = flow.first()+        assertEquals(37.0, first.latitude, 1e-9)++        val got = mutableListOf<Location>()+        val job = launch { flow.toList(got) }+        // Let the collector register before delivering a live fix.+        var tries = 0+        while (shadow.requestLocationUpdateListeners.isEmpty() && tries++ < 50) yield()+        assertTrue(shadow.requestLocationUpdateListeners.isNotEmpty())+        shadow.requestLocationUpdateListeners.forEach {+            it.onLocationChanged(fix(LocationManager.GPS_PROVIDER, 38.0))+        }+        tries = 0+        while (got.size < 2 && tries++ < 50) yield()+        job.cancel()+        assertEquals(listOf(37.0, 38.0), got.map { it.latitude })+    }++    @Test+    fun `reverse geocode with no shadow match succeeds with null`() = runBlocking {+        // The internally-built Geocoder's shadow has no canned answer, so the listener+        // reports an empty result set, which the production code maps to success(null).+        val result = reverseGeocode(context, 37.4215, -122.084)+        assertTrue(result.isSuccess)+        assertNull(result.getOrNull())+    }+}
networklocation/src/test/java/com/vayunmathur/networklocation/provider/DatabaseStatusProviderTest.kt
diff --git a/networklocation/src/test/java/com/vayunmathur/networklocation/provider/DatabaseStatusProviderTest.kt b/networklocation/src/test/java/com/vayunmathur/networklocation/provider/DatabaseStatusProviderTest.ktnew file mode 100644index 0000000000..2d74159c5b--- /dev/null+++ b/networklocation/src/test/java/com/vayunmathur/networklocation/provider/DatabaseStatusProviderTest.kt@@ -0,0 +1,98 @@+package com.vayunmathur.networklocation.provider++import android.content.Context+import android.net.Uri+import android.os.Process+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.networklocation.OfflineDatabases+import com.vayunmathur.networklocation.writeGeocoderDb+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFailsWith+import kotlin.test.assertNull+import kotlin.test.assertTrue+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.RobolectricTestRunner+@RunWith(RobolectricTestRunner::class)+class DatabaseStatusProviderTest {++    private val context: Context get() = ApplicationProvider.getApplicationContext()++    private fun clearAll() {+        for (n in listOf(OfflineDatabases.GEOCODER, OfflineDatabases.WIFI, OfflineDatabases.CELL)) {+            OfflineDatabases.file(context, n).delete()+        }+    }++    private fun installAll() {+        writeGeocoderDb(OfflineDatabases.file(context, OfflineDatabases.GEOCODER))+        OfflineDatabases.file(context, OfflineDatabases.WIFI).writeBytes(byteArrayOf(1))+        OfflineDatabases.file(context, OfflineDatabases.CELL).writeBytes(byteArrayOf(1))+    }++    @Test+    fun `contract values are the published ones`() {+        assertEquals("com.vayunmathur.networklocation.status", DatabaseStatusContract.AUTHORITY)+        assertEquals(+            "content://com.vayunmathur.networklocation.status/databases",+            DatabaseStatusContract.DATABASES.toString(),+        )+        assertEquals("all_present", DatabaseStatusContract.COLUMN_ALL_PRESENT)+    }++    @Test+    fun `query reports zero until every database is present then one`() {+        clearAll()+        val provider = Robolectric.buildContentProvider(DatabaseStatusProvider::class.java).create().get()+        provider.query(+            DatabaseStatusContract.DATABASES, null, null, null, null,+        )!!.use { c ->+            assertEquals(1, c.count)+            assertTrue(c.moveToFirst())+            assertEquals(0, c.getInt(0))+            assertEquals(DatabaseStatusContract.COLUMN_ALL_PRESENT, c.getColumnName(0))+        }+        installAll()+        provider.query(+            DatabaseStatusContract.DATABASES, null, null, null, null,+        )!!.use { c ->+            assertTrue(c.moveToFirst())+            assertEquals(1, c.getInt(0))+        }+    }++    @Test+    fun `query for another uri returns null and writes are no-ops`() {+        clearAll()+        val provider = Robolectric.buildContentProvider(DatabaseStatusProvider::class.java).create().get()+        val other = Uri.parse("content://com.vayunmathur.networklocation.status/other")+        assertNull(provider.query(other, null, null, null, null))+        assertNull(provider.getType(DatabaseStatusContract.DATABASES))+        assertNull(provider.insert(DatabaseStatusContract.DATABASES, null))+        assertEquals(0, provider.update(DatabaseStatusContract.DATABASES, null, null, null))+        assertEquals(0, provider.delete(DatabaseStatusContract.DATABASES, null, null))+    }++    @Test+    fun `a non-system caller is rejected`() {+        clearAll()+        val provider = Robolectric.buildContentProvider(DatabaseStatusProvider::class.java).create().get()+        // Robolectric's Binder shadow defaults the calling uid to our own; move it elsewhere.+        org.robolectric.shadows.ShadowBinder.setCallingUid(Process.SYSTEM_UID + 4242)+        try {+            assertFailsWith<SecurityException> {+                provider.query(DatabaseStatusContract.DATABASES, null, null, null, null)+            }+        } finally {+            org.robolectric.shadows.ShadowBinder.reset()+        }+        // As the system uid the same query is admitted.+        org.robolectric.shadows.ShadowBinder.setCallingUid(Process.SYSTEM_UID)+        try {+            provider.query(DatabaseStatusContract.DATABASES, null, null, null, null)!!.close()+        } finally {+            org.robolectric.shadows.ShadowBinder.reset()+        }+    }+}
networklocation/src/test/java/com/vayunmathur/networklocation/provider/LocationReportingTaskTest.kt
diff --git a/networklocation/src/test/java/com/vayunmathur/networklocation/provider/LocationReportingTaskTest.kt b/networklocation/src/test/java/com/vayunmathur/networklocation/provider/LocationReportingTaskTest.ktnew file mode 100644index 0000000000..5cf6f0978b--- /dev/null+++ b/networklocation/src/test/java/com/vayunmathur/networklocation/provider/LocationReportingTaskTest.kt@@ -0,0 +1,124 @@+package com.vayunmathur.networklocation.provider++import android.content.Context+import android.location.Location+import android.location.LocationManager+import android.net.wifi.ScanResult+import android.net.wifi.WifiManager+import android.telephony.TelephonyManager+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.networklocation.BeaconKeys+import com.vayunmathur.networklocation.OfflineDatabases+import com.vayunmathur.networklocation.WpsRec+import com.vayunmathur.networklocation.writeWpsStore+import java.util.concurrent.CountDownLatch+import java.util.concurrent.TimeUnit+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows.shadowOf++@RunWith(RobolectricTestRunner::class)+class LocationReportingTaskTest {++    private val context: Context get() = ApplicationProvider.getApplicationContext()++    private fun setWifi(bssids: List<String>) {+        val wm = context.getSystemService(Context.WIFI_SERVICE) as WifiManager+        shadowOf(wm).setScanResults(+            bssids.map { bssid ->+                ScanResult().apply {+                    BSSID = bssid+                    SSID = "test"+                }+            },+        )+    }++    private fun clearTelephony() {+        val tm = context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager+        shadowOf(tm).setAllCellInfo(emptyList())+    }++    private fun clearStores() {+        OfflineDatabases.file(context, OfflineDatabases.WIFI).delete()+        OfflineDatabases.file(context, OfflineDatabases.CELL).delete()+    }++    @Test+    fun `a resolved wifi beacon produces a network location fix`() {+        clearStores()+        clearTelephony()+        val mac = BeaconKeys.parseMac("00:11:22:33:44:55")!!+        writeWpsStore(+            OfflineDatabases.file(context, OfflineDatabases.WIFI),+            BeaconKeys.WIFI_UNIVERSE_BITS,+            listOf(WpsRec(0L, mac, 3_742_150_000L, -12_208_400_000L, 25L, null)),+        )+        setWifi(listOf("00:11:22:33:44:55"))++        val latch = CountDownLatch(1)+        val fixes = mutableListOf<Location>()+        val task = LocationReportingTask(context) { loc ->+            fixes.add(loc)+            latch.countDown()+        }+        task.start(60_000L)+        task.start(60_000L) // a second start while running is a no-op+        assertTrue(latch.await(10, TimeUnit.SECONDS), "expected a fix from the resolved beacon")+        task.stop()+        task.stop() // idempotent++        assertEquals(1, fixes.size)+        val fix = fixes[0]+        assertEquals(LocationManager.NETWORK_PROVIDER, fix.provider)+        assertEquals(37.4215, fix.latitude, 5e-4)+        assertEquals(-122.084, fix.longitude, 5e-4)+        assertTrue(fix.hasAccuracy())+        assertTrue(fix.accuracy > 0f)+        assertTrue(fix.time > 0L)+    }++    @Test+    fun `no scanned beacons produces no fix`() {+        clearStores()+        clearTelephony()+        setWifi(emptyList())+        val latch = CountDownLatch(1)+        val task = LocationReportingTask(context) { latch.countDown() }+        task.start(60_000L)+        assertFalse(latch.await(3, TimeUnit.SECONDS), "no beacons must mean no fix")+        task.stop()+    }++    @Test+    fun `scanned but unresolved beacons produce no fix`() {+        clearStores()+        clearTelephony()+        setWifi(listOf("00:11:22:33:44:55"))+        val latch = CountDownLatch(1)+        val task = LocationReportingTask(context) { latch.countDown() }+        task.start(60_000L)+        assertFalse(+            latch.await(3, TimeUnit.SECONDS),+            "a beacon the stores do not know must not invent a position",+        )+        task.stop()+    }++    @Test+    fun `interval below the floor is clamped and stop halts the loop`() {+        clearStores()+        clearTelephony()+        setWifi(emptyList())+        val task = LocationReportingTask(context) { }+        task.start(0L)+        task.stop()+        // Restarting after stop works: a fresh scope is created.+        task.start(0L)+        task.stop()+    }+}
networklocation/src/test/java/com/vayunmathur/networklocation/provider/OfflineBeaconStoreTest.kt
diff --git a/networklocation/src/test/java/com/vayunmathur/networklocation/provider/OfflineBeaconStoreTest.kt b/networklocation/src/test/java/com/vayunmathur/networklocation/provider/OfflineBeaconStoreTest.ktnew file mode 100644index 0000000000..bcb6a5307d--- /dev/null+++ b/networklocation/src/test/java/com/vayunmathur/networklocation/provider/OfflineBeaconStoreTest.kt@@ -0,0 +1,169 @@+package com.vayunmathur.networklocation.provider++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.networklocation.BeaconId+import com.vayunmathur.networklocation.BeaconKeys+import com.vayunmathur.networklocation.OfflineDatabases+import com.vayunmathur.networklocation.RadioType+import com.vayunmathur.networklocation.WpsRec+import com.vayunmathur.networklocation.writeWpsStore+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner++@RunWith(RobolectricTestRunner::class)+class OfflineBeaconStoreTest {++    private val context: Context get() = ApplicationProvider.getApplicationContext()++    private val ap = BeaconId.Wifi("00:11:22:33:44:55")+    private val apUnknown = BeaconId.Wifi("00:aa:bb:cc:dd:ee")+    private val cell = BeaconId.Cell(310, 260, RadioType.LTE, 4242, 1234)++    private fun clearStores() {+        OfflineDatabases.file(context, OfflineDatabases.WIFI).delete()+        OfflineDatabases.file(context, OfflineDatabases.CELL).delete()+    }++    private fun installWifiStore() {+        writeWpsStore(+            OfflineDatabases.file(context, OfflineDatabases.WIFI),+            BeaconKeys.WIFI_UNIVERSE_BITS,+            listOf(+                WpsRec(0L, BeaconKeys.parseMac(ap.bssid)!!, 3_742_150_000L, -12_208_400_000L, 25L, 10L),+                // Unknown accuracy (0xFFFF sentinel) and unknown altitude.+                WpsRec(0L, BeaconKeys.parseMac(apUnknown.bssid)!!, 4_000_000_000L, -7_000_000_000L, 0xFFFFL, null),+            ),+        )+    }++    private fun installCellStore() {+        writeWpsStore(+            OfflineDatabases.file(context, OfflineDatabases.CELL),+            BeaconKeys.CELL_UNIVERSE_BITS,+            listOf(+                WpsRec(+                    BeaconKeys.cellKeyHi(cell), BeaconKeys.cellKeyLo(cell),+                    5_100_000_000L, 0L, 80L, null,+                ),+            ),+        )+    }++    @Test+    fun `missing stores resolve nothing and describe as closed`() {+        clearStores()+        val store = OfflineBeaconStore(context)+        assertTrue(store.resolveWifi(listOf(ap)).isEmpty())+        assertTrue(store.resolveCell(listOf(cell)).isEmpty())+        assertTrue(store.resolveWifi(emptyList()).isEmpty())+        assertTrue(store.resolveCell(emptyList()).isEmpty())+        val desc = store.describe()+        assertTrue(desc.contains("wifi=closed"), desc)+        assertTrue(desc.contains("cell=closed"), desc)+        store.close()+        store.close() // idempotent+    }++    @Test+    fun `wifi hits resolve with coordinates accuracy and altitude`() {+        clearStores()+        installWifiStore()+        val store = OfflineBeaconStore(context)+        assertTrue(store.describe().contains("wifi=open"), store.describe())+        val out = store.resolveWifi(listOf(ap, BeaconId.Wifi("00:99:88:77:66:55")))+        assertEquals(1, out.size, "absent AP is omitted, not invented")+        val fix = out.getValue(ap)+        assertEquals(ap, fix.id)+        assertEquals(37.4215, fix.latitude, 1e-6)+        assertEquals(-122.084, fix.longitude, 1e-6)+        assertEquals(25.0, fix.accuracyMeters, 1e-6)+        assertEquals(10.0, fix.altitudeMeters!!, 1e-6)+        store.close()+    }++    @Test+    fun `unknown accuracy becomes the conservative default and unknown altitude is null`() {+        clearStores()+        installWifiStore()+        val store = OfflineBeaconStore(context)+        val fix = store.resolveWifi(listOf(apUnknown)).getValue(apUnknown)+        assertEquals(40.0, fix.latitude, 1e-6)+        assertEquals(-70.0, fix.longitude, 1e-6)+        assertEquals(100.0, fix.accuracyMeters, "negative native accuracy must be substituted")+        assertNull(fix.altitudeMeters, "native NaN altitude must become null")+        store.close()+    }++    @Test+    fun `malformed and randomized bssids never resolve`() {+        clearStores()+        installWifiStore()+        val store = OfflineBeaconStore(context)+        val out = store.resolveWifi(+            listOf(+                BeaconId.Wifi("not-a-mac"),+                BeaconId.Wifi("02:11:22:33:44:55"), // locally administered+                BeaconId.Wifi("01:11:22:33:44:55"), // multicast+                BeaconId.Wifi(""),+            ),+        )+        assertTrue(out.isEmpty())+        store.close()+    }++    @Test+    fun `cell hits resolve and absent cells are omitted`() {+        clearStores()+        installCellStore()+        val store = OfflineBeaconStore(context)+        assertTrue(store.describe().contains("cell=open"), store.describe())+        val absent = BeaconId.Cell(310, 260, RadioType.LTE, 9999, 1234)+        val out = store.resolveCell(listOf(cell, absent))+        assertEquals(1, out.size)+        val fix = out.getValue(cell)+        assertEquals(51.0, fix.latitude, 1e-6)+        assertEquals(0.0, fix.longitude, 1e-6)+        assertEquals(80.0, fix.accuracyMeters, 1e-6)+        assertNull(fix.altitudeMeters)+        store.close()+    }++    @Test+    fun `a store that arrives after open is picked up on the next lookup`() {+        clearStores()+        val store = OfflineBeaconStore(context)+        assertTrue(store.resolveWifi(listOf(ap)).isEmpty())+        installWifiStore()+        val out = store.resolveWifi(listOf(ap))+        assertEquals(1, out.size, "downloaded store must be reopened without a restart")+        store.close()+        assertTrue(store.describe().contains("wifi=closed"), store.describe())+    }++    @Test+    fun `explicit reopen releases and reopens handles`() {+        clearStores()+        installWifiStore()+        installCellStore()+        val store = OfflineBeaconStore(context)+        store.open()+        assertEquals(1, store.resolveWifi(listOf(ap)).size)+        assertEquals(1, store.resolveCell(listOf(cell)).size)+        store.close()+    }++    @Test+    fun `a truncated store file leaves the handle closed instead of crashing`() {+        clearStores()+        OfflineDatabases.file(context, OfflineDatabases.WIFI).writeBytes(byteArrayOf(1, 2, 3))+        val store = OfflineBeaconStore(context)+        assertTrue(store.resolveWifi(listOf(ap)).isEmpty())+        assertTrue(store.describe().contains("wifi=closed"), store.describe())+        store.close()+    }+}
networklocation/src/test/java/com/vayunmathur/networklocation/ui/ScreensComposeTest.kt
diff --git a/networklocation/src/test/java/com/vayunmathur/networklocation/ui/ScreensComposeTest.kt b/networklocation/src/test/java/com/vayunmathur/networklocation/ui/ScreensComposeTest.ktnew file mode 100644index 0000000000..bfce5d8863--- /dev/null+++ b/networklocation/src/test/java/com/vayunmathur/networklocation/ui/ScreensComposeTest.kt@@ -0,0 +1,256 @@+package com.vayunmathur.networklocation.ui++import android.Manifest+import android.app.Application+import android.content.Context+import android.location.Location+import android.location.LocationManager+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onAllNodesWithText+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.compose.ui.test.performScrollTo+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.networklocation.OfflineDatabases+import com.vayunmathur.networklocation.writeGeocoderDb+import kotlin.test.Test+import kotlin.test.assertTrue+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.Shadows.shadowOf++@RunWith(AndroidJUnit4::class)+class ScreensComposeTest {++    @get:Rule+    val rule = createComposeRule()++    private val context: Context get() = ApplicationProvider.getApplicationContext()++    private fun clearDbs() {+        for (n in listOf(OfflineDatabases.GEOCODER, OfflineDatabases.WIFI, OfflineDatabases.CELL)) {+            OfflineDatabases.file(context, n).delete()+        }+    }++    private fun installAllDbs() {+        writeGeocoderDb(OfflineDatabases.file(context, OfflineDatabases.GEOCODER))+        OfflineDatabases.file(context, OfflineDatabases.WIFI).writeBytes(byteArrayOf(1))+        OfflineDatabases.file(context, OfflineDatabases.CELL).writeBytes(byteArrayOf(1))+    }++    @Test+    fun `setup screen explains the provider and offers the download`() {+        clearDbs()+        shadowOf(context as Application)+            .denyPermissions(Manifest.permission.ACCESS_FINE_LOCATION)+        var ready = false+        rule.setContent { SetupScreen(onReady = { ready = true }) }+        rule.onNodeWithText("Network Location").assertIsDisplayed()+        rule.onNodeWithText(+            "Provides the system network-location provider and an on-device, offline " ++                "geocoder. Both resolve entirely on device from the downloaded databases " ++                "below — nothing is sent to a positioning service. Always on — there is no " ++                "disable switch.",+        ).assertIsDisplayed()+        rule.onNodeWithText("Offline databases").assertIsDisplayed()+        // The button sits below the fold of the scrolling column.+        rule.onNodeWithText("Download offline databases").assertExists()+        assertTrue(!ready, "onReady must not fire before the databases exist")+    }++    @Test+    fun `setup screen reports ready once every database is installed`() {+        installAllDbs()+        var ready = false+        rule.setContent { SetupScreen(onReady = { ready = true }) }+        rule.onNodeWithText(+            "All offline databases are installed. Positioning and geocoding work without " ++                "a network connection.",+        ).assertIsDisplayed()+        rule.waitUntil(5_000) { ready }+        assertTrue(ready)+    }++    @Test+    fun `status screen without location permission says so`() {+        installAllDbs()+        shadowOf(context as Application)+            .denyPermissions(Manifest.permission.ACCESS_FINE_LOCATION)+        rule.setContent { StatusScreen() }+        rule.onNodeWithText("Network Location").assertIsDisplayed()+        rule.onNodeWithText(+            "Location permission is not granted, so live positions cannot be shown.",+        ).assertIsDisplayed()+        rule.onNodeWithText(+            "All offline databases are installed. Positioning and geocoding work without " ++                "a network connection.",+        ).assertIsDisplayed()+    }++    @Test+    fun `live section with permission waits for fixes`() {+        shadowOf(context as Application)+            .grantPermissions(Manifest.permission.ACCESS_FINE_LOCATION)+        val lm = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager+        val shadow = shadowOf(lm)+        shadow.setProviderEnabled(LocationManager.GPS_PROVIDER, true)+        shadow.setProviderEnabled(LocationManager.NETWORK_PROVIDER, true)+        rule.setContent { LiveLocationSection() }+        rule.onNodeWithText("Live check").assertIsDisplayed()+        rule.onNodeWithText("GPS").assertIsDisplayed()+        rule.onNodeWithText("Waiting for a GPS fix… (go outside or near a window)").assertIsDisplayed()+        rule.onNodeWithText("Network location (this app)").assertIsDisplayed()+        rule.onNodeWithText(+            "No network fix yet. Cell and Wi-Fi scans resolve against the offline stores.",+        ).assertIsDisplayed()+        rule.onNodeWithText("Offline geocoder (GPS position)").assertIsDisplayed()+        rule.onNodeWithText("Waiting for a GPS fix to look up.").assertIsDisplayed()+    }++    @Test+    fun `live section shows a gps fix and the geocoder no-match state`() {+        shadowOf(context as Application)+            .grantPermissions(Manifest.permission.ACCESS_FINE_LOCATION)+        val lm = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager+        val shadow = shadowOf(lm)+        shadow.setProviderEnabled(LocationManager.GPS_PROVIDER, true)+        shadow.setProviderEnabled(LocationManager.NETWORK_PROVIDER, true)+        val fix = Location(LocationManager.GPS_PROVIDER).apply {+            latitude = 37.4215+            longitude = -122.084+            accuracy = 5f+            elapsedRealtimeNanos = System.nanoTime()+        }+        shadow.setLastKnownLocation(LocationManager.GPS_PROVIDER, fix)+        rule.setContent { LiveLocationSection() }+        rule.onNodeWithText("37.421500, -122.084000").assertIsDisplayed()+        // The shadow geocoder has no canned address, so the lookup settles on no-match.+        rule.waitUntil(5_000) {+            rule.onAllNodesWithText("No nearby record in the database.")+                .fetchSemanticsNodes().isNotEmpty()+        }+        rule.onNodeWithText("No nearby record in the database.").assertIsDisplayed()+    }++    @Test+    fun `live section shows gps and network fixes with their comparison`() {+        shadowOf(context as Application)+            .grantPermissions(Manifest.permission.ACCESS_FINE_LOCATION)+        val lm = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager+        val shadow = shadowOf(lm)+        shadow.setProviderEnabled(LocationManager.GPS_PROVIDER, true)+        shadow.setProviderEnabled(LocationManager.NETWORK_PROVIDER, true)+        fun fix(provider: String, lat: Double, lon: Double) = Location(provider).apply {+            latitude = lat+            longitude = lon+            accuracy = 8f+            elapsedRealtimeNanos = System.nanoTime()+        }+        shadow.setLastKnownLocation(+            LocationManager.GPS_PROVIDER,+            fix(LocationManager.GPS_PROVIDER, 37.4215, -122.084),+        )+        shadow.setLastKnownLocation(+            LocationManager.NETWORK_PROVIDER,+            fix(LocationManager.NETWORK_PROVIDER, 37.4225, -122.085),+        )+        rule.setContent { LiveLocationSection() }+        rule.onNodeWithText("37.421500, -122.084000").assertIsDisplayed()+        rule.onNodeWithText("37.422500, -122.085000").assertExists()+        // The network card annotates its distance from the GPS fix.+        rule.waitUntil(5_000) {+            rule.onAllNodesWithText("m from GPS", substring = true)+                .fetchSemanticsNodes().isNotEmpty()+        }+    }++    private fun setGpsFix() {+        shadowOf(context as Application)+            .grantPermissions(Manifest.permission.ACCESS_FINE_LOCATION)+        val lm = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager+        val shadow = shadowOf(lm)+        shadow.setProviderEnabled(LocationManager.GPS_PROVIDER, true)+        shadow.setProviderEnabled(LocationManager.NETWORK_PROVIDER, true)+        shadow.setLastKnownLocation(+            LocationManager.GPS_PROVIDER,+            Location(LocationManager.GPS_PROVIDER).apply {+                latitude = 37.4215+                longitude = -122.084+                accuracy = 5f+                elapsedRealtimeNanos = System.nanoTime()+            },+        )+    }++    @Test+    fun `live section shows a found geocode result`() {+        setGpsFix()+        val address = android.location.Address(java.util.Locale.US).apply {+            latitude = 37.4216+            longitude = -122.0841+            setAddressLine(0, "123 Main St")+            featureName = "123"+            thoroughfare = "Main St"+            locality = "Springfield"+            adminArea = "CA"+            postalCode = "12345"+            countryCode = "US"+        }+        rule.setContent {+            LiveLocationSection(geocodeLookup = { _, _, _ -> Result.success(address) })+        }+        rule.waitUntil(5_000) {+            rule.onAllNodesWithText("123 Main St").fetchSemanticsNodes().isNotEmpty()+        }+        rule.onNodeWithText("123 Main St").assertIsDisplayed()+        rule.onNodeWithText("Main St, Springfield, CA, 12345, US").assertExists()+        rule.onNodeWithText("m from the GPS fix", substring = true).assertExists()+    }++    @Test+    fun `live section shows a failed geocode lookup`() {+        setGpsFix()+        rule.setContent {+            LiveLocationSection(+                geocodeLookup = { _, _, _ -> Result.failure(IllegalStateException("boom")) },+            )+        }+        rule.waitUntil(5_000) {+            rule.onAllNodesWithText("Lookup failed: boom").fetchSemanticsNodes().isNotEmpty()+        }+        rule.onNodeWithText("Lookup failed: boom").assertIsDisplayed()+    }++    @Test+    fun `live section shows the looking state while a lookup is in flight`() {+        setGpsFix()+        val gate = kotlinx.coroutines.CompletableDeferred<Result<android.location.Address?>>()+        rule.setContent {+            LiveLocationSection(geocodeLookup = { _, _, _ -> gate.await() })+        }+        rule.waitUntil(5_000) {+            rule.onAllNodesWithText("Looking up…", substring = true)+                .fetchSemanticsNodes().isNotEmpty()+        }+        gate.complete(Result.success(null))+    }++    @Test+    fun `download button can be tapped and then disables itself`() {+        clearDbs()+        try {+            androidx.work.WorkManager.initialize(+                context,+                androidx.work.Configuration.Builder().build(),+            )+        } catch (_: Exception) {+            // Already initialised by an earlier test in this process.+        }+        rule.setContent { SetupScreen(onReady = {}) }+        rule.onNodeWithText("Download offline databases").performScrollTo().performClick()+        rule.onNodeWithText("Downloading over Wi-Fi…").assertExists()+    }+}
networklocation/src/test/java/com/vayunmathur/networklocation/wifi/NearbyWifiTest.kt
diff --git a/networklocation/src/test/java/com/vayunmathur/networklocation/wifi/NearbyWifiTest.kt b/networklocation/src/test/java/com/vayunmathur/networklocation/wifi/NearbyWifiTest.ktnew file mode 100644index 0000000000..fc16cf7cfb--- /dev/null+++ b/networklocation/src/test/java/com/vayunmathur/networklocation/wifi/NearbyWifiTest.kt@@ -0,0 +1,70 @@+package com.vayunmathur.networklocation.wifi++import android.content.Context+import android.net.wifi.ScanResult+import android.net.wifi.WifiManager+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.networklocation.BeaconId+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows.shadowOf++@RunWith(RobolectricTestRunner::class)+class NearbyWifiTest {++    private val context: Context get() = ApplicationProvider.getApplicationContext()++    private fun scanResult(bssid: String?): ScanResult {+        val r = ScanResult()+        r.BSSID = bssid+        r.SSID = "test"+        return r+    }++    private fun setResults(results: List<ScanResult>) {+        val wm = context.getSystemService(Context.WIFI_SERVICE) as WifiManager+        shadowOf(wm).setScanResults(results)+    }++    @Test+    fun `scan returns fixed aps deduplicated`() {+        setResults(+            listOf(+                scanResult("00:11:22:33:44:55"),+                scanResult("00:11:22:33:44:55"),+                scanResult("10:22:33:44:55:66"),+            ),+        )+        assertEquals(+            listOf(BeaconId.Wifi("00:11:22:33:44:55"), BeaconId.Wifi("10:22:33:44:55:66")),+            NearbyWifi(context).scan(),+        )+    }++    @Test+    fun `scan drops null blank placeholder randomized and multicast bssids`() {+        setResults(+            listOf(+                scanResult(null),+                scanResult(""),+                scanResult("   "),+                scanResult("00:00:00:00:00:00"),+                scanResult("02:11:22:33:44:55"), // locally administered+                scanResult("01:11:22:33:44:55"), // multicast+                scanResult("zz:11:22:33:44:55"), // malformed+                scanResult("00:11:22:33:44"), // malformed+                scanResult("00:11:22:33:44:55"),+            ),+        )+        assertEquals(listOf(BeaconId.Wifi("00:11:22:33:44:55")), NearbyWifi(context).scan())+    }++    @Test+    fun `no scan results yields an empty list`() {+        setResults(emptyList())+        assertTrue(NearbyWifi(context).scan().isEmpty())+    }+}