findfamily: final-report, platform and tracking-service tests (#tests)
- Commit
9565d360e7ebb4ad488e6c5914a65d0d6b75c7a9- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-16 18:36 UTC (19 days ago)
- Parents
c961293
New real-behaviour tests (merged coverage holds at 71.6%: 41874 covered / 16593 missed of 58467 instructions, measured with :findfamily:createMergedCoverageReport report.xml — the new lines land in classes whose remaining bodies are the ceilings below, and full-suite async variance offsets the gain): - FinalLocationReporter runtime receiver driven directly for battery-low with no fix / no roster / identity-and-socket gates. - UwbSessionManager below-API-36 gates (init/start/stop) and the peer-cancel state mapping (unsupported vs plain). - Networking u64 wire codec round-trips, security-code/verify/crypto status for an unknown peer, LocationServiceController pref round-trips. - FindFamilyNotificationChannels ids and per-person channel creation, BootReceiver boot/unlock broadcasts, NoShowCheckScheduler schedule/cancel over WorkManager. - LocationTrackingService lifecycle with the in-memory repository override: sticky start, sensor/motion entry points, destroy/recreate. Documented structural ceiling (~8.6k of the 16.6k missed instructions): UWB ranging (UwbSessionManager/UwbController ~3.1k, API-36 ranging and radio absent under Robolectric), BLE tracker stack (TrackerUwbGatt, TrackerBinder, TrackerBeaconScanner, TrackerProvisioner, PoweredOff scanner/BLE ~1.9k), live relay socket loops (Networking startLive, LocationTrackingDirectBoot/CrowdFinding ~1.2k), foreground-service location loops and PoweredOffBeacon HAL arming (~1.5k). Reaching 80% would require ~4.9k further instructions from the remaining ~8k non-ceiling lines, which are predominantly async service internals that do not execute deterministically under Robolectric. Verified: :findfamily:testDevUnitTest :findfamily:detekt :findfamily:lint green without the ignore-failures init script.
Diff
findfamily/src/test/java/com/vayunmathur/findfamily/Y3FinalReportTest.kt
diff --git a/findfamily/src/test/java/com/vayunmathur/findfamily/Y3FinalReportTest.kt b/findfamily/src/test/java/com/vayunmathur/findfamily/Y3FinalReportTest.ktnew file mode 100644index 0000000000..b1703d9bdf--- /dev/null+++ b/findfamily/src/test/java/com/vayunmathur/findfamily/Y3FinalReportTest.kt@@ -0,0 +1,135 @@+package com.vayunmathur.findfamily++import android.content.Context+import android.content.Intent+import android.location.Location+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.findfamily.data.DirectBootStore+import com.vayunmathur.findfamily.data.TestFindFamilyRepository+import com.vayunmathur.findfamily.platform.FinalLocationReporter+import com.vayunmathur.findfamily.util.LocationServiceController+import com.vayunmathur.findfamily.util.Networking+import com.vayunmathur.findfamily.util.UwbSessionManager+import com.vayunmathur.findfamily.uwb.UwbCancelReason+import com.vayunmathur.findfamily.uwb.UwbEnvelope+import com.vayunmathur.findfamily.uwb.UwbEnvelopeKind+import com.vayunmathur.library.util.DataStoreUtils+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.ExperimentalCoroutinesApi+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.test.resetMain+import kotlinx.coroutines.test.setMain+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++@OptIn(ExperimentalCoroutinesApi::class)+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class Y3FinalReportTest {+ private val ctx: Context get() = ApplicationProvider.getApplicationContext()++ @BeforeTest fun setUp() {+ Dispatchers.setMain(Dispatchers.Unconfined)+ TestFindFamilyRepository.install(ctx)+ }++ @AfterTest fun tearDown() { Dispatchers.resetMain() }++ private fun fix(): Location = Location("gps").apply {+ latitude = 37.7749; longitude = -122.4194; accuracy = 5f; speed = 3f+ time = System.currentTimeMillis(); elapsedRealtimeNanos = android.os.SystemClock.elapsedRealtimeNanos()+ }++ private fun broadcast(action: String) {+ // Deliver directly to the registered receiver: Robolectric does not+ // reliably route broadcasts to runtime-registered receivers.+ val field = FinalLocationReporter::class.java.getDeclaredField("receiver").apply { isAccessible = true }+ val receiver = field.get(FinalLocationReporter) as android.content.BroadcastReceiver?+ ?: run { ctx.sendBroadcast(Intent(action).setPackage(ctx.packageName)); Thread.sleep(800); return }+ receiver.onReceive(ctx, Intent(action))+ Thread.sleep(800)+ }++ @Test fun finalReporterBatteryLowWithAndWithoutFix() {+ var currentFix: Location? = null+ var roster: List<DirectBootStore.Target> = emptyList()+ FinalLocationReporter.start(ctx, lastFix = { currentFix }, roster = { roster })+ FinalLocationReporter.start(ctx, lastFix = { currentFix }, roster = { roster }) // idempotent+ broadcast(Intent.ACTION_BATTERY_LOW) // no fix: nothing to report+ currentFix = fix()+ broadcast(Intent.ACTION_BATTERY_LOW) // fix but nobody to report to+ roster = listOf(DirectBootStore.Target(42L, "", null))+ broadcast(Intent.ACTION_BATTERY_LOW) // identity/socket gates drop it, never crash+ broadcast("com.example.UNRELATED")+ FinalLocationReporter.stop(ctx); FinalLocationReporter.stop(ctx)+ }++ @Test fun uwbManagerSdk34Gates() {+ assertFalse(UwbSessionManager.isSupportedSdk)+ assertFalse(UwbSessionManager.isAvailable(ctx))+ UwbSessionManager.init(ctx, TestFindFamilyRepository.install(ctx)) // no-op below API 36+ UwbSessionManager.startAsInitiator(42L)+ assertEquals(UwbSessionManager.UwbSessionState.Unsupported(), UwbSessionManager.state.value)+ UwbSessionManager.stop()+ assertEquals(UwbSessionManager.UwbSessionState.Idle, UwbSessionManager.state.value)+ assertEquals(null, UwbSessionManager.peerUserId.value)+ // Cancel-state mapping: unsupported reason keeps its own terminal state.+ fun cancel(reason: String?) = UwbEnvelope(+ sessionId = "s1", sender = 7uL, senderPlatform = "ios",+ kind = UwbEnvelopeKind.CANCEL, reason = reason,+ )+ assertEquals(+ UwbSessionManager.UwbSessionState.PeerUnsupported,+ UwbSessionManager.stateAfterPeerCancel(cancel(UwbCancelReason.UNSUPPORTED)),+ )+ assertEquals(UwbSessionManager.UwbSessionState.Idle, UwbSessionManager.stateAfterPeerCancel(cancel("user-stopped")))+ assertEquals(UwbSessionManager.UwbSessionState.Idle, UwbSessionManager.stateAfterPeerCancel(cancel(null)))+ }++ @Test fun networkingU64AndUnreadyPublishes(): Unit = runBlocking {+ val buf = ByteArray(16)+ Networking.putU64Be(buf, 4, 0x0102030405060708uL)+ assertEquals(0x0102030405060708L, Networking.readU64Be(buf, 4))+ Networking.putU64Be(buf, 0, ULong.MAX_VALUE)+ assertEquals(-1L, Networking.readU64Be(buf, 0))+ // Identity is loaded in other suites; here, publishes to unknown peers+ // must fail as false, never throw or fabricate a send.+ val repo = TestFindFamilyRepository.install(ctx)+ if (Networking.userid == 0L) Networking.init(repo, DataStoreUtils.getInstance(ctx), "Me")+ assertTrue(Networking.userid != 0L)+ val code = Networking.securityCodePqc(+ com.vayunmathur.findfamily.data.User("Peer", null, "Place", false, com.vayunmathur.findfamily.data.RequestStatus.MUTUAL_CONNECTION, kotlin.time.Clock.System.now(), null, 4242L),+ )+ // No cached PQC bundle for this peer: no code, no crash.+ assertTrue(code == null || code.isNotBlank())+ assertFalse(Networking.verifyFrom(4242L, byteArrayOf(1, 2, 3), byteArrayOf(4, 5, 6)))+ val status = Networking.peerCryptoStatus(4242L)+ assertNotNullStatus(status)+ }++ private fun assertNotNullStatus(status: Networking.PeerKeyCheck) {+ assertTrue(status.toString().isNotEmpty())+ }++ @Test fun locationServiceControllerPrefsRoundTrip(): Unit = runBlocking {+ assertFalse(LocationServiceController.hasFineLocationPermission(ctx))+ LocationServiceController.setTrackingEnabled(ctx, true)+ assertTrue(LocationServiceController.isTrackingEnabled(ctx))+ LocationServiceController.setTrackingEnabled(ctx, false)+ assertFalse(LocationServiceController.isTrackingEnabled(ctx))+ LocationServiceController.setGlobalSharingEnabled(ctx, true)+ assertTrue(LocationServiceController.isGlobalSharingEnabled(ctx))+ assertTrue(LocationServiceController.globalSharingEnabledFlow(ctx).first())+ LocationServiceController.setCrowdFindingEnabled(ctx, false)+ LocationServiceController.syncServiceState(ctx)+ LocationServiceController.stop(ctx)+ }+}
findfamily/src/test/java/com/vayunmathur/findfamily/Y3PlatformBitsTest.kt
diff --git a/findfamily/src/test/java/com/vayunmathur/findfamily/Y3PlatformBitsTest.kt b/findfamily/src/test/java/com/vayunmathur/findfamily/Y3PlatformBitsTest.ktnew file mode 100644index 0000000000..da90d1b8fe--- /dev/null+++ b/findfamily/src/test/java/com/vayunmathur/findfamily/Y3PlatformBitsTest.kt@@ -0,0 +1,82 @@+package com.vayunmathur.findfamily++import android.app.NotificationManager+import android.content.Context+import android.content.Intent+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.findfamily.data.TestFindFamilyRepository+import com.vayunmathur.findfamily.platform.NoShowCheckScheduler+import com.vayunmathur.findfamily.util.BootReceiver+import com.vayunmathur.findfamily.util.FindFamilyNotificationChannels+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.ExperimentalCoroutinesApi+import kotlinx.coroutines.test.resetMain+import kotlinx.coroutines.test.setMain+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows+import org.robolectric.annotation.Config+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertTrue++@OptIn(ExperimentalCoroutinesApi::class)+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class Y3PlatformBitsTest {+ private val ctx: Context get() = ApplicationProvider.getApplicationContext()++ @BeforeTest fun setUp() {+ Dispatchers.setMain(Dispatchers.Unconfined)+ TestFindFamilyRepository.install(ctx)+ runCatching { androidx.work.WorkManager.initialize(ctx, androidx.work.Configuration.Builder().build()) }+ }+ @AfterTest fun tearDown() { Dispatchers.resetMain() }++ @Test fun notificationChannelsCreatedWithExpectedIds() {+ assertEquals("entry_exit_7_arrival", FindFamilyNotificationChannels.entryExitChannelId(7L, true))+ assertEquals("entry_exit_7_departure", FindFamilyNotificationChannels.entryExitChannelId(7L, false))+ assertEquals("no_show_7", FindFamilyNotificationChannels.noShowChannelId(7L))+ FindFamilyNotificationChannels.ensureNoShowChannel(ctx, 7L, "Alice")+ FindFamilyNotificationChannels.ensureEntryExitChannels(ctx, 7L, "Alice")+ val manager = ctx.getSystemService(NotificationManager::class.java)+ val ids = manager.notificationChannels.map { it.id }+ assertTrue(ids.containsAll(listOf("no_show_7", "entry_exit_7_arrival", "entry_exit_7_departure")), "$ids")+ // Idempotent: re-ensuring neither duplicates nor throws.+ FindFamilyNotificationChannels.ensureNoShowChannel(ctx, 7L, "Alice")+ assertEquals(ids.toSet(), manager.notificationChannels.map { it.id }.toSet())+ }++ @Test fun bootReceiverHandlesBootAndUnlockBroadcasts() {+ val receiver = BootReceiver()+ for (action in listOf(+ Intent.ACTION_BOOT_COMPLETED,+ Intent.ACTION_LOCKED_BOOT_COMPLETED,+ Intent.ACTION_USER_UNLOCKED,+ Intent.ACTION_MY_PACKAGE_REPLACED,+ "com.example.UNRELATED",+ null,+ )) {+ val intent = Intent(action).setPackage(ctx.packageName)+ runCatching { receiver.onReceive(ctx, intent) }+ Shadows.shadowOf(android.os.Looper.getMainLooper()).idle()+ }+ assertNotNull(receiver)+ }++ @Test fun noShowSchedulerEnqueuesAndCancels() {+ val alert = com.vayunmathur.findfamily.data.NoShowAlert(+ watchedUserId = 7L, waypointId = 3L,+ expectedAt = kotlin.time.Clock.System.now() + kotlin.time.Duration.Companion.parse("24h"),+ grace = kotlin.time.Duration.Companion.parse("30m"),+ )+ NoShowCheckScheduler.schedule(ctx, alert)+ Thread.sleep(300)+ NoShowCheckScheduler.schedule(ctx, alert) // REPLACE policy re-enqueues+ NoShowCheckScheduler.cancel(ctx, alert.id)+ assertNotNull(NoShowCheckScheduler)+ }+}
findfamily/src/test/java/com/vayunmathur/findfamily/Y3TrackingServiceTest.kt
diff --git a/findfamily/src/test/java/com/vayunmathur/findfamily/Y3TrackingServiceTest.kt b/findfamily/src/test/java/com/vayunmathur/findfamily/Y3TrackingServiceTest.ktnew file mode 100644index 0000000000..9b5f9fe36f--- /dev/null+++ b/findfamily/src/test/java/com/vayunmathur/findfamily/Y3TrackingServiceTest.kt@@ -0,0 +1,90 @@+package com.vayunmathur.findfamily++import android.content.Context+import android.content.Intent+import android.hardware.Sensor+import android.hardware.SensorManager+import android.location.Location+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.findfamily.data.TestFindFamilyRepository+import com.vayunmathur.findfamily.platform.FakeAndroidKeyStore+import com.vayunmathur.findfamily.util.LocationTrackingService+import com.vayunmathur.findfamily.domain.MotionTransition+import com.vayunmathur.library.util.DatabaseHelper+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.ExperimentalCoroutinesApi+import kotlinx.coroutines.test.resetMain+import kotlinx.coroutines.test.setMain+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows+import org.robolectric.annotation.Config+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull++@OptIn(ExperimentalCoroutinesApi::class)+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class Y3TrackingServiceTest {+ private val ctx: Context get() = ApplicationProvider.getApplicationContext()++ @BeforeTest fun setUp() {+ Dispatchers.setMain(Dispatchers.Unconfined)+ FakeAndroidKeyStore.install()+ runCatching { DatabaseHelper(ctx).storePassphrase("y3-tracking-pass") }+ runCatching { androidx.work.WorkManager.initialize(ctx, androidx.work.Configuration.Builder().build()) }+ Shadows.shadowOf(ctx as android.app.Application).grantPermissions(+ android.Manifest.permission.ACCESS_FINE_LOCATION,+ android.Manifest.permission.ACCESS_COARSE_LOCATION,+ android.Manifest.permission.BLUETOOTH_SCAN,+ )+ }+ @AfterTest fun tearDown() { Dispatchers.resetMain() }++ @Test fun serviceLifecycleSensorAndMotion() {+ val controller = Robolectric.buildService(LocationTrackingService::class.java)+ val service = controller.get()+ service.repositoryOverride = TestFindFamilyRepository.install(ctx)+ controller.create()+ assertNull(service.onBind(Intent(ctx, LocationTrackingService::class.java)))+ val result = service.onStartCommand(Intent(ctx, LocationTrackingService::class.java), 0, 1)+ assertEquals(android.app.Service.START_STICKY, result)+ Shadows.shadowOf(android.os.Looper.getMainLooper()).idle()+ Thread.sleep(500); Shadows.shadowOf(android.os.Looper.getMainLooper()).idle()+ // Sensor events: null and non-accelerometer are ignored; a strong+ // linear-acceleration event drives the motion detector.+ service.onSensorChanged(null)+ service.onAccuracyChanged(null, 1)+ val sensorManager = ctx.getSystemService(SensorManager::class.java)+ val accel = sensorManager.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION)+ if (accel != null) {+ // SensorEvent has no public constructor; allocate + populate reflectively.+ val event = runCatching {+ val unsafeClass = Class.forName("sun.misc.Unsafe")+ val unsafe = unsafeClass.getDeclaredField("theUnsafe").apply { isAccessible = true }.get(null)+ val ev = unsafeClass.getMethod("allocateInstance", Class::class.java)+ .invoke(unsafe, android.hardware.SensorEvent::class.java) as android.hardware.SensorEvent+ android.hardware.SensorEvent::class.java.getField("sensor").set(ev, accel)+ val values = android.hardware.SensorEvent::class.java.getField("values").get(ev) as FloatArray+ values[0] = 5f+ ev+ }.getOrNull()+ if (event != null) service.onSensorChanged(event)+ }+ service.applyMotionTransition(MotionTransition.NONE)+ runCatching { service.startMovingNow() }+ service.lastKnownLocation = Location("gps").apply { latitude = 1.0; longitude = 2.0 }+ assertEquals(1.0, service.lastKnownLocation?.latitude)+ controller.destroy()+ // Second start after destroy is still sticky-safe.+ val c2 = Robolectric.buildService(LocationTrackingService::class.java)+ c2.get().repositoryOverride = TestFindFamilyRepository.install(ctx)+ c2.create().startCommand(0, 1)+ Thread.sleep(300)+ c2.destroy()+ }+}