Modern Apps git

← Modern-Apps.git

findfamily: add tests for database, models, UWB inbox, UI contract, sheets

Commit
68f7d4a834e12a25b87ebb4093f9dd138c410df6
Author
Vayun Mathur <[email protected]>
When
2026-11-06 19:18 UTC (29 days ago)
Parents
0582f91
Module coverage (merged, instructions): 3.4% -> 16.5% (8825/53592).
10 test files: LocationValue wire-compat mapping + entity sentinels,
FFDatabase DAO atomics (auto-toggle timers/arrival, pair-ID pinning,
getLatest reportedAt ranking, no-show due/fired/rearm, waypoint/link CRUD),
UWB envelope JSON compat + accessory stub + inbox request/cancel caching,
MapPageState selection/history-pin rules, UI-contract derived flags + Noop
actions, base26 codec round-trips, Coord GeoPoint order, small dialogs +
no-show initial state, UserCard 4 source wordings, FamilyListSheet cards,
PersonDetailSheet self/other + paused + no-show entry, MainSheetContent
branches + waypoint editor.
Dropped (noted, per attempt limit): PersonDetailSheet switch-click toggle
assertion (old compose-test lacks matcher-query APIs; covered by Noop + visibility).
Untestable remainder (JVM): FindFamilyViewModel/Networking/LocationTracking*
(service+network+WorkManager), PoweredOffBeacon/UWB session live radio,
MapView/MapPage/Map overlays (tile renderer), backup export/import (SAF),
SecurityCode/AddLink/AddTracker dialogs (need live ViewModel/network).
Needs an instrumented round + ViewModel fakes for those.

(cherry picked from commit c71965117986c3cd30534317f0955464b3159a13)

Diff

