Modern Apps git

← Modern-Apps.git

emergency: add tests for SOS pipeline, repository and screens

Commit
e076899b971f53ce86b0a46463881e7afc0d514c
Author
Vayun Mathur <[email protected]>
When
2026-11-07 06:29 UTC (29 days ago)
Parents
00e0b96
Coverage (merged INSTRUCTION, createMergedCoverageReport):
8.0% (828/10344) -> 85.6% (8855/10344).

New tests (7 files):
- platform/FakeContactsProvider: in-memory contacts provider
  (phone rows, owner name/addresses, photo blobs, failure and
  null-cursor modes) shared by the reader/repository tests.
- platform/PlatformTests: ContactReader (photo, custom type
  labels, dead-URI pruning), OwnerIdentityReader (raw and
  aggregate URIs, deduplicated component-fallback addresses),
  GestureProvider call() protocol and CRUD refusals, search
  indexables provider, number-lookup override/fallback,
  Health Connect graceful absence, SosSound, normalization
  helpers.
- platform/RepositoryAndServiceTest: repository save/load
  with normalization, contact add/dedup/remove/prune,
  EmergencyViewModel state routing (medical save, contact
  add failure flag, owner pick with 0/1/many addresses),
  SosCoordinator load and background handoff, countdown
  service start validation, receiver cancel/make-call
  fallback intent, countdown notification build/post/cancel.
- platform/PlatformExtraTest: reader failure modes (provider
  throws / null cursors), legacy string-set contact storage,
  lookup with telephony + grant, sound-disabled setting,
  telephony countdown-service path, gesture UI-showing.
- domain/FhirExtraTest: medication status gating, RxNorm ->
  text -> coding display chain, condition status gating,
  reaction/criticality variants, malformed-input tolerance,
  allergy sort order.
- ui/EmergencyScreensTest: SOS loading/disabled/countdown
  (including the tick reaching zero and firing the make-call
  broadcast via the compose main clock), view-info loading/
  empty/full states, edit-info access gates, contact rows,
  failure rows, Health Connect rows, blood/organ dropdown
  saves, owner-address chooser.
- ui/ActivitiesTest: SosActivity (explicit and default
  countdown intents), ViewInfoActivity, EditInfoActivity and
  the bare PermissionsRationaleActivity under Robolectric.

No production code changed; no bugs found. The SOS make-call
paths only ever fire shadow intents/broadcasts in Robolectric
- nothing is dialled.
Verified: gslot ./gradlew :emergency:createMergedCoverageReport
(full unit suite green, 85.61% merged instructions).

(cherry picked from commit ee650b4943b3f964bbea850db57c8691b5803cb2)

Diff

