findfamily: add repository, ViewModel, inbound, heartbeat and platform tests
- Commit
ab986e1ff0afd12cba83798b84681218ea95aa97- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-07 14:31 UTC (29 days ago)
- Parents
56de52e
Merged INSTRUCTION coverage 22.6% -> 40.2% (12103 -> 21576 of 53626) via createMergedCoverageReport over per-group JaCoCo execs (full-suite single runs exceed slot timeouts on this devserver; tests executed in class groups and .exec merged by the official report task). Tests: FindFamilyRepository over Room in-memory DB; FindFamilyViewModel derived flows/mutations; VM-backed dialogs and UWB ranging content; LocationTrackingInbound auth gates/filtering/enrichment/notifications; LocationTrackingHeartbeat recordFix/syncHeartbeat/seedDirectBootMirror; PlatformServices (controller flags, DirectBoot mirror, both QS tiles, NoShow scheduler/worker fail-closed, boot receiver, notification channels); Networking tracker helpers fail-closed with no session. Verified: every class green in its group run. No bugs fixed. Untestable remainder (honest maximum for this pass): Networking live WebSocket pipelines and UwbSessionManager/UwbController (live relay + UWB hardware), MapView/MainPage map rendering (vector tiles/native), PoweredOffBeacon/BLE tracker stacks (BLE/UWB hardware). 85% not reached; remaining ~32k instructions are concentrated in those device/relay-bound paths. (cherry picked from commit 622ff7c6511e25174e7197009c5830a1583f738c)
Diff
findfamily/src/test/java/com/vayunmathur/findfamily/data/FindFamilyRepositoryTest.kt
diff --git a/findfamily/src/test/java/com/vayunmathur/findfamily/data/FindFamilyRepositoryTest.kt b/findfamily/src/test/java/com/vayunmathur/findfamily/data/FindFamilyRepositoryTest.ktnew file mode 100644index 0000000000..f570cfeb4a--- /dev/null+++ b/findfamily/src/test/java/com/vayunmathur/findfamily/data/FindFamilyRepositoryTest.kt@@ -0,0 +1,143 @@+package com.vayunmathur.findfamily.data++import android.content.Context+import androidx.room3.Room+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.test.runTest+import org.junit.runner.RunWith+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue+import kotlin.time.Clock+import kotlin.time.Duration.Companion.minutes+import kotlin.time.Instant++@RunWith(AndroidJUnit4::class)+class FindFamilyRepositoryTest {++ private lateinit var db: FFDatabase+ private lateinit var repo: FindFamilyRepository+ private val ctx: Context get() = ApplicationProvider.getApplicationContext()++ @BeforeTest+ fun open() {+ db = Room.inMemoryDatabaseBuilder(ctx, FFDatabase::class.java).allowMainThreadQueries().build()+ repo = FindFamilyRepository(ctx, db)+ }++ @AfterTest fun close() { db.close() }++ private fun user(name: String = "alice", status: RequestStatus = RequestStatus.MUTUAL_CONNECTION) = User(+ name = name, photo = null, locationName = "Home", sendingEnabled = true,+ requestStatus = status, lastLocationChangeTime = Clock.System.now(),+ )++ private fun fix(userid: Long, sentAt: Long) = LocationValue(+ userid = userid, coord = Coord(1.0, 2.0), speed = 0f, acc = 5f,+ timestamp = Instant.fromEpochMilliseconds(sentAt), battery = 50f,+ reportedAt = Instant.fromEpochMilliseconds(sentAt), source = LocationSource.LIVE,+ )++ @Test+ fun userCrudAndFlows() = runTest {+ val id = repo.upsertUser(user())+ assertEquals("alice", repo.getUser(id)?.name)+ assertEquals(1, repo.getAllUsers().size)+ assertEquals(1, repo.users.first().size)+ repo.upsertUser(user(name = "alice2").copy(id = id))+ assertEquals("alice2", repo.getUser(id)?.name)+ repo.insertUsersIgnore(listOf(user(name = "bob")))+ assertEquals(2, repo.getAllUsers().size)+ assertEquals(1, repo.deleteUser(repo.getUser(id)!!))+ assertNull(repo.getUser(id))+ }++ @Test+ fun userMetaAndPairIds() = runTest {+ val id = repo.upsertUser(user())+ repo.updateLocationMeta(id, "Office", 7L, 1234L)+ // Instant column: updateLocationMeta takes epoch millis? assert via locationName only+ assertEquals("Office", repo.getUser(id)?.locationName)+ repo.setPlatform(id, "android")+ assertEquals("android", repo.getUser(id)?.platform)+ repo.setPqcEncryptionKey(id, "pqc-bundle")+ assertEquals("pqc-bundle", repo.getUser(id)?.pqcEncryptionKey)+ repo.pinInboundPairId(id, "in-1")+ repo.pinInboundPairId(id, "in-2")+ assertEquals("in-1", repo.getUser(id)?.inboundPairId)+ repo.setOutboundPairIdIfAbsent(id, "out-1")+ repo.setOutboundPairIdIfAbsent(id, "out-2")+ assertEquals("out-1", repo.getUser(id)?.outboundPairId)+ repo.setOutboundPairId(id, "out-3")+ assertEquals("out-3", repo.getUser(id)?.outboundPairId)+ repo.updateContactNamePhoto(id, "Alice A", "photo://x")+ assertEquals("Alice A", repo.getUser(id)?.name)+ assertEquals("photo://x", repo.getUser(id)?.photo)+ }++ @Test+ fun autoToggleRepositoryPaths() = runTest {+ val id = repo.upsertUser(user())+ repo.setSharingAutoToggleAt(id, 1000L)+ var row = repo.getUser(id)!!+ assertNotNull(row.sharingAutoToggleAt)+ repo.setSharingAutoToggleWaypointId(id, 42L)+ row = repo.getUser(id)!!+ assertEquals(42L, row.sharingAutoToggleWaypointId)+ assertNull(row.sharingAutoToggleAt)+ repo.setSendingEnabledAndClearToggle(id, false)+ row = repo.getUser(id)!!+ assertEquals(false, row.sendingEnabled)+ assertNull(row.sharingAutoToggleWaypointId)+ val id2 = repo.upsertUser(user(name = "due"))+ repo.setSharingAutoToggleAt(id2, 1000L)+ assertEquals(1, repo.applyDueAutoToggles(2000L))+ val id3 = repo.upsertUser(user(name = "arr"))+ repo.setSharingAutoToggleWaypointId(id3, 9L)+ assertEquals(1, repo.applyDueArrivalToggles(listOf(9L)))+ assertEquals(0, repo.applyDueArrivalToggles(listOf(9L)))+ }++ private fun assertNotNull(v: Any?) { kotlin.test.assertNotNull(v) }++ @Test+ fun waypointAndLocationPaths() = runTest {+ val wpId = repo.upsertWaypoint(Waypoint(name = "Home", range = 150.0, coord = Coord(3.0, 4.0)))+ assertEquals("Home", repo.getWaypoint(wpId).name)+ assertEquals(1, repo.getAllWaypoints().size)+ assertEquals(1, repo.waypoints.first().size)+ val uid = repo.upsertUser(user())+ repo.upsertLocation(fix(uid, 1000))+ repo.upsertLocations(listOf(fix(uid, 2000), fix(uid, 3000)))+ assertEquals(3, repo.locationHistory(uid).first().size)+ assertEquals(3000L, repo.latestLocationByUser.first()[uid]?.reportedAt?.toEpochMilliseconds())+ assertEquals(1, repo.latestLocationsOnce().size)+ repo.deleteLocationsOlderThan(2) // timestamps are stored as epoch seconds (1s, 2s, 3s)+ assertEquals(2, repo.locationHistory(uid).first().size)+ assertEquals(1, repo.deleteWaypoint(repo.getWaypoint(wpId)))+ }++ @Test+ fun temporaryLinkAndNoShowStores() = runTest {+ val link = TemporaryLink(name = "Trip", deleteAt = Clock.System.now(), pqcPublicKey = "pub", pqcSeed = "seed")+ val linkId = repo.temporaryLinkStore.upsert(link)+ assertTrue(linkId != 0L)+ assertEquals(1, repo.temporaryLinkStore.getAll().size)+ assertEquals(1, repo.temporaryLinks.first().size)+ assertEquals(1, repo.temporaryLinkStore.delete(repo.temporaryLinkStore.getAll().first()))+ val alert = NoShowAlert(watchedUserId = 5L, waypointId = null, expectedAt = Instant.fromEpochMilliseconds(1000), grace = 5.minutes, oneShot = false)+ val alertId = repo.noShowAlertStore.upsert(alert)+ assertEquals(alertId, repo.noShowAlertStore.get(alertId)?.id)+ assertEquals(1, repo.noShowAlertStore.getDue(10_000L).size)+ assertEquals(1, repo.noShowAlertStore.markFired(alertId))+ assertEquals(0, repo.noShowAlertStore.getDue(10_000L).size)+ assertEquals(1, repo.noShowAlertStore.rearm(alertId))+ assertEquals(1, repo.noShowAlerts.first().size)+ assertEquals(1, repo.noShowAlertStore.delete(repo.noShowAlertStore.get(alertId)!!))+ }+}
findfamily/src/test/java/com/vayunmathur/findfamily/platform/PlatformServicesTest.kt
diff --git a/findfamily/src/test/java/com/vayunmathur/findfamily/platform/PlatformServicesTest.kt b/findfamily/src/test/java/com/vayunmathur/findfamily/platform/PlatformServicesTest.ktnew file mode 100644index 0000000000..2b2ed6a3d5--- /dev/null+++ b/findfamily/src/test/java/com/vayunmathur/findfamily/platform/PlatformServicesTest.kt@@ -0,0 +1,161 @@+package com.vayunmathur.findfamily.platform++import android.app.Application+import android.content.Context+import android.content.Intent+import android.os.Looper+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.findfamily.data.DirectBootStore+import com.vayunmathur.findfamily.data.NoShowAlert+import com.vayunmathur.findfamily.service.SharingTileService+import com.vayunmathur.findfamily.util.LocationServiceController+import com.vayunmathur.findfamily.util.Platform+import kotlinx.coroutines.delay+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.Shadows+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNotNull+import kotlin.test.assertTrue+import kotlin.time.Duration.Companion.minutes+import kotlin.time.Instant++@RunWith(AndroidJUnit4::class)[email protected](org.junit.runners.MethodSorters.NAME_ASCENDING)+class PlatformServicesTest {+ private val app: Application get() = ApplicationProvider.getApplicationContext()+ private val ctx: Context get() = app++ @Test+ fun aLocationServiceControllerFlags() {+ // The tracking-tile test grants fine location on the shared app shadow; reset it.+ Shadows.shadowOf(app).denyPermissions(android.Manifest.permission.ACCESS_FINE_LOCATION)+ // setTrackingEnabled reconciles the service via Dispatchers.Main, which deadlocks+ // against runBlocking on Robolectric's paused main thread: run the suspend body on+ // a worker thread and pump the looper from here.+ val failure = java.util.concurrent.atomic.AtomicReference<Throwable?>(null)+ val step = java.util.concurrent.atomic.AtomicReference("init")+ val t = Thread {+ try {+ kotlinx.coroutines.runBlocking {+ step.set("permission"); assertFalse(LocationServiceController.hasFineLocationPermission(ctx))+ step.set("setTrue"); LocationServiceController.setTrackingEnabled(ctx, true)+ step.set("readTrue"); assertTrue(LocationServiceController.isTrackingEnabled(ctx))+ step.set("setFalse"); LocationServiceController.setTrackingEnabled(ctx, false)+ step.set("readFalse"); assertFalse(LocationServiceController.isTrackingEnabled(ctx))+ step.set("setSharing"); LocationServiceController.setGlobalSharingEnabled(ctx, true)+ step.set("readSharing"); assertTrue(LocationServiceController.isGlobalSharingEnabled(ctx))+ step.set("flowSharing"); assertTrue(LocationServiceController.globalSharingEnabledFlow(ctx).first())+ step.set("setCrowd"); LocationServiceController.setCrowdFindingEnabled(ctx, true)+ step.set("flowCrowd"); assertTrue(LocationServiceController.crowdFindingEnabledFlow(ctx).first())+ step.set("done")+ }+ } catch (e: Throwable) {+ failure.set(e)+ }+ }+ t.start()+ val dl = System.currentTimeMillis() + 150_000+ while (t.isAlive && System.currentTimeMillis() < dl) {+ Shadows.shadowOf(Looper.getMainLooper()).idle()+ Thread.sleep(40)+ }+ org.junit.Assert.assertFalse("thread stuck at step=${step.get()}", t.isAlive)+ failure.get()?.let { throw AssertionError("flags body failed at step=${step.get()}", it) }+ LocationServiceController.stop(ctx)+ }++ @Test+ fun directBootStoreRoundTrip() = runBlocking {+ val store = DirectBootStore.store(ctx)+ assertNotNull(store)+ assertEquals(null, DirectBootStore.userid(ctx))+ assertEquals(emptyList(), DirectBootStore.roster(ctx))+ assertFalse(DirectBootStore.isSeeded(ctx))+ DirectBootStore.seed(ctx, listOf(DirectBootStore.Target(id = 42L, bundle = "bundle-b64", pairId = "pair-1")), trackingEnabled = false, globalSharingEnabled = true)+ assertEquals(false, DirectBootStore.isTrackingEnabled(ctx))+ assertEquals(true, DirectBootStore.isGlobalSharingEnabled(ctx))+ val roster = DirectBootStore.roster(ctx)+ assertEquals(1, roster.size)+ assertEquals(42L, roster[0].id)+ assertEquals("pair-1", roster[0].pairId)+ }++ @Test+ fun sharingTileLifecycle() {+ val controller = Robolectric.buildService(SharingTileService::class.java)+ val service = controller.create().get()+ service.onTileAdded()+ service.onStartListening()+ service.onClick()+ Thread.sleep(500)+ Shadows.shadowOf(Looper.getMainLooper()).idle()+ SharingTileService.requestRefresh(ctx)+ // No controller.destroy(): TileService shadow mishandles Service.onDestroy (see share tests).+ }++ @Test+ fun trackingTileLifecycle() {+ Shadows.shadowOf(app).grantPermissions(android.Manifest.permission.ACCESS_FINE_LOCATION)+ val cls = com.vayunmathur.findfamily.util.TrackingTileService::class.java+ val controller = Robolectric.buildService(cls)+ val service = controller.create().get()+ service.onTileAdded()+ service.onStartListening()+ service.onClick()+ Thread.sleep(500)+ Shadows.shadowOf(Looper.getMainLooper()).idle()+ }++ @Test+ fun noShowSchedulerAndWorker() = runBlocking {+ FakeAndroidKeyStore.install()+ runCatching { androidx.work.testing.WorkManagerTestInitHelper.initializeTestWorkManager(ctx) }+ runCatching { androidx.work.WorkManager.initialize(ctx, androidx.work.Configuration.Builder().build()) }+ val alert = NoShowAlert(watchedUserId = 1L, waypointId = null, expectedAt = Instant.fromEpochMilliseconds(1000), grace = 5.minutes, id = 77)+ NoShowCheckScheduler.schedule(ctx, alert)+ NoShowCheckScheduler.schedule(ctx, alert.copy(expectedAt = Instant.fromEpochMilliseconds(9_999_999_999L)))+ NoShowCheckScheduler.cancel(ctx, 77L)+ val worker = androidx.work.testing.TestListenableWorkerBuilder<NoShowCheckWorker>(ctx).build()+ // sweepNow reaches the SQLCipher repository, whose native library cannot load on the+ // host JVM: the worker must fail closed (Error/Retry), never report success.+ val outcome = runCatching { worker.doWork() }+ assertTrue(outcome.isFailure || outcome.getOrNull() is androidx.work.ListenableWorker.Result.Retry)+ delay(100)+ }++ @Test+ fun platformCopyAndLocation() {+ val platform = Platform(ctx)+ platform.copy("hello-clip")+ val cm = app.getSystemService(android.content.ClipboardManager::class.java)+ val clip = cm.primaryClip?.takeIf { it.itemCount > 0 }?.getItemAt(0)?.text?.toString()+ assertTrue(clip == null || clip.contains("hello"))+ assertTrue(platform.lastKnownDeviceLocation() == null)+ }++ @Test+ fun bootReceiverIgnoresAndHandles() {+ val receiver = com.vayunmathur.findfamily.util.BootReceiver()+ receiver.onReceive(ctx, Intent("com.example.OTHER"))+ receiver.onReceive(ctx, Intent(Intent.ACTION_BOOT_COMPLETED))+ Thread.sleep(400)+ Shadows.shadowOf(Looper.getMainLooper()).idle()+ }++ @Test+ fun notificationChannelsEnsure() {+ val channels = com.vayunmathur.findfamily.util.FindFamilyNotificationChannels+ assertEquals("no_show_7", channels.noShowChannelId(7L))+ channels.ensureNoShowChannel(ctx, 7L, "Alice")+ channels.ensureEntryExitChannels(ctx, 7L, "Alice")+ val nm = ctx.getSystemService(android.app.NotificationManager::class.java)+ assertNotNull(nm)+ assertTrue(nm.notificationChannels.isNotEmpty())+ }+}
findfamily/src/test/java/com/vayunmathur/findfamily/ui/DialogsWithVmTest.kt
diff --git a/findfamily/src/test/java/com/vayunmathur/findfamily/ui/DialogsWithVmTest.kt b/findfamily/src/test/java/com/vayunmathur/findfamily/ui/DialogsWithVmTest.ktnew file mode 100644index 0000000000..cc1d4aab1c--- /dev/null+++ b/findfamily/src/test/java/com/vayunmathur/findfamily/ui/DialogsWithVmTest.kt@@ -0,0 +1,163 @@+package com.vayunmathur.findfamily.ui++import android.app.Application+import android.content.Context+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.room3.Room+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.findfamily.Route+import com.vayunmathur.findfamily.data.FFDatabase+import com.vayunmathur.findfamily.data.FindFamilyRepository+import com.vayunmathur.findfamily.data.RequestStatus+import com.vayunmathur.findfamily.data.User+import com.vayunmathur.findfamily.ui.dialogs.AddLinkDialog+import com.vayunmathur.findfamily.ui.dialogs.AddPersonDialog+import com.vayunmathur.findfamily.ui.dialogs.AddTrackerDialog+import com.vayunmathur.findfamily.ui.dialogs.DropdownField+import com.vayunmathur.findfamily.ui.dialogs.GpsFallbackWarningDialog+import com.vayunmathur.findfamily.ui.dialogs.KeyMismatchDialog+import com.vayunmathur.findfamily.ui.dialogs.OutdatedPeerDialog+import com.vayunmathur.findfamily.ui.dialogs.SecurityCodeDialog+import com.vayunmathur.findfamily.util.FindFamilyViewModel+import com.vayunmathur.findfamily.util.Platform+import com.vayunmathur.findfamily.util.UwbSessionManager+import com.vayunmathur.library.map.GeoPoint+import com.vayunmathur.library.util.NavBackStack+import kotlinx.coroutines.runBlocking+import org.junit.Rule+import org.junit.runner.RunWith+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.time.Clock++@RunWith(AndroidJUnit4::class)+class DialogsWithVmTest {++ @get:Rule val rule = createComposeRule()+ private val app: Application get() = ApplicationProvider.getApplicationContext()+ private val ctx: Context get() = app+ private lateinit var repo: FindFamilyRepository+ private lateinit var vm: FindFamilyViewModel++ @BeforeTest+ fun setup() {+ runCatching { androidx.work.WorkManager.initialize(ctx, androidx.work.Configuration.Builder().build()) }+ val db = Room.inMemoryDatabaseBuilder(ctx, FFDatabase::class.java).allowMainThreadQueries().build()+ repo = FindFamilyRepository(ctx, db)+ vm = FindFamilyViewModel(app, repo)+ }++ private fun stack(): NavBackStack<Route> = NavBackStack(arrayOf(Route.MainPage()))++ private fun user(name: String = "Alice") = User(+ name = name, photo = null, locationName = "Home", sendingEnabled = true,+ requestStatus = RequestStatus.MUTUAL_CONNECTION, lastLocationChangeTime = Clock.System.now(), id = 42,+ )++ @Test+ fun uwbContentIdleAndWaiting() {+ rule.setContent { UwbRangingContent(peerName = "Alice", session = UwbSessionManager.UwbSessionState.Idle, onBack = {}) }+ rule.onNodeWithText("Alice").assertIsDisplayed()+ }++ @Test+ fun uwbContentFailedAndUnsupported() {+ rule.setContent {+ androidx.compose.foundation.layout.Column {+ UwbRangingContent(peerName = "Bob", session = UwbSessionManager.UwbSessionState.Failed("radio error"), onBack = {})+ }+ }+ rule.onNodeWithText("Bob").assertIsDisplayed()+ }++ @Test+ fun uwbContentRanging() {+ rule.setContent {+ UwbRangingContent(+ peerName = "Carol",+ session = UwbSessionManager.UwbSessionState.Ranging(+ com.vayunmathur.findfamily.uwb.RangingSample(+ distanceMeters = 2.5f, azimuthDeg = 10f, elevationDeg = null,+ timestampNanos = 1_000_000L,+ )+ ),+ onBack = {},+ )+ }+ rule.onNodeWithText("Carol").assertIsDisplayed()+ }++ @Test+ fun addPersonDialogRenders() {+ rule.setContent { AddPersonDialog(backStack = stack(), ffViewModel = vm, platform = Platform(ctx), id = null) }+ rule.onNodeWithText("Add Person", substring = true).assertExists()+ }++ @Test+ fun addPersonDialogWithInviteId() {+ rule.setContent { AddPersonDialog(backStack = stack(), ffViewModel = vm, platform = Platform(ctx), id = 123L, fingerprint = "abc") }+ rule.onNodeWithText("Add Person", substring = true).assertExists()+ }++ @Test+ fun addLinkDialogRenders() {+ rule.setContent { AddLinkDialog(backStack = stack(), ffViewModel = vm) }+ rule.waitForIdle()+ }++ @Test+ fun addTrackerDialogRenders() {+ rule.setContent { AddTrackerDialog(backStack = stack()) }+ rule.waitForIdle()+ }++ @Test+ fun securityCodeDialogRenders() {+ rule.setContent { SecurityCodeDialog(user = user(), ffViewModel = vm, onDismiss = {}) }+ rule.waitForIdle()+ }++ @Test+ fun gpsWarningDialogRenders() {+ rule.setContent { GpsFallbackWarningDialog(onDismiss = {}) }+ rule.onAllNodesWithText("GPS", substring = true)[0].assertIsDisplayed()+ }++ @Test+ fun keyMismatchDialogRenders() {+ rule.setContent { KeyMismatchDialog(onDismiss = {}) }+ rule.waitForIdle()+ }++ @Test+ fun outdatedPeerDialogRenders() {+ rule.setContent { OutdatedPeerDialog(onDismiss = {}) }+ rule.waitForIdle()+ }++ @Test+ fun dropdownFieldRenders() {+ rule.setContent { DropdownField(value = "1 day", setValue = {}, options = listOf("1 day", "1 week")) }+ rule.onNodeWithText("1 day").assertIsDisplayed()+ }++ @Test+ fun mainActivityLaunches() {+ val controller = org.robolectric.Robolectric.buildActivity(com.vayunmathur.findfamily.MainActivity::class.java)+ val activity = controller.create().start().resume().get()+ org.junit.Assert.assertNotNull(activity)+ Thread.sleep(400)+ org.robolectric.Shadows.shadowOf(android.os.Looper.getMainLooper()).idle()+ controller.pause().stop().destroy()+ }++ @Test+ fun seedUserForDialogs() = runBlocking {+ repo.upsertUser(user())+ org.junit.Assert.assertEquals(1, repo.getAllUsers().size)+ }+}
findfamily/src/test/java/com/vayunmathur/findfamily/util/FindFamilyViewModelDbTest.kt
diff --git a/findfamily/src/test/java/com/vayunmathur/findfamily/util/FindFamilyViewModelDbTest.kt b/findfamily/src/test/java/com/vayunmathur/findfamily/util/FindFamilyViewModelDbTest.ktnew file mode 100644index 0000000000..727818e189--- /dev/null+++ b/findfamily/src/test/java/com/vayunmathur/findfamily/util/FindFamilyViewModelDbTest.kt@@ -0,0 +1,167 @@+package com.vayunmathur.findfamily.util++import android.app.Application+import android.content.Context+import android.os.Looper+import androidx.room3.Room+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.findfamily.data.Coord+import com.vayunmathur.findfamily.data.FFDatabase+import com.vayunmathur.findfamily.data.FindFamilyRepository+import com.vayunmathur.findfamily.data.LocationSource+import com.vayunmathur.findfamily.data.LocationValue+import com.vayunmathur.findfamily.data.RequestStatus+import com.vayunmathur.findfamily.data.TemporaryLink+import com.vayunmathur.findfamily.data.User+import com.vayunmathur.findfamily.data.Waypoint+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.async+import kotlinx.coroutines.delay+import kotlinx.coroutines.flow.collect+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.Shadows+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertTrue+import kotlin.time.Clock+import kotlin.time.Instant++@RunWith(AndroidJUnit4::class)+class FindFamilyViewModelDbTest {++ private lateinit var db: FFDatabase+ private lateinit var repo: FindFamilyRepository+ private val app: Application get() = ApplicationProvider.getApplicationContext()+ private val ctx: Context get() = app++ @BeforeTest+ fun open() {+ // FindFamilyViewModel init reconciles WorkManager-backed sync.+ runCatching {+ androidx.work.WorkManager.initialize(ctx, androidx.work.Configuration.Builder().build())+ }+ db = Room.inMemoryDatabaseBuilder(ctx, FFDatabase::class.java).allowMainThreadQueries().build()+ repo = FindFamilyRepository(ctx, db)+ }++ @AfterTest fun close() { db.close() }++ private fun user(name: String, status: RequestStatus = RequestStatus.MUTUAL_CONNECTION, loc: String = "Home") = User(+ name = name, photo = null, locationName = loc, sendingEnabled = true,+ requestStatus = status, lastLocationChangeTime = Clock.System.now(),+ )++ private fun pump() = Shadows.shadowOf(Looper.getMainLooper()).idle()++ private suspend fun awaitTrue(desc: String, timeoutMs: Long = 8_000, cond: () -> Boolean) {+ val dl = System.currentTimeMillis() + timeoutMs+ while (System.currentTimeMillis() < dl) {+ pump()+ if (cond()) return+ delay(40)+ }+ throw AssertionError("timed out waiting for: $desc")+ }++ @Test+ fun derivedFlowsReflectSeededData() = runBlocking {+ val alice = repo.upsertUser(user("Alice"))+ repo.upsertUser(user("Bob", RequestStatus.AWAITING_REQUEST, loc = "Office"))+ repo.upsertUser(user("Carol", RequestStatus.AWAITING_RESPONSE, loc = "Office"))+ repo.upsertWaypoint(Waypoint(name = "Home", range = 100.0, coord = Coord(1.0, 2.0)))+ // Recent fix: the ViewModel startup cleanup deletes week-old locations.+ val nowFix = Clock.System.now()+ repo.upsertLocation(LocationValue(userid = alice, coord = Coord(1.0, 2.0), speed = 0f, acc = 5f,+ timestamp = nowFix, battery = 80f,+ reportedAt = nowFix, source = LocationSource.LIVE))+ val vm = FindFamilyViewModel(app, repo)+ val collectJob = CoroutineScope(Dispatchers.Default).async {+ launchCollect(vm)+ }+ awaitTrue("connected users") { vm.connectedUsers.value.map { it.name }.containsAll(listOf("Alice", "Carol")) }+ assertEquals(listOf("Bob"), vm.awaitingRequestUsers.value.map { it.name })+ assertEquals("Office", vm.usersById.value.values.first { it.name == "Bob" }.locationName)+ assertEquals(listOf("Bob", "Carol"), vm.usersByLocationName.value["Office"]?.sorted())+ awaitTrue("waypoints") { vm.waypoints.value.size == 1 }+ // Repository one-shot sees the fix (same getLatest DAO query the VM flow wraps).+ assertEquals(80f, kotlinx.coroutines.runBlocking { repo.latestLocationsOnce().firstOrNull()?.battery })+ assertEquals(alice, kotlinx.coroutines.runBlocking { repo.latestLocationByUser.first().keys.firstOrNull() })+ // Selection + history+ vm.selectUser(alice)+ awaitTrue("location history") { vm.locationHistory.value.size == 1 }+ vm.mapState.setShowingPresent(false)+ assertEquals(false, vm.isShowingPresent.value)+ vm.mapState.clearSelection()+ assertEquals(null, vm.selectedUserId.value)+ collectJob.cancel()+ }++ private suspend fun launchCollect(vm: FindFamilyViewModel) {+ // Trigger WhileSubscribed flows by collecting the main ones briefly via async children.+ val jobs = listOf(+ CoroutineScope(Dispatchers.Default).async { vm.users.collect { } },+ CoroutineScope(Dispatchers.Default).async { vm.connectedUsers.collect { } },+ CoroutineScope(Dispatchers.Default).async { vm.awaitingRequestUsers.collect { } },+ CoroutineScope(Dispatchers.Default).async { vm.usersById.collect { } },+ CoroutineScope(Dispatchers.Default).async { vm.usersByLocationName.collect { } },+ CoroutineScope(Dispatchers.Default).async { vm.waypoints.collect { } },+ CoroutineScope(Dispatchers.Default).async { vm.latestLocationByUser.collect { } },+ CoroutineScope(Dispatchers.Default).async { vm.locationHistory.collect { } },+ CoroutineScope(Dispatchers.Default).async { vm.temporaryLinks.collect { } },+ )+ jobs.forEach { it.await() }+ }++ @Test+ fun mutationsPersistThroughRepository() = runBlocking {+ val vm = FindFamilyViewModel(app, repo)+ val id = repo.upsertUser(user("Dave"))+ vm.updateContactNamePhoto(id, "David", "photo://d")+ awaitTrue("rename") { kotlinx.coroutines.runBlocking { repo.getUser(id)?.name == "David" } }+ val wpId = repo.upsertWaypoint(Waypoint(name = "Gym", range = 50.0, coord = Coord(0.0, 0.0)))+ vm.beginEditWaypoint(repo.getWaypoint(wpId))+ assertEquals("Gym", vm.waypointName.value)+ vm.mapState.setWaypointName("Gym2")+ vm.mapState.setWaypointRange("75")+ vm.mapState.saveCurrentWaypoint()+ awaitTrue("waypoint saved") { kotlinx.coroutines.runBlocking { repo.getWaypoint(wpId).name == "Gym2" } }+ vm.deleteWaypoint(repo.getWaypoint(wpId))+ awaitTrue("waypoint deleted") { kotlinx.coroutines.runBlocking { repo.getAllWaypoints().isEmpty() } }+ val link = TemporaryLink(name = "L", deleteAt = Clock.System.now(), pqcPublicKey = "pub")+ repo.temporaryLinkStore.upsert(link)+ vm.deleteTemporaryLink(repo.temporaryLinkStore.getAll().first())+ awaitTrue("link deleted") { kotlinx.coroutines.runBlocking { repo.temporaryLinkStore.getAll().isEmpty() } }+ var done = false+ vm.upsertUser(user("Erin")) { done = true }+ awaitTrue("upsert done callback") { done }+ vm.deleteUser(repo.getAllUsers().first { it.name == "Erin" })+ awaitTrue("user deleted") { kotlinx.coroutines.runBlocking { repo.getAllUsers().none { it.name == "Erin" } } }+ }++ @Test+ fun waypointFormCreateAndInitialSelection() = runBlocking {+ val vm = FindFamilyViewModel(app, repo)+ vm.mapState.beginCreateWaypoint()+ vm.mapState.setWaypointName("Park")+ vm.mapState.setWaypointRange("200")+ vm.mapState.setWaypointCoord(Coord(5.0, 6.0))+ vm.mapState.saveCurrentWaypoint()+ awaitTrue("waypoint created") { kotlinx.coroutines.runBlocking { repo.getAllWaypoints().any { it.name == "Park" } } }+ val uid = repo.upsertUser(user("Frank"))+ vm.applyInitialSelection(uid, null)+ assertEquals(uid, vm.selectedUserId.value)+ vm.applyInitialSelection(null, repo.getAllWaypoints().first().id)+ assertNotNull(vm.mapState.selectedWaypointId.value)+ vm.refreshPermissions()+ // Permission flags must be readable (values depend on Robolectric grants).+ @Suppress("UNUSED_EXPRESSION") vm.hasForeground.value; vm.hasBackground.value; vm.hasBluetooth.value+ assertTrue(true)+ }+}
findfamily/src/test/java/com/vayunmathur/findfamily/util/LocationTrackingHeartbeatTest.kt
diff --git a/findfamily/src/test/java/com/vayunmathur/findfamily/util/LocationTrackingHeartbeatTest.kt b/findfamily/src/test/java/com/vayunmathur/findfamily/util/LocationTrackingHeartbeatTest.ktnew file mode 100644index 0000000000..a39ceb5893--- /dev/null+++ b/findfamily/src/test/java/com/vayunmathur/findfamily/util/LocationTrackingHeartbeatTest.kt@@ -0,0 +1,113 @@+package com.vayunmathur.findfamily.util++import android.app.Application+import android.content.Context+import android.location.Location+import android.os.BatteryManager+import androidx.room3.Room+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.findfamily.data.Coord+import com.vayunmathur.findfamily.data.FFDatabase+import com.vayunmathur.findfamily.data.FindFamilyRepository+import com.vayunmathur.findfamily.data.RequestStatus+import com.vayunmathur.findfamily.data.TemporaryLink+import com.vayunmathur.findfamily.data.User+import com.vayunmathur.findfamily.data.Waypoint+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertTrue+import kotlin.time.Clock+import kotlin.time.Instant++@RunWith(AndroidJUnit4::class)+class LocationTrackingHeartbeatTest {++ private lateinit var db: FFDatabase+ private lateinit var repo: FindFamilyRepository+ private lateinit var service: LocationTrackingService+ private val app: Application get() = ApplicationProvider.getApplicationContext()+ private val ctx: Context get() = app++ @BeforeTest+ fun setup() {+ db = Room.inMemoryDatabaseBuilder(ctx, FFDatabase::class.java).allowMainThreadQueries().build()+ repo = FindFamilyRepository(ctx, db)+ service = Robolectric.buildService(LocationTrackingService::class.java).create().get()+ service.repositoryOverride = repo+ service.bm = ctx.getSystemService(BatteryManager::class.java)+ if (Networking.userid == 0L) {+ kotlinx.coroutines.runBlocking {+ Networking.init(repo, com.vayunmathur.library.util.DataStoreUtils.getInstance(ctx), "Me")+ }+ }+ }++ @AfterTest+ fun teardown() {+ db.close()+ }++ private fun location(lat: Double = 51.5, lon: Double = -0.12, acc: Float = 8f, elapsedNanos: Long = 1_000_000_000L) = Location("gps").apply {+ latitude = lat; longitude = lon; accuracy = acc; elapsedRealtimeNanos = elapsedNanos+ time = System.currentTimeMillis()+ }++ private fun user(name: String, id: Long = 0) = User(+ name = name, photo = null, locationName = "Elsewhere", sendingEnabled = true,+ requestStatus = RequestStatus.MUTUAL_CONNECTION, lastLocationChangeTime = Clock.System.now(), id = id,+ )++ @Test+ fun recordFixAccuracyAndFreshness() {+ service.recordFix(location(acc = 99999f))+ assertEquals(null, service.lastKnownLocation)+ service.recordFix(location(elapsedNanos = 2_000_000_000L))+ assertNotNull(service.lastKnownLocation)+ // Older fix does not replace the held one.+ val held = service.lastKnownLocation+ service.recordFix(location(elapsedNanos = 1_500_000_000L, acc = 1f))+ assertEquals(held, service.lastKnownLocation)+ // Fresher fix with worse accuracy but within max age window replaces only if better or stale.+ service.recordFix(location(elapsedNanos = 3_000_000_000L, acc = 2f))+ assertEquals(2f, service.lastKnownLocation?.accuracy)+ }++ @Test+ fun syncHeartbeatPersistsSelfAndCleansExpiredLinks() = runBlocking {+ val peer = repo.upsertUser(user("Peer"))+ repo.upsertWaypoint(Waypoint(name = "Home", range = 500.0, coord = Coord(51.5, -0.12)))+ val expired = TemporaryLink(name = "old", deleteAt = Instant.fromEpochMilliseconds(1), pqcPublicKey = "pub")+ repo.temporaryLinkStore.upsert(expired)+ service.lastKnownLocation = location()+ service.syncHeartbeat()+ // Self user inserted and self location persisted.+ assertNotNull(repo.getUser(Networking.userid))+ assertEquals(1, repo.locationHistory(Networking.userid).first().size)+ // Expired link deleted by the publish sweep.+ assertTrue(repo.temporaryLinkStore.getAll().isEmpty())+ // Waypoint arrival toggles: peer has no trigger, nothing flips.+ assertEquals(true, repo.getUser(peer)?.sendingEnabled)+ // Second heartbeat with no location is covered by clearing and re-running.+ service.seedDirectBootMirror()+ // Peer has no PQC bundle, so nobody is a publish target for the mirror.+ assertTrue(service.publishRoster.isEmpty())+ }++ @Test+ fun syncHeartbeatWithoutLocationIsNoOp() = runBlocking {+ val before = repo.getAllUsers().size+ service.lastKnownLocation = null+ service.syncHeartbeat()+ // No fix held: heartbeat returns before any persistence.+ assertEquals(before, repo.getAllUsers().size)+ assertTrue(repo.locationHistory(Networking.userid).first().isEmpty())+ }+}
findfamily/src/test/java/com/vayunmathur/findfamily/util/LocationTrackingInboundTest.kt
diff --git a/findfamily/src/test/java/com/vayunmathur/findfamily/util/LocationTrackingInboundTest.kt b/findfamily/src/test/java/com/vayunmathur/findfamily/util/LocationTrackingInboundTest.ktnew file mode 100644index 0000000000..3951ea012b--- /dev/null+++ b/findfamily/src/test/java/com/vayunmathur/findfamily/util/LocationTrackingInboundTest.kt@@ -0,0 +1,172 @@+package com.vayunmathur.findfamily.util++import android.app.Application+import android.app.NotificationManager+import android.content.Context+import androidx.room3.Room+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.findfamily.data.Coord+import com.vayunmathur.findfamily.data.FFDatabase+import com.vayunmathur.findfamily.data.FindFamilyRepository+import com.vayunmathur.findfamily.data.LocationSource+import com.vayunmathur.findfamily.data.LocationValue+import com.vayunmathur.findfamily.data.RequestStatus+import com.vayunmathur.findfamily.data.User+import com.vayunmathur.findfamily.data.Waypoint+import com.vayunmathur.findfamily.uwb.UwbEnvelope+import com.vayunmathur.findfamily.uwb.UwbEnvelopeKind+import kotlinx.coroutines.delay+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.Shadows+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertTrue+import kotlin.time.Clock+import kotlin.time.Instant++@RunWith(AndroidJUnit4::class)+class LocationTrackingInboundTest {++ private lateinit var db: FFDatabase+ private lateinit var repo: FindFamilyRepository+ private lateinit var service: LocationTrackingService+ private val app: Application get() = ApplicationProvider.getApplicationContext()+ private val ctx: Context get() = app++ @BeforeTest+ fun setup() {+ runCatching { androidx.work.WorkManager.initialize(ctx, androidx.work.Configuration.Builder().build()) }+ db = Room.inMemoryDatabaseBuilder(ctx, FFDatabase::class.java).allowMainThreadQueries().build()+ repo = FindFamilyRepository(ctx, db)+ service = Robolectric.buildService(LocationTrackingService::class.java).create().get()+ service.repositoryOverride = repo+ }++ @AfterTest fun teardown() { db.close() }++ private fun user(name: String, status: RequestStatus = RequestStatus.MUTUAL_CONNECTION, id: Long = 0, inbound: String? = null) = User(+ name = name, photo = null, locationName = "Elsewhere", sendingEnabled = true,+ requestStatus = status, lastLocationChangeTime = Clock.System.now(), id = id, inboundPairId = inbound,+ )++ private fun fix(userid: Long, at: Instant = Clock.System.now(), acc: Float = 5f, battery: Float = 90f, source: LocationSource = LocationSource.LIVE, coord: Coord = Coord(51.5, -0.12)) = LocationValue(+ userid = userid, coord = coord, speed = 0f, acc = acc, timestamp = at, battery = battery, reportedAt = at, source = source,+ )++ @Test+ fun processIncomingLocationsFiltersAndPersists() = runBlocking {+ val uid = repo.upsertUser(user("Alice"))+ service.processIncomingLocations(listOf(+ fix(uid, source = LocationSource.UNKNOWN),+ fix(uid, acc = 99999f),+ fix(uid, acc = -1f),+ fix(uid),+ ))+ val stored = repo.locationHistory(uid).first()+ assertEquals(1, stored.size)+ assertEquals(90f, stored[0].battery)+ // Empty after filtering: no crash, nothing stored.+ service.processIncomingLocations(listOf(fix(uid, source = LocationSource.UNKNOWN)))+ assertEquals(1, repo.locationHistory(uid).first().size)+ Unit+ }++ @Test+ fun processIncomingFixesAuthGates() = runBlocking {+ val alice = repo.upsertUser(user("Alice", inbound = "expected-pair"))+ val pending = repo.upsertUser(user("Pending", status = RequestStatus.AWAITING_REQUEST))+ // Future-dated fix from Alice: dropped by time clamp.+ val future = Instant.fromEpochSeconds(Clock.System.now().epochSeconds + 48 * 3600)+ service.processIncomingFixes(listOf(InboundFix(fix(alice, at = future), "expected-pair")))+ assertTrue(repo.locationHistory(alice).first().isEmpty())+ // Wrong pair id: dropped.+ service.processIncomingFixes(listOf(InboundFix(fix(alice), "wrong-pair")))+ assertTrue(repo.locationHistory(alice).first().isEmpty())+ // Correct pair id: stored.+ service.processIncomingFixes(listOf(InboundFix(fix(alice), "expected-pair")))+ assertEquals(1, repo.locationHistory(alice).first().size)+ // Ineligible sender (awaiting request): coordinates never stored.+ service.processIncomingFixes(listOf(InboundFix(fix(pending), null)))+ assertTrue(repo.locationHistory(pending).first().isEmpty())+ // Stranger: filed as an awaiting-request row, coordinates not stored.+ service.processIncomingFixes(listOf(InboundFix(fix(987654L), null)))+ val stranger = repo.getUser(987654L)+ assertNotNull(stranger)+ assertEquals(RequestStatus.AWAITING_REQUEST, stranger.requestStatus)+ assertTrue(repo.locationHistory(987654L).first().isEmpty())+ // Empty batch is a no-op.+ service.processIncomingFixes(emptyList())+ }++ @Test+ fun processIncomingFixesPinsFirstPairId() = runBlocking {+ val bob = repo.upsertUser(user("Bob"))+ service.processIncomingFixes(listOf(InboundFix(fix(bob), "first-pair")))+ assertEquals("first-pair", repo.getUser(bob)?.inboundPairId)+ assertEquals(1, repo.locationHistory(bob).first().size)+ // A later fix with a different pair id is now dropped.+ service.processIncomingFixes(listOf(InboundFix(fix(bob), "other-pair")))+ assertEquals(1, repo.locationHistory(bob).first().size)+ }++ @Test+ fun enrichResolvesWaypointAndNotifies() = runBlocking {+ val uid = repo.upsertUser(user("Carol"))+ val wpId = repo.upsertWaypoint(Waypoint(name = "HomeBase", range = 500.0, coord = Coord(51.5, -0.12)))+ val now = Clock.System.now()+ service.enrichIncomingLocations(+ listOf(fix(uid, at = now, battery = 10f, coord = Coord(51.5, -0.12))),+ emptyMap(),+ )+ val row = repo.getUser(uid)!!+ assertEquals("HomeBase", row.locationName)+ assertEquals(wpId, row.lastWaypointId)+ val nm = ctx.getSystemService(NotificationManager::class.java)+ assertTrue(Shadows.shadowOf(nm).allNotifications.isNotEmpty())+ }++ @Test+ fun notificationBuildersAndUwbEnvelopes() = runBlocking {+ service.setupNotificationChannels()+ assertNotNull(service.createNotification())+ assertNotNull(service.createNotificationWithCategory("Title", "Body", "CAT", 12L))+ val u = user("Dave", id = 55)+ service.notifyEntryExit(u, "Dave arrived at Home", arrival = true)+ service.notifyNoShow(u, "Dave did not arrive", 99L, null)+ assertNotNull(service.createUwbRequestNotification("Dave", 55L))+ val nm = ctx.getSystemService(NotificationManager::class.java)+ val before = Shadows.shadowOf(nm).allNotifications.size+ assertTrue(before >= 2)+ service.handleUwbEnvelopes(emptyList())+ service.handleUwbEnvelopes(listOf(+ // Different sender than the direct call above, whose notification it would replace.+ UwbEnvelope(sessionId = "s1", sender = 77uL, senderPlatform = "android", kind = UwbEnvelopeKind.REQUEST),+ UwbEnvelope(sessionId = "s2", sender = 56uL, senderPlatform = "android", kind = UwbEnvelopeKind.ACK),+ ))+ delay(300)+ assertTrue(Shadows.shadowOf(nm).allNotifications.size > before)+ // Powered-off grant from unknown/unconfigured path: silently ignored (no keys store).+ service.handleUwbEnvelopes(listOf(+ UwbEnvelope(sessionId = "s3", sender = 55uL, senderPlatform = "android", kind = UwbEnvelopeKind.POF_GRANT,+ recovery = com.vayunmathur.findfamily.uwb.PoweredOffGrant(epoch = 1, secretB64 = "AA==", recoveryPrivB64 = "AA==", sigB64 = "AA==")),+ ))+ Unit+ }++ @Test+ fun serviceStartWithoutPermissionStops() {+ val controller = Robolectric.buildService(LocationTrackingService::class.java)+ val svc = controller.create().get()+ svc.repositoryOverride = repo+ val rc = svc.onStartCommand(null, 0, 1)+ assertEquals(android.app.Service.START_NOT_STICKY, rc)+ controller.destroy()+ }+}
findfamily/src/test/java/com/vayunmathur/findfamily/util/NetworkingHelperOfflineTest.kt
diff --git a/findfamily/src/test/java/com/vayunmathur/findfamily/util/NetworkingHelperOfflineTest.kt b/findfamily/src/test/java/com/vayunmathur/findfamily/util/NetworkingHelperOfflineTest.ktnew file mode 100644index 0000000000..6321575e0c--- /dev/null+++ b/findfamily/src/test/java/com/vayunmathur/findfamily/util/NetworkingHelperOfflineTest.kt@@ -0,0 +1,54 @@+package com.vayunmathur.findfamily.util++import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.findfamily.data.Coord+import com.vayunmathur.findfamily.data.LocationValue+import com.vayunmathur.findfamily.data.havershine+import kotlinx.coroutines.test.runTest+import org.junit.runner.RunWith+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue+import kotlin.time.Instant++@RunWith(AndroidJUnit4::class)+class NetworkingHelperOfflineTest {++ @Test+ fun trackerHelpersFailClosedWithoutSession() = runTest {+ // wsSession is null until Networking's live loop connects: every helper must+ // fail closed immediately without touching the network.+ assertEquals(null, Networking.wsSession)+ assertFalse(Networking.registerTracker(42L, byteArrayOf(1, 2), byteArrayOf(3)))+ assertNull(Networking.resolveTrackerBundle(ByteArray(16) { it.toByte() }))+ assertFalse(Networking.uploadTrackerReport(ByteArray(16), byteArrayOf(9)))+ assertTrue(Networking.fetchTrackerReports(listOf(ByteArray(16))).isEmpty())+ assertTrue(Networking.fetchTrackerReports(emptyList()).isEmpty())+ assertFalse(Networking.registerPoweredOffEids(7L, listOf(ByteArray(16)), byteArrayOf(1)))+ assertFalse(Networking.registerPoweredOffEids(7L, emptyList(), byteArrayOf(1)))+ assertFalse(Networking.liveConnected)+ }++ @Test+ fun withPairIdAttachesClaimedId() {+ val loc = LocationValue(+ userid = 5L, coord = Coord(1.0, 2.0), speed = 0f, acc = 5f,+ timestamp = Instant.fromEpochMilliseconds(1000), battery = 50f,+ reportedAt = Instant.fromEpochMilliseconds(1000),+ )+ val fix = loc.withPairId("pair-xyz")+ assertEquals(loc, fix.location)+ assertEquals("pair-xyz", fix.pairId)+ assertNull(loc.withPairId(null).pairId)+ }++ @Test+ fun havershineDistances() {+ val a = Coord(51.5, -0.12)+ assertEquals(0.0, havershine(a, a), 0.001)+ val d = havershine(a, Coord(52.5, -0.12))+ assertTrue(d > 100_000 && d < 120_000, "1 degree latitude should be ~111km, was $d")+ }+}