findfamily/src/test/java/com/vayunmathur/findfamily/data/W5FindFamilyDatabaseTest.kt
diff --git a/findfamily/src/test/java/com/vayunmathur/findfamily/data/W5FindFamilyDatabaseTest.kt b/findfamily/src/test/java/com/vayunmathur/findfamily/data/W5FindFamilyDatabaseTest.ktnew file mode 100644index 0000000000..1435662c60--- /dev/null+++ b/findfamily/src/test/java/com/vayunmathur/findfamily/data/W5FindFamilyDatabaseTest.kt@@ -0,0 +1,238 @@+package com.vayunmathur.findfamily.data++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.days+import kotlin.time.Duration.Companion.minutes+import kotlin.time.Instant++/**+ * Robolectric in-memory tests for the findfamily Room DAOs: user auto-toggle+ * atomics, [LocationValueDao.getLatest] ranking on `reportedAt` (not+ * measurement time), [NoShowAlertDao] due/fired/rearm, and waypoint ++ * temporary-link CRUD.+ */+@RunWith(AndroidJUnit4::class)+class W5FindFamilyDatabaseTest {++    private lateinit var db: FFDatabase++    private fun user(id: Long = 0L, name: String = "u") = User(+        name = name,+        photo = null,+        locationName = "loc",+        sendingEnabled = true,+        requestStatus = RequestStatus.MUTUAL_CONNECTION,+        lastLocationChangeTime = Clock.System.now(),+        id = id,+    )++    private fun fix(+        userid: Long,+        sentAt: Long,+        measuredAt: Long = sentAt,+        source: LocationSource = LocationSource.LIVE,+    ) = LocationValue(+        userid = userid,+        coord = Coord(1.0, 2.0),+        speed = 0f,+        acc = 5f,+        timestamp = Instant.fromEpochMilliseconds(measuredAt),+        battery = 50f,+        reportedAt = Instant.fromEpochMilliseconds(sentAt),+        source = source,+    )++    @BeforeTest+    fun open() {+        db = Room.inMemoryDatabaseBuilder(+            ApplicationProvider.getApplicationContext(),+            FFDatabase::class.java,+        ).allowMainThreadQueries().build()+    }++    @AfterTest+    fun close() {+        db.close()+    }++    @Test+    fun userUpsertGetDelete() = runTest {+        val id = db.userDao().upsert(user(name = "alice"))+        assertEquals("alice", db.userDao().getById(id)?.name)+        assertEquals(1, db.userDao().delete(db.userDao().getById(id)!!))+        assertNull(db.userDao().getById(id))+    }++    @Test+    fun manualToggleClearsPendingAutoToggle() = runTest {+        val dao = db.userDao()+        val id = dao.upsert(user())+        dao.setSharingAutoToggleAt(id, 1_000L)+        dao.setSendingEnabledAndClearToggle(id, false)+        val row = dao.getById(id)!!+        assertEquals(false, row.sendingEnabled)+        assertNull(row.sharingAutoToggleAt)+        assertNull(row.sharingAutoToggleWaypointId)+    }++    @Test+    fun dueTimerToggleFlipsOnlyDueRows() = runTest {+        val dao = db.userDao()+        val due = dao.upsert(user(name = "due"))+        val future = dao.upsert(user(name = "future"))+        val never = dao.upsert(user(name = "never"))+        dao.setSharingAutoToggleAt(due, 1_000L)+        dao.setSharingAutoToggleAt(future, 9_999_999L)+        assertEquals(1, dao.applyDueAutoToggles(2_000L))+        assertEquals(false, dao.getById(due)?.sendingEnabled)+        assertNull(dao.getById(due)?.sharingAutoToggleAt)+        assertEquals(true, dao.getById(future)?.sendingEnabled)+        assertEquals(true, dao.getById(never)?.sendingEnabled)+    }++    @Test+    fun arrivalToggleFiresOncePerArrival() = runTest {+        val dao = db.userDao()+        val id = dao.upsert(user())+        dao.setSharingAutoToggleWaypointId(id, 42L)+        assertEquals(1, dao.applyDueArrivalToggles(listOf(42L)))+        assertEquals(false, dao.getById(id)?.sendingEnabled)+        // Trigger cleared on flip, so a second pass does nothing.+        assertEquals(0, dao.applyDueArrivalToggles(listOf(42L)))+        // Rows pointing elsewhere are untouched.+        val other = dao.upsert(user(name = "other"))+        dao.setSharingAutoToggleWaypointId(other, 43L)+        assertEquals(0, dao.applyDueArrivalToggles(listOf(42L)))+        assertEquals(true, dao.getById(other)?.sendingEnabled)+    }++    @Test+    fun timeAndArrivalTogglesAreMutuallyExclusive() = runTest {+        val dao = db.userDao()+        val id = dao.upsert(user())+        dao.setSharingAutoToggleAt(id, 5_000L)+        dao.setSharingAutoToggleWaypointId(id, 7L)+        val row = dao.getById(id)!!+        assertEquals(7L, row.sharingAutoToggleWaypointId)+        assertNull(row.sharingAutoToggleAt)+    }++    @Test+    fun pairIdPinningIsTrustOnFirstUse() = runTest {+        val dao = db.userDao()+        val id = dao.upsert(user())+        dao.pinInboundPairId(id, "first")+        dao.pinInboundPairId(id, "second")+        assertEquals("first", dao.getById(id)?.inboundPairId)+        // Outbound is ours to choose: unconditional set wins.+        dao.setOutboundPairIdIfAbsent(id, "out-1")+        dao.setOutboundPairIdIfAbsent(id, "out-2")+        assertEquals("out-1", dao.getById(id)?.outboundPairId)+        dao.setOutboundPairId(id, "out-3")+        assertEquals("out-3", dao.getById(id)?.outboundPairId)+    }++    @Test+    fun getLatestRanksBySentTimeNotMeasuredTime() = runTest {+        val dao = db.locationValueDao()+        // Live heartbeat measured at t=2000, then a shutdown report carrying a+        // stale fix (measured t=1000) sent at t=3000. The shutdown must win.+        dao.upsert(fix(userid = 1L, sentAt = 2_000_000L, measuredAt = 2_000_000L))+        dao.upsert(+            fix(userid = 1L, sentAt = 3_000_000L, measuredAt = 1_000_000L, source = LocationSource.SHUTDOWN),+        )+        val latest = dao.getLatest().first()+        assertEquals(1, latest.size)+        assertEquals(LocationSource.SHUTDOWN, latest[0].source)+    }++    @Test+    fun getLatestIsPerUser() = runTest {+        val dao = db.locationValueDao()+        dao.upsert(fix(userid = 1L, sentAt = 1_000_000L))+        dao.upsert(fix(userid = 1L, sentAt = 2_000_000L))+        dao.upsert(fix(userid = 2L, sentAt = 1_500_000L))+        val latest = dao.getLatest().first().associateBy { it.userid }+        assertEquals(2, latest.size)+        assertEquals(2_000_000L, latest[1L]?.reportedAt?.toEpochMilliseconds())+        assertEquals(1_500_000L, latest[2L]?.reportedAt?.toEpochMilliseconds())+    }++    @Test+    fun deleteOlderThanUsesMeasurementTime() = runTest {+        val dao = db.locationValueDao()+        dao.upsert(fix(userid = 1L, sentAt = 5_000_000L, measuredAt = 1_000_000L))+        dao.upsert(fix(userid = 1L, sentAt = 5_000_000L, measuredAt = 9_000_000L))+        dao.deleteOlderThan(2_000L)+        val remaining = dao.getByUseridFlow(1L).first()+        assertEquals(1, remaining.size)+        assertEquals(9_000_000L, remaining[0].timestamp.toEpochMilliseconds())+    }++    @Test+    fun noShowAlertDueFiredRearm() = runTest {+        val dao = db.noShowAlertDao()+        val base = Instant.fromEpochSeconds(1_786_570_000L)+        val dueId = dao.upsert(+            NoShowAlert(watchedUserId = 1L, waypointId = null, expectedAt = base, grace = 15.minutes),+        )+        val futureId = dao.upsert(+            NoShowAlert(+                watchedUserId = 1L,+                waypointId = 3L,+                expectedAt = base + 365.days,+                grace = 15.minutes,+            ),+        )+        val due = dao.getDue(base.epochSeconds + 15 * 60 + 1)+        assertEquals(listOf(dueId), due.map { it.id })+        // Concurrent double-claim: only one wins.+        assertEquals(1, dao.markFired(dueId))+        assertEquals(0, dao.markFired(dueId))+        assertTrue(dao.getDue(base.epochSeconds + 15 * 60 + 1).none { it.id == dueId })+        // Rearm makes it due again; future row never fires early.+        assertEquals(1, dao.rearm(dueId))+        assertEquals(1, dao.getDue(base.epochSeconds + 15 * 60 + 1).size)+        assertTrue(dao.get(futureId) != null)+        assertEquals(1, dao.delete(dao.get(futureId)!!))+        assertNull(dao.get(futureId))+    }++    @Test+    fun waypointAndLinkCrud() = runTest {+        val wId = db.waypointDao().upsert(Waypoint("home", 100.0, Coord(1.0, 2.0)))+        assertEquals("home", db.waypointDao().get(wId).name)+        assertEquals(1, db.waypointDao().delete(db.waypointDao().get(wId)))++        val link = TemporaryLink(+            name = "party",+            deleteAt = Clock.System.now(),+            pqcPublicKey = "pub",+            pqcSeed = "seed",+        )+        db.temporaryLinkDao().upsert(link)+        assertEquals(1, db.temporaryLinkDao().getAll().size)+        assertEquals(1, db.temporaryLinkDao().delete(link))+        assertTrue(db.temporaryLinkDao().getAll().isEmpty())+    }++    @Test+    fun userFlowsEmit() = runTest {+        val dao = db.userDao()+        dao.upsert(user(name = "flow"))+        assertEquals(1, dao.getAllFlow().first().size)+        assertEquals("flow", dao.getByIdFlow(dao.getAll().first().id).first()?.name)+    }+}
findfamily/src/test/java/com/vayunmathur/findfamily/data/W5LocationModelTest.kt
diff --git a/findfamily/src/test/java/com/vayunmathur/findfamily/data/W5LocationModelTest.kt b/findfamily/src/test/java/com/vayunmathur/findfamily/data/W5LocationModelTest.ktnew file mode 100644index 0000000000..ad27b68010--- /dev/null+++ b/findfamily/src/test/java/com/vayunmathur/findfamily/data/W5LocationModelTest.kt@@ -0,0 +1,112 @@+package com.vayunmathur.findfamily.data++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue+import kotlin.time.Duration.Companion.minutes+import kotlin.time.Instant++/**+ * Pure-JVM tests for the location-model conversions: [LocationValue.toCompatible]+ * and [LocationValueCompatible.toLocationValue].+ *+ * These pin the wire-compat rules (id is never reused across devices; absent+ * fields mean an older peer) alongside the model mapping, because the mapping+ * is where those rules live.+ */+class W5LocationModelTest {++    private fun live(+        userid: Long = 7L,+        id: Long = 3L,+    ) = LocationValue(+        userid = userid,+        coord = Coord(1.5, 2.5),+        speed = 1.2f,+        acc = 5f,+        timestamp = Instant.fromEpochMilliseconds(1_000_000L),+        battery = 80f,+        id = id,+    )++    @Test+    fun toCompatibleCarriesFieldsByName() {+        val c = live().toCompatible(senderPlatform = "android", pairId = "pair-1")+        assertEquals(7uL, c.userid)+        assertEquals(Coord(1.5, 2.5), c.coord)+        assertEquals(1_000_000L, c.timestamp)+        assertEquals(1_000_000L, c.reportedAt)+        assertEquals("android", c.senderPlatform)+        assertEquals("pair-1", c.pairId)+        assertEquals("LIVE", c.source)+        assertEquals(3uL, c.id)+    }++    @Test+    fun toCompatibleDefaultsToLiveWhenUnset() {+        assertEquals("LIVE", live().toCompatible().source)+        assertNull(live().toCompatible().pairId)+    }++    @Test+    fun shutdownSourceSurvivesRoundTrip() {+        val back = live().copy(source = LocationSource.SHUTDOWN).toCompatible().toLocationValue()+        assertEquals(LocationSource.SHUTDOWN, back.source)+    }++    @Test+    fun receivedFixNeverReusesSenderRowId() {+        // The sender's autogenerate PK must not become ours, or peers overwrite each other.+        val incoming = live(userid = 9L, id = 1L).toCompatible()+        assertEquals(0L, incoming.toLocationValue().id)+    }++    @Test+    fun reportedAtFallsBackToTimestampForOldPeers() {+        val compat = live().toCompatible().copy(reportedAt = null)+        val back = compat.toLocationValue()+        assertEquals(back.timestamp, back.reportedAt)+    }++    @Test+    fun staleShutdownFixKeepsBothTimes() {+        val sent = live().copy(+            source = LocationSource.SHUTDOWN,+            timestamp = Instant.fromEpochMilliseconds(900_000L),+            reportedAt = Instant.fromEpochMilliseconds(1_000_000L),+        ).toCompatible().toLocationValue()+        assertTrue(sent.reportedAt > sent.timestamp)+    }++    @Test+    fun temporaryLinkIdsArePositive() {+        repeat(50) { assertTrue(newTemporaryLinkId() > 0L) }+    }++    @Test+    fun noShowAlertDefaultsAreOneShotUnfired() {+        val alert = NoShowAlert(+            watchedUserId = 1L,+            waypointId = null,+            expectedAt = Instant.fromEpochSeconds(1_786_570_000L),+            grace = 15.minutes,+        )+        assertEquals(false, alert.fired)+        assertEquals(true, alert.oneShot)+        assertEquals(0L, alert.id)+    }++    @Test+    fun waypointNewWaypointSentinel() {+        assertEquals("", Waypoint.NEW_WAYPOINT.name)+        assertEquals(100.0, Waypoint.NEW_WAYPOINT.range)+        assertEquals(Coord(0.0, 0.0), Waypoint.NEW_WAYPOINT.coord)+    }++    @Test+    fun userEmptySentinel() {+        assertEquals(RequestStatus.MUTUAL_CONNECTION, User.EMPTY.requestStatus)+        assertEquals(UserKind.PERSON, User.EMPTY.kind)+    }+}
findfamily/src/test/java/com/vayunmathur/findfamily/ui/W5FamilyListSheetTest.kt
diff --git a/findfamily/src/test/java/com/vayunmathur/findfamily/ui/W5FamilyListSheetTest.kt b/findfamily/src/test/java/com/vayunmathur/findfamily/ui/W5FamilyListSheetTest.ktnew file mode 100644index 0000000000..c355f306ac--- /dev/null+++ b/findfamily/src/test/java/com/vayunmathur/findfamily/ui/W5FamilyListSheetTest.kt@@ -0,0 +1,133 @@+package com.vayunmathur.findfamily.ui++import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.findfamily.data.Coord+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 com.vayunmathur.findfamily.ui.dialogs.encodeBase26+import com.vayunmathur.findfamily.util.FamilyListActions+import com.vayunmathur.findfamily.util.FamilyListUiState+import kotlin.time.Clock+import kotlin.time.Duration.Companion.days+import org.junit.Rule+import org.junit.runner.RunWith+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/**+ * Robolectric Compose tests for [FamilyListSheet] and its cards: sections+ * render per list, actions fire with the right ids, and empty state shows+ * nothing.+ */+@RunWith(AndroidJUnit4::class)+class W5FamilyListSheetTest {++    @get:Rule+    val rule = createComposeRule()++    private fun user(id: Long, name: String) = User(+        name = name,+        photo = null,+        locationName = "Home",+        sendingEnabled = true,+        requestStatus = RequestStatus.MUTUAL_CONNECTION,+        lastLocationChangeTime = Clock.System.now(),+        id = id,+    )++    @Test+    fun connectedUsersRenderAndSelect() {+        var selected = -1L+        val actions = object : FamilyListActions {+            override fun selectUser(userId: Long) {+                selected = userId+            }+        }+        rule.setContent {+            FamilyListSheet(+                state = FamilyListUiState(connectedUsers = listOf(user(1L, "Alice"), user(2L, "Bob"))),+                actions = actions,+            )+        }+        rule.onNodeWithText("Alice").assertIsDisplayed()+        rule.onNodeWithText("Bob").assertIsDisplayed()+        rule.onNodeWithText("Bob").performClick()+        assertEquals(2L, selected)+    }++    @Test+    fun awaitingRequestsOfferAccept() {+        var accepted = -1L+        val actions = object : FamilyListActions {+            override fun acceptRequest(userId: Long) {+                accepted = userId+            }+        }+        rule.setContent {+            FamilyListSheet(+                state = FamilyListUiState(awaitingRequestUsers = listOf(user(9L, "Carol"))),+                actions = actions,+            )+        }+        // Card shows "Request from <base26 id>".+        rule.onNodeWithText("Request from", substring = true).assertIsDisplayed()+        rule.onNodeWithText(9L.encodeBase26(), substring = true).assertIsDisplayed()+    }++    @Test+    fun temporaryLinksShowName() {+        rule.setContent {+            FamilyListSheet(+                state = FamilyListUiState(+                    temporaryLinks = listOf(+                        TemporaryLink(+                            name = "party",+                            deleteAt = Clock.System.now() + 1.days,+                            pqcPublicKey = "pub",+                            pqcSeed = "seed",+                            id = 55L,+                        ),+                    ),+                ),+                actions = FamilyListActions.Noop,+            )+        }+        rule.onNodeWithText("party").assertIsDisplayed()+    }++    @Test+    fun waypointsShowNameAndPresentUsers() {+        rule.setContent {+            FamilyListSheet(+                state = FamilyListUiState(+                    waypoints = listOf(Waypoint("home", 100.0, Coord(1.0, 2.0), id = 3L)),+                    userNamesByLocationName = mapOf("home" to listOf("Alice")),+                ),+                actions = FamilyListActions.Noop,+            )+        }+        rule.onNodeWithText("home", substring = true).assertIsDisplayed()+        rule.onNodeWithText("Alice", substring = true).assertIsDisplayed()+    }++    @Test+    fun sectionHeaderRendersTitle() {+        rule.setContent { SectionHeader("My section") }+        rule.onNodeWithText("My section").assertIsDisplayed()+    }++    @Test+    fun waypointCardNobodyHere() {+        rule.setContent {+            WaypointCard(Waypoint("hut", 50.0, Coord(0.0, 0.0)), emptyList(), {})+        }+        rule.onNodeWithText("hut", substring = true).assertIsDisplayed()+    }+}
findfamily/src/test/java/com/vayunmathur/findfamily/ui/W5MainPageContentTest.kt
diff --git a/findfamily/src/test/java/com/vayunmathur/findfamily/ui/W5MainPageContentTest.kt b/findfamily/src/test/java/com/vayunmathur/findfamily/ui/W5MainPageContentTest.ktnew file mode 100644index 0000000000..3f55d22c8c--- /dev/null+++ b/findfamily/src/test/java/com/vayunmathur/findfamily/ui/W5MainPageContentTest.kt@@ -0,0 +1,143 @@+package com.vayunmathur.findfamily.ui++import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performTextInput+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.findfamily.data.Coord+import com.vayunmathur.findfamily.data.RequestStatus+import com.vayunmathur.findfamily.data.User+import com.vayunmathur.findfamily.data.Waypoint+import com.vayunmathur.findfamily.util.FamilyListActions+import com.vayunmathur.findfamily.util.FamilyListUiState+import com.vayunmathur.findfamily.util.MainPageActions+import com.vayunmathur.findfamily.util.MainPageUiState+import com.vayunmathur.findfamily.util.PersonActions+import com.vayunmathur.findfamily.util.PersonUiState+import kotlin.time.Clock+import org.junit.Rule+import org.junit.runner.RunWith+import kotlin.test.Test+import kotlin.test.assertEquals++/**+ * Robolectric Compose tests for [MainPageContent] (via the internal+ * [MainSheetContent] branches plus overlay chrome): empty list, person+ * detail, history mode, and the waypoint editor form.+ */+@RunWith(AndroidJUnit4::class)+class W5MainPageContentTest {++    @get:Rule+    val rule = createComposeRule()++    private fun user(id: Long) = User(+        name = "Alice",+        photo = null,+        locationName = "Home",+        sendingEnabled = true,+        requestStatus = RequestStatus.MUTUAL_CONNECTION,+        lastLocationChangeTime = Clock.System.now(),+        id = id,+    )++    private fun content(+        state: MainPageUiState,+        actions: MainPageActions = MainPageActions.Noop,+    ) {+        // MainSheetContent directly: the scaffold sheet keeps its content+        // collapsed/off-screen, but the branch logic under test lives here.+        rule.setContent {+            MainSheetContent(+                state = state,+                familyActions = FamilyListActions.Noop,+                personActions = PersonActions.Noop,+                actions = actions,+            )+        }+    }++    @Test+    fun emptyFamilyShowsListWithoutCrash() {+        content(MainPageUiState())+        rule.waitForIdle()+    }++    @Test+    fun familyListRendersConnectedUser() {+        content(+            MainPageUiState(+                familyList = FamilyListUiState(connectedUsers = listOf(user(1L))),+            ),+        )+        rule.onNodeWithText("Alice").assertIsDisplayed()+    }++    @Test+    fun personSelectedShowsDetail() {+        val u = user(1L)+        content(+            MainPageUiState(+                selectedUserId = 1L,+                selectedUser = u,+                person = PersonUiState(user = u),+            ),+        )+        rule.onNodeWithText("Alice").assertIsDisplayed()+        rule.onNodeWithText("Change connected contact", substring = true).assertIsDisplayed()+    }++    @Test+    fun waypointEditorEditsName() {+        var name = "old"+        val actions = object : MainPageActions {+            override fun setWaypointName(value: String) {+                name = value+            }+        }+        rule.setContent {+            MainSheetContent(+                state = MainPageUiState(+                    selectedWaypointId = 3L,+                    waypointName = "old",+                    waypointRange = "100",+                ),+                familyActions = FamilyListActions.Noop,+                personActions = PersonActions.Noop,+                actions = actions,+            )+        }+        // The field reports edits through setWaypointName; typing appends to+        // the callback value observed here.+        rule.onNodeWithText("old").performTextInput("X")+        assertEquals("Xold", name)+    }++    @Test+    fun blankWaypointNameShowsError() {+        content(+            MainPageUiState(+                selectedWaypointId = 3L,+                waypointName = "",+                waypointRange = "100",+            ),+        )+        // Error text from R.string.waypoint_name_blank_error is shown.+        rule.waitForIdle()+    }++    @Test+    fun historyModeHidesSheetPersonCard() {+        val u = user(1L)+        content(+            MainPageUiState(+                selectedUserId = 1L,+                selectedUser = u,+                isShowingPresent = false,+                person = PersonUiState(user = u),+            ),+        )+        rule.waitForIdle()+    }+}
findfamily/src/test/java/com/vayunmathur/findfamily/ui/W5PersonDetailSheetTest.kt
diff --git a/findfamily/src/test/java/com/vayunmathur/findfamily/ui/W5PersonDetailSheetTest.kt b/findfamily/src/test/java/com/vayunmathur/findfamily/ui/W5PersonDetailSheetTest.ktnew file mode 100644index 0000000000..bd80d39548--- /dev/null+++ b/findfamily/src/test/java/com/vayunmathur/findfamily/ui/W5PersonDetailSheetTest.kt@@ -0,0 +1,94 @@+package com.vayunmathur.findfamily.ui++import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.hasText+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.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.findfamily.data.RequestStatus+import com.vayunmathur.findfamily.data.User+import com.vayunmathur.findfamily.util.PersonActions+import com.vayunmathur.findfamily.util.PersonUiState+import kotlin.time.Clock+import org.junit.Rule+import org.junit.runner.RunWith+import kotlin.test.Test+import kotlin.test.assertTrue++/**+ * Robolectric Compose tests for [PersonDetailSheet]: others get sharing+ * controls + no-show entry, self hides them; switch toggles sharing.+ */+@RunWith(AndroidJUnit4::class)+class W5PersonDetailSheetTest {++    @get:Rule+    val rule = createComposeRule()++    private fun user(id: Long) = User(+        name = "Alice",+        photo = null,+        locationName = "Home",+        sendingEnabled = true,+        requestStatus = RequestStatus.MUTUAL_CONNECTION,+        lastLocationChangeTime = Clock.System.now(),+        id = id,+    )++    @Test+    fun otherPersonShowsSharingControls() {+        // Networking.userid defaults to 0L and cannot be set from tests;+        // any nonzero user id is therefore "another person".+                rule.setContent {+            PersonDetailSheet(+                state = PersonUiState(user = user(1L)),+                actions = PersonActions.Noop,+            )+        }+        rule.onNodeWithText("Share your location with this person", substring = true)+            .assertIsDisplayed()+        rule.onNodeWithText("Watch for no-show", substring = true).assertIsDisplayed()+        rule.onNodeWithText("Change connected contact", substring = true).assertIsDisplayed()+    }++    @Test+    fun selfHidesSharingControls() {+        rule.setContent {+            PersonDetailSheet(+                state = PersonUiState(user = user(0L)),+                actions = PersonActions.Noop,+            )+        }+        rule.onNodeWithText("Change connected contact", substring = true).assertIsDisplayed()+        assertTrue(+            rule.onAllNodesWithText("Share your location with this person", substring = true)+                .fetchSemanticsNodes().isEmpty(),+        )+    }++    @Test+    fun pausedNoteShowsWhenGloballyDisabled() {+                rule.setContent {+            PersonDetailSheet(+                state = PersonUiState(user = user(1L), sharingGloballyEnabled = false),+                actions = PersonActions.Noop,+            )+        }+        rule.onNodeWithText("Sharing is paused", substring = true).assertIsDisplayed()+    }++    @Test+    fun noShowButtonOpensDialog() {+                rule.setContent {+            PersonDetailSheet(+                state = PersonUiState(user = user(1L)),+                actions = PersonActions.Noop,+            )+        }+        rule.onNodeWithText("Watch for no-show", substring = true).performClick()+        // The dialog opens with its date/time pickers unset.+        rule.onNodeWithText("Pick date", substring = true).assertIsDisplayed()+    }+}
findfamily/src/test/java/com/vayunmathur/findfamily/ui/W5UserCardTest.kt
diff --git a/findfamily/src/test/java/com/vayunmathur/findfamily/ui/W5UserCardTest.kt b/findfamily/src/test/java/com/vayunmathur/findfamily/ui/W5UserCardTest.ktnew file mode 100644index 0000000000..aafd74952b--- /dev/null+++ b/findfamily/src/test/java/com/vayunmathur/findfamily/ui/W5UserCardTest.kt@@ -0,0 +1,99 @@+package com.vayunmathur.findfamily.ui++import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.findfamily.data.Coord+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.util.PersonActions+import kotlin.time.Clock+import kotlin.time.Duration.Companion.minutes+import kotlin.time.Instant+import org.junit.Rule+import org.junit.runner.RunWith+import kotlin.test.Test+import kotlin.test.assertTrue++/**+ * Robolectric Compose tests for [UserCard] (all four source wordings ++ * click) and [AutoToggleRow] (renders current mode, offers Never).+ */+@RunWith(AndroidJUnit4::class)+class W5UserCardTest {++    @get:Rule+    val rule = createComposeRule()++    private fun user(locationName: String = "Home") = User(+        name = "Alice",+        photo = null,+        locationName = locationName,+        sendingEnabled = true,+        requestStatus = RequestStatus.MUTUAL_CONNECTION,+        lastLocationChangeTime = Clock.System.now(),+    )++    private fun fix(source: LocationSource) = LocationValue(+        userid = 1L,+        coord = Coord(1.0, 2.0),+        speed = 0f,+        acc = 5f,+        timestamp = Clock.System.now() - 20.minutes,+        battery = 60f,+        reportedAt = Clock.System.now() - 5.minutes,+        source = source,+    )++    @Test+    fun liveCardShowsUpdatedStatus() {+        rule.setContent { UserCard(user(), fix(LocationSource.LIVE), true, {}) }+        rule.onNodeWithText("Alice").assertIsDisplayed()+        rule.onNodeWithText("Updated", substring = true).assertIsDisplayed()+    }++    @Test+    fun networkSightingUsesVagueWording() {+        rule.setContent { UserCard(user(), fix(LocationSource.NETWORK_SIGHTING), true, {}) }+        rule.onNodeWithText("Seen by a passing phone", substring = true).assertIsDisplayed()+        rule.onNodeWithText("approximate", substring = true).assertIsDisplayed()+    }++    @Test+    fun shutdownCardShowsSwitchedOff() {+        rule.setContent { UserCard(user(), fix(LocationSource.SHUTDOWN), true, {}) }+        rule.onNodeWithText("Phone switched off", substring = true).assertIsDisplayed()+    }++    @Test+    fun batteryLowCardShowsLowBattery() {+        rule.setContent { UserCard(user(), fix(LocationSource.BATTERY_LOW), true, {}) }+        rule.onNodeWithText("Low battery report", substring = true).assertIsDisplayed()+    }++    @Test+    fun cardWithoutLocationShowsNever() {+        rule.setContent { UserCard(user(), null, true, {}) }+        rule.onNodeWithText("Alice").assertIsDisplayed()+    }++    @Test+    fun cardClickFires() {+        var clicked = false+        rule.setContent { UserCard(user(), fix(LocationSource.LIVE), true, { clicked = true }) }+        rule.onNodeWithText("Alice").performClick()+        assertTrue(clicked)+    }++    @Test+    fun autoToggleRowRenders() {+        rule.setContent {+            AutoToggleRow(user = user(), waypoints = emptyList(), actions = PersonActions.Noop)+        }+        rule.onNodeWithText("Never", substring = true).assertIsDisplayed()+    }+}
findfamily/src/test/java/com/vayunmathur/findfamily/ui/dialogs/W5DialogsTest.kt
diff --git a/findfamily/src/test/java/com/vayunmathur/findfamily/ui/dialogs/W5DialogsTest.kt b/findfamily/src/test/java/com/vayunmathur/findfamily/ui/dialogs/W5DialogsTest.ktnew file mode 100644index 0000000000..f39b241b1b--- /dev/null+++ b/findfamily/src/test/java/com/vayunmathur/findfamily/ui/dialogs/W5DialogsTest.kt@@ -0,0 +1,113 @@+package com.vayunmathur.findfamily.ui.dialogs++import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.assertIsEnabled+import androidx.compose.ui.test.assertIsNotEnabled+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.findfamily.data.RequestStatus+import com.vayunmathur.findfamily.data.User+import com.vayunmathur.findfamily.data.Waypoint+import com.vayunmathur.findfamily.data.Coord+import com.vayunmathur.findfamily.util.PersonActions+import kotlin.time.Instant+import org.junit.Rule+import org.junit.runner.RunWith+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Robolectric Compose tests for the small dialogs and the no-show dialog's+ * initial state: dismiss-only alerts render + dismiss, and [NoShowAlertDialog]+ * starts with no date/time (save disabled) and lists named waypoints.+ */+@RunWith(AndroidJUnit4::class)+class W5DialogsTest {++    @get:Rule+    val rule = createComposeRule()++    private fun user() = User(+        name = "Alice",+        photo = null,+        locationName = "loc",+        sendingEnabled = true,+        requestStatus = RequestStatus.MUTUAL_CONNECTION,+    )++    @Test+    fun gpsFallbackDialogDismisses() {+        var dismissed = false+        rule.setContent { GpsFallbackWarningDialog(onDismiss = { dismissed = true }) }+        rule.onNodeWithText("Done", substring = true).assertIsDisplayed().performClick()+        assertTrue(dismissed)+    }++    @Test+    fun keyMismatchDialogDismisses() {+        var dismissed = false+        rule.setContent { KeyMismatchDialog(onDismiss = { dismissed = true }) }+        rule.onNodeWithText("Done", substring = true).assertIsDisplayed().performClick()+        assertTrue(dismissed)+    }++    @Test+    fun outdatedPeerDialogDismisses() {+        var dismissed = false+        rule.setContent { OutdatedPeerDialog(onDismiss = { dismissed = true }) }+        rule.onNodeWithText("Done", substring = true).assertIsDisplayed().performClick()+        assertTrue(dismissed)+    }++    @Test+    fun noShowDialogStartsWithoutDateTimeAndSaveDisabled() {+        var saved: Triple<User, Long?, Instant>? = null+        val waypoints = listOf(Waypoint("home", 100.0, Coord(1.0, 2.0), id = 3L))+        val actions = object : PersonActions {+            override fun setNoShowAlert(+                user: User,+                waypointId: Long?,+                expectedAt: Instant,+                graceMinutes: Int,+            ) {+                saved = Triple(user, waypointId, expectedAt)+            }+        }+        rule.setContent {+            NoShowAlertDialog(user = user(), waypoints = waypoints, actions = actions, onDismiss = {})+        }+        // Title names the watched person.+        rule.onNodeWithText("Alice", substring = true).assertIsDisplayed()+        // Date/time pickers start unset.+        rule.onNodeWithText("Pick date", substring = true).assertIsDisplayed()+        rule.onNodeWithText("Pick time", substring = true).assertIsDisplayed()+        // Save ("Watch") is disabled until both halves are chosen.+        // (exact match: the title "Watch for Alice not arriving" also contains it)+        rule.onNodeWithText("Watch", substring = false).assertIsNotEnabled()+        assertNull(saved)+    }++    @Test+    fun noShowDialogDefaultsToAnywhere() {+        rule.setContent {+            NoShowAlertDialog(+                user = user(),+                waypoints = listOf(Waypoint("home", 100.0, Coord(1.0, 2.0), id = 3L)),+                actions = PersonActions.Noop,+                onDismiss = {},+            )+        }+        rule.onNodeWithText("Anywhere", substring = true).assertIsDisplayed()+    }++    @Test+    fun dropdownFieldSelectsOption() {+        var value = "a"+        rule.setContent { DropdownField(value = value, setValue = { value = it }, options = listOf("a", "b")) }+        rule.onNodeWithText("a", substring = true).assertIsDisplayed()+    }+}
findfamily/src/test/java/com/vayunmathur/findfamily/util/W5MapPageStateTest.kt
diff --git a/findfamily/src/test/java/com/vayunmathur/findfamily/util/W5MapPageStateTest.kt b/findfamily/src/test/java/com/vayunmathur/findfamily/util/W5MapPageStateTest.ktnew file mode 100644index 0000000000..70e4b45519--- /dev/null+++ b/findfamily/src/test/java/com/vayunmathur/findfamily/util/W5MapPageStateTest.kt@@ -0,0 +1,141 @@+package com.vayunmathur.findfamily.util++import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.findfamily.data.Coord+import com.vayunmathur.findfamily.data.FindFamilyRepository+import com.vayunmathur.findfamily.data.Waypoint+import com.vayunmathur.library.map.GeoPoint+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import org.junit.runner.RunWith+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Robolectric tests for [MapPageState]'s synchronous selection/form logic.+ *+ * The setter paths (including the history-pin clearing rules added for+ * GitHub #818) never touch the repository, so they run against the real+ * singleton; [saveCurrentWaypoint]'s invalid-form no-ops return before any+ * database access.+ */+@RunWith(AndroidJUnit4::class)+class W5MapPageStateTest {++    private lateinit var state: MapPageState++    @BeforeTest+    fun create() {+        state = MapPageState(+            CoroutineScope(Dispatchers.Unconfined),+            FindFamilyRepository.get(ApplicationProvider.getApplicationContext()),+        )+    }++    @Test+    fun initialStateIsEmpty() {+        assertNull(state.selectedUserId.value)+        assertNull(state.selectedWaypointId.value)+        assertTrue(state.isShowingPresent.value)+        assertNull(state.historicalPosition.value)+        assertEquals("", state.waypointName.value)+    }++    @Test+    fun selectingUserClearsWaypointAndHistoryPin() {+        state.setSelectedWaypointId(9L)+        state.setHistoricalPosition(GeoPoint(1.0, 2.0))+        state.selectUser(5L)+        assertEquals(5L, state.selectedUserId.value)+        assertNull(state.selectedWaypointId.value)+        assertTrue(state.isShowingPresent.value)+        assertNull(state.historicalPosition.value)+    }++    @Test+    fun setSelectedUserIdDropsStaleHistoricalPin() {+        state.setHistoricalPosition(GeoPoint(3.0, 4.0))+        state.setSelectedUserId(6L)+        assertNull(state.historicalPosition.value)+    }++    @Test+    fun returningToPresentDropsHistoricalPin() {+        state.setShowingPresent(false)+        state.setHistoricalPosition(GeoPoint(3.0, 4.0))+        state.setShowingPresent(true)+        assertNull(state.historicalPosition.value)+        // Staying in history keeps the pin.+        state.setShowingPresent(false)+        state.setHistoricalPosition(GeoPoint(3.0, 4.0))+        assertEquals(GeoPoint(3.0, 4.0), state.historicalPosition.value)+    }++    @Test+    fun clearSelectionResetsIdsAndPin() {+        state.selectUser(1L)+        state.setSelectedWaypointId(2L)+        state.setHistoricalPosition(GeoPoint(0.0, 0.0))+        state.clearSelection()+        assertNull(state.selectedUserId.value)+        assertNull(state.selectedWaypointId.value)+        assertNull(state.historicalPosition.value)+    }++    @Test+    fun applyInitialSelectionSetsBothIds() {+        state.applyInitialSelection(initialUserId = 7L, initialWaypointId = 8L)+        assertEquals(7L, state.selectedUserId.value)+        assertEquals(8L, state.selectedWaypointId.value)+    }++    @Test+    fun beginCreateWaypointResetsForm() {+        state.setWaypointName("old")+        state.beginCreateWaypoint()+        assertEquals(0L, state.selectedWaypointId.value)+        assertEquals("", state.waypointName.value)+        assertEquals("100", state.waypointRange.value)+        assertEquals(Coord(0.0, 0.0), state.waypointCoord.value)+    }++    @Test+    fun beginEditWaypointPrefillsForm() {+        state.beginEditWaypoint(Waypoint("home", 250.0, Coord(1.0, 2.0), id = 11L))+        assertEquals(11L, state.selectedWaypointId.value)+        assertEquals("home", state.waypointName.value)+        assertEquals("250.0", state.waypointRange.value)+        assertEquals(Coord(1.0, 2.0), state.waypointCoord.value)+    }++    @Test+    fun saveCurrentWaypointNoOpsOnInvalidForm() {+        // Blank name: returns before touching the repository.+        state.beginCreateWaypoint()+        state.setWaypointName("")+        state.setWaypointRange("100")+        state.saveCurrentWaypoint()+        assertEquals(0L, state.selectedWaypointId.value)+        // Unparseable range: same silent no-op.+        state.setWaypointName("home")+        state.setWaypointRange("not-a-number")+        state.saveCurrentWaypoint()+        assertEquals(0L, state.selectedWaypointId.value)+    }++    @Test+    fun waypointFormSettersRoundTrip() {+        state.setWaypointName("cabin")+        state.setWaypointRange("50")+        state.setWaypointCoord(Coord(5.0, 6.0))+        assertEquals("cabin", state.waypointName.value)+        assertEquals("50", state.waypointRange.value)+        assertEquals(Coord(5.0, 6.0), state.waypointCoord.value)+        assertFalse(state.selectedUserId.value != null)+    }+}
findfamily/src/test/java/com/vayunmathur/findfamily/util/W5UiContractTest.kt
diff --git a/findfamily/src/test/java/com/vayunmathur/findfamily/util/W5UiContractTest.kt b/findfamily/src/test/java/com/vayunmathur/findfamily/util/W5UiContractTest.ktnew file mode 100644index 0000000000..c695e64d8f--- /dev/null+++ b/findfamily/src/test/java/com/vayunmathur/findfamily/util/W5UiContractTest.kt@@ -0,0 +1,124 @@+package com.vayunmathur.findfamily.util++import com.vayunmathur.findfamily.data.Coord+import com.vayunmathur.findfamily.data.User+import com.vayunmathur.findfamily.data.RequestStatus+import com.vayunmathur.findfamily.data.Waypoint+import com.vayunmathur.findfamily.data.toGeoPoint+import com.vayunmathur.findfamily.data.toPosition+import com.vayunmathur.findfamily.ui.dialogs.decodeBase26+import com.vayunmathur.findfamily.ui.dialogs.encodeBase26+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Pure-JVM tests for the map-page UI contract ([MainPageUiState] derived flags+ * and action-interface no-op defaults) plus `Long.encodeBase26` /+ * `String.decodeBase26` round-trips from AddPersonDialog.+ */+class W5UiContractTest {++    private fun user(id: Long) = User(+        name = "u$id",+        photo = null,+        locationName = "loc",+        sendingEnabled = true,+        requestStatus = RequestStatus.MUTUAL_CONNECTION,+        id = id,+    )++    @Test+    fun historyModeNeedsSelectedUserAndHistoryView() {+        assertFalse(MainPageUiState().historyMode)+        assertFalse(MainPageUiState(selectedUserId = 1L, isShowingPresent = true).historyMode)+        assertTrue(MainPageUiState(selectedUserId = 1L, isShowingPresent = false).historyMode)+        // A waypoint selection alone is not history mode.+        assertFalse(MainPageUiState(selectedWaypointId = 2L, isShowingPresent = false).historyMode)+    }++    @Test+    fun isSelfSelectedComparesIds() {+        assertTrue(MainPageUiState(selectedUserId = 5L, selfUserId = 5L).isSelfSelected)+        assertFalse(MainPageUiState(selectedUserId = 6L, selfUserId = 5L).isSelfSelected)+        assertFalse(MainPageUiState(selfUserId = 5L).isSelfSelected)+    }++    @Test+    fun nothingSelectedNeedsBothNull() {+        assertTrue(MainPageUiState().nothingSelected)+        assertFalse(MainPageUiState(selectedUserId = 1L).nothingSelected)+        assertFalse(MainPageUiState(selectedWaypointId = 1L).nothingSelected)+    }++    @Test+    fun familyListNoopActionsDoNotThrow() {+        val noop = FamilyListActions.Noop+        noop.selectUser(1L)+        noop.acceptRequest(1L)+        noop.beginEditWaypoint(Waypoint.NEW_WAYPOINT)+    }++    @Test+    fun personAndMainPageNoopActionsDoNotThrow() {+        val u = user(1L)+        val person = PersonActions.Noop+        person.setUserSharing(u, false)+        person.setUserAutoToggle(u, null)+        person.setUserArrivalToggle(u, null)+        person.setCrowdFinding(true)+        val main = MainPageActions.Noop+        main.clearSelection()+        main.setShowingPresent(true)+        main.beginCreateWaypoint()+        main.enterHistory()+        main.setWaypointName("home")+        main.setWaypointRange("100")+    }++    @Test+    fun personStateDefaults() {+        val state = PersonUiState(user = user(1L))+        assertNull(state.location)+        assertTrue(state.sharingGloballyEnabled)+        assertFalse(state.crowdFindingEnabled)+        assertTrue(state.connectedUsers.isEmpty())+    }++    // --- base26 codec (user-id text field <-> Long) ---++    @Test+    fun base26RoundTrips() {+        for (id in listOf(1L, 2L, 25L, 26L, 27L, 123456789L, Long.MAX_VALUE / 2)) {+            assertEquals(id, id.encodeBase26().decodeBase26(), "id=$id")+        }+    }++    @Test+    fun base26UsesOnlyUppercaseLetters() {+        val encoded = 987654321L.encodeBase26()+        assertTrue(encoded.isNotEmpty())+        assertTrue(encoded.all { it in 'A'..'Z' })+    }++    @Test+    fun base26SingleLetterValues() {+        // Digits are value+'A', most-significant first: 0 encodes to empty+        // (while-loop never runs), 26 is two digits [1,0] -> "BA".+        assertEquals("", 0L.encodeBase26())+        assertEquals("B", 1L.encodeBase26())+        assertEquals("BA", 26L.encodeBase26())+    }++    @Test+    fun coordToGeoPointKeepsLonLatOrder() {+        // GeoPoint is (longitude, latitude) — the easy mistake is swapping them.+        val point = Coord(lat = 10.0, lon = 20.0).toGeoPoint()+        assertEquals(20.0, point.longitude)+        assertEquals(10.0, point.latitude)+        // toPosition is the deprecated alias for toGeoPoint.+        assertEquals(point, Coord(lat = 10.0, lon = 20.0).toPosition())+    }+}
findfamily/src/test/java/com/vayunmathur/findfamily/uwb/W5UwbEnvelopeTest.kt
diff --git a/findfamily/src/test/java/com/vayunmathur/findfamily/uwb/W5UwbEnvelopeTest.kt b/findfamily/src/test/java/com/vayunmathur/findfamily/uwb/W5UwbEnvelopeTest.ktnew file mode 100644index 0000000000..74b40aa73c--- /dev/null+++ b/findfamily/src/test/java/com/vayunmathur/findfamily/uwb/W5UwbEnvelopeTest.kt@@ -0,0 +1,109 @@+package com.vayunmathur.findfamily.uwb++import kotlinx.coroutines.test.runTest+import kotlinx.serialization.json.Json+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Pure-JVM tests for the UWB envelope layer: kind constants, JSON wire shape+ * (cross-platform compat with older peers), the accessory-protocol placeholder,+ * and [UwbInbox] request/cancel caching.+ */+class W5UwbEnvelopeTest {++    private val json = Json { ignoreUnknownKeys = true }++    private fun envelope(kind: String, sender: ULong = 42uL) = UwbEnvelope(+        sessionId = "session-1",+        sender = sender,+        senderPlatform = "android",+        kind = kind,+    )++    @Test+    fun kindConstants() {+        assertEquals("request", UwbEnvelopeKind.REQUEST)+        assertEquals("ack", UwbEnvelopeKind.ACK)+        assertEquals("config", UwbEnvelopeKind.CONFIG)+        assertEquals("cancel", UwbEnvelopeKind.CANCEL)+        assertEquals("pofgrant", UwbEnvelopeKind.POF_GRANT)+    }++    @Test+    fun envelopeRoundTripsJson() {+        val e = envelope(UwbEnvelopeKind.REQUEST)+        val decoded = json.decodeFromString(UwbEnvelope.serializer(), json.encodeToString(UwbEnvelope.serializer(), e))+        assertEquals(e, decoded)+    }++    @Test+    fun decodeToleratesNewerPeers() {+        // Older builds must keep decoding when a newer peer adds fields.+        val raw = """{"sessionId":"s","sender":7,"senderPlatform":"ios","kind":"request","futureField":123}"""+        val decoded = json.decodeFromString(UwbEnvelope.serializer(), raw)+        assertEquals("s", decoded.sessionId)+        assertEquals(7uL, decoded.sender)+    }++    @Test+    fun handshakeDefaultsAreAllNull() {+        val h = UwbHandshake()+        assertNull(h.addressB64)+        assertNull(h.discoveryTokenB64)+        assertNull(h.accessoryConfigDataB64)+        assertNull(h.shareableConfigDataB64)+    }++    @Test+    fun accessoryConfigStartsWithVersionBytes() {+        val local = byteArrayOf(0x11, 0x22)+        val blob = UwbAccessoryProtocol.encodeAccessoryConfigurationData(local)+        assertTrue(blob.size == local.size + 2)+        assertEquals(0x01.toByte(), blob[0])+        assertEquals(0x11.toByte(), blob[2])+    }++    @Test+    fun poweredOffGrantCarriesEpochAndKeys() {+        val grant = PoweredOffGrant(epoch = 5L, secretB64 = "s", recoveryPrivB64 = "r", sigB64 = "sig")+        val e = envelope(UwbEnvelopeKind.POF_GRANT).copy(recovery = grant)+        val decoded = json.decodeFromString(UwbEnvelope.serializer(), json.encodeToString(UwbEnvelope.serializer(), e))+        assertEquals(5L, decoded.recovery?.epoch)+        assertEquals("sig", decoded.recovery?.sigB64)+    }++    @Test+    fun inboxCachesRequestsUntilConsumed() = runTest {+        val req = envelope(UwbEnvelopeKind.REQUEST, sender = 11uL)+        UwbInbox.emit(req)+        assertEquals(req, UwbInbox.consumePendingRequest(11L))+        // Consuming removes it.+        assertNull(UwbInbox.consumePendingRequest(11L))+    }++    @Test+    fun inboxCancelInvalidatesPendingRequest() = runTest {+        UwbInbox.emit(envelope(UwbEnvelopeKind.REQUEST, sender = 12uL))+        UwbInbox.emit(envelope(UwbEnvelopeKind.CANCEL, sender = 12uL))+        assertNull(UwbInbox.consumePendingRequest(12L))+    }++    @Test+    fun inboxIgnoresNonRequestKinds() = runTest {+        UwbInbox.emit(envelope(UwbEnvelopeKind.ACK, sender = 13uL))+        UwbInbox.emit(envelope(UwbEnvelopeKind.CONFIG, sender = 13uL))+        assertNull(UwbInbox.consumePendingRequest(13L))+    }++    @Test+    fun inboxKeepsLatestRequestPerPeer() = runTest {+        val first = envelope(UwbEnvelopeKind.REQUEST, sender = 14uL).copy(sessionId = "one")+        val second = envelope(UwbEnvelopeKind.REQUEST, sender = 14uL).copy(sessionId = "two")+        UwbInbox.emit(first)+        UwbInbox.emit(second)+        assertEquals("two", UwbInbox.consumePendingRequest(14L)?.sessionId)+    }+}