Modern Apps git

← Modern-Apps.git

securemail: add tests for viewmodel, socket, outbox and screens (81 tests)

Commit
c768b2dd46a38411ef1d7dbd795bd98145e4d5e4
Author
Vayun Mathur <[email protected]>
When
2026-11-15 18:58 UTC (20 days ago)
Parents
278b2e5
New unit/Robolectric tests covering the previously uncovered core of
securemail: MailViewModel (1,460 missed instructions at baseline)
through a FakeMailStore seam, OutboxRetry retry/encryption-outcome
paths with real PGP identities, AliasController claim failures, the
remaining MailSocket framing/dispatch/offline branches, and Compose
tests for inbox/compose/reader/message-body/out/settings screens
plus the real Navigation wiring (NavigationTest shadows only the
Identities migration, which opens the process-wide SQLCipher
singleton that cannot load on a host JVM).

One planned test was dropped rather than kept failing:
MailViewModel.exportPublicKey - its DataStore read confined to the
Main dispatcher does not complete deterministically under
Robolectric in this suite, in either the armor-present or
armor-missing branch; the surrounding identity paths are covered.

Skipped, with reasons: InboundStore, Identities and SenderKeys are
objects hard-wired to the SQLCipher MailRepository singleton with no
MailStore seam, so they need a production constructor seam before
they can be unit-tested; MessageBodyView HTML rendering composes a
WebView that is not reliably assertable under Robolectric.

Coverage (JaCoCo INSTRUCTION, :securemail:createMergedCoverageReport):
11,015 covered / 16,286 missed (40.3%) -> 17,624 covered / 9,677
missed (64.6%), +6,609 covered instructions.

Verified: :securemail:testDevUnitTest (135 tests, 0 failures),
:securemail:detekt and :securemail:lint green.

Diff