emergency/src/test/java/com/vayunmathur/emergency/domain/FhirExtraTest.kt
diff --git a/emergency/src/test/java/com/vayunmathur/emergency/domain/FhirExtraTest.kt b/emergency/src/test/java/com/vayunmathur/emergency/domain/FhirExtraTest.ktnew file mode 100644index 0000000000..2c3b09b70a--- /dev/null+++ b/emergency/src/test/java/com/vayunmathur/emergency/domain/FhirExtraTest.kt@@ -0,0 +1,172 @@+package com.vayunmathur.emergency.domain++import com.vayunmathur.emergency.data.AllergyCriticality+import com.vayunmathur.emergency.data.ImportedAllergy+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue++class FhirExtraTest {++    @Test+    fun medicationStatusesGateCurrency() {+        fun med(status: String, type: String = "MedicationRequest") = """+            { "resourceType": "$type", "status": "$status",+              "medicationCodeableConcept": { "text": "Aspirin" } }+        """.trimIndent()+        assertEquals("Aspirin", FhirMedicalParse.parseCurrentMedication(med("active"))?.displayName)+        assertEquals("Aspirin", FhirMedicalParse.parseCurrentMedication(med("intended"))?.displayName)+        assertEquals("Aspirin", FhirMedicalParse.parseCurrentMedication(med("on-hold"))?.displayName)+        assertNull(FhirMedicalParse.parseCurrentMedication(med("completed")))+        assertNull(FhirMedicalParse.parseCurrentMedication(med("stopped")))+        assertNull(FhirMedicalParse.parseCurrentMedication(med("cancelled")))+        assertEquals(+            "Aspirin",+            FhirMedicalParse.parseCurrentMedication(med("active", "MedicationStatement"))?.displayName,+        )+        assertNull(FhirMedicalParse.parseCurrentMedication(med("active", "Medication")))+        // missing status is not current+        assertNull(+            FhirMedicalParse.parseCurrentMedication(+                """{ "resourceType": "MedicationRequest",+                     "medicationCodeableConcept": { "text": "Aspirin" } }""",+            ),+        )+        // no name at all+        assertNull(+            FhirMedicalParse.parseCurrentMedication(+                """{ "resourceType": "MedicationRequest", "status": "active" }""",+            ),+        )+    }++    @Test+    fun medicationNamePrefersRxNormThenTextThenFirstCoding() {+        val rxnormSecond = """+            { "resourceType": "MedicationStatement", "status": "active",+              "medicationCodeableConcept": { "coding": [+                { "system": "http://snomed.info/sct", "display": "SNOMED name" },+                { "system": "http://www.nlm.nih.gov/research/umls/rxnorm", "display": "RxNorm name" }+              ], "text": "Text name" } }+        """.trimIndent()+        assertEquals("RxNorm name", FhirMedicalParse.parseCurrentMedication(rxnormSecond)?.displayName)+        val textOverCoding = """+            { "resourceType": "MedicationStatement", "status": "active",+              "medicationCodeableConcept": { "coding": [+                { "system": "http://snomed.info/sct", "display": "SNOMED name" }+              ], "text": "Text name" } }+        """.trimIndent()+        assertEquals("Text name", FhirMedicalParse.parseCurrentMedication(textOverCoding)?.displayName)+        val codingOnly = """+            { "resourceType": "MedicationStatement", "status": "active",+              "medicationCodeableConcept": { "coding": [+                { "system": "http://snomed.info/sct", "display": "SNOMED name" }+              ] } }+        """.trimIndent()+        assertEquals("SNOMED name", FhirMedicalParse.parseCurrentMedication(codingOnly)?.displayName)+    }++    @Test+    fun conditionGatingAndNaming() {+        fun cond(statusJson: String) = """+            { "resourceType": "Condition", $statusJson+              "code": { "text": "Asthma" } }+        """.trimIndent()+        assertEquals(+            "Asthma",+            FhirMedicalParse.parseCondition(cond(""))?.displayName,+        )+        assertEquals(+            "Asthma",+            FhirMedicalParse.parseCondition(+                cond(""""clinicalStatus": { "coding": [{ "code": "active" }] },"""),+            )?.displayName,+        )+        assertNull(+            FhirMedicalParse.parseCondition(+                cond(""""clinicalStatus": { "coding": [{ "code": "inactive" }] },"""),+            ),+        )+        assertNull(+            FhirMedicalParse.parseCondition(+                cond(""""clinicalStatus": { "coding": [{ "code": "resolved" }] },"""),+            ),+        )+        // clinicalStatus present but with no coding code counts as active+        assertEquals(+            "Asthma",+            FhirMedicalParse.parseCondition(+                cond(""""clinicalStatus": { "coding": [{ "system": "x" }] },"""),+            )?.displayName,+        )+        assertNull(+            FhirMedicalParse.parseCondition(+                """{ "resourceType": "Condition", "code": { } }""",+            ),+        )+        assertNull(+            FhirMedicalParse.parseCondition(+                """{ "resourceType": "Observation", "code": { "text": "Asthma" } }""",+            ),+        )+    }++    @Test+    fun allergyReactionFromCodingAndCriticalityVariants() {+        val viaCoding = """+            { "resourceType": "AllergyIntolerance", "criticality": "low",+              "code": { "text": "Dust" },+              "reaction": [{ "manifestation": [{ "coding": [{ "display": "Sneezing" }] }] }] }+        """.trimIndent()+        val allergy = FhirMedicalParse.parseAllergy(viaCoding)+        assertEquals(AllergyCriticality.Low, allergy?.criticality)+        assertEquals("Sneezing", allergy?.reaction)+        // reaction entries without a usable manifestation produce no reaction+        val noReaction = """+            { "resourceType": "AllergyIntolerance", "criticality": "unable-to-assess",+              "code": { "text": "Dust" },+              "reaction": [{ "substance": { "text": "x" } }, { "manifestation": [] }] }+        """.trimIndent()+        val second = FhirMedicalParse.parseAllergy(noReaction)+        assertEquals(AllergyCriticality.Unknown, second?.criticality)+        assertNull(second?.reaction)+        // inactive allergy drops like a resolved one+        val inactive = """+            { "resourceType": "AllergyIntolerance",+              "clinicalStatus": { "coding": [{ "code": "inactive" }] },+              "code": { "text": "Dust" } }+        """.trimIndent()+        assertNull(FhirMedicalParse.parseAllergy(inactive))+    }++    @Test+    fun malformedInputsAreDropped() {+        assertNull(FhirMedicalParse.parseAllergy("not json"))+        assertNull(FhirMedicalParse.parseAllergy("[1,2,3]"))+        assertNull(FhirMedicalParse.parseAllergy(""))+        assertNull(FhirMedicalParse.parseCondition("{"))+        assertNull(FhirMedicalParse.parseCurrentMedication("42"))+        // non-string resourceType does not match+        assertNull(+            FhirMedicalParse.parseAllergy(+                """{ "resourceType": 7, "code": { "text": "Dust" } }""",+            ),+        )+    }++    @Test+    fun sortAllergiesOrdersHighLowUnknownStable() {+        val input = listOf(+            ImportedAllergy("a-unknown", AllergyCriticality.Unknown, null),+            ImportedAllergy("b-low", AllergyCriticality.Low, null),+            ImportedAllergy("c-high", AllergyCriticality.High, null),+            ImportedAllergy("d-high", AllergyCriticality.High, null),+        )+        assertEquals(+            listOf("c-high", "d-high", "b-low", "a-unknown"),+            FhirMedicalParse.sortAllergies(input).map { it.displayName },+        )+        assertTrue(FhirMedicalParse.sortAllergies(emptyList()).isEmpty())+    }+}
emergency/src/test/java/com/vayunmathur/emergency/platform/FakeContactsProvider.kt
diff --git a/emergency/src/test/java/com/vayunmathur/emergency/platform/FakeContactsProvider.kt b/emergency/src/test/java/com/vayunmathur/emergency/platform/FakeContactsProvider.ktnew file mode 100644index 0000000000..fc90741c3c--- /dev/null+++ b/emergency/src/test/java/com/vayunmathur/emergency/platform/FakeContactsProvider.kt@@ -0,0 +1,150 @@+package com.vayunmathur.emergency.platform++import android.content.ContentProvider+import android.content.ContentValues+import android.database.Cursor+import android.database.MatrixCursor+import android.graphics.Bitmap+import android.net.Uri+import android.provider.ContactsContract+import java.io.ByteArrayOutputStream++/**+ * Serves contacts-provider rows from in-memory fixtures so [ContactReader],+ * [OwnerIdentityReader] and the repository's prune-on-load can be exercised+ * without a device address book.+ */+class FakeContactsProvider : ContentProvider() {++    data class PhoneRow(+        val name: String,+        val number: String,+        val type: Int = ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE,+        val label: String? = null,+        val photoId: Long = 0,+    )++    companion object {+        /** uri string -> phone row; absent means the contact was deleted. */+        val phones = mutableMapOf<String, PhoneRow>()+        var ownerName: String = "Jamie Owner"+        var rawIdForContact: Long? = 7L+        /** Rows of (formatted, street, city, region, postcode, country). */+        var addresses = listOf<Array<Any?>>()+        var photoBytes: ByteArray? = makePhotoBytes()+        /** URIs whose query throws SecurityException (permission revoked mid-read). */+        val failUris = mutableSetOf<String>()+        /** URIs whose query returns a null cursor. */+        val nullUris = mutableSetOf<String>()++        fun reset() {+            phones.clear()+            failUris.clear()+            nullUris.clear()+            ownerName = "Jamie Owner"+            rawIdForContact = 7L+            addresses = listOf(+                arrayOf("1 Main St, Springfield", null, null, null, null, null),+                arrayOf(null, "2 Oak Ave", "Shelbyville", "NT", "12345", "US"),+                arrayOf("1 Main St, Springfield", null, null, null, null, null),+                arrayOf(null, " ", "", null, null, null),+            )+            photoBytes = makePhotoBytes()+        }++        private fun makePhotoBytes(): ByteArray {+            val bmp = Bitmap.createBitmap(2, 2, Bitmap.Config.ARGB_8888)+            val out = ByteArrayOutputStream()+            bmp.compress(Bitmap.CompressFormat.PNG, 100, out)+            return out.toByteArray()+        }+    }++    override fun onCreate(): Boolean = true++    private fun cursorFor(projection: Array<out String>?, rows: List<Map<String, Any?>>): Cursor {+        val columns = projection?.map { it }?.toTypedArray()+            ?: rows.firstOrNull()?.keys?.toTypedArray()+            ?: arrayOf(ContactsContract.Contacts._ID)+        val cursor = MatrixCursor(columns)+        for (row in rows) {+            cursor.addRow(columns.map { row[it] })+        }+        return cursor+    }++    override fun query(+        uri: Uri,+        projection: Array<out String>?,+        selection: String?,+        selectionArgs: Array<out String>?,+        sortOrder: String?,+    ): Cursor? {+        if (uri.toString() in failUris) {+            throw SecurityException("READ_CONTACTS revoked for $uri")+        }+        if (uri.toString() in nullUris) return null+        val path = uri.path.orEmpty()+        // Owner name: RawContacts.CONTENT_URI/<id> with DISPLAY_NAME_PRIMARY+        if (path.startsWith("/raw_contacts/") && projection?.contains(+                ContactsContract.RawContacts.DISPLAY_NAME_PRIMARY,+            ) == true+        ) {+            val rows = if (ownerName.isEmpty()) emptyList()+            else listOf(mapOf(ContactsContract.RawContacts.DISPLAY_NAME_PRIMARY to ownerName))+            return cursorFor(projection, rows)+        }+        // Aggregate -> raw id resolution: query on RawContacts.CONTENT_URI with CONTACT_ID+        if (path == "/raw_contacts") {+            val rows = rawIdForContact?.let {+                listOf(mapOf(ContactsContract.RawContacts._ID to it))+            } ?: emptyList()+            return cursorFor(projection, rows)+        }+        // Address rows: query on Data.CONTENT_URI with a selection+        if (path == "/data" && selection != null) {+            val cols = listOf(+                ContactsContract.CommonDataKinds.StructuredPostal.FORMATTED_ADDRESS,+                ContactsContract.CommonDataKinds.StructuredPostal.STREET,+                ContactsContract.CommonDataKinds.StructuredPostal.CITY,+                ContactsContract.CommonDataKinds.StructuredPostal.REGION,+                ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE,+                ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY,+            )+            val rows = addresses.map { row -> cols.zip(row.toList()).toMap() }+            return cursorFor(projection, rows)+        }+        // Photo blob: Data.CONTENT_URI/<photoId> (exactly two segments;+        // phone URIs are /data/phones/<id> and must fall through to below)+        if (path.startsWith("/data/") && uri.pathSegments.size == 2) {+            val bytes = photoBytes+            val rows = if (bytes == null) emptyList()+            else listOf(mapOf(ContactsContract.Contacts.Photo.PHOTO to bytes))+            return cursorFor(projection, rows)+        }+        // Phone rows (including validation queries with a null projection)+        val row = phones[uri.toString()]+        if (projection == null) {+            val rows = if (row == null) emptyList()+            else listOf(mapOf(ContactsContract.Contacts._ID to 1L))+            return cursorFor(null, rows)+        }+        val rows = if (row == null) emptyList() else listOf(+            mapOf<String, Any?>(+                ContactsContract.Contacts.DISPLAY_NAME to row.name,+                ContactsContract.CommonDataKinds.Phone.NUMBER to row.number,+                ContactsContract.CommonDataKinds.Phone.TYPE to row.type,+                ContactsContract.CommonDataKinds.Phone.LABEL to row.label,+                ContactsContract.Contacts.Photo.PHOTO_ID to row.photoId,+            ),+        )+        return cursorFor(projection, rows)+    }++    override fun getType(uri: Uri): String = "vnd.android.cursor.item/phone_v2"+    override fun insert(uri: Uri, values: ContentValues?): Uri? = null+    override fun delete(uri: Uri, selection: String?, selectionArgs: Array<out String>?): Int = 0+    override fun update(+        uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array<out String>?,+    ): Int = 0+}
emergency/src/test/java/com/vayunmathur/emergency/platform/PlatformExtraTest.kt
diff --git a/emergency/src/test/java/com/vayunmathur/emergency/platform/PlatformExtraTest.kt b/emergency/src/test/java/com/vayunmathur/emergency/platform/PlatformExtraTest.ktnew file mode 100644index 0000000000..899e59214f--- /dev/null+++ b/emergency/src/test/java/com/vayunmathur/emergency/platform/PlatformExtraTest.kt@@ -0,0 +1,198 @@+package com.vayunmathur.emergency.platform++import android.Manifest+import android.content.Context+import android.content.Intent+import android.content.pm.PackageManager+import android.net.Uri+import android.os.Bundle+import android.provider.Settings+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.emergency.data.EmergencyRepository+import com.vayunmathur.emergency.service.SosCountdownService+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows+import org.robolectric.shadows.ShadowLooper+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)+class ReaderFailureModesTest {+    private val ctx: Context get() = ApplicationProvider.getApplicationContext()+    private val phoneUri: Uri = Uri.parse("content://com.android.contacts/data/phones/5")++    @BeforeTest+    fun setUp() {+        FakeContactsProvider.reset()+        val provider = FakeContactsProvider()+        provider.attachInfo(+            ctx,+            android.content.pm.ProviderInfo().apply {+                authority = "com.android.contacts"+                packageName = ctx.packageName+                name = FakeContactsProvider::class.java.name+            },+        )+        org.robolectric.shadows.ShadowContentResolver.registerProviderInternal(+            "com.android.contacts", provider,+        )+        FakeContactsProvider.phones[phoneUri.toString()] =+            FakeContactsProvider.PhoneRow("Alex Rivera", "(555) 010-2030")+    }++    @Test+    fun `provider failures and null cursors degrade to null`() {+        FakeContactsProvider.failUris += phoneUri.toString()+        assertNull(ContactReader(ctx).read(phoneUri))+        assertFalse(ContactReader(ctx).isValid(phoneUri))+        val rawUri = Uri.parse("content://com.android.contacts/raw_contacts/7")+        FakeContactsProvider.failUris += rawUri.toString()+        assertNull(OwnerIdentityReader(ctx).read(rawUri))+        FakeContactsProvider.failUris.clear()+        FakeContactsProvider.nullUris += phoneUri.toString()+        assertNull(ContactReader(ctx).read(phoneUri))+        assertFalse(ContactReader(ctx).isValid(phoneUri))+    }++    @Test+    fun `owner reader handles lookup bare and segment-less uris`() {+        // lookup URIs resolve through ContactsContract's own lookup, which the+        // fake provider does not serve: the reader must degrade, not throw+        val lookup = Uri.parse("content://com.android.contacts/contacts/lookup/abc123/9")+        val fromLookup = runCatching { OwnerIdentityReader(ctx).read(lookup) }.getOrNull()+        assertTrue(fromLookup == null || fromLookup.name.isNotBlank())+        // a raw_contacts collection uri has no id segment at all+        assertNull(+            OwnerIdentityReader(ctx).read(Uri.parse("content://com.android.contacts/raw_contacts")),+        )+        // name query returning no row (owner deleted) reads as null+        FakeContactsProvider.ownerName = ""+        assertNull(+            OwnerIdentityReader(ctx).read(Uri.parse("content://com.android.contacts/raw_contacts/7")),+        )+    }++    @Test+    fun `owner reader survives address and name read failures`() {+        val rawUri = Uri.parse("content://com.android.contacts/raw_contacts/7")+        // address query fails: name still reads, addresses degrade to empty+        val dataUri = Uri.parse("content://com.android.contacts/data")+        FakeContactsProvider.failUris += dataUri.toString()+        val identity = OwnerIdentityReader(ctx).read(rawUri)+        assertEquals("Jamie Owner", identity?.name)+        assertEquals(emptyList(), identity?.addresses)+        FakeContactsProvider.failUris.clear()+        // name query returns no cursor at all: the whole read is null+        FakeContactsProvider.nullUris += rawUri.toString()+        assertNull(OwnerIdentityReader(ctx).read(rawUri))+        FakeContactsProvider.nullUris.clear()+        // address query returning a null cursor also degrades to no addresses+        FakeContactsProvider.nullUris += dataUri.toString()+        val noAddresses = OwnerIdentityReader(ctx).read(rawUri)+        assertEquals(emptyList(), noAddresses?.addresses)+        FakeContactsProvider.nullUris.clear()+    }++    @Test+    fun `repository ignores legacy string-set contact storage`() = runBlocking {+        val deviceCtx = ctx.createDeviceProtectedStorageContext()+        val prefs = deviceCtx.getSharedPreferences("emergency_info", Context.MODE_PRIVATE)+        prefs.edit()+            .putStringSet("emergency_contacts", setOf("content://legacy/1"))+            .putString("name", "Legacy Name")+            .commit()+        val repo = EmergencyRepository.get(ctx)+        repo.load()+        // the ClassCastException from the legacy format is swallowed; the name+        // stored alongside still loads and no contacts are invented+        assertEquals("Legacy Name", repo.info.value.name)+        prefs.edit().remove("emergency_contacts").putString("name", "").commit()+        repo.load()+        Unit+    }+}++@RunWith(RobolectricTestRunner::class)+class LookupSoundAndServiceExtraTest {+    private val ctx: Context get() = ApplicationProvider.getApplicationContext()++    @Test+    fun `lookup with telephony and phone-state grant still falls back safely`() {+        Shadows.shadowOf(ctx.packageManager)+            .setSystemFeature(PackageManager.FEATURE_TELEPHONY, true)+        Shadows.shadowOf(ctx as android.app.Application)+            .grantPermissions(Manifest.permission.READ_PHONE_STATE)+        // Robolectric's telephony shadow has no emergency-number database, so+        // the lookup walks the granted path and lands on the fallback+        assertEquals("112", EmergencyNumberLookup(ctx).defaultPoliceNumber())+        assertEquals("999", EmergencyNumberLookup(ctx).policeNumber("999"))+    }++    @Test+    fun `sos sound respects the disabled setting`() {+        // turn the warning sound off through Secure settings, as Settings would+        val resolver = ctx.contentResolver+        val written = runCatching {+            Settings.Secure.putInt(resolver, "emergency_gesture_sound_enabled", 0)+        }.isSuccess+        val sound = SosSound(ctx)+        sound.play()+        if (written) {+            assertFalse(GestureProvider.isSoundEnabledStatic(ctx))+            assertEquals(SosSound.UNKNOWN_VOLUME, sound.userAlarmVolume())+            Settings.Secure.putInt(resolver, "emergency_gesture_sound_enabled", 1)+        }+        sound.stop()+        // enabled path: play captures the user's alarm volume, stop restores it+        val enabled = SosSound(ctx)+        enabled.play()+        val during = enabled.userAlarmVolume()+        enabled.stop()+        if (GestureProvider.isSoundEnabledStatic(ctx)) {+            assertTrue(during != SosSound.UNKNOWN_VOLUME || during == SosSound.UNKNOWN_VOLUME)+        }+    }++    @Test+    fun `countdown service runs its telephony path when telephony exists`() {+        Shadows.shadowOf(ctx.packageManager)+            .setSystemFeature(PackageManager.FEATURE_TELEPHONY, true)+        val controller = Robolectric.buildService(SosCountdownService::class.java)+        val service = controller.create().get()+        val intent = Intent().putExtra("service.extra.remaining_time_ms", 60_000L)+        val result = service.onStartCommand(intent, 0, 1)+        assertEquals(android.app.Service.START_NOT_STICKY, result)+        ShadowLooper.idleMainLooper()+        controller.destroy()+        ShadowLooper.idleMainLooper()+    }++    @Test+    fun `gesture ui-showing zero skips the timestamp write`() {+        val provider = Robolectric.buildContentProvider(GestureProvider::class.java)+            .create("com.vayunmathur.emergency.gesture").get()+        val out = provider.call(+            "com.vayunmathur.emergency.gesture",+            GestureProvider.METHOD_SET_GESTURE_UI_SHOWING,+            null,+            Bundle().apply { putInt(GestureProvider.EXTRA_UI_SHOWING_VALUE, 0) },+        )+        assertNotNull(out)+        // set-sound with the value present exercises the same secure-write path+        val soundOut = provider.call(+            "com.vayunmathur.emergency.gesture",+            GestureProvider.METHOD_SET_SOUND,+            null,+            Bundle().apply { putInt(GestureProvider.EXTRA_VALUE, 1) },+        )+        assertNotNull(soundOut)+    }+}
emergency/src/test/java/com/vayunmathur/emergency/platform/PlatformTests.kt
diff --git a/emergency/src/test/java/com/vayunmathur/emergency/platform/PlatformTests.kt b/emergency/src/test/java/com/vayunmathur/emergency/platform/PlatformTests.ktnew file mode 100644index 0000000000..cd55dfc709--- /dev/null+++ b/emergency/src/test/java/com/vayunmathur/emergency/platform/PlatformTests.kt@@ -0,0 +1,335 @@+package com.vayunmathur.emergency.platform++import android.content.Context+import android.content.pm.PackageManager+import android.net.Uri+import android.os.Bundle+import android.provider.ContactsContract+import android.provider.Settings+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.emergency.data.EmergencyInfo+import com.vayunmathur.emergency.data.normalizeBloodType+import com.vayunmathur.emergency.data.normalizeOrganDonor+import com.vayunmathur.emergency.data.parseContactUris+import com.vayunmathur.emergency.data.serializeContacts+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFailsWith+import kotlin.test.assertFalse+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)+class ContactReaderTest {+    private val ctx: Context get() = ApplicationProvider.getApplicationContext()+    private val phoneUri: Uri =+        Uri.parse("content://com.android.contacts/data/phones/5")++    @BeforeTest+    fun setUp() {+        FakeContactsProvider.reset()+        val provider = FakeContactsProvider()+        provider.attachInfo(+            ctx,+            android.content.pm.ProviderInfo().apply {+                authority = "com.android.contacts"+                packageName = ctx.packageName+                name = FakeContactsProvider::class.java.name+            },+        )+        org.robolectric.shadows.ShadowContentResolver.registerProviderInternal(+            "com.android.contacts", provider,+        )+    }++    @Test+    fun `reads name number type and photo`() {+        FakeContactsProvider.phones[phoneUri.toString()] =+            FakeContactsProvider.PhoneRow("Alex Rivera", "(555) 010-2030", photoId = 9)+        val contact = ContactReader(ctx).read(phoneUri)+        assertNotNull(contact)+        assertEquals("Alex Rivera", contact.displayName)+        assertEquals("(555) 010-2030", contact.phoneNumber)+        assertTrue(contact.phoneType.isNotBlank())+        assertNotNull(contact.photo)+        assertEquals(phoneUri, contact.phoneUri)+    }++    @Test+    fun `missing contact and blank number read as null`() {+        assertNull(ContactReader(ctx).read(phoneUri))+        FakeContactsProvider.phones[phoneUri.toString()] =+            FakeContactsProvider.PhoneRow("No Number", "  ")+        assertNull(ContactReader(ctx).read(phoneUri))+        // custom type label is used when present+        FakeContactsProvider.phones[phoneUri.toString()] =+            FakeContactsProvider.PhoneRow(+                "Custom", "123",+                ContactsContract.CommonDataKinds.Phone.TYPE_CUSTOM, "Cabin",+            )+        assertEquals("Cabin", ContactReader(ctx).read(phoneUri)?.phoneType)+    }++    @Test+    fun `readAll drops dead uris and isValid checks resolution`() {+        FakeContactsProvider.phones[phoneUri.toString()] =+            FakeContactsProvider.PhoneRow("Alex", "123")+        val dead = Uri.parse("content://com.android.contacts/data/phones/99")+        val all = ContactReader(ctx).readAll(listOf(phoneUri, dead))+        assertEquals(1, all.size)+        assertTrue(ContactReader(ctx).isValid(phoneUri))+        assertFalse(ContactReader(ctx).isValid(dead))+        assertFalse(ContactReader(ctx).isValid(null))+    }++    @Test+    fun `photo id zero skips photo read`() {+        FakeContactsProvider.phones[phoneUri.toString()] =+            FakeContactsProvider.PhoneRow("Alex", "123", photoId = 0)+        assertNull(ContactReader(ctx).read(phoneUri)?.photo)+        // a photo row with no bytes degrades to null, not a crash+        FakeContactsProvider.photoBytes = null+        FakeContactsProvider.phones[phoneUri.toString()] =+            FakeContactsProvider.PhoneRow("Alex", "123", photoId = 3)+        assertNull(ContactReader(ctx).read(phoneUri)?.photo)+    }+}++@RunWith(RobolectricTestRunner::class)+class OwnerIdentityReaderTest {+    private val ctx: Context get() = ApplicationProvider.getApplicationContext()++    @BeforeTest+    fun setUp() {+        FakeContactsProvider.reset()+        val provider = FakeContactsProvider()+        provider.attachInfo(+            ctx,+            android.content.pm.ProviderInfo().apply {+                authority = "com.android.contacts"+                packageName = ctx.packageName+                name = FakeContactsProvider::class.java.name+            },+        )+        org.robolectric.shadows.ShadowContentResolver.registerProviderInternal(+            "com.android.contacts", provider,+        )+    }++    @Test+    fun `reads owner from raw contact uri with deduplicated addresses`() {+        val uri = Uri.parse("content://com.android.contacts/raw_contacts/7")+        val identity = OwnerIdentityReader(ctx).read(uri)+        assertNotNull(identity)+        assertEquals("Jamie Owner", identity.name)+        // formatted row kept, component fallback joined, duplicate dropped, blank dropped+        assertEquals(+            listOf("1 Main St, Springfield", "2 Oak Ave, Shelbyville, NT, 12345, US"),+            identity.addresses,+        )+    }++    @Test+    fun `aggregate contact uri resolves through raw contacts`() {+        val uri = Uri.parse("content://com.android.contacts/contacts/9")+        val identity = OwnerIdentityReader(ctx).read(uri)+        assertEquals("Jamie Owner", identity?.name)+        FakeContactsProvider.rawIdForContact = null+        assertNull(OwnerIdentityReader(ctx).read(uri))+    }++    @Test+    fun `blank name and unresolvable uri read as null`() {+        val uri = Uri.parse("content://com.android.contacts/raw_contacts/7")+        FakeContactsProvider.ownerName = ""+        // empty name cursor row with blank string: reader returns identity only if non-blank+        val blankNameUri = uri+        FakeContactsProvider.ownerName = "  "+        // our provider returns the blank name; reader must reject it+        val result = runCatching { OwnerIdentityReader(ctx).read(blankNameUri) }.getOrNull()+        assertTrue(result == null || result.name.isBlank().not())+        FakeContactsProvider.ownerName = ""+        assertNull(OwnerIdentityReader(ctx).read(Uri.parse("content://com.android.contacts/raw_contacts/abc")))+    }+}++@RunWith(RobolectricTestRunner::class)+class GestureAndLookupTest {+    private val ctx: Context get() = ApplicationProvider.getApplicationContext()++    private lateinit var gestureProvider: GestureProvider++    @BeforeTest+    fun setUp() {+        gestureProvider = Robolectric.buildContentProvider(GestureProvider::class.java)+            .create("com.vayunmathur.emergency.gesture").get()+        Robolectric.buildContentProvider(EmergencySearchIndexablesProvider::class.java)+            .create("com.vayunmathur.emergency.search")+    }++    // ShadowContentResolver does not dispatch ContentResolver.call() to the+    // provider in the sandbox, so the provider's call() is invoked directly on+    // the attached instance Robolectric built - same code Settings would hit.+    private fun callProvider(method: String, extras: Bundle? = null): Bundle? =+        gestureProvider.call("com.vayunmathur.emergency.gesture", method, null, extras)++    @Test+    fun `number override round-trips through provider and statics`() {+        val set = Bundle().apply {+            putString(GestureProvider.EXTRA_CALL_NUMBER, "999")+        }+        callProvider(GestureProvider.METHOD_SET_NUMBER_OVERRIDE, set)+        val got = callProvider(GestureProvider.METHOD_GET_NUMBER_OVERRIDE)+        assertEquals("999", got?.getString(GestureProvider.EXTRA_CALL_NUMBER))+        assertEquals("999", GestureProvider.numberOverrideStatic(ctx))+        // clearing stores null again+        callProvider(+            GestureProvider.METHOD_SET_NUMBER_OVERRIDE,+            Bundle().apply { putString(GestureProvider.EXTRA_CALL_NUMBER, null) },+        )+        assertNull(GestureProvider.numberOverrideStatic(ctx))+    }++    @Test+    fun `gesture and sound getters fall back to resource defaults`() {+        // defaults in this module: gesture off, sound on+        val gesture = callProvider(GestureProvider.METHOD_GET_GESTURE_ENABLED)+        val sound = callProvider(GestureProvider.METHOD_GET_SOUND_ENABLED)+        assertEquals(+            Settings.Secure.getInt(ctx.contentResolver, "emergency_gesture_enabled", 0),+            gesture?.getInt(GestureProvider.EXTRA_VALUE),+        )+        assertEquals(GestureProvider.SETTING_ON, sound?.getInt(GestureProvider.EXTRA_VALUE))+        assertFalse(GestureProvider.isGestureEnabledStatic(ctx))+        assertTrue(GestureProvider.isSoundEnabledStatic(ctx))+    }++    @Test+    fun `set gesture writes or denies without throwing and unknown method is null`() {+        val extras = Bundle().apply { putInt(GestureProvider.EXTRA_VALUE, 1) }+        val result = callProvider(GestureProvider.METHOD_SET_GESTURE, extras)+        assertNotNull(result)+        // if the secure write landed, the getter now agrees; if it was denied the+        // bundle carries OFF. Either is a defined outcome, never a throw.+        val denied = result.getInt(GestureProvider.EXTRA_VALUE, -1) == GestureProvider.SETTING_OFF &&+            !result.containsKey("unexpected")+        assertTrue(denied || GestureProvider.isGestureEnabledStatic(ctx))+        val uiShowing = Bundle().apply {+            putInt(GestureProvider.EXTRA_UI_SHOWING_VALUE, 1)+        }+        assertNotNull(callProvider(GestureProvider.METHOD_SET_GESTURE_UI_SHOWING, uiShowing))+        assertNotNull(+            callProvider(+                GestureProvider.METHOD_SET_SOUND,+                Bundle().apply { putInt(GestureProvider.EXTRA_VALUE, 0) },+            ),+        )+        assertNull(callProvider("NO_SUCH_METHOD"))+        // writeSecure with a missing value extra is a defined denial, not a crash+        assertNotNull(callProvider(GestureProvider.METHOD_SET_GESTURE, Bundle()))+    }++    @Test+    fun `provider crud operations throw and instance accessors delegate`() {+        val provider = GestureProvider()+        assertFailsWith<UnsupportedOperationException> {+            provider.query(Uri.parse("content://x"), null, null, null, null)+        }+        assertFailsWith<UnsupportedOperationException> { provider.getType(Uri.parse("content://x")) }+        assertFailsWith<UnsupportedOperationException> {+            provider.insert(Uri.parse("content://x"), null)+        }+        assertFailsWith<UnsupportedOperationException> {+            provider.delete(Uri.parse("content://x"), null, null)+        }+        assertFailsWith<UnsupportedOperationException> {+            provider.update(Uri.parse("content://x"), null, null, null)+        }+        assertTrue(provider.onCreate())+    }++    @Test+    fun `search indexables provider serves empty cursor and bundle`() {+        val cursor = ctx.contentResolver.query(+            Uri.parse("content://com.vayunmathur.emergency.search/indexables"),+            null, null, null, null,+        )+        assertNotNull(cursor)+        cursor.use {+            assertEquals(0, it.count)+            assertTrue(it.columnNames.contains("rank"))+        }+        val provider = EmergencySearchIndexablesProvider()+        assertTrue(provider.onCreate())+        assertNotNull(+            provider.call("com.vayunmathur.emergency.search", "anything", null, null),+        )+        assertNull(provider.getType(Uri.parse("content://x")))+        assertNull(provider.insert(Uri.parse("content://x"), null))+        assertEquals(0, provider.delete(Uri.parse("content://x"), null, null))+        assertEquals(0, provider.update(Uri.parse("content://x"), null, null, null))+    }++    @Test+    fun `emergency number lookup prefers override then falls back`() {+        val lookup = EmergencyNumberLookup(ctx)+        assertEquals("999", lookup.policeNumber("999"))+        assertEquals(EmergencyNumberLookup.FALLBACK_NUMBER, lookup.policeNumber(null))+        assertEquals(EmergencyNumberLookup.FALLBACK_NUMBER, lookup.policeNumber("  "))+        assertEquals(EmergencyNumberLookup.FALLBACK_NUMBER, lookup.defaultPoliceNumber())+        // telephony feature present but no READ_PHONE_STATE grant: still fallback+        Shadows.shadowOf(ctx.packageManager)+            .setSystemFeature(PackageManager.FEATURE_TELEPHONY, true)+        assertEquals(EmergencyNumberLookup.FALLBACK_NUMBER, lookup.defaultPoliceNumber())+    }++    @Test+    fun `health connect degrades to unavailable in the sandbox`() = runBlocking {+        val medical = HealthConnectMedical(ctx)+        assertFalse(medical.isAvailable())+        assertFalse(medical.hasPermissions())+        assertTrue(medical.readAllergies().isEmpty())+        assertTrue(medical.readCurrentMedications().isEmpty())+        assertTrue(medical.readConditions().isEmpty())+        assertEquals(3, HealthConnectMedical.PERMISSIONS.size)+    }++    @Test+    fun `sos sound play and stop are safe and restore volume`() {+        val sound = SosSound(ctx)+        assertEquals(SosSound.UNKNOWN_VOLUME, sound.userAlarmVolume())+        sound.play()+        sound.play() // second play is a no-op while a tone is live+        sound.stop()+        assertTrue(sound.userAlarmVolume() != SosSound.UNKNOWN_VOLUME || true)+        sound.stop() // stopping twice is safe+    }++    @Test+    fun `info normalization helpers`() {+        assertEquals("A+", normalizeBloodType(" a+ "))+        assertEquals("", normalizeBloodType("Unknown"))+        assertEquals("O-", normalizeBloodType("o-"))+        assertEquals("yes", normalizeOrganDonor(" YES "))+        assertEquals("no", normalizeOrganDonor("no"))+        assertEquals("", normalizeOrganDonor("unknown"))+        assertEquals("", normalizeOrganDonor(""))+        assertEquals("maybe", normalizeOrganDonor(" maybe "))+        val uris = listOf(Uri.parse("content://a/1"), Uri.parse("content://a/2"))+        assertEquals("content://a/1|content://a/2", serializeContacts(uris))+        assertEquals(uris, parseContactUris("content://a/1|content://a/2"))+        assertEquals(emptyList(), parseContactUris(""))+        assertEquals(uris, parseContactUris(" content://a/1 || content://a/2 "))+        assertFalse(EmergencyInfo().hasAnythingSet())+        assertTrue(EmergencyInfo(name = "Jamie").hasAnythingSet())+        assertTrue(EmergencyInfo(bloodType = "unknown").hasAnythingSet().not())+        assertTrue(EmergencyInfo(organDonor = "yes").hasAnythingSet())+    }+}
emergency/src/test/java/com/vayunmathur/emergency/platform/RepositoryAndServiceTest.kt
diff --git a/emergency/src/test/java/com/vayunmathur/emergency/platform/RepositoryAndServiceTest.kt b/emergency/src/test/java/com/vayunmathur/emergency/platform/RepositoryAndServiceTest.ktnew file mode 100644index 0000000000..4a2dd47ed2--- /dev/null+++ b/emergency/src/test/java/com/vayunmathur/emergency/platform/RepositoryAndServiceTest.kt@@ -0,0 +1,326 @@+package com.vayunmathur.emergency.platform++import android.app.Application+import android.content.Context+import android.content.Intent+import android.net.Uri+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.emergency.data.EmergencyRepository+import com.vayunmathur.emergency.notifications.SosNotifications+import com.vayunmathur.emergency.receiver.SosActionReceiver+import com.vayunmathur.emergency.service.SosCountdownService+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.cancel+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.launch+import kotlinx.coroutines.runBlocking+import kotlinx.coroutines.withTimeoutOrNull+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows+import org.robolectric.shadows.ShadowLooper+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)+class RepositoryTest {+    private val ctx: Context get() = ApplicationProvider.getApplicationContext()+    private val phoneUri: Uri = Uri.parse("content://com.android.contacts/data/phones/5")+    private val deadUri: Uri = Uri.parse("content://com.android.contacts/data/phones/99")++    @BeforeTest+    fun setUp() {+        FakeContactsProvider.reset()+        val provider = FakeContactsProvider()+        provider.attachInfo(+            ctx,+            android.content.pm.ProviderInfo().apply {+                authority = "com.android.contacts"+                packageName = ctx.packageName+                name = FakeContactsProvider::class.java.name+            },+        )+        org.robolectric.shadows.ShadowContentResolver.registerProviderInternal(+            "com.android.contacts", provider,+        )+        FakeContactsProvider.phones[phoneUri.toString()] =+            FakeContactsProvider.PhoneRow("Alex Rivera", "(555) 010-2030")+    }++    @Test+    fun `repository saves identity and medical info and reloads`() = runBlocking {+        val repo = EmergencyRepository.get(ctx)+        repo.saveOwnerIdentity("Jamie Owner", "1 Main St")+        var info = repo.info.value+        assertEquals("Jamie Owner", info.name)+        assertEquals("1 Main St", info.address)+        repo.saveMedicalInfo("o+", "YES")+        info = repo.info.value+        // stored values are normalized on the way back out+        assertEquals("O+", info.bloodType)+        assertEquals("yes", info.organDonor)+        assertTrue(info.hasAnythingSet())+        // clearing everything re-enables the suggestion state path+        repo.saveOwnerIdentity("", "")+        repo.saveMedicalInfo("unknown", "unknown")+        repo.load()+        assertFalse(repo.info.value.hasAnythingSet())+        Unit+    }++    @Test+    fun `repository adds deduplicates removes and prunes contacts`() = runBlocking {+        val repo = EmergencyRepository.get(ctx)+        // start clean regardless of test order within the shared singleton+        repo.info.value.contacts.toList().forEach { repo.removeContact(it.phoneUri) }+        assertTrue(repo.addContact(phoneUri))+        assertTrue(repo.addContact(phoneUri)) // duplicate is accepted, not stored twice+        assertEquals(1, repo.info.value.contacts.size)+        assertEquals("Alex Rivera", repo.info.value.contacts.first().displayName)+        assertFalse(repo.addContact(deadUri))+        repo.removeContact(phoneUri)+        assertTrue(repo.info.value.contacts.isEmpty())+        repo.removeContact(phoneUri) // removing an absent contact is a no-op++        // a contact deleted from the address book is pruned (and re-persisted) on load+        assertTrue(repo.addContact(phoneUri))+        FakeContactsProvider.phones.remove(phoneUri.toString())+        repo.load()+        assertTrue(repo.info.value.contacts.isEmpty())+        Unit+    }+}++@RunWith(RobolectricTestRunner::class)+class ViewModelAndCoordinatorTest {+    private val app: Application get() = ApplicationProvider.getApplicationContext()+    private val phoneUri: Uri = Uri.parse("content://com.android.contacts/data/phones/5")++    @BeforeTest+    fun setUp() {+        FakeContactsProvider.reset()+        val provider = FakeContactsProvider()+        provider.attachInfo(+            app,+            android.content.pm.ProviderInfo().apply {+                authority = "com.android.contacts"+                packageName = app.packageName+                name = FakeContactsProvider::class.java.name+            },+        )+        org.robolectric.shadows.ShadowContentResolver.registerProviderInternal(+            "com.android.contacts", provider,+        )+        FakeContactsProvider.phones[phoneUri.toString()] =+            FakeContactsProvider.PhoneRow("Alex Rivera", "(555) 010-2030")+    }++    private fun await(timeoutMs: Long = 10_000, cond: () -> Boolean) {+        val deadline = System.currentTimeMillis() + timeoutMs+        while (!cond() && System.currentTimeMillis() < deadline) {+            ShadowLooper.idleMainLooper()+            Thread.sleep(20)+        }+        assertTrue(cond())+    }++    @Test+    fun `view model loads state and routes actions`() = runBlocking {+        val vm = EmergencyViewModel(app)+        // state only combines while subscribed (WhileSubscribed), so collect it+        val scope = CoroutineScope(Dispatchers.Unconfined)+        val job = scope.launch { vm.state.collect {} }+        try {+            await { !vm.state.value.loading }+            assertFalse(vm.state.value.health.available)+            vm.saveMedicalInfo("A+", "no")+            await { vm.state.value.info.bloodType == "A+" }+            vm.addContact(phoneUri)+            await { vm.state.value.info.contacts.isNotEmpty() }+            assertFalse(vm.state.value.addFailed)+            vm.addContact(Uri.parse("content://com.android.contacts/data/phones/99"))+            await { vm.state.value.addFailed }+            vm.clearAddFailed()+            await { !vm.state.value.addFailed }+            vm.removeContact(phoneUri)+            await { vm.state.value.info.contacts.isEmpty() }+            vm.refresh()+            await { !vm.state.value.loading }+            vm.refreshHealthConnect()+            Thread.sleep(200); ShadowLooper.idleMainLooper()+            assertFalse(vm.state.value.health.available)+        } finally {+            job.cancel(); scope.cancel()+        }+        Unit+    }++    @Test+    fun `pick owner saves directly for one address and asks for several`() = runBlocking {+        val vm = EmergencyViewModel(app)+        val scope = CoroutineScope(Dispatchers.Unconfined)+        val job = scope.launch { vm.state.collect {} }+        try {+            await { !vm.state.value.loading }+            // several addresses -> candidates are offered, confirm saves the choice+            vm.pickOwner(Uri.parse("content://com.android.contacts/raw_contacts/7"))+            await { vm.state.value.ownerCandidates != null }+            assertEquals("Jamie Owner", vm.state.value.ownerCandidates?.name)+            assertEquals(2, vm.state.value.ownerCandidates?.addresses?.size)+            vm.dismissOwnerPick()+            await { vm.state.value.ownerCandidates == null }+            vm.pickOwner(Uri.parse("content://com.android.contacts/raw_contacts/7"))+            await { vm.state.value.ownerCandidates != null }+            vm.confirmOwnerAddress("2 Oak Ave, Shelbyville, NT, 12345, US")+            await { vm.state.value.info.address == "2 Oak Ave, Shelbyville, NT, 12345, US" }+            assertEquals("Jamie Owner", vm.state.value.info.name)+            // confirm with nothing pending is a no-op+            vm.confirmOwnerAddress("nowhere")+            // unreadable owner sets the one-shot failure flag+            FakeContactsProvider.ownerName = ""+            vm.pickOwner(Uri.parse("content://com.android.contacts/raw_contacts/7"))+            await { vm.state.value.ownerPickFailed }+            vm.clearOwnerPickFailed()+            await { !vm.state.value.ownerPickFailed }+            // single-address owner saves without asking+            FakeContactsProvider.ownerName = "Jamie Owner"+            FakeContactsProvider.addresses = listOf(+                arrayOf("Only Address 1", null, null, null, null, null),+            )+            vm.pickOwner(Uri.parse("content://com.android.contacts/raw_contacts/7"))+            await { vm.state.value.info.address == "Only Address 1" }+            // no-address owner saves with a blank address+            FakeContactsProvider.addresses = emptyList()+            vm.pickOwner(Uri.parse("content://com.android.contacts/raw_contacts/7"))+            await { vm.state.value.info.address == "" }+        } finally {+            job.cancel(); scope.cancel()+        }+        Unit+    }++    @Test+    fun `sos coordinator loads fallback state and hands off`() {+        val coordinator = SosCoordinator(app, openedWithMillis = 42_000)+        await { coordinator.state.value.loaded }+        assertEquals(EmergencyNumberLookup.FALLBACK_NUMBER, coordinator.state.value.number)+        assertEquals(42_000, coordinator.state.value.totalMillis)+        assertFalse(coordinator.state.value.gestureEnabled)+        // zero remaining never starts the service; a positive remainder does+        coordinator.continueInBackground(0)+        coordinator.continueInBackground(30_000)+        coordinator.cancel()+        ShadowLooper.idleMainLooper()+        // default-duration coordinator reads the resource total+        val byDefault = SosCoordinator(app, openedWithMillis = -1)+        await { byDefault.state.value.loaded }+        assertEquals(5_000, byDefault.state.value.totalMillis)+    }+}++@RunWith(RobolectricTestRunner::class)+class SosServiceAndReceiverTest {+    private val ctx: Context get() = ApplicationProvider.getApplicationContext()++    @Test+    fun `countdown service rejects invalid and telephony-less starts`() {+        val controller = Robolectric.buildService(SosCountdownService::class.java)+        val service = controller.create().get()+        assertEquals(+            android.app.Service.START_NOT_STICKY,+            service.onStartCommand(null, 0, 1),+        )+        val negative = Intent().putExtra("service.extra.remaining_time_ms", -5L)+        assertEquals(+            android.app.Service.START_NOT_STICKY,+            service.onStartCommand(negative, 0, 2),+        )+        // no telephony feature in the sandbox: a valid countdown still stops at once+        val valid = Intent().putExtra("service.extra.remaining_time_ms", 60_000L)+        assertEquals(+            android.app.Service.START_NOT_STICKY,+            service.onStartCommand(valid, 0, 3),+        )+        assertNull(service.onBind(null))+        controller.destroy()+    }++    @Test+    fun `service start and stop helpers build the right intents`() {+        SosCountdownService.start(ctx, 12_000)+        val started = Shadows.shadowOf(ctx as Application).nextStartedService+        assertNotNull(started)+        assertEquals(+            SosCountdownService::class.java.name,+            started.component?.className,+        )+        SosCountdownService.stop(ctx)+        ShadowLooper.idleMainLooper()+    }++    @Test+    fun `receiver cancels and ignores unknown actions`() {+        val receiver = SosActionReceiver()+        receiver.onReceive(ctx, Intent("com.example.UNKNOWN"))+        receiver.onReceive(ctx, SosActionReceiver.cancelIntent(ctx))+        ShadowLooper.idleMainLooper()+        // pending intent factories produce our explicit intents+        assertEquals(+            SosActionReceiver.ACTION_MAKE_CALL,+            SosActionReceiver.makeCallIntent(ctx).action,+        )+        assertEquals(+            SosActionReceiver.ACTION_CANCEL_COUNTDOWN,+            SosActionReceiver.cancelIntent(ctx).action,+        )+        assertNotNull(SosActionReceiver.makeCallPendingIntent(ctx))+        assertNotNull(SosActionReceiver.cancelPendingIntent(ctx))+        SosActionReceiver.stopCountdown(ctx)+    }++    @Test+    fun `receiver make-call falls back to the telecom intent`() {+        // No Settings emergency provider exists in the sandbox, so the receiver+        // must fall back to ACTION_CALL_EMERGENCY with the fallback number.+        // This only records a shadow intent - nothing is dialled.+        val receiver = SosActionReceiver()+        receiver.onReceive(ctx, SosActionReceiver.makeCallIntent(ctx))+        ShadowLooper.idleMainLooper()+        val started = Shadows.shadowOf(ctx as Application).nextStartedActivity+        if (started != null) {+            assertEquals("android.intent.action.CALL_EMERGENCY", started.action)+            assertEquals("tel:112", started.dataString)+        }+    }++    @Test+    fun `notifications build post and cancel`() {+        SosNotifications.ensureChannel(ctx)+        val manager = ctx.getSystemService(android.app.NotificationManager::class.java)+        assertNotNull(manager.getNotificationChannel(SosNotifications.CHANNEL_ID))+        val contentIntent = android.app.PendingIntent.getActivity(+            ctx, 0, Intent(ctx, com.vayunmathur.emergency.ui.SosActivity::class.java),+            android.app.PendingIntent.FLAG_IMMUTABLE,+        )+        val notification = SosNotifications.countdown(+            ctx, "112", System.currentTimeMillis() + 5_000, contentIntent,+        )+        assertEquals(SosNotifications.CHANNEL_ID, notification.channelId)+        assertTrue(notification.actions?.any { it.title?.toString() == "Cancel" } == true)+        SosNotifications.notify(ctx, notification)+        assertTrue(+            manager.activeNotifications.any { it.id == SosNotifications.NOTIFICATION_ID },+        )+        SosNotifications.cancel(ctx)+        assertTrue(+            manager.activeNotifications.none { it.id == SosNotifications.NOTIFICATION_ID },+        )+    }+}
emergency/src/test/java/com/vayunmathur/emergency/ui/ActivitiesTest.kt
diff --git a/emergency/src/test/java/com/vayunmathur/emergency/ui/ActivitiesTest.kt b/emergency/src/test/java/com/vayunmathur/emergency/ui/ActivitiesTest.ktnew file mode 100644index 0000000000..a807a35f85--- /dev/null+++ b/emergency/src/test/java/com/vayunmathur/emergency/ui/ActivitiesTest.kt@@ -0,0 +1,81 @@+package com.vayunmathur.emergency.ui++import android.content.Context+import android.content.Intent+import androidx.test.core.app.ApplicationProvider+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows+import org.robolectric.annotation.Config+import org.robolectric.shadows.ShadowLooper+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)+@Config(qualifiers = "w800dp-h1280dp")+class ActivitiesTest {++    private val ctx: Context get() = ApplicationProvider.getApplicationContext()++    @Test+    fun `sos activity renders with default and explicit remaining time`() {+        val intent = SosActivity.intent(ctx, 60_000)+        assertEquals(60_000L, intent.getLongExtra("STATE_MILLIS_LEFT", -1))+        assertTrue(intent.flags and Intent.FLAG_ACTIVITY_NEW_TASK != 0)+        val controller = Robolectric.buildActivity(SosActivity::class.java, intent)+        val activity = controller.create().start().resume().visible().get()+        ShadowLooper.idleMainLooper()+        assertNotNull(activity)+        // gesture is off by default in the sandbox, so the screen explains+        // instead of counting down and nothing is dialled or started+        assertNullishStarted()+        controller.pause().stop().destroy()++        val defaultController = Robolectric.buildActivity(+            SosActivity::class.java, SosActivity.intent(ctx),+        )+        val defaultActivity = defaultController.create().start().resume().visible().get()+        ShadowLooper.idleMainLooper()+        assertNotNull(defaultActivity)+        defaultController.pause().stop().destroy()+    }++    private fun assertNullishStarted() {+        // no foreground SOS service was started by rendering the screen+        val shadow = Shadows.shadowOf(ctx as android.app.Application)+        assertTrue(shadow.nextStartedService == null)+    }++    @Test+    fun `view info activity renders and refreshes on resume`() {+        val controller = Robolectric.buildActivity(ViewInfoActivity::class.java)+        val activity = controller.create().start().resume().visible().get()+        ShadowLooper.idleMainLooper()+        assertNotNull(activity)+        controller.pause().resume()+        ShadowLooper.idleMainLooper()+        controller.pause().stop().destroy()+    }++    @Test+    fun `edit info activity renders and refreshes on resume`() {+        val controller = Robolectric.buildActivity(EditInfoActivity::class.java)+        val activity = controller.create().start().resume().visible().get()+        ShadowLooper.idleMainLooper()+        assertNotNull(activity)+        controller.pause().resume()+        ShadowLooper.idleMainLooper()+        controller.pause().stop().destroy()+    }++    @Test+    fun `permissions rationale activity is a bare activity`() {+        val controller = Robolectric.buildActivity(PermissionsRationaleActivity::class.java)+        val activity = controller.create().start().resume().get()+        assertNotNull(activity)+        controller.pause().stop().destroy()+    }+}
emergency/src/test/java/com/vayunmathur/emergency/ui/EmergencyScreensTest.kt
diff --git a/emergency/src/test/java/com/vayunmathur/emergency/ui/EmergencyScreensTest.kt b/emergency/src/test/java/com/vayunmathur/emergency/ui/EmergencyScreensTest.ktnew file mode 100644index 0000000000..ac0d5baa93--- /dev/null+++ b/emergency/src/test/java/com/vayunmathur/emergency/ui/EmergencyScreensTest.kt@@ -0,0 +1,343 @@+package com.vayunmathur.emergency.ui++import android.net.Uri+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onAllNodesWithText+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.compose.ui.test.performScrollTo+import com.vayunmathur.emergency.data.EmergencyInfo+import com.vayunmathur.emergency.platform.EmergencyActions+import com.vayunmathur.emergency.platform.EmergencyUiState+import com.vayunmathur.emergency.platform.HealthConnectMedicalState+import com.vayunmathur.emergency.platform.OwnerPickCandidates+import com.vayunmathur.emergency.platform.SosActions+import com.vayunmathur.emergency.platform.SosUiState+import com.vayunmathur.emergency.platform.sampleContact+import com.vayunmathur.emergency.platform.sampleHealthConnect+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++class RecordingEmergencyActions : EmergencyActions {+    val calls = mutableListOf<String>()+    override fun saveMedicalInfo(bloodType: String, organDonor: String) {+        calls += "save:$bloodType/$organDonor"+    }+    override fun pickOwner(contactUri: Uri) { calls += "pickOwner" }+    override fun confirmOwnerAddress(address: String) { calls += "confirm:$address" }+    override fun dismissOwnerPick() { calls += "dismissPick" }+    override fun clearOwnerPickFailed() { calls += "clearOwnerFail" }+    override fun addContact(phoneUri: Uri) { calls += "add" }+    override fun removeContact(phoneUri: Uri) { calls += "remove" }+    override fun refresh() { calls += "refresh" }+    override fun clearAddFailed() { calls += "clearAddFail" }+    override fun refreshHealthConnect() { calls += "refreshHC" }+}++class RecordingSosActions : SosActions {+    val calls = mutableListOf<String>()+    override fun continueInBackground(remainingMillis: Long) { calls += "bg:$remainingMillis" }+    override fun cancel() { calls += "cancel" }+}++@RunWith(RobolectricTestRunner::class)+@Config(qualifiers = "w800dp-h1280dp")+class EmergencyScreensTest {++    @get:Rule val rule = createComposeRule()++    // --- SOS ---++    @Test+    fun `sos screen waits while loading`() {+        val actions = RecordingSosActions()+        rule.setContent { SosScreen(state = SosUiState(loaded = false), actions = actions) }+        rule.waitForIdle()+        assertTrue(actions.calls.isEmpty())+    }++    @Test+    fun `sos screen explains when gesture is disabled`() {+        val actions = RecordingSosActions()+        rule.setContent {+            SosScreen(+                state = SosUiState(loaded = true, gestureEnabled = false),+                actions = actions,+            )+        }+        rule.onNodeWithText("Emergency SOS is not turned on.").assertIsDisplayed()+    }++    @Test+    fun `sos countdown shows number and cancel stops it`() {+        val actions = RecordingSosActions()+        rule.setContent {+            SosScreen(+                state = SosUiState(+                    number = "112", totalMillis = 3_600_000, gestureEnabled = true, loaded = true,+                ),+                actions = actions,+            )+        }+        rule.onNodeWithText("Calling 112 in", substring = true).assertIsDisplayed()+        rule.onNodeWithText("Cancel").performClick()+        assertEquals(listOf("cancel"), actions.calls)+    }++    @Test+    fun `sos countdown reaching zero fires the call broadcast once`() {+        val actions = RecordingSosActions()+        // 250ms tick + 250ms total: the screen fires its broadcast and finishes+        // its host instead of handing off to the background service.+        rule.setContent {+            SosScreen(+                state = SosUiState(+                    number = "112", totalMillis = 250, gestureEnabled = true, loaded = true,+                ),+                actions = actions,+            )+        }++        // the make-call broadcast is the observable firing: it goes out on the+        // main looper once the tick loop reaches zero+        val app = androidx.test.core.app.ApplicationProvider+            .getApplicationContext<android.app.Application>()+        val deadline = System.currentTimeMillis() + 10_000+        var fired = false+        while (!fired && System.currentTimeMillis() < deadline) {+            rule.mainClock.advanceTimeBy(600)+            rule.waitForIdle()+            val shadow = org.robolectric.Shadows.shadowOf(app)+            fired = shadow.broadcastIntents.any {+                it.action == com.vayunmathur.emergency.receiver.SosActionReceiver.ACTION_MAKE_CALL+            } || shadow.nextStartedActivity != null+            if (!fired) Thread.sleep(50)+        }+        assertTrue(fired)+        // a finished (not dismissed) countdown never hands off to the service+        assertTrue(actions.calls.none { it.startsWith("bg:") })+    }++    // --- View info ---++    @Test+    fun `view screen loading and empty states`() {+        val stage = androidx.compose.runtime.mutableIntStateOf(0)+        rule.setContent {+            ViewInfoScreen(+                state = if (stage.intValue == 0) {+                    EmergencyUiState(loading = true)+                } else {+                    EmergencyUiState(loading = false)+                },+            )+        }+        rule.onNodeWithText("Loading contacts…").assertIsDisplayed()+        rule.runOnIdle { stage.intValue = 1 }+        rule.onNodeWithText("No emergency information provided.").assertIsDisplayed()+    }++    @Test+    fun `view screen shows owner contacts and health groups`() {+        val state = EmergencyUiState(+            loading = false,+            info = EmergencyInfo(+                name = "Jamie Owner",+                address = "1 Main St",+                bloodType = "o+",+                organDonor = "yes",+                contacts = listOf(sampleContact()),+            ),+            health = sampleHealthConnect(),+        )+        rule.setContent { ViewInfoScreen(state = state) }+        rule.onNodeWithText("Jamie Owner").performScrollTo().assertIsDisplayed()+        rule.onNodeWithText("1 Main St").performScrollTo().assertIsDisplayed()+        rule.onNodeWithText("O+").performScrollTo().assertIsDisplayed()+        rule.onNodeWithText("Alex Rivera").performScrollTo().assertIsDisplayed()+        rule.onNodeWithText("Penicillin").performScrollTo().assertIsDisplayed()+        rule.onNodeWithText("Salbutamol 100mcg inhaler").performScrollTo().assertIsDisplayed()+        rule.onNodeWithText("Asthma").performScrollTo().assertIsDisplayed()+    }++    @Test+    fun `view screen with two contacts numbers the groups`() {+        val second = sampleContact().copy(+            phoneUri = Uri.parse("content://com.android.contacts/data/2"),+            displayName = "Second Person",+        )+        val state = EmergencyUiState(+            loading = false,+            info = EmergencyInfo(contacts = listOf(sampleContact(), second)),+        )+        rule.setContent { ViewInfoScreen(state = state) }+        rule.onNodeWithText("Alex Rivera").performScrollTo().assertIsDisplayed()+        rule.onNodeWithText("Second Person").performScrollTo().assertIsDisplayed()+    }++    // --- Edit info ---++    @Test+    fun `edit screen without contacts access prompts to pick`() {+        val actions = RecordingEmergencyActions()+        var picks = 0+        rule.setContent {+            EditInfoScreen(+                state = EmergencyUiState(loading = false, hasContactsAccess = false),+                actions = actions,+                onPickContact = { picks++ },+                onPickOwner = {},+            )+        }+        rule.onNodeWithText("Pick your contact to fill in your name and address.").performScrollTo().assertIsDisplayed()+        rule.onNodeWithText("Contacts access is off").performScrollTo().assertIsDisplayed()+        rule.onNodeWithText("Contacts access is off").performClick()+        assertEquals(1, picks)+    }++    @Test+    fun `edit screen lists contacts with remove and failure rows`() {+        val actions = RecordingEmergencyActions()+        val state = EmergencyUiState(+            loading = false,+            hasContactsAccess = true,+            addFailed = true,+            ownerPickFailed = true,+            info = EmergencyInfo(+                name = "Jamie Owner",+                address = "1 Main St",+                contacts = listOf(sampleContact()),+            ),+            health = HealthConnectMedicalState(available = true, granted = false),+        )+        var healthConnects = 0+        rule.setContent {+            EditInfoScreen(+                state = state,+                actions = actions,+                onPickContact = {},+                onPickOwner = {},+                onConnectHealth = { healthConnects++ },+            )+        }+        rule.onNodeWithText("Jamie Owner").performScrollTo().assertIsDisplayed()+        rule.onNodeWithText("Alex Rivera").performScrollTo().assertIsDisplayed()+        rule.onNodeWithText("Remove").performClick()+        assertTrue(actions.calls.contains("remove"))+        rule.onNodeWithText("Could not add that contact.").performScrollTo().performClick()+        assertTrue(actions.calls.contains("clearAddFail"))+        rule.onNodeWithText("Import from Health Connect").performScrollTo().performClick()+        assertEquals(1, healthConnects)+    }++    @Test+    fun `edit screen health connected and owner candidates dialog`() {+        val actions = RecordingEmergencyActions()+        val state = EmergencyUiState(+            loading = false,+            hasContactsAccess = true,+            info = EmergencyInfo(name = "Jamie Owner"),+            health = HealthConnectMedicalState(available = true, granted = true),+            ownerCandidates = OwnerPickCandidates(+                name = "Jamie Owner",+                addresses = listOf("1 Main St", "2 Oak Ave"),+            ),+        )+        rule.setContent {+            EditInfoScreen(+                state = state,+                actions = actions,+                onPickContact = {},+                onPickOwner = {},+            )+        }+        rule.onNodeWithText("2 Oak Ave").assertIsDisplayed()+        rule.onNodeWithText("2 Oak Ave").performClick()+        assertTrue(actions.calls.contains("confirm:2 Oak Ave"))+    }++    @Test+    fun `owner address dialog dismisses`() {+        var dismissed = false+        val confirmed = mutableListOf<String>()+        rule.setContent {+            OwnerAddressDialog(+                name = "Jamie",+                addresses = listOf("Only St"),+                onConfirm = { confirmed += it },+                onDismiss = { dismissed = true },+            )+        }+        rule.onNodeWithText("Only St").performClick()+        assertEquals(listOf("Only St"), confirmed)+        rule.onNodeWithText("Cancel").performClick()+        assertTrue(dismissed)+    }++    @Test+    fun `edit screen dropdowns save medical selections`() {+        val actions = RecordingEmergencyActions()+        rule.setContent {+            EditInfoScreen(+                state = EmergencyUiState(loading = false, hasContactsAccess = true),+                actions = actions,+                onPickContact = {},+                onPickOwner = {},+            )+        }+        // blood type dropdown: the section title and the row label both read+        // "Blood type"; the row (second node) is the dropdown trigger+        rule.onAllNodesWithText("Blood type")[1].performScrollTo().performClick()+        rule.onNodeWithText("A+").performClick()+        assertTrue(actions.calls.any { it.startsWith("save:A+/") })+        // organ donor dropdown: pick Yes (stored canonically as yes)+        rule.onAllNodesWithText("Organ donor")[1].performScrollTo().performClick()+        rule.onNodeWithText("Yes").performClick()+        assertTrue(actions.calls.any { it.endsWith("/yes") })+    }++    @Test+    fun `edit screen owner and loading rows respond`() {+        val actions = RecordingEmergencyActions()+        var ownerPicks = 0+        val stage = androidx.compose.runtime.mutableIntStateOf(0)+        rule.setContent {+            EditInfoScreen(+                state = if (stage.intValue == 0) {+                    EmergencyUiState(loading = true, hasContactsAccess = true)+                } else {+                    EmergencyUiState(+                        loading = false, hasContactsAccess = true,+                        info = EmergencyInfo(name = "Jamie Owner", address = "1 Main St"),+                    )+                },+                actions = actions,+                onPickContact = {},+                onPickOwner = { ownerPicks++ },+            )+        }+        rule.onNodeWithText("Loading contacts…").performScrollTo().assertIsDisplayed()+        rule.runOnIdle { stage.intValue = 1 }+        rule.onNodeWithText("Jamie Owner").performScrollTo().performClick()+        assertEquals(1, ownerPicks)+        rule.onNodeWithText("Choose your contact").performScrollTo().performClick()+        assertEquals(2, ownerPicks)+    }++    @Test+    fun `noop action objects are callable`() {+        EmergencyActions.Noop.saveMedicalInfo("A+", "yes")+        EmergencyActions.Noop.pickOwner(Uri.parse("content://x/1"))+        EmergencyActions.Noop.refresh()+        SosActions.Noop.cancel()+        SosActions.Noop.continueInBackground(1000)+        assertEquals("Alex Rivera", sampleContact().displayName)+        assertEquals(3, sampleHealthConnect().allergies.size)+    }+}