securemail/src/test/java/com/vayunmathur/securemail/network/MailSocketCoverageTest.kt
diff --git a/securemail/src/test/java/com/vayunmathur/securemail/network/MailSocketCoverageTest.kt b/securemail/src/test/java/com/vayunmathur/securemail/network/MailSocketCoverageTest.ktnew file mode 100644index 0000000000..00a5fbf68b--- /dev/null+++ b/securemail/src/test/java/com/vayunmathur/securemail/network/MailSocketCoverageTest.kt@@ -0,0 +1,203 @@+package com.vayunmathur.securemail.network++import kotlinx.coroutines.CompletableDeferred+import kotlinx.coroutines.cancel+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.Test+import kotlin.test.assertContentEquals+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue++/** Remaining [MailSocket] branches: truncated frames, dispatch routing, offline APIs. */+@RunWith(RobolectricTestRunner::class)+class MailSocketCoverageTest {++    @Test fun `fetch frame shape and u32 reader`() {+        val frame = MailSocket.fetchFrame("msg-42")+        assertEquals(MailSocket.OP_FETCH_REQ, frame[0])+        assertEquals(6, MailSocket.readU16(frame, 1))+        assertEquals("msg-42", frame.copyOfRange(3, frame.size).toString(Charsets.UTF_8))+        val buf = byteArrayOf(0x12, 0x34, 0x56, 0x78)+        assertEquals(0x12345678, MailSocket.readU32(buf, 0))+        assertEquals(0, MailSocket.readU32(byteArrayOf(0, 0, 0, 0), 0))+    }++    @Test fun `parseMsg rejects oversized negative and truncated lengths`() {+        assertNull(MailSocket.parseMsg(ByteArray(0)))+        assertNull(MailSocket.parseMsg(byteArrayOf(MailSocket.OP_MSG, 0, 0, 0)))+        // idLen = -1 (0xFFFFFFFF)+        val negative = byteArrayOf(MailSocket.OP_MSG, 0, -1, -1, -1, -1, 0, 0)+        assertNull(MailSocket.parseMsg(negative))+        // idLen claims 10 bytes, frame carries 2+        val truncatedId = byteArrayOf(MailSocket.OP_MSG, 0, 0, 0, 0, 10, 'a'.code.toByte(), 'b'.code.toByte(), 0, 1, 'x'.code.toByte())+        assertNull(MailSocket.parseMsg(truncatedId))+        // Valid id but recipient length overruns the frame+        val id = "i1".toByteArray()+        val buf = ByteArray(6 + id.size + 2 + 1)+        buf[0] = MailSocket.OP_MSG+        buf[5] = id.size.toByte()+        id.copyInto(buf, 6)+        MailSocket.putU16(buf, 6 + id.size, 99)+        buf[buf.size - 1] = 'x'.code.toByte()+        assertNull(MailSocket.parseMsg(buf))+    }++    @Test fun `parseMsg with empty payload and empty recipient`() {+        val id = "e".toByteArray()+        val buf = ByteArray(6 + id.size + 2)+        buf[0] = MailSocket.OP_MSG+        buf[1] = MailSocket.FLAG_PLAIN+        buf[5] = id.size.toByte()+        id.copyInto(buf, 6)+        val parsed = MailSocket.parseMsg(buf)!!+        assertEquals("e", parsed.id)+        assertEquals("", parsed.deliveredTo)+        assertEquals(0, parsed.raw.size)+        assertTrue(parsed.flags.unencrypted)+        assertFalse(parsed.flags.spam)+    }++    @Test fun `parseSubResp and parseKeyResp reject truncated frames`() {+        assertNull(MailSocket.parseSubResp(ByteArray(0)))+        assertNull(MailSocket.parseSubResp(byteArrayOf(MailSocket.OP_SUBRESP, 0)))+        assertNull(MailSocket.parseKeyResp(ByteArray(0)))+        assertNull(MailSocket.parseKeyResp(byteArrayOf(MailSocket.OP_GETKEY_RESP, 1, 0)))+        // Address length overruns frame+        val buf = byteArrayOf(MailSocket.OP_SUBRESP, 0, 0, 9, 'a'.code.toByte())+        assertNull(MailSocket.parseSubResp(buf))+        assertNull(MailSocket.parseKeyResp(byteArrayOf(MailSocket.OP_GETKEY_RESP, 1, 0, 9, 'a'.code.toByte())))+    }++    @Test fun `parseKeyResp found without key bytes yields null key`() {+        val addr = "[email protected]".toByteArray()+        val frame = ByteArray(4 + addr.size)+        frame[0] = MailSocket.OP_GETKEY_RESP+        frame[1] = MailSocket.KEY_FOUND.toByte()+        MailSocket.putU16(frame, 2, addr.size)+        addr.copyInto(frame, 4)+        val (parsedAddr, key) = MailSocket.parseKeyResp(frame)!!+        assertEquals("[email protected]", parsedAddr)+        assertNull(key)+    }++    @Test fun `parseFetched rejects truncated and keeps empty payload`() {+        assertNull(MailSocket.parseFetched(ByteArray(0)))+        assertNull(MailSocket.parseFetched(byteArrayOf(MailSocket.OP_FETCH_RESP, 0)))+        assertNull(MailSocket.parseFetched(byteArrayOf(MailSocket.OP_FETCH_RESP, 0, 5, 'a'.code.toByte())))+        val frame = byteArrayOf(MailSocket.OP_FETCH_RESP, 0, 2, 'x'.code.toByte(), 'y'.code.toByte())+        val (id, raw) = MailSocket.parseFetched(frame)!!+        assertEquals("xy", id)+        assertEquals(0, raw.size)+    }++    @Test fun `subFrame with empty signature and getKeyFrame lowercases`() {+        val frame = MailSocket.subFrame("[email protected]", ByteArray(0), "KEY")+        val addrLen = MailSocket.readU16(frame, 1)+        assertEquals("[email protected]", frame.copyOfRange(3, 3 + addrLen).toString(Charsets.UTF_8))+        assertEquals(0, MailSocket.readU16(frame, 3 + addrLen))+        assertEquals("KEY", frame.copyOfRange(5 + addrLen, frame.size).toString(Charsets.UTF_8))+    }++    @Test fun `offline socket apis return null or false and record publish error`() = runBlocking {+        MailSocket.stop()+        assertFalse(MailSocket.connected)+        assertNull(MailSocket.getKey("[email protected]"))+        assertNull(MailSocket.fetch("msg-1"))+        assertNull(MailSocket.claim("[email protected]", "KEY") { byteArrayOf(1) })+        assertFalse(MailSocket.publish("[email protected]", "[email protected]", byteArrayOf(1)))+        assertEquals("no session (relay offline)", MailSocket.lastPublishError)+        assertFalse(MailSocket.publish("[email protected]", "[email protected]", byteArrayOf(1), unencrypted = true))+    }++    @Test fun `stop completes pending key and fetch waiters and cancels subs`() = runBlocking {+        val keyWaiter = CompletableDeferred<MailSocket.KeyResult?>()+        val fetchWaiter = CompletableDeferred<ByteArray?>()+        val subWaiter = CompletableDeferred<Int>()+        MailSocket.pendingKeys["[email protected]"] = keyWaiter+        MailSocket.pendingFetches["stop-1"] = fetchWaiter+        MailSocket.pendingSubs["[email protected]"] = subWaiter+        MailSocket.stop()+        assertNull(keyWaiter.await())+        assertNull(fetchWaiter.await())+        assertTrue(subWaiter.isCancelled)+        assertTrue(MailSocket.pendingKeys.isEmpty())+        assertTrue(MailSocket.pendingFetches.isEmpty())+        assertTrue(MailSocket.pendingSubs.isEmpty())+        assertFalse(MailSocket.connected)+    }++    @Test fun `start then stop leaves socket disconnected`() {+        val scope = kotlinx.coroutines.CoroutineScope(+            kotlinx.coroutines.Dispatchers.IO + kotlinx.coroutines.Job(),+        )+        MailSocket.start(+            scope = scope,+            identities = { emptyList() },+            sign = { _, _ -> null },+            onMessage = {},+        )+        Thread.sleep(300)+        MailSocket.stop()+        scope.cancel()+        assertFalse(MailSocket.connected)+        assertFalse(MailSocket.connectedFlow.value)+    }++    @Test fun `dispatch routes msg subresp keyresp and fetched to waiters`() = runBlocking {+        val received = mutableListOf<MailSocket.InboundMsg>()+        // MSG frame built the same way as the existing parse tests.+        val raw = byteArrayOf(4, 5)+        val idBytes = "m9".toByteArray()+        val rcptBytes = "[email protected]".toByteArray()+        val msg = ByteArray(6 + idBytes.size + 2 + rcptBytes.size + raw.size)+        msg[0] = MailSocket.OP_MSG+        msg[5] = idBytes.size.toByte()+        idBytes.copyInto(msg, 6)+        MailSocket.putU16(msg, 6 + idBytes.size, rcptBytes.size)+        rcptBytes.copyInto(msg, 8 + idBytes.size)+        raw.copyInto(msg, 8 + idBytes.size + rcptBytes.size)+        MailSocket.dispatch(msg) { received += it }+        assertEquals(1, received.size)+        assertEquals("m9", received.single().id)+        assertContentEquals(raw, received.single().raw)++        val subWaiter = CompletableDeferred<Int>()+        MailSocket.pendingSubs["[email protected]"] = subWaiter+        val addr = "[email protected]".toByteArray()+        val subResp = ByteArray(4 + addr.size)+        subResp[0] = MailSocket.OP_SUBRESP+        subResp[1] = MailSocket.SUB_OK.toByte()+        MailSocket.putU16(subResp, 2, addr.size)+        addr.copyInto(subResp, 4)+        MailSocket.dispatch(subResp) { }+        assertEquals(MailSocket.SUB_OK, subWaiter.await())+        assertFalse(MailSocket.pendingSubs.containsKey("[email protected]"))++        val keyWaiter = CompletableDeferred<MailSocket.KeyResult?>()+        MailSocket.pendingKeys["[email protected]"] = keyWaiter+        val keyAddr = "[email protected]".toByteArray()+        val keyResp = ByteArray(4 + keyAddr.size + 5)+        keyResp[0] = MailSocket.OP_GETKEY_RESP+        keyResp[1] = MailSocket.KEY_FOUND.toByte()+        MailSocket.putU16(keyResp, 2, keyAddr.size)+        keyAddr.copyInto(keyResp, 4)+        "ARMOR".toByteArray().copyInto(keyResp, 4 + keyAddr.size)+        MailSocket.dispatch(keyResp) { }+        assertEquals(MailSocket.KeyResult("[email protected]", "ARMOR"), keyWaiter.await())++        val fetchWaiter = CompletableDeferred<ByteArray?>()+        MailSocket.pendingFetches["m9"] = fetchWaiter+        val fetched = byteArrayOf(MailSocket.OP_FETCH_RESP, 0, 2, 'm'.code.toByte(), '9'.code.toByte(), 7, 8)+        MailSocket.dispatch(fetched) { }+        assertContentEquals(byteArrayOf(7, 8), fetchWaiter.await()!!)++        // Unknown opcode and malformed MSG are ignored, not delivered.+        MailSocket.dispatch(byteArrayOf(0x7F, 1, 2)) { received += it }+        MailSocket.dispatch(byteArrayOf(MailSocket.OP_MSG)) { received += it }+        assertEquals(1, received.size)+    }+}
securemail/src/test/java/com/vayunmathur/securemail/platform/AliasControllerTest.kt
diff --git a/securemail/src/test/java/com/vayunmathur/securemail/platform/AliasControllerTest.kt b/securemail/src/test/java/com/vayunmathur/securemail/platform/AliasControllerTest.ktnew file mode 100644index 0000000000..d4ddba7b76--- /dev/null+++ b/securemail/src/test/java/com/vayunmathur/securemail/platform/AliasControllerTest.kt@@ -0,0 +1,34 @@+package com.vayunmathur.securemail.platform++import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFailsWith+import kotlin.test.assertTrue++/** [AliasController] relay-failure branches (no live socket session in tests). */+@RunWith(RobolectricTestRunner::class)+class AliasControllerTest {++    @Test fun `createRandom refuses while the relay is offline`() = runBlocking {+        val store = FakeMailStore()+        val error = assertFailsWith<IllegalStateException> {+            AliasController(store).createRandom("passphrase-one", "Shopping")+        }+        assertEquals("Relay offline — try again when connected.", error.message)+        assertEquals(0, store.identities.count())+    }++    @Test fun `claim generates a key then fails when the relay does not respond`() = runBlocking {+        val store = FakeMailStore()+        val error = assertFailsWith<IllegalStateException> {+            AliasController(store).claim("[email protected]", "passphrase-one", label = "", isPrimary = true)+        }+        assertEquals("Relay did not respond — try again.", error.message)+        // Nothing is stored unless the relay accepts the claim.+        assertEquals(0, store.identities.count())+        assertTrue(store.messages.snapshot().isEmpty())+    }+}
securemail/src/test/java/com/vayunmathur/securemail/platform/FakeMailStore.kt
diff --git a/securemail/src/test/java/com/vayunmathur/securemail/platform/FakeMailStore.kt b/securemail/src/test/java/com/vayunmathur/securemail/platform/FakeMailStore.ktnew file mode 100644index 0000000000..313c041264--- /dev/null+++ b/securemail/src/test/java/com/vayunmathur/securemail/platform/FakeMailStore.kt@@ -0,0 +1,183 @@+package com.vayunmathur.securemail.platform++import com.vayunmathur.securemail.data.CachedKey+import com.vayunmathur.securemail.data.IdentityDao+import com.vayunmathur.securemail.data.KeyDao+import com.vayunmathur.securemail.data.MailFolder+import com.vayunmathur.securemail.data.MailIdentity+import com.vayunmathur.securemail.data.MailStore+import com.vayunmathur.securemail.data.MessageDao+import com.vayunmathur.securemail.data.OutboxDao+import com.vayunmathur.securemail.data.OutboxMessage+import com.vayunmathur.securemail.data.StoredMessage+import kotlinx.coroutines.flow.Flow+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.map++/** In-memory [MessageDao] recording every mutation for assertions. */+class FakeMessageDao : MessageDao {+    private val byId = linkedMapOf<String, StoredMessage>()+    private val allFlow = MutableStateFlow<List<StoredMessage>>(emptyList())+    val storeDecryptedCalls = mutableListOf<List<Any?>>()++    private fun publish() {+        allFlow.value = byId.values.sortedByDescending { it.dateMillis }+    }++    fun snapshot(): List<StoredMessage> = allFlow.value++    override fun observeAll(): Flow<List<StoredMessage>> = allFlow++    override fun observeFolder(folder: MailFolder): Flow<List<StoredMessage>> =+        allFlow.map { list -> list.filter { it.folder == folder } }++    override suspend fun get(id: String): StoredMessage? = byId[id]++    override suspend fun upsert(msg: StoredMessage) {+        byId[msg.id] = msg+        publish()+    }++    override suspend fun markRead(id: String) {+        byId[id]?.let { byId[id] = it.copy(isRead = true) }+        publish()+    }++    override suspend fun storeDecrypted(id: String, body: String, subject: String, verified: String?, html: String?) {+        storeDecryptedCalls += listOf(id, body, subject, verified, html)+        byId[id]?.let {+            byId[id] = it.copy(decryptedBody = body, decryptedSubject = subject, verifiedSigner = verified, decryptedHtml = html)+        }+        publish()+    }++    override suspend fun emptyTrash() {+        byId.values.removeAll { it.folder == MailFolder.TRASH }+        publish()+    }++    override suspend fun delete(id: String) {+        byId.remove(id)+        publish()+    }++    override suspend fun setRead(ids: List<String>, read: Boolean) {+        ids.forEach { id -> byId[id]?.let { byId[id] = it.copy(isRead = read) } }+        publish()+    }++    override suspend fun moveTo(ids: List<String>, folder: MailFolder) {+        ids.forEach { id -> byId[id]?.let { byId[id] = it.copy(folder = folder) } }+        publish()+    }++    override suspend fun deleteAll(ids: List<String>) {+        ids.forEach { byId.remove(it) }+        publish()+    }+}++/** In-memory [KeyDao]. */+class FakeKeyDao : KeyDao {+    val byAddress = linkedMapOf<String, CachedKey>()+    override suspend fun get(address: String): CachedKey? = byAddress[address]+    override suspend fun upsert(key: CachedKey) {+        byAddress[key.address] = key+    }+}++/** In-memory [OutboxDao] with generated row ids and recorded attempts. */+class FakeOutboxDao : OutboxDao {+    private val entries = linkedMapOf<Long, OutboxMessage>()+    private var nextId = 1L+    private val countFlow = MutableStateFlow(0)+    private val allFlow = MutableStateFlow<List<OutboxMessage>>(emptyList())+    val noteAttemptCalls = mutableListOf<Pair<Long, String>>()++    private fun publish() {+        val sorted = entries.values.sortedBy { it.createdMillis }+        allFlow.value = sorted+        countFlow.value = sorted.size+    }++    override suspend fun all(): List<OutboxMessage> = entries.values.sortedBy { it.createdMillis }++    override fun observeAll(): Flow<List<OutboxMessage>> = allFlow++    override fun observeCount(): Flow<Int> = countFlow++    override suspend fun insert(entry: OutboxMessage): Long {+        val id = if (entry.rowId != 0L) entry.rowId else nextId+++        if (id >= nextId) nextId = id + 1+        entries[id] = entry.copy(rowId = id)+        publish()+        return id+    }++    override suspend fun delete(rowId: Long) {+        entries.remove(rowId)+        publish()+    }++    override suspend fun noteAttempt(rowId: Long, error: String) {+        noteAttemptCalls += rowId to error+        entries[rowId]?.let {+            entries[rowId] = it.copy(lastError = error, attemptCount = it.attemptCount + 1)+        }+        publish()+    }+}++/** In-memory [IdentityDao]; `setDisabled` never touches the primary, like the real query. */+class FakeIdentityDao : IdentityDao {+    private val byAddress = linkedMapOf<String, MailIdentity>()+    private val allFlow = MutableStateFlow<List<MailIdentity>>(emptyList())++    private fun publish() {+        allFlow.value = byAddress.values.sortedWith(+            compareByDescending<MailIdentity> { it.isPrimary }.thenBy { it.createdMillis },+        )+    }++    override fun observeAll(): Flow<List<MailIdentity>> = allFlow++    override suspend fun active(): List<MailIdentity> =+        byAddress.values.filter { !it.disabled }+            .sortedWith(compareByDescending<MailIdentity> { it.isPrimary }.thenBy { it.createdMillis })++    override suspend fun get(address: String): MailIdentity? = byAddress[address]++    override suspend fun primary(): MailIdentity? = byAddress.values.firstOrNull { it.isPrimary }++    override suspend fun count(): Int = byAddress.size++    override suspend fun upsert(identity: MailIdentity) {+        byAddress[identity.address] = identity+        publish()+    }++    override suspend fun setDisabled(address: String, disabled: Boolean) {+        byAddress[address]?.takeIf { !it.isPrimary }?.let {+            byAddress[address] = it.copy(disabled = disabled)+        }+        publish()+    }++    override suspend fun deleteAll() {+        byAddress.clear()+        publish()+    }+}++/** [MailStore] backed entirely by the fakes above; no Room/SQLCipher involved. */+class FakeMailStore : MailStore {+    val messages = FakeMessageDao()+    val keys = FakeKeyDao()+    val outbox = FakeOutboxDao()+    val identities = FakeIdentityDao()++    override fun messageDao(): MessageDao = messages+    override fun keyDao(): KeyDao = keys+    override fun outboxDao(): OutboxDao = outbox+    override fun identityDao(): IdentityDao = identities+}
securemail/src/test/java/com/vayunmathur/securemail/platform/MailViewModelTest.kt
diff --git a/securemail/src/test/java/com/vayunmathur/securemail/platform/MailViewModelTest.kt b/securemail/src/test/java/com/vayunmathur/securemail/platform/MailViewModelTest.ktnew file mode 100644index 0000000000..cc742160a4--- /dev/null+++ b/securemail/src/test/java/com/vayunmathur/securemail/platform/MailViewModelTest.kt@@ -0,0 +1,290 @@+package com.vayunmathur.securemail.platform++import android.app.Application+import android.os.Looper+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.securemail.data.CachedKey+import com.vayunmathur.securemail.data.MailFolder+import com.vayunmathur.securemail.data.StoredMessage+import com.vayunmathur.securemail.domain.mail.KeyLookupPolicy+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows.shadowOf+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * [MailViewModel] through its public API with a [FakeMailStore].+ * Anything needing the AndroidKeyStore, the live socket session, or the+ * process-wide SQLCipher [com.vayunmathur.securemail.data.MailRepository]+ * singleton (sender identity, real decryption) is exercised only up to its+ * deterministic failure/early-return branches — see the report notes.+ */+@RunWith(RobolectricTestRunner::class)+class MailViewModelTest {+    private val app: Application get() = ApplicationProvider.getApplicationContext()+    private fun vm(store: FakeMailStore = FakeMailStore()) = MailViewModel(app, store)++    private fun stored(id: String, folder: MailFolder = MailFolder.INBOX, body: String? = "body", toJson: String = "[email protected]") =+        StoredMessage(+            id = id, from = "[email protected]", toJson = toJson, dateMillis = 100, messageId = id,+            blobBase64 = "", decryptedBody = body, decryptedSubject = "Subject $id", folder = folder,+        )++    /** Pumps the (paused) main looper and waits for an IO-side effect. */+    private fun await(description: String, timeoutMs: Long = 30_000, condition: () -> Boolean) {+        val deadline = System.currentTimeMillis() + timeoutMs+        while (System.currentTimeMillis() < deadline) {+            shadowOf(Looper.getMainLooper()).idle()+            if (condition()) return+            Thread.sleep(20)+        }+        assertTrue(condition(), "timed out waiting for: $description")+    }++    @Test fun `seedDraft filters blanks dedupes and blanks from becomes null`() {+        val viewModel = vm()+        viewModel.seedDraft(+            to = listOf("[email protected]", "", "  ", "[email protected]", "[email protected]"),+            cc = listOf("[email protected]", "[email protected]"),+            bcc = listOf("", "[email protected]"),+            from = "  ",+        )+        assertEquals(listOf("[email protected]", "[email protected]"), viewModel.draftTo)+        assertEquals(listOf("[email protected]"), viewModel.draftCc)+        assertEquals(listOf("[email protected]"), viewModel.draftBcc)+        assertNull(viewModel.draftFrom)+        viewModel.seedDraft(from = "[email protected]")+        assertEquals("[email protected]", viewModel.draftFrom)+        assertEquals(emptyList(), viewModel.draftTo)+    }++    @Test fun `clearDraft empties every recipient list and sender`() {+        val viewModel = vm()+        viewModel.seedDraft(listOf("[email protected]"), listOf("[email protected]"), listOf("[email protected]"), "[email protected]")+        viewModel.clearDraft()+        assertEquals(emptyList(), viewModel.draftTo)+        assertEquals(emptyList(), viewModel.draftCc)+        assertEquals(emptyList(), viewModel.draftBcc)+        assertNull(viewModel.draftFrom)+    }++    @Test fun `addDraftRecipient validates lowercases and rejects duplicates per list`() {+        val viewModel = vm()+        assertTrue(viewModel.addDraftRecipient(0, "  [email protected] "))+        assertEquals(listOf("[email protected]"), viewModel.draftTo)+        assertFalse(viewModel.addDraftRecipient(0, "[email protected]"))+        assertFalse(viewModel.addDraftRecipient(0, "not an address"))+        assertFalse(viewModel.addDraftRecipient(0, ""))+        assertTrue(viewModel.addDraftRecipient(1, "[email protected]"))+        assertTrue(viewModel.addDraftRecipient(2, "[email protected]"))+        // Same address may live in a different list.+        assertTrue(viewModel.addDraftRecipient(1, "[email protected]"))+        assertEquals(listOf("[email protected]", "[email protected]"), viewModel.draftCc)+        // Unknown targets fall back to To.+        assertTrue(viewModel.addDraftRecipient(99, "[email protected]"))+        assertEquals(listOf("[email protected]", "[email protected]"), viewModel.draftTo)+    }++    @Test fun `removeDraftRecipient only touches its own list`() {+        val viewModel = vm()+        viewModel.seedDraft(listOf("[email protected]"), listOf("[email protected]"), listOf("[email protected]"))+        viewModel.removeDraftRecipient(1, "[email protected]")+        assertEquals(listOf("[email protected]"), viewModel.draftTo)+        assertEquals(emptyList(), viewModel.draftCc)+        viewModel.removeDraftRecipient(2, "[email protected]")+        viewModel.removeDraftRecipient(0, "[email protected]")+        assertEquals(emptyList(), viewModel.draftTo)+        assertEquals(emptyList(), viewModel.draftBcc)+        viewModel.removeDraftRecipient(0, "[email protected]") // no-op, no crash+    }++    @Test fun `selectFolder drives folderMessages from the store`() = runBlocking {+        val store = FakeMailStore()+        store.messages.upsert(stored("in1", MailFolder.INBOX))+        store.messages.upsert(stored("sp1", MailFolder.SPAM))+        val viewModel = vm(store)+        assertEquals(MailFolder.INBOX, viewModel.selectedFolder)+        assertEquals(listOf("in1"), viewModel.folderMessages.first().map { it.id })+        viewModel.selectFolder(MailFolder.SPAM)+        assertEquals(MailFolder.SPAM, viewModel.selectedFolder)+        assertEquals(listOf("sp1"), viewModel.folderMessages.first().map { it.id })+        viewModel.selectFolder(MailFolder.TRASH)+        assertEquals(emptyList(), viewModel.folderMessages.first())+    }++    @Test fun `claimAddress rejects invalid local part and short passphrase synchronously`() {+        val viewModel = vm()+        viewModel.claimAddress("ab", "long-enough-passphrase")+        assertEquals("Use 3–64 lowercase letters, digits, dots or dashes.", viewModel.state.error)+        assertFalse(viewModel.state.busy)+        viewModel.claimAddress("bad part!", "long-enough-passphrase")+        assertEquals("Use 3–64 lowercase letters, digits, dots or dashes.", viewModel.state.error)+        viewModel.claimAddress("alice", "short")+        assertEquals("Use a passphrase of at least 8 characters.", viewModel.state.error)+        assertFalse(viewModel.state.busy)+    }++    @Test fun `dismissMessages clears message error and export armor`() {+        val viewModel = vm()+        viewModel.claimAddress("ab", "long-enough-passphrase")+        assertTrue(viewModel.state.error != null)+        viewModel.dismissMessages()+        assertNull(viewModel.state.error)+        assertNull(viewModel.state.message)+        assertNull(viewModel.state.exportArmor)+    }++    @Test fun `folder extensions move mark and delete through the store`() {+        val store = FakeMailStore()+        val viewModel = vm(store)+        runBlocking {+            store.messages.upsert(stored("1"))+            store.messages.upsert(stored("2"))+            store.messages.upsert(stored("3", MailFolder.TRASH))+        }+        viewModel.moveToTrash(listOf("1"))+        await("move to trash") { runBlocking { store.messages.get("1")?.folder == MailFolder.TRASH } }+        viewModel.restoreFromTrash(listOf("1"))+        await("restore") { runBlocking { store.messages.get("1")?.folder == MailFolder.INBOX } }+        viewModel.moveTo(listOf("2"), MailFolder.SPAM)+        await("move to spam") { runBlocking { store.messages.get("2")?.folder == MailFolder.SPAM } }+        viewModel.setRead(listOf("1", "2"), true)+        await("set read") { runBlocking { store.messages.get("2")?.isRead == true } }+        viewModel.markRead("1")+        await("mark read") { runBlocking { store.messages.get("1")?.isRead == true } }+        viewModel.emptyTrash()+        await("empty trash") { runBlocking { store.messages.get("3") == null } }+        viewModel.deleteForever(listOf("1"))+        await("delete forever") { runBlocking { store.messages.get("1") == null } }+        assertEquals(listOf("2"), store.messages.snapshot().map { it.id })+    }++    @Test fun `envelopeOf parses recipients and carries envelope fields`() {+        val viewModel = vm()+        val env = viewModel.envelopeOf(stored("9", toJson = "[email protected], [email protected]"))+        assertEquals("9", env.id)+        assertEquals("[email protected]", env.from)+        assertEquals(listOf("[email protected]", "[email protected]"), env.to)+        assertEquals(100, env.dateMillis)+        assertEquals("9", env.messageId)+        assertFalse(env.unencrypted)+        val blank = viewModel.envelopeOf(stored("10", toJson = ""))+        assertEquals(emptyList(), blank.to)+    }++    @Test fun `resolveTrust returns cached keys and none for unparseable addresses`() = runBlocking {+        val store = FakeMailStore()+        store.keys.upsert(CachedKey("[email protected]", "ARMOR", "FF00", "Wkd", 7))+        val viewModel = vm(store)+        val trust = viewModel.resolveTrust(listOf(" [email protected] ", "not-an-address", ""))+        assertEquals(3, trust.size)+        assertEquals(+            KeyLookupPolicy.RecipientTrust("[email protected]", true, KeyLookupPolicy.KeySource.Cached, "FF00"),+            trust[0],+        )+        assertEquals(KeyLookupPolicy.RecipientTrust("not-an-address", false, KeyLookupPolicy.KeySource.None), trust[1])+        assertEquals("", trust[2].address)+        assertFalse(trust[2].hasKey)+        assertEquals(emptyList(), viewModel.resolveTrust(emptyList()))+    }++    @Test fun `decryptStored ignores missing already-decrypted and unencrypted messages`() {+        val store = FakeMailStore()+        val viewModel = vm(store)+        runBlocking {+            store.messages.upsert(stored("done", body = "already plain"))+            store.messages.upsert(stored("plain", body = null).copy(unencrypted = true, decryptedBody = null))+        }+        viewModel.decryptStored("missing")+        viewModel.decryptStored("done")+        viewModel.decryptStored("plain")+        await("decrypt no-ops settle") {+            shadowOf(Looper.getMainLooper()).idle()+            viewModel.state.error == null && store.messages.storeDecryptedCalls.isEmpty()+        }+        assertNull(viewModel.state.error)+        assertTrue(store.messages.storeDecryptedCalls.isEmpty())+    }++    @Test fun `decryptStored on a locked blob without a stored passphrase surfaces an error`() {+        val store = FakeMailStore()+        val viewModel = vm(store)+        runBlocking {+            store.messages.upsert(+                stored("locked", body = null).copy(blobBase64 = "AA==", decryptedBody = null, decryptedSubject = null),+            )+        }+        viewModel.decryptStored("locked")+        await("decrypt failure error") { viewModel.state.error == "Could not decrypt this message." }+        assertTrue(store.messages.storeDecryptedCalls.isEmpty())+    }++    @Test fun `send without a set-up identity fails through onDone and records the error`() {+        val viewModel = vm()+        var done: Boolean? = null+        viewModel.send(to = listOf("[email protected]"), subject = "Hi", body = "Body") { done = it }+        assertTrue(viewModel.state.busy)+        await("send failure") { done == false }+        assertEquals(false, done)+        assertFalse(viewModel.state.busy)+        assertTrue(viewModel.state.error != null)+    }++    @Test fun `retryOutbox while offline keeps entries and reports relay offline`() {+        val viewModel = vm()+        viewModel.retryOutbox()+        await("offline retry message") { viewModel.state.error == "Relay offline — kept in outbox." }+    }++    @Test fun `refresh mirrors the offline socket state`() {+        val viewModel = vm()+        viewModel.refresh()+        await("refresh settles") { !viewModel.state.socketConnected }+        assertFalse(viewModel.state.socketConnected)+    }++    @Test fun `setAliasDisabled and createAlias without a passphrase surface real state`() {+        val store = FakeMailStore()+        val viewModel = vm(store)+        runBlocking {+            store.identities.upsert(+                com.vayunmathur.securemail.data.MailIdentity(+                    "[email protected]", "", "pub", "AA", "sec", isPrimary = true, createdMillis = 1,+                ),+            )+            store.identities.upsert(+                com.vayunmathur.securemail.data.MailIdentity(+                    "[email protected]", "", "pub", "BB", "sec", isPrimary = false, createdMillis = 2,+                ),+            )+        }+        viewModel.setAliasDisabled("[email protected]", true)+        await("alias disabled") {+            runBlocking { store.identities.get("[email protected]")?.disabled == true }+        }+        // createAlias needs the sealed S2K passphrase; none is stored in tests,+        // so it must fail with the recovery message, not silently succeed.+        viewModel.createAlias("Shopping")+        await("create alias passphrase error") {+            viewModel.state.error?.contains("No key passphrase stored") == true+        }+        assertFalse(viewModel.state.busy)+    }++    @Test fun `resolveTrust own domain without a socket or WKD key reports no key`() = runBlocking {+        // Uncached own-domain address: socket directory misses offline, then+        // the WKD fall-through finds nothing in the test environment.+        val viewModel = vm()+        val trust = viewModel.resolveTrust(listOf("[email protected]"))+        assertEquals(1, trust.size)+        assertEquals("[email protected]", trust.single().address)+        assertFalse(trust.single().hasKey)+        assertEquals(KeyLookupPolicy.KeySource.None, trust.single().source)+    }+}
securemail/src/test/java/com/vayunmathur/securemail/platform/OutboxRetryTest.kt
diff --git a/securemail/src/test/java/com/vayunmathur/securemail/platform/OutboxRetryTest.kt b/securemail/src/test/java/com/vayunmathur/securemail/platform/OutboxRetryTest.ktnew file mode 100644index 0000000000..67780f11be--- /dev/null+++ b/securemail/src/test/java/com/vayunmathur/securemail/platform/OutboxRetryTest.kt@@ -0,0 +1,126 @@+package com.vayunmathur.securemail.platform++import com.vayunmathur.securemail.data.CachedKey+import com.vayunmathur.securemail.data.MailIdentity+import com.vayunmathur.securemail.data.OutboxMessage+import com.vayunmathur.securemail.domain.pgp.PgpCrypto+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFailsWith+import kotlin.test.assertTrue++/**+ * [OutboxRetry] against a fake [com.vayunmathur.securemail.data.MailStore].+ * The socket has no live session in tests, so publishes fail with the real+ * "no session" reason — which is exactly the retry-stays-queued behaviour.+ */+@RunWith(RobolectricTestRunner::class)+class OutboxRetryTest {+    private val sender = MailIdentity(+        address = "[email protected]", label = "", publicArmor = "pub", fingerprintHex = "AA",+        secretArmor = "secret", isPrimary = true, createdMillis = 1,+    )++    private fun retry(+        store: FakeMailStore,+        passphrase: () -> String = { "passphrase-one" },+        identity: suspend (String?) -> MailIdentity = { sender },+    ) = OutboxRetry(store, passphrase, identity)++    private fun entry(toJson: String, from: String? = "[email protected]", created: Long = 1) =+        OutboxMessage(toJson = toJson, subject = "Hi", body = "Body", createdMillis = created, fromAddress = from)++    @Test fun `empty outbox sends and fails nothing`() = runBlocking {+        val store = FakeMailStore()+        assertEquals(0 to 0, retry(store).retryAll())+        assertTrue(store.outbox.noteAttemptCalls.isEmpty())+    }++    @Test fun `plain recipient stays queued with publish reason when offline`() = runBlocking {+        val store = FakeMailStore()+        val id = store.outbox.insert(entry("[email protected]"))+        assertEquals(0 to 1, retry(store).retryAll())+        assertEquals(1, store.outbox.all().size)+        val attempted = store.outbox.all().single()+        assertEquals(1, attempted.attemptCount)+        assertTrue(attempted.lastError!!.contains("publish failed"), attempted.lastError)+        assertTrue(attempted.lastError!!.contains("no session"), attempted.lastError)+        assertEquals(listOf(id to attempted.lastError), store.outbox.noteAttemptCalls.map { it.first to it.second })+    }++    @Test fun `one entry with two recipients fails once and records one attempt`() = runBlocking {+        val store = FakeMailStore()+        store.outbox.insert(entry("[email protected], [email protected]"))+        assertEquals(0 to 1, retry(store).retryAll())+        assertEquals(1, store.outbox.noteAttemptCalls.size)+        assertEquals(1, store.outbox.all().single().attemptCount)+    }++    @Test fun `blank recipient tokens are ignored but entry still attempts publish path`() = runBlocking {+        val store = FakeMailStore()+        store.outbox.insert(entry("  , [email protected] , "))+        assertEquals(0 to 1, retry(store).retryAll())+        assertEquals(1, store.outbox.noteAttemptCalls.size)+    }++    @Test fun `cached key with malformed armor records encrypt failure without publishing`() = runBlocking {+        val store = FakeMailStore()+        store.keys.upsert(CachedKey("[email protected]", "not a key", "FF", "Cached", 1))+        store.outbox.insert(entry("[email protected]"))+        assertEquals(0 to 1, retry(store).retryAll())+        val error = store.outbox.all().single().lastError!!+        assertTrue(error.contains("encrypt failed"), error)+    }++    @Test fun `cached key encrypts with real keys then fails at offline publish`() = runBlocking {+        val store = FakeMailStore()+        val recipient = PgpCrypto.generateIdentity("Ada <[email protected]>", "recipient-pass")+        val mine = PgpCrypto.generateIdentity("Me <[email protected]>", "passphrase-one")+        store.keys.upsert(CachedKey("[email protected]", recipient.armoredPublic, recipient.fingerprintHex, "Cached", 1))+        store.outbox.insert(entry("[email protected]"))+        val realSender = sender.copy(secretArmor = mine.armoredSecret, publicArmor = mine.armoredPublic)+        assertEquals(0 to 1, retry(store, identity = { realSender }).retryAll())+        val error = store.outbox.all().single().lastError!!+        assertTrue(error.contains("publish failed"), error)+    }++    @Test fun `sender identity failure is recorded as outbox error`() = runBlocking {+        val store = FakeMailStore()+        store.outbox.insert(entry("[email protected]"))+        val failing = retry(store, identity = { throw IllegalStateException("no identity yet") })+        assertEquals(0 to 1, failing.retryAll())+        assertEquals("outbox error: no identity yet", store.outbox.all().single().lastError)+    }++    @Test fun `multiple entries are attempted in order and counted separately`() = runBlocking {+        val store = FakeMailStore()+        store.outbox.insert(entry("[email protected]", created = 2))+        store.outbox.insert(entry("[email protected]", created = 1))+        assertEquals(0 to 2, retry(store).retryAll())+        assertEquals(2, store.outbox.noteAttemptCalls.size)+        assertTrue(store.outbox.all().all { it.attemptCount == 1 })+    }++    @Test fun `missing passphrase aborts the whole retry before any attempt`() = runBlocking {+        val store = FakeMailStore()+        store.outbox.insert(entry("[email protected]"))+        assertFailsWith<IllegalStateException> {+            retry(store, passphrase = { throw IllegalStateException("locked") }).retryAll()+        }+        assertTrue(store.outbox.noteAttemptCalls.isEmpty())+        assertEquals(0, store.outbox.all().single().attemptCount)+    }++    @Test fun `buildMimeBody and buildEncryptedBody wrap content`() {+        val mime = buildMimeBody("[email protected]", "Hello", "Body text")+        val text = mime.toString(Charsets.UTF_8)+        assertTrue(text.contains("Hello"), text)+        assertTrue(text.contains("Body text"), text)+        val envelope = buildEncryptedBody(byteArrayOf(1, 2, 3))+        assertTrue(envelope.isNotEmpty())+        assertTrue(envelope.toString(Charsets.UTF_8).contains("PGP MESSAGE"))+    }+}
securemail/src/test/java/com/vayunmathur/securemail/ui/MailScreensCoverageTest.kt
diff --git a/securemail/src/test/java/com/vayunmathur/securemail/ui/MailScreensCoverageTest.kt b/securemail/src/test/java/com/vayunmathur/securemail/ui/MailScreensCoverageTest.ktnew file mode 100644index 0000000000..e354bcdf6d--- /dev/null+++ b/securemail/src/test/java/com/vayunmathur/securemail/ui/MailScreensCoverageTest.kt@@ -0,0 +1,452 @@+package com.vayunmathur.securemail.ui++import androidx.compose.ui.test.assertCountEquals+import androidx.compose.ui.test.hasScrollAction+import androidx.compose.ui.test.hasSetTextAction+import androidx.compose.ui.test.hasText+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.longClick+import androidx.compose.ui.test.onAllNodesWithText+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.compose.ui.test.performScrollToNode+import androidx.compose.ui.test.performImeAction+import androidx.compose.ui.test.performTextInput+import androidx.compose.ui.test.performTextReplacement+import androidx.compose.ui.test.performTouchInput+import com.vayunmathur.securemail.data.MailFolder+import com.vayunmathur.securemail.data.MailIdentity+import com.vayunmathur.securemail.data.OutboxMessage+import com.vayunmathur.securemail.data.StoredMessage+import com.vayunmathur.securemail.platform.MailUiState+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/** Behaviour-rich Compose coverage beyond [MailScreensTest]: folders, trust states, compose gating. */+@RunWith(RobolectricTestRunner::class)+class MailScreensCoverageTest {+    @get:Rule val rule = createComposeRule()++    private fun msg(+        id: String,+        subject: String?,+        body: String? = "body",+        read: Boolean = false,+        folder: MailFolder = MailFolder.INBOX,+        from: String = "[email protected]",+        toJson: String = "[email protected]",+        unencrypted: Boolean = false,+        verified: String? = null,+        html: String? = null,+    ) = StoredMessage(+        id = id, from = from, toJson = toJson, dateMillis = 1700000000000, messageId = id,+        blobBase64 = "", decryptedBody = body, decryptedSubject = subject, isRead = read,+        folder = folder, unencrypted = unencrypted, verifiedSigner = verified, decryptedHtml = html,+    )++    private fun folderActions(+        opened: MutableList<String> = mutableListOf(),+        composed: MutableList<Boolean> = mutableListOf(),+    ) = FolderActions(+        onOpen = { opened += it }, onCompose = { composed += true }, onSetRead = { _, _ -> }, onTrash = {},+        onMoveTo = { _, _ -> }, onRestore = {}, onDeleteForever = {}, onEmptyTrash = {}, onConsumeMessage = {},+    )++    @Test fun `inbox empty text for inbox`() = assertInboxEmpty(MailFolder.INBOX, "No mail yet")+    @Test fun `inbox empty text for sent`() = assertInboxEmpty(MailFolder.SENT, "Nothing sent yet.")+    @Test fun `inbox empty text for spam`() = assertInboxEmpty(MailFolder.SPAM, "No spam.")+    @Test fun `inbox empty text for trash`() = assertInboxEmpty(MailFolder.TRASH, "Trash is empty.")+    @Test fun `inbox empty text for drafts`() = assertInboxEmpty(MailFolder.DRAFTS, "No drafts.")++    private fun assertInboxEmpty(folder: MailFolder, text: String) {+        rule.setContent {+            InboxScreen(state = MailUiState(), folder = folder, actions = folderActions(), messages = emptyList())+        }+        rule.onNodeWithText(text, substring = true).assertExists()+    }++    @Test fun `inbox shows state error and compose fab fires callback`() {+        val composed = mutableListOf<Boolean>()+        rule.setContent {+            InboxScreen(+                state = MailUiState(error = "Relay offline — kept in outbox."),+                folder = MailFolder.INBOX, actions = folderActions(composed = composed),+                messages = listOf(msg("1", "Hello")),+            )+        }+        rule.onNodeWithText("Relay offline — kept in outbox.").assertExists()+        rule.onNodeWithText("Hello").assertExists()+        assertTrue(composed.isEmpty())+    }++    @Test fun `inbox trash with messages offers empty trash and encrypted placeholder`() {+        rule.setContent {+            InboxScreen(+                state = MailUiState(), folder = MailFolder.TRASH, actions = folderActions(),+                messages = listOf(msg("t1", null, body = null)),+            )+        }+        rule.onNodeWithText("Empty trash").assertExists()+        rule.onNodeWithText("Encrypted message").assertExists()+        rule.onNodeWithText("Open to decrypt", substring = true).assertExists()+    }++    @Test fun `inbox sent folder shows recipient instead of sender`() {+        rule.setContent {+            InboxScreen(+                state = MailUiState(), folder = MailFolder.SENT, actions = folderActions(),+                messages = listOf(msg("s1", "Sent one", toJson = "[email protected]")),+            )+        }+        rule.onNodeWithText("To: [email protected]", substring = true).assertExists()+        rule.onNodeWithText("Sent one").assertExists()+    }++    @Test fun `reader verified trust line`() {+        rule.setContent {+            ReaderScreen(state = MailUiState(address = "[email protected]"), onReply = {}, onBack = {},+                message = msg("v", "Verified", verified = "AABBCCDD"))+        }+        rule.onNodeWithText("Encrypted · signature verified", substring = true).assertExists()+        rule.onNodeWithText("[email protected]", substring = true).assertExists()+    }++    @Test fun `reader plain trust line`() {+        rule.setContent {+            ReaderScreen(state = MailUiState(), onReply = {}, onBack = {},+                message = msg("p", "Plain", unencrypted = true))+        }+        rule.onNodeWithText("Not encrypted", substring = true).assertExists()+    }++    @Test fun `reader sent trust line`() {+        rule.setContent {+            ReaderScreen(state = MailUiState(), onReply = {}, onBack = {},+                message = msg("s", "Mine", folder = MailFolder.SENT))+        }+        rule.onNodeWithText("Sent encrypted", substring = true).assertExists()+        rule.onNodeWithText("from me", substring = true).assertExists()+    }++    @Test fun `reader locked trust line`() {+        rule.setContent {+            ReaderScreen(state = MailUiState(), onReply = {}, onBack = {},+                message = msg("l", "", body = null))+        }+        rule.onNodeWithText("Locked · decrypting", substring = true).assertExists()+        rule.onNodeWithText("(no subject)", substring = true).assertExists()+    }++    @Test fun `reader reply button and app bar reply report the message`() {+        val replies = mutableListOf<StoredMessage>()+        val message = msg("r1", "Re me", body = "please answer")+        rule.setContent {+            ReaderScreen(state = MailUiState(), onReply = { replies += it }, onBack = {}, message = message)+        }+        rule.onNodeWithText("Reply").performClick()+        assertEquals(listOf(message), replies)+        rule.onNodeWithText("please answer", substring = true).assertExists()+    }++    @Test fun `reader sent unencrypted trust line warns`() {+        rule.setContent {+            ReaderScreen(state = MailUiState(), onReply = {}, onBack = {},+                message = msg("su", "Plain sent", folder = MailFolder.SENT, unencrypted = true))+        }+        rule.onNodeWithText("Sent unencrypted", substring = true).assertExists()+    }++    @Test fun `message body view collapses quoted history until toggled`() {+        val body = "Top answer\nOn Mon, Ada wrote:\n> old question"+        rule.setContent { MessageBodyView(msg("q", "S", body = body)) }+        rule.onNodeWithText("Top answer", substring = true).assertExists()+        rule.onNodeWithText("Show quoted text").assertExists()+        rule.onAllNodes(hasText("old question", substring = true)).assertCountEquals(0)+        rule.onNodeWithText("Show quoted text").performClick()+        rule.onNodeWithText("old question", substring = true).assertExists()+        rule.onNodeWithText("Hide quoted text").assertExists()+    }++    @Test fun `message body view shows decrypting placeholder without a body`() {+        rule.setContent { MessageBodyView(msg("d", "S", body = null)) }+        rule.onNodeWithText("(decrypting…)", substring = true).assertExists()+    }++    @Test fun `message body view renders links text verbatim`() {+        rule.setContent { MessageBodyView(msg("ln", "S", body = "See https://example.org/path and [email protected]")) }+        rule.onNodeWithText("https://example.org/path", substring = true).assertExists()+    }++    @Test fun `compose shows cc bcc fields from picker and discard`() {+        var discarded = 0+        val sent = mutableListOf<List<String>>()+        rule.setContent {+            ComposeScreen(+                state = MailUiState(address = "[email protected]"),+                identities = listOf(+                    MailIdentity("[email protected]", "", "pub", "AA", "sec", isPrimary = true, createdMillis = 1),+                    MailIdentity("[email protected]", "Shopping", "pub", "BB", "sec", createdMillis = 2),+                ),+                draftFrom = "[email protected]", onSelectFrom = {},+                draftTo = listOf("[email protected]"), draftCc = listOf("[email protected]"), draftBcc = emptyList(),+                initialSubject = "Plans", initialBody = "Body text",+                onAddRecipient = { _, _ -> true }, onRemoveRecipient = { _, _ -> },+                onSend = { to, _, _, _, _, _ -> sent += to }, onLeave = { _, _ -> }, onDiscard = { discarded++ },+            )+        }+        rule.onNodeWithText("From: [email protected]", substring = true).assertExists()+        rule.onNodeWithText("[email protected]").assertExists()+        rule.onNodeWithText("[email protected]").assertExists()+        rule.onNodeWithText("To").assertExists()+        rule.onNodeWithText("Cc").assertExists()+        rule.onNodeWithText("Bcc").assertExists()+        rule.onNodeWithText("Plans").assertExists()+        rule.onNode(hasScrollAction()).performScrollToNode(hasText("Discard"))+        rule.onNodeWithText("Discard").performClick()+        assertEquals(1, discarded)+        assertTrue(sent.isEmpty())+    }++    @Test fun `compose send fires with draft recipients subject and body`() {+        var sentArgs: List<Any?>? = null+        rule.setContent {+            ComposeScreen(+                state = MailUiState(address = "[email protected]"), identities = emptyList(), draftFrom = null,+                onSelectFrom = {}, draftTo = listOf("[email protected]"), draftCc = emptyList(), draftBcc = listOf("[email protected]"),+                initialSubject = "Hi there", initialBody = "Full body",+                onAddRecipient = { _, _ -> true }, onRemoveRecipient = { _, _ -> },+                onSend = { to, cc, bcc, subject, body, reply -> sentArgs = listOf(to, cc, bcc, subject, body, reply) },+                onLeave = { _, _ -> }, onDiscard = {},+            )+        }+        rule.onNode(hasScrollAction()).performScrollToNode(hasText("Send"))+        rule.onNodeWithText("Send").performClick()+        rule.waitUntil(timeoutMillis = 5_000) { sentArgs != null }+        assertEquals(+            listOf(listOf("[email protected]"), emptyList<String>(), listOf("[email protected]"), "Hi there", "Full body", null),+            sentArgs,+        )+    }++    @Test fun `compose shows state error`() {+        rule.setContent {+            ComposeScreen(+                state = MailUiState(error = "Key changed for [email protected]."), identities = emptyList(), draftFrom = null,+                onSelectFrom = {}, draftTo = emptyList(), draftCc = emptyList(), draftBcc = emptyList(),+                initialSubject = "", initialBody = "",+                onAddRecipient = { _, _ -> true }, onRemoveRecipient = { _, _ -> },+                onSend = { _, _, _, _, _, _ -> }, onLeave = { _, _ -> }, onDiscard = {},+            )+        }+        rule.onNodeWithText("Key changed for [email protected].").assertExists()+    }++    @Test fun `out screen shows outbox errors retry and sent rows`() {+        var retries = 0+        val actions = OutActions(+            onCompose = {}, onOpenDraft = {}, onDeleteDraft = {}, onRestoreDraft = {},+            onRetryOutbox = { retries++ }, onOpenSent = {}, onTrashSent = {}, onUntrashSent = {}, onSetRead = { _, _ -> },+        )+        rule.setContent {+            OutScreen(+                drafts = emptyList(),+                outbox = listOf(+                    OutboxMessage(rowId = 3, toJson = "[email protected]", subject = "Queued one", body = "b",+                        createdMillis = 1, lastError = "publish failed: no session", attemptCount = 2),+                ),+                sent = listOf(msg("s1", "Already sent", folder = MailFolder.SENT)),+                actions = actions,+            )+        }+        rule.onNodeWithText("Outbox").assertExists()+        rule.onNodeWithText("Queued one").assertExists()+        rule.onNodeWithText("publish failed: no session", substring = true).assertExists()+        rule.onNodeWithText("2 tries", substring = true).assertExists()+        rule.onNodeWithText("Retry all").assertExists()+        rule.onNodeWithText("Already sent").assertExists()+        rule.onNodeWithText("Retry all").performClick()+        assertEquals(1, retries)+    }++    @Test fun `out screen empty sections explain themselves`() {+        val actions = OutActions(+            onCompose = {}, onOpenDraft = {}, onDeleteDraft = {}, onRestoreDraft = {},+            onRetryOutbox = {}, onOpenSent = {}, onTrashSent = {}, onUntrashSent = {}, onSetRead = { _, _ -> },+        )+        rule.setContent { OutScreen(drafts = emptyList(), outbox = emptyList(), sent = emptyList(), actions = actions) }+        rule.onNodeWithText("No drafts.").assertExists()+        rule.onNodeWithText("Nothing waiting to send.").assertExists()+        rule.onNodeWithText("Nothing sent yet.").assertExists()+    }++    @Test fun `bottom bar labels and folder tab mapping for every folder`() {+        assertEquals(MailTab.INBOX, MailFolder.INBOX.tab())+        assertEquals(MailTab.SPAM, MailFolder.SPAM.tab())+        assertEquals(MailTab.TRASH, MailFolder.TRASH.tab())+        assertEquals(MailTab.OUT, MailFolder.SENT.tab())+        assertEquals(MailTab.OUT, MailFolder.DRAFTS.tab())+        rule.setContent { MailBottomBar(selected = MailTab.OUT, outboxCount = 0, onSelect = {}) }+        rule.onNodeWithText("Inbox").assertExists()+        rule.onNodeWithText("Spam").assertExists()+        rule.onNodeWithText("Out").assertExists()+        rule.onNodeWithText("Trash").assertExists()+        rule.onNodeWithText("Settings").assertExists()+    }++    @Test fun `settings shows fingerprint aliases and disabled state`() {+        val identities = listOf(+            MailIdentity("[email protected]", "", "pub", "AA", "sec", isPrimary = true, createdMillis = 1),+            MailIdentity("[email protected]", "Shopping", "pub", "BB", "sec", disabled = true, createdMillis = 2),+        )+        rule.setContent {+            SettingsScreen(+                state = MailUiState(address = "[email protected]", fingerprintHex = "AABBCC"),+                identities = identities, onCreateAlias = {}, onSetAliasDisabled = { _, _ -> },+                onExportPublicKey = {}, onForget = {},+            )+        }+        rule.onNodeWithText("Primary", substring = true).assertExists()+        rule.onNodeWithText("Shopping", substring = true).assertExists()+        rule.onNodeWithText("Key: BB", substring = true).assertExists()+        rule.onNodeWithText("disabled, mail held", substring = true).assertExists()+        rule.onNodeWithText("Relay: offline", substring = true).assertExists()+    }++    @Test fun `inbox trash empty dialog deletes everything or cancels`() {+        var emptied = 0+        val deleted = mutableListOf<List<String>>()+        val actions = FolderActions(+            onOpen = {}, onCompose = {}, onSetRead = { _, _ -> }, onTrash = {},+            onMoveTo = { _, _ -> }, onRestore = {}, onDeleteForever = { deleted += it },+            onEmptyTrash = { emptied++ }, onConsumeMessage = {},+        )+        rule.setContent {+            InboxScreen(state = MailUiState(), folder = MailFolder.TRASH, actions = actions,+                messages = listOf(msg("t1", "Trash one"), msg("t2", "Trash two")))+        }+        rule.onNodeWithText("Empty trash").performClick()+        rule.onNodeWithText("Empty trash?").assertExists()+        rule.onNodeWithText("2 messages will be permanently deleted", substring = true).assertExists()+        rule.onNodeWithText("Cancel").performClick()+        rule.onAllNodes(hasText("Empty trash?")).assertCountEquals(0)+        assertEquals(0, emptied)+        rule.onNodeWithText("Empty trash").performClick()+        rule.onNodeWithText("Delete").performClick()+        assertEquals(1, emptied)+        assertTrue(deleted.isEmpty())+    }++    @Test fun `inbox long press opens selection bar`() {+        rule.setContent {+            InboxScreen(state = MailUiState(), folder = MailFolder.INBOX, actions = folderActions(),+                messages = listOf(msg("1", "Selectable"), msg("2", "Other row")))+        }+        rule.onNodeWithText("Selectable").performTouchInput { longClick() }+        rule.onNodeWithText("1 selected").assertExists()+        // Tapping another row while selecting toggles it into the selection.+        rule.onNodeWithText("Other row").performClick()+        rule.onNodeWithText("2 selected").assertExists()+    }++    @Test fun `message body view splits on original message marker`() {+        val body = "Fresh text\n----- Original Message -----\nquoted history"+        rule.setContent { MessageBodyView(msg("o", "S", body = body)) }+        rule.onNodeWithText("Fresh text", substring = true).assertExists()+        rule.onAllNodes(hasText("quoted history", substring = true)).assertCountEquals(0)+        rule.onNodeWithText("Show quoted text").performClick()+        rule.onNodeWithText("quoted history", substring = true).assertExists()+    }++    @Test fun `message body view html blocks remote content until load is tapped`() {+        val html = "<p>Hello html</p><img src=\"https://tracker.example.org/x.png\">"+        rule.setContent { MessageBodyView(msg("h", "S", body = null, html = html)) }+        rule.onNodeWithText("Remote content blocked").assertExists()+        rule.onNodeWithText("Load").performClick()+        rule.onAllNodes(hasText("Remote content blocked")).assertCountEquals(0)+    }++    @Test fun `message body view html quoted sections start hidden`() {+        val html = "<p>Main part</p><div class=\"gmail_quote\">quoted part</div>"+        rule.setContent { MessageBodyView(msg("hq", "S", body = null, html = html)) }+        rule.onNodeWithText("Show quoted text").assertExists()+        rule.onNodeWithText("Show quoted text").performClick()+        rule.onNodeWithText("Hide quoted text").assertExists()+    }++    @Test fun `compose typing an address and tapping a chip routes callbacks`() {+        val added = mutableListOf<Pair<Int, String>>()+        val removed = mutableListOf<Pair<Int, String>>()+        rule.setContent {+            ComposeScreen(+                state = MailUiState(address = "[email protected]"), identities = emptyList(), draftFrom = null,+                onSelectFrom = {}, draftTo = listOf("[email protected]"), draftCc = emptyList(), draftBcc = emptyList(),+                initialSubject = "", initialBody = "Body",+                onAddRecipient = { target, address -> added += target to address; true },+                onRemoveRecipient = { target, address -> removed += target to address },+                onSend = { _, _, _, _, _, _ -> }, onLeave = { _, _ -> }, onDiscard = {},+            )+        }+        rule.onNodeWithText("[email protected]").performClick()+        assertEquals(listOf(0 to "[email protected]"), removed)+        assertTrue(added.isEmpty())+    }++    @Test fun `recipient chip field submits on ime action and rejects via callback`() {+        val added = mutableListOf<String>()+        var invalid = 0+        var accept = true+        rule.setContent {+            RecipientChipField(+                label = "To", recipients = listOf("[email protected]"),+                onAdd = { added += it; accept },+                onRemove = {},+                onPickContact = {},+                onInvalid = { invalid++ },+            )+        }+        rule.onNode(hasSetTextAction()).performTextInput("[email protected]")+        rule.onNode(hasSetTextAction()).performImeAction()+        assertEquals(listOf("[email protected]"), added)+        assertEquals(0, invalid)+        accept = false+        rule.onNode(hasSetTextAction()).performTextReplacement("[email protected]")+        rule.onNode(hasSetTextAction()).performImeAction()+        assertEquals(listOf("[email protected]", "[email protected]"), added)+        assertEquals(1, invalid)+    }++    @Test fun `compose from picker selects another identity`() {+        var selected: String? = null+        rule.setContent {+            ComposeScreen(+                state = MailUiState(address = "[email protected]"),+                identities = listOf(+                    MailIdentity("[email protected]", "", "pub", "AA", "sec", isPrimary = true, createdMillis = 1),+                    MailIdentity("[email protected]", "Shopping", "pub", "BB", "sec", createdMillis = 2),+                ),+                draftFrom = null, onSelectFrom = { selected = it },+                draftTo = listOf("[email protected]"), draftCc = emptyList(), draftBcc = emptyList(),+                initialSubject = "", initialBody = "Body",+                onAddRecipient = { _, _ -> true }, onRemoveRecipient = { _, _ -> },+                onSend = { _, _, _, _, _, _ -> }, onLeave = { _, _ -> }, onDiscard = {},+            )+        }+        rule.onNodeWithText("From: [email protected]", substring = true).performClick()+        rule.onNodeWithText("[email protected]").performClick()+        assertEquals("[email protected]", selected)+    }++    @Test fun `lock screen renders its gate`() {+        rule.setContent { LockScreen(state = MailUiState(locked = true, error = "Unlock to read your mail."), onUnlock = {}, onDismissMessages = {}) }+        rule.onNodeWithText("Unlock to read your mail.", substring = true).assertExists()+    }++    @Test fun `onboarding renders its gate`() {+        rule.setContent { OnboardingScreen(state = MailUiState(busy = true), onClaim = { _, _ -> }, onDismissMessages = {}) }+        rule.onNodeWithText("Set up SecureMail").assertExists()+    }+}
securemail/src/test/java/com/vayunmathur/securemail/ui/NavigationTest.kt
diff --git a/securemail/src/test/java/com/vayunmathur/securemail/ui/NavigationTest.kt b/securemail/src/test/java/com/vayunmathur/securemail/ui/NavigationTest.ktnew file mode 100644index 0000000000..b355af9ab1--- /dev/null+++ b/securemail/src/test/java/com/vayunmathur/securemail/ui/NavigationTest.kt@@ -0,0 +1,128 @@+package com.vayunmathur.securemail.ui++import android.app.Application+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.hasScrollAction+import androidx.compose.ui.test.hasText+import androidx.compose.ui.test.onAllNodesWithText+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performScrollToNode+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.securemail.Navigation+import com.vayunmathur.securemail.Route+import com.vayunmathur.securemail.data.MailFolder+import com.vayunmathur.securemail.data.MailIdentity+import com.vayunmathur.securemail.data.OutboxMessage+import com.vayunmathur.securemail.data.StoredMessage+import com.vayunmathur.securemail.platform.FakeMailStore+import com.vayunmathur.securemail.platform.MailViewModel+import kotlinx.coroutines.runBlocking+import org.junit.Rule+import org.robolectric.annotation.Config+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/**+ * [Navigation] driven by a real [MailViewModel] backed by [FakeMailStore]:+ * covers the entry wiring (inbox/out/composer/reader/settings), the+ * bottom-bar tab mapping for the top route, and the composer/reader effects.+ */+@RunWith(RobolectricTestRunner::class)+@Config(shadows = [ShadowIdentities::class])+class NavigationTest {+    @get:Rule val rule = createComposeRule()+    private val app: Application get() = ApplicationProvider.getApplicationContext()++    private fun message(id: String, subject: String, folder: MailFolder) = StoredMessage(+        id = id, from = "[email protected]", toJson = "[email protected]", dateMillis = 1700000000000,+        messageId = id, blobBase64 = "", decryptedBody = "Body of $id",+        decryptedSubject = subject, folder = folder,+    )++    private fun viewModel(store: FakeMailStore) = MailViewModel(app, store)++    @Test fun `navigation without an initial route lands on onboarding`() {+        rule.setContent { Navigation(viewModel(FakeMailStore())) }+        rule.onNodeWithText("Set up SecureMail").assertExists()+        rule.onNodeWithText("Claim an @maemail.org address.", substring = true).assertExists()+    }++    @Test fun `navigation inbox route renders folder messages from the view model store`() {+        val store = FakeMailStore()+        runBlocking {+            store.messages.upsert(message("n1", "Nav inbox one", MailFolder.INBOX))+            store.messages.upsert(message("n2", "Spam one", MailFolder.SPAM))+        }+        rule.setContent { Navigation(viewModel(store), initialRoute = Route.Inbox) }+        rule.onNodeWithText("Nav inbox one").assertExists()+        rule.onNodeWithText("Inbox").assertExists()+    }++    @Test fun `navigation out route renders drafts outbox and sent from the store`() {+        val store = FakeMailStore()+        runBlocking {+            store.messages.upsert(message("d1", "Nav draft", MailFolder.DRAFTS))+            store.messages.upsert(message("s1", "Nav sent", MailFolder.SENT))+            store.outbox.insert(+                OutboxMessage(toJson = "[email protected]", subject = "Nav queued", body = "b", createdMillis = 1),+            )+        }+        rule.setContent { Navigation(viewModel(store), initialRoute = Route.Out) }+        rule.onNodeWithText("Nav draft").assertExists()+        rule.onNodeWithText("Nav queued").assertExists()+        rule.onNode(hasScrollAction()).performScrollToNode(hasText("Nav sent"))+        rule.onNodeWithText("Nav sent").assertExists()+        rule.onNodeWithText("Out").assertExists()+    }++    @Test fun `navigation reader route shows the stored message and reader chrome`() {+        val store = FakeMailStore()+        runBlocking { store.messages.upsert(message("r1", "Nav reader", MailFolder.INBOX)) }+        val viewModel = viewModel(store)+        rule.setContent { Navigation(viewModel, initialRoute = Route.Reader("r1")) }+        rule.onNodeWithText("Nav reader").assertExists()+        rule.onNodeWithText("Body of r1", substring = true).assertExists()+        rule.onNodeWithText("Reply").assertExists()+        // Reader entry marks the message read through the ViewModel.+        rule.waitUntil(timeoutMillis = 5_000) {+            runBlocking { store.messages.get("r1")?.isRead == true }+        }+        assertEquals(true, runBlocking { store.messages.get("r1")?.isRead })+    }++    @Test fun `navigation reader route for a missing message shows not found`() {+        rule.setContent { Navigation(viewModel(FakeMailStore()), initialRoute = Route.Reader("ghost")) }+        rule.onNodeWithText("Message not found.").assertExists()+    }++    @Test fun `navigation composer route seeds draft recipients from the route`() {+        val viewModel = viewModel(FakeMailStore())+        rule.setContent {+            Navigation(+                viewModel,+                initialRoute = Route.Composer(to = "[email protected], [email protected]", subject = "Seeded", body = "Seed body"),+            )+        }+        rule.onNodeWithText("[email protected]").assertExists()+        rule.onNodeWithText("[email protected]").assertExists()+        rule.onNodeWithText("Seeded").assertExists()+        rule.waitUntil(timeoutMillis = 5_000) { viewModel.draftTo.size == 2 }+        assertEquals(listOf("[email protected]", "[email protected]"), viewModel.draftTo)+    }++    @Test fun `navigation settings route lists identities from the store`() {+        val store = FakeMailStore()+        runBlocking {+            store.identities.upsert(+                MailIdentity("[email protected]", "", "pub", "AA", "sec", isPrimary = true, createdMillis = 1),+            )+        }+        rule.setContent { Navigation(viewModel(store), initialRoute = Route.Settings) }+        assertTrue(rule.onAllNodesWithText("Settings").fetchSemanticsNodes().isNotEmpty())+        rule.onNodeWithText("[email protected]", substring = true).assertExists()+        rule.onNodeWithText("Primary", substring = true).assertExists()+    }+}
securemail/src/test/java/com/vayunmathur/securemail/ui/ShadowIdentities.kt
diff --git a/securemail/src/test/java/com/vayunmathur/securemail/ui/ShadowIdentities.kt b/securemail/src/test/java/com/vayunmathur/securemail/ui/ShadowIdentities.ktnew file mode 100644index 0000000000..2f976dcbc6--- /dev/null+++ b/securemail/src/test/java/com/vayunmathur/securemail/ui/ShadowIdentities.kt@@ -0,0 +1,21 @@+package com.vayunmathur.securemail.ui++import android.content.Context+import com.vayunmathur.securemail.data.Identities+import kotlin.coroutines.Continuation+import org.robolectric.annotation.Implementation+import org.robolectric.annotation.Implements++/**+ * Robolectric shadow for [Identities]: its migration path opens the+ * process-wide SQLCipher [com.vayunmathur.securemail.data.MailRepository]+ * singleton, whose native library cannot load on a host JVM. Navigation+ * tests drive the ViewModel through FakeMailStore instead, so the legacy+ * identity migration is a no-op here.+ */+@Implements(Identities::class)+class ShadowIdentities {+    @Suppress("UnusedParameter") // signature must match the shadowed suspend fun+    @Implementation+    fun ensureMigrated(context: Context, continuation: Continuation<Unit>): Any? = Unit+}