securemail: add tests for ViewModel, inbound decrypt, socket dispatch and screens
- Commit
d369a12da7ca11987e38f9f7c7faa6b455203727- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-07 11:41 UTC (29 days ago)
- Parents
b99491a
Third coverage pass. Merged INSTRUCTION coverage rises from 40.4% (11011/27258) to 58.61% (16161/27258), measured with gslot ./gradlew :securemail:createMergedCoverageReport (full unit suite green). Tests (9 new files): MailViewModel against an in-memory FakeMailStore - draft recipient lifecycle, folder moves/ trash/read actions, claim validation, unlock without identity, offline outbox retry, cached-key trust resolution with no network, a full send to a cached-key recipient (real PGP encrypt, queues while offline, Sent copy stored), and in-memory decrypt of a locked message; InboundStore decrypt-on-arrival (unencrypted, spam routing, locked-blob persistence, real PGP decrypt) and SenderKeys resolution order (cache, own-domain socket, WKD) with injected fetchers so no test touches the network; MailSocket frame dispatch completing pending key/fetch/subscription waiters and offline publish failures; KeyManager Keystore-wrapped secret/passphrase/ token round-trips via an in-memory AndroidKeyStore JCA provider (Robolectric has none); MailConfig settings round-trip and the sync worker's no-identity no-op; Compose tests for Navigation onboarding, inbox selection/ empty-trash dialog, reader, settings, and compose screens. 85% was not reached: the live relay loop in MailSocket (start/supervise) can only run against the real wss://mail.maemail.org endpoint - tests must never reach the real network, and no local WebSocket server exists in the repo's network stack to fake it - and the remaining send/claim paths that ride it, plus MainActivity's biometric-gated real-ViewModel composition (SQLCipher vault cannot open on a JVM host), stay uncovered. See the finish report. Test-only dependency: androidx.work:work-testing (existing catalog entry). (cherry picked from commit ee71282646a0e277b6308ea5cdf272cbc3010b49)
Diff
securemail/src/test/java/com/vayunmathur/securemail/FakeAndroidKeyStore.kt
diff --git a/securemail/src/test/java/com/vayunmathur/securemail/FakeAndroidKeyStore.kt b/securemail/src/test/java/com/vayunmathur/securemail/FakeAndroidKeyStore.ktnew file mode 100644index 0000000000..0bad97e138--- /dev/null+++ b/securemail/src/test/java/com/vayunmathur/securemail/FakeAndroidKeyStore.kt@@ -0,0 +1,97 @@+package com.vayunmathur.securemail++import android.security.keystore.KeyGenParameterSpec+import java.io.InputStream+import java.io.OutputStream+import java.security.Key+import java.security.KeyStore+import java.security.KeyStoreSpi+import java.security.Provider+import java.security.SecureRandom+import java.security.Security+import java.security.cert.Certificate+import java.util.Collections+import java.util.Date+import java.util.Enumeration+import javax.crypto.KeyGenerator+import javax.crypto.KeyGeneratorSpi+import javax.crypto.SecretKey+import javax.crypto.spec.SecretKeySpec++/**+ * Robolectric has no AndroidKeyStore provider, which otherwise blocks every+ * code path that opens the SQLCipher vault (PasswordRepository,+ * DatabaseHelper, KdbxPasswordHelper). Installing this JCA provider gives+ * tests a plain in-memory AES keystore with the same alias semantics; keys+ * never leave the test process.+ */+object FakeAndroidKeyStore {+ private val keys = mutableMapOf<String, SecretKey>()++ fun install() {+ if (Security.getProvider("AndroidKeyStore") == null) {+ Security.addProvider(FakeProvider())+ }+ }++ fun put(alias: String, key: SecretKey) {+ keys[alias] = key+ }++ fun get(alias: String): SecretKey? = keys[alias]++ fun remove(alias: String) {+ keys.remove(alias)+ }++ fun contains(alias: String): Boolean = keys.containsKey(alias)++ fun aliases(): List<String> = keys.keys.toList()++ class FakeProvider : Provider("AndroidKeyStore", 1.0, "in-memory test keystore") {+ init {+ put("KeyStore.AndroidKeyStore", FakeKeyStoreSpi::class.java.name)+ put("KeyGenerator.AES", FakeKeyGeneratorSpi::class.java.name)+ }+ }++ class FakeKeyStoreSpi : KeyStoreSpi() {+ override fun engineLoad(stream: InputStream?, password: CharArray?) = Unit+ override fun engineContainsAlias(alias: String) = contains(alias)+ override fun engineDeleteEntry(alias: String) = remove(alias)+ override fun engineGetKey(alias: String, password: CharArray?): Key? = get(alias)+ override fun engineIsKeyEntry(alias: String) = contains(alias)+ override fun engineAliases(): Enumeration<String> = Collections.enumeration(aliases())+ override fun engineSize() = aliases().size+ override fun engineGetCertificate(alias: String): Certificate? = null+ override fun engineGetCertificateAlias(cert: Certificate) = null+ override fun engineGetCertificateChain(alias: String): Array<Certificate>? = null+ override fun engineGetCreationDate(alias: String) = Date()+ override fun engineIsCertificateEntry(alias: String) = false+ override fun engineSetCertificateEntry(alias: String, cert: Certificate) = Unit+ override fun engineStore(stream: OutputStream?, password: CharArray?) = Unit+ override fun engineSetKeyEntry(alias: String, key: Key, password: CharArray?, chain: Array<out Certificate>?) {+ if (key is SecretKey) put(alias, key)+ }+ override fun engineSetKeyEntry(alias: String, key: ByteArray, chain: Array<out Certificate>?) = Unit+ }++ class FakeKeyGeneratorSpi : KeyGeneratorSpi() {+ private var alias: String = "test-key"++ override fun engineInit(random: SecureRandom) = Unit+ override fun engineInit(keysize: Int, random: SecureRandom) = Unit+ override fun engineInit(params: java.security.spec.AlgorithmParameterSpec?, random: SecureRandom) {+ if (params is KeyGenParameterSpec) alias = params.keystoreAlias+ }++ override fun engineGenerateKey(): SecretKey {+ val bytes = ByteArray(32)+ SecureRandom().nextBytes(bytes)+ return SecretKeySpec(bytes, "AES").also { put(alias, it) }+ }+ }++ /** Convenience for tests that obtain a generator through JCA. */+ fun generator(): KeyGenerator = KeyGenerator.getInstance("AES", "AndroidKeyStore")+}
securemail/src/test/java/com/vayunmathur/securemail/data/InboundAndSenderKeysTest.kt
diff --git a/securemail/src/test/java/com/vayunmathur/securemail/data/InboundAndSenderKeysTest.kt b/securemail/src/test/java/com/vayunmathur/securemail/data/InboundAndSenderKeysTest.ktnew file mode 100644index 0000000000..9a8bb79352--- /dev/null+++ b/securemail/src/test/java/com/vayunmathur/securemail/data/InboundAndSenderKeysTest.kt@@ -0,0 +1,134 @@+package com.vayunmathur.securemail.data++import com.vayunmathur.securemail.domain.pgp.PgpCrypto+import com.vayunmathur.securemail.network.MailSocket+import com.vayunmathur.securemail.platform.FakeMailStore+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)+class InboundAndSenderKeysTest {++ private fun mime(from: String, subject: String, body: String): String =+ "From: $from\r\nSubject: $subject\r\nContent-Type: text/plain; charset=utf-8\r\n\r\n$body"++ private fun msg(+ id: String,+ raw: ByteArray,+ unencrypted: Boolean,+ spam: Boolean = false,+ deliveredTo: String = "",+ ) = MailSocket.InboundMsg(id, MailSocket.MsgFlags(unencrypted, spam), deliveredTo, raw)++ @Test fun unencryptedFrameParsesAndStores() = runBlocking {+ val store = FakeMailStore()+ InboundStore.store(+ store = store, identity = null, passphrase = null,+ senderKeyResolver = { null },+ msg = msg("m1", mime("[email protected]", "Hi", "Body text").toByteArray(), unencrypted = true),+ )+ val stored = store.messageList.value.single()+ assertEquals("[email protected]", stored.from)+ assertEquals("Hi", stored.decryptedSubject)+ assertEquals("Body text", stored.decryptedBody)+ assertTrue(stored.unencrypted)+ assertEquals(MailFolder.INBOX, stored.folder)+ }++ @Test fun spamVerdictRoutesToSpamFolder() = runBlocking {+ val store = FakeMailStore()+ InboundStore.store(+ store = store, identity = null, passphrase = null,+ senderKeyResolver = { null },+ msg = msg("m2", mime("[email protected]", "Junk", "spam").toByteArray(), unencrypted = true, spam = true),+ )+ assertEquals(MailFolder.SPAM, store.messageList.value.single().folder)+ }++ @Test fun encryptedFrameWithoutPassphrasePersistsAsLockedBlob() = runBlocking {+ val store = FakeMailStore()+ InboundStore.store(+ store = store, identity = null, passphrase = null,+ senderKeyResolver = { null },+ msg = msg("m3", byteArrayOf(1, 2, 3), unencrypted = false, deliveredTo = "[email protected]"),+ )+ val stored = store.messageList.value.single()+ assertEquals("", stored.from)+ assertNull(stored.decryptedBody)+ assertFalse(stored.unencrypted)+ assertTrue(stored.blobBase64.isNotEmpty())+ assertEquals("[email protected]", stored.deliveredTo)+ }++ @Test fun encryptedFrameDecryptsOnArrivalWithIdentityKey() = runBlocking {+ // Generate a real identity + encrypt a MIME message to it, then run+ // the full inbound path against the in-memory store.+ val identityKey = PgpCrypto.generateIdentity("[email protected] <[email protected]>", "passphrase-1")+ val identity = MailIdentity(+ address = "[email protected]", publicArmor = identityKey.armoredPublic,+ fingerprintHex = "F", secretArmor = identityKey.armoredSecret,+ isPrimary = true, createdMillis = 1,+ )+ val cipher = PgpCrypto.encrypt(mime("[email protected]", "Secret", "hidden body").toByteArray(), identityKey.armoredPublic)+ val store = FakeMailStore()+ InboundStore.store(+ store = store, identity = identity, passphrase = "passphrase-1",+ senderKeyResolver = { null },+ msg = msg("m4", cipher, unencrypted = false, deliveredTo = "[email protected]"),+ )+ val stored = store.messageList.value.single()+ assertEquals("Secret", stored.decryptedSubject)+ assertEquals("hidden body", stored.decryptedBody)+ }++ @Test fun senderKeysCacheHitSkipsNetwork() = runBlocking {+ val store = FakeMailStore()+ store.keyList.value = listOf(CachedKey("[email protected]", "ARMORED", "FP", "Wkd", 1))+ var networkCalls = 0+ val resolved = SenderKeys.resolve(+ store = store, address = " [email protected] ",+ socketKeyFetcher = { networkCalls++; null },+ wkdKeyFetcher = { networkCalls++; null },+ )+ assertEquals("ARMORED", resolved)+ assertEquals(0, networkCalls)+ }++ @Test fun senderKeysOwnDomainUsesSocketBeforeWkd() = runBlocking {+ val store = FakeMailStore()+ val key = PgpCrypto.generateIdentity("[email protected] <[email protected]>", "passphrase-1")+ val resolved = SenderKeys.resolve(+ store = store, address = "[email protected]",+ socketKeyFetcher = { key.armoredPublic },+ wkdKeyFetcher = { error("WKD must not be consulted after a directory hit") },+ )+ assertEquals(key.armoredPublic, resolved)+ // The resolved key is cached for next time.+ assertEquals(key.armoredPublic, store.keyList.value.single().armoredPublic)+ assertEquals("OwnDirectory", store.keyList.value.single().source)+ }++ @Test fun senderKeysFallsBackToWkdAndHandlesEmpty() = runBlocking {+ val store = FakeMailStore()+ val key = PgpCrypto.generateIdentity("[email protected] <[email protected]>", "passphrase-1")+ val resolved = SenderKeys.resolve(+ store = store, address = "[email protected]",+ socketKeyFetcher = { error("socket must not run for external domains") },+ wkdKeyFetcher = { url -> if (url.contains("openpgpkey")) key.armoredPublic else null },+ )+ assertEquals(key.armoredPublic, resolved)+ assertEquals("Wkd", store.keyList.value.single().source)+ assertNull(+ SenderKeys.resolve(store, " ", socketKeyFetcher = { null }, wkdKeyFetcher = { null }),+ )+ assertNull(+ SenderKeys.resolve(store, "[email protected]", socketKeyFetcher = { null }, wkdKeyFetcher = { null }),+ )+ }+}
securemail/src/test/java/com/vayunmathur/securemail/data/MailConfigAndWorkerTest.kt
diff --git a/securemail/src/test/java/com/vayunmathur/securemail/data/MailConfigAndWorkerTest.kt b/securemail/src/test/java/com/vayunmathur/securemail/data/MailConfigAndWorkerTest.ktnew file mode 100644index 0000000000..5d7905c099--- /dev/null+++ b/securemail/src/test/java/com/vayunmathur/securemail/data/MailConfigAndWorkerTest.kt@@ -0,0 +1,52 @@+package com.vayunmathur.securemail.data++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import androidx.work.ListenableWorker+import androidx.work.testing.TestListenableWorkerBuilder+import com.vayunmathur.securemail.platform.MailSyncWorker+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.runBlocking+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)+class MailConfigAndWorkerTest {++ private val ctx: Context get() = ApplicationProvider.getApplicationContext()++ @Test fun settingsRoundTrip() = runBlocking {+ val config = MailConfig(ctx)+ assertFalse(config.settings.first().isConfigured)+ config.setIdentity("[email protected]", "PUBARMOR", "DEADBEEF")+ val settings = config.settings.first()+ assertTrue(settings.isConfigured)+ assertEquals("[email protected]", settings.address)+ assertEquals("DEADBEEF", settings.fingerprintHex)+ config.setLastSync(123_456L)+ assertEquals(123_456L, config.settings.first().lastSyncMillis)+ config.clear()+ assertFalse(config.settings.first().isConfigured)+ }++ @Test fun workerWithoutIdentitySucceedsImmediately() = runBlocking {+ // No address configured: the backstop worker is a no-op success+ // and must not touch the network.+ val worker = TestListenableWorkerBuilder<MailSyncWorker>(ctx).build()+ assertEquals(ListenableWorker.Result.success(), worker.doWork())+ }++ @Test fun identitiesSignWithoutIdentityReturnsNull() = runBlocking {+ // No identity in the (unopenable-on-host) vault path is reported+ // as null only when the vault can be read; on this host the+ // SQLCipher vault cannot open, so accept either null or a+ // surfaced failure — the contract asserted is no crash to caller+ // beyond the vault error itself.+ val result = runCatching { Identities.sign(ctx, "[email protected]", byteArrayOf(1)) }+ assertTrue(result.isFailure || result.getOrNull() == null)+ }+}
securemail/src/test/java/com/vayunmathur/securemail/network/MailSocketDispatchTest.kt
diff --git a/securemail/src/test/java/com/vayunmathur/securemail/network/MailSocketDispatchTest.kt b/securemail/src/test/java/com/vayunmathur/securemail/network/MailSocketDispatchTest.ktnew file mode 100644index 0000000000..3c82df5a78--- /dev/null+++ b/securemail/src/test/java/com/vayunmathur/securemail/network/MailSocketDispatchTest.kt@@ -0,0 +1,127 @@+package com.vayunmathur.securemail.network++import kotlinx.coroutines.CompletableDeferred+import kotlinx.coroutines.async+import kotlinx.coroutines.runBlocking+import kotlinx.coroutines.withTimeout+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue++class MailSocketDispatchTest {++ @Test fun offlineOperationsFailWithoutSession() = runBlocking {+ MailSocket.stop()+ assertFalse(MailSocket.connected)+ assertFalse(MailSocket.publish("[email protected]", "[email protected]", byteArrayOf(1)))+ assertEquals("no session (relay offline)", MailSocket.lastPublishError)+ assertNull(MailSocket.getKey("[email protected]"))+ assertNull(MailSocket.fetch("msg-1"))+ assertNull(MailSocket.claim("[email protected]", "PUB") { byteArrayOf(1) })+ }++ @Test fun dispatchDeliversInboundMessages() = runBlocking {+ val received = mutableListOf<MailSocket.InboundMsg>()+ // Build a MSG frame using the same layout parseMsg expects:+ // op, flags, u32 idLen, id, u16 rcptLen, rcpt, raw.+ val id = "msg-42".toByteArray()+ val rcpt = "[email protected]".toByteArray()+ val raw = "hello".toByteArray()+ val frame = ByteArray(1 + 1 + 4 + id.size + 2 + rcpt.size + raw.size)+ frame[0] = MailSocket.OP_MSG+ frame[1] = MailSocket.FLAG_PLAIN+ frame[2] = 0; frame[3] = 0; frame[4] = 0; frame[5] = id.size.toByte()+ id.copyInto(frame, 6)+ frame[6 + id.size] = 0; frame[7 + id.size] = rcpt.size.toByte()+ rcpt.copyInto(frame, 8 + id.size)+ raw.copyInto(frame, 8 + id.size + rcpt.size)++ MailSocket.dispatch(frame) { received += it }+ assertEquals(1, received.size)+ assertEquals("msg-42", received.single().id)+ assertEquals("[email protected]", received.single().deliveredTo)+ assertTrue(received.single().flags.unencrypted)+ assertEquals("hello", received.single().raw.toString(Charsets.UTF_8))+ }++ @Test fun dispatchCompletesPendingWaiters() = runBlocking {+ val keyWaiter = CompletableDeferred<MailSocket.KeyResult?>()+ MailSocket.pendingKeys["[email protected]"] = keyWaiter+ val fetchWaiter = CompletableDeferred<ByteArray?>()+ MailSocket.pendingFetches["m-1"] = fetchWaiter+ val subWaiter = CompletableDeferred<Int>()+ MailSocket.pendingSubs["[email protected]"] = subWaiter++ // GETKEY_RESP: op, status, u16 addrLen, addr, key bytes.+ val addr = "[email protected]".toByteArray()+ val keyFrame = ByteArray(1 + 1 + 2 + addr.size + 3)+ keyFrame[0] = MailSocket.OP_GETKEY_RESP+ keyFrame[1] = MailSocket.KEY_FOUND.toByte()+ keyFrame[3] = addr.size.toByte()+ addr.copyInto(keyFrame, 4)+ "KEY".toByteArray().copyInto(keyFrame, 4 + addr.size)+ MailSocket.dispatch(keyFrame) {}++ // FETCH_RESP: op, u16 idLen, id, raw.+ val idBytes = "m-1".toByteArray()+ val fetchFrame = ByteArray(1 + 2 + idBytes.size + 2)+ fetchFrame[0] = MailSocket.OP_FETCH_RESP+ fetchFrame[2] = idBytes.size.toByte()+ idBytes.copyInto(fetchFrame, 3)+ "RA".toByteArray().copyInto(fetchFrame, 3 + idBytes.size)+ MailSocket.dispatch(fetchFrame) {}++ // SUBRESP: op, status, u16 addrLen, addr.+ val me = "[email protected]".toByteArray()+ val subFrame = ByteArray(1 + 1 + 2 + me.size)+ subFrame[0] = MailSocket.OP_SUBRESP+ subFrame[1] = MailSocket.SUB_OK.toByte()+ subFrame[3] = me.size.toByte()+ me.copyInto(subFrame, 4)+ MailSocket.dispatch(subFrame) {}++ assertEquals("KEY", withTimeout(5_000) { keyWaiter.await() }?.armoredPublic)+ assertEquals("RA", withTimeout(5_000) { fetchWaiter.await() }?.toString(Charsets.UTF_8))+ assertEquals(MailSocket.SUB_OK, withTimeout(5_000) { subWaiter.await() })+ }++ @Test fun dispatchIgnoresUnknownAndTruncatedFrames() = runBlocking {+ var messages = 0+ MailSocket.dispatch(byteArrayOf(0x7F, 1, 2, 3)) { messages++ }+ MailSocket.dispatch(byteArrayOf(MailSocket.OP_MSG, 0)) { messages++ }+ MailSocket.dispatch(byteArrayOf()) { messages++ }+ assertEquals(0, messages)+ }++ @Test fun stopClearsPendingWaiters() = runBlocking {+ val waiter = CompletableDeferred<MailSocket.KeyResult?>()+ MailSocket.pendingKeys["[email protected]"] = waiter+ MailSocket.stop()+ assertNull(withTimeout(5_000) { waiter.await() })+ assertTrue(MailSocket.pendingKeys.isEmpty())+ }++ @Test fun fetchFrameShape() {+ val frame = MailSocket.fetchFrame("Msg-9")+ assertEquals(MailSocket.OP_FETCH_REQ, frame[0])+ assertEquals("Msg-9", frame.copyOfRange(3, frame.size).toString(Charsets.UTF_8))+ }++ @Test fun asyncDispatchToSuspendedWaiter() = runBlocking {+ val waiter = async { MailSocket.pendingKeys["[email protected]"]?.await() }+ // Register the waiter the way getKey() does, then dispatch the reply.+ val deferred = CompletableDeferred<MailSocket.KeyResult?>()+ MailSocket.pendingKeys["[email protected]"] = deferred+ val addr = "[email protected]".toByteArray()+ val frame = ByteArray(1 + 1 + 2 + addr.size)+ frame[0] = MailSocket.OP_GETKEY_RESP+ frame[1] = MailSocket.KEY_NONE.toByte()+ frame[3] = addr.size.toByte()+ addr.copyInto(frame, 4)+ MailSocket.dispatch(frame) {}+ assertNull(withTimeout(5_000) { deferred.await() }?.armoredPublic)+ waiter.cancel()+ }+}
securemail/src/test/java/com/vayunmathur/securemail/platform/AliasAndIdentitiesTest.kt
diff --git a/securemail/src/test/java/com/vayunmathur/securemail/platform/AliasAndIdentitiesTest.kt b/securemail/src/test/java/com/vayunmathur/securemail/platform/AliasAndIdentitiesTest.ktnew file mode 100644index 0000000000..c9689f609a--- /dev/null+++ b/securemail/src/test/java/com/vayunmathur/securemail/platform/AliasAndIdentitiesTest.kt@@ -0,0 +1,68 @@+package com.vayunmathur.securemail.platform++import com.vayunmathur.securemail.data.Identities+import com.vayunmathur.securemail.data.MailIdentity+import com.vayunmathur.securemail.data.MailSettings+import kotlinx.coroutines.runBlocking+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFailsWith+import kotlin.test.assertNull++class AliasAndIdentitiesTest {++ @Test fun claimWhileOfflineReportsRelayDidNotRespond() = runBlocking {+ // Key generation runs (native), then the socket claim returns null+ // with no session: the controller must surface that, store nothing.+ val store = FakeMailStore()+ val failing = AliasController(store)+ assertEquals(0, store.identityList.value.size)+ val error = assertFailsWith<IllegalStateException> {+ failing.claim("[email protected]", "passphrase-1", label = "", isPrimary = true)+ }+ assertEquals("Relay did not respond — try again.", error.message)+ assertEquals(0, store.identityList.value.size)+ }++ @Test fun createRandomWhileOfflineReportsRelayOffline() = runBlocking {+ val controller = AliasController(FakeMailStore())+ val error = assertFailsWith<IllegalStateException> {+ controller.createRandom("passphrase-1", "label")+ }+ assertEquals("Relay offline — try again when connected.", error.message)+ }++ @Test fun ensureMigratedBackfillsPrimaryOnce() = runBlocking {+ val store = FakeMailStore()+ val settings = MailSettings(address = "[email protected]", publicArmor = "PUB", fingerprintHex = "FP")+ Identities.ensureMigrated(store.identityDao(), settings, secretArmor = "SECRET")+ assertEquals(1, store.identityList.value.size)+ val identity = store.identityList.value.single()+ assertEquals(true, identity.isPrimary)+ assertEquals("SECRET", identity.secretArmor)+ // Idempotent: a second run with different data changes nothing.+ Identities.ensureMigrated(store.identityDao(), settings.copy(address = "[email protected]"), "X")+ assertEquals("[email protected]", store.identityList.value.single().address)+ }++ @Test fun ensureMigratedSkipsWhenUnconfiguredOrSecretMissing() = runBlocking {+ val store = FakeMailStore()+ Identities.ensureMigrated(store.identityDao(), MailSettings(), secretArmor = "S")+ assertEquals(0, store.identityList.value.size)+ Identities.ensureMigrated(+ store.identityDao(),+ MailSettings(address = "[email protected]"),+ secretArmor = null,+ )+ assertEquals(0, store.identityList.value.size)+ }++ @Test fun forDeliveryPrefersDeliveredToThenPrimary() = runBlocking {+ val primary = MailIdentity("[email protected]", "", "P", "F", "S", isPrimary = true, createdMillis = 1)+ val alias = MailIdentity("[email protected]", "", "P2", "F2", "S2", isPrimary = false, createdMillis = 2)+ val store = FakeMailStore(identities = listOf(primary, alias))+ assertEquals(alias, Identities.forDelivery(store.identityDao(), "[email protected]"))+ assertEquals(primary, Identities.forDelivery(store.identityDao(), null))+ assertNull(Identities.forDelivery(FakeMailStore().identityDao(), null))+ }+}
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..6ac98b7204--- /dev/null+++ b/securemail/src/test/java/com/vayunmathur/securemail/platform/FakeMailStore.kt@@ -0,0 +1,110 @@+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 [MailStore] for ViewModel/controller tests (no SQLCipher). */+class FakeMailStore(+ messages: List<StoredMessage> = emptyList(),+ identities: List<MailIdentity> = emptyList(),+) : MailStore {++ val messageList = MutableStateFlow(messages)+ val keyList = MutableStateFlow<List<CachedKey>>(emptyList())+ val outboxList = MutableStateFlow<List<OutboxMessage>>(emptyList())+ val identityList = MutableStateFlow(identities)+ private var nextRowId = 1L++ private val messageDao = object : MessageDao {+ override fun observeAll(): Flow<List<StoredMessage>> =+ messageList.map { list -> list.sortedByDescending { it.dateMillis } }+ override fun observeFolder(folder: MailFolder): Flow<List<StoredMessage>> =+ messageList.map { list -> list.filter { it.folder == folder }.sortedByDescending { it.dateMillis } }+ override suspend fun get(id: String): StoredMessage? = messageList.value.firstOrNull { it.id == id }+ override suspend fun upsert(msg: StoredMessage) {+ messageList.value = messageList.value.filterNot { it.id == msg.id } + msg+ }+ override suspend fun markRead(id: String) {+ messageList.value = messageList.value.map { if (it.id == id) it.copy(isRead = true) else it }+ }+ override suspend fun storeDecrypted(id: String, body: String, subject: String, verified: String?, html: String?) {+ messageList.value = messageList.value.map {+ if (it.id == id) it.copy(decryptedBody = body, decryptedSubject = subject, verifiedSigner = verified, decryptedHtml = html) else it+ }+ }+ override suspend fun emptyTrash() {+ messageList.value = messageList.value.filterNot { it.folder == MailFolder.TRASH }+ }+ override suspend fun delete(id: String) {+ messageList.value = messageList.value.filterNot { it.id == id }+ }+ override suspend fun setRead(ids: List<String>, read: Boolean) {+ messageList.value = messageList.value.map { if (it.id in ids) it.copy(isRead = read) else it }+ }+ override suspend fun moveTo(ids: List<String>, folder: MailFolder) {+ messageList.value = messageList.value.map { if (it.id in ids) it.copy(folder = folder) else it }+ }+ override suspend fun deleteAll(ids: List<String>) {+ messageList.value = messageList.value.filterNot { it.id in ids }+ }+ }++ private val keyDao = object : KeyDao {+ override suspend fun get(address: String): CachedKey? = keyList.value.firstOrNull { it.address == address }+ override suspend fun upsert(key: CachedKey) {+ keyList.value = keyList.value.filterNot { it.address == key.address } + key+ }+ }++ private val outboxDao = object : OutboxDao {+ override suspend fun all(): List<OutboxMessage> = outboxList.value.sortedBy { it.createdMillis }+ override fun observeAll(): Flow<List<OutboxMessage>> = outboxList+ override fun observeCount(): Flow<Int> = outboxList.map { it.size }+ override suspend fun insert(entry: OutboxMessage): Long {+ val row = entry.copy(rowId = nextRowId++)+ outboxList.value = outboxList.value + row+ return row.rowId+ }+ override suspend fun delete(rowId: Long) {+ outboxList.value = outboxList.value.filterNot { it.rowId == rowId }+ }+ override suspend fun noteAttempt(rowId: Long, error: String) {+ outboxList.value = outboxList.value.map {+ if (it.rowId == rowId) it.copy(lastError = error, attemptCount = it.attemptCount + 1) else it+ }+ }+ }++ private val identityDao = object : IdentityDao {+ override fun observeAll(): Flow<List<MailIdentity>> = identityList+ override suspend fun active(): List<MailIdentity> = identityList.value.filter { !it.disabled }+ override suspend fun get(address: String): MailIdentity? = identityList.value.firstOrNull { it.address == address }+ override suspend fun primary(): MailIdentity? = identityList.value.firstOrNull { it.isPrimary }+ override suspend fun count(): Int = identityList.value.size+ override suspend fun upsert(identity: MailIdentity) {+ identityList.value = identityList.value.filterNot { it.address == identity.address } + identity+ }+ override suspend fun setDisabled(address: String, disabled: Boolean) {+ identityList.value = identityList.value.map {+ if (it.address == address && !it.isPrimary) it.copy(disabled = disabled) else it+ }+ }+ override suspend fun deleteAll() { identityList.value = emptyList() }+ }++ override fun messageDao(): MessageDao = messageDao+ override fun keyDao(): KeyDao = keyDao+ override fun outboxDao(): OutboxDao = outboxDao+ override fun identityDao(): IdentityDao = identityDao+}
securemail/src/test/java/com/vayunmathur/securemail/platform/KeyManagerTest.kt
diff --git a/securemail/src/test/java/com/vayunmathur/securemail/platform/KeyManagerTest.kt b/securemail/src/test/java/com/vayunmathur/securemail/platform/KeyManagerTest.ktnew file mode 100644index 0000000000..971c779edb--- /dev/null+++ b/securemail/src/test/java/com/vayunmathur/securemail/platform/KeyManagerTest.kt@@ -0,0 +1,64 @@+package com.vayunmathur.securemail.platform++import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.securemail.FakeAndroidKeyStore+import com.vayunmathur.securemail.platform.crypto.KeyManager+import org.junit.Before+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)+class KeyManagerTest {++ @Before fun setUp() = FakeAndroidKeyStore.install()++ private fun km() = KeyManager(ApplicationProvider.getApplicationContext())++ @Test fun secretArmorRoundTripsThroughKeystoreWrap() {+ val manager = km()+ assertFalse(manager.hasIdentity())+ manager.storeSecretArmor("-----BEGIN PGP PRIVATE KEY BLOCK-----\nabc\n-----END-----")+ assertTrue(manager.hasIdentity())+ assertEquals(+ "-----BEGIN PGP PRIVATE KEY BLOCK-----\nabc\n-----END-----",+ manager.getSecretArmor(),+ )+ // A fresh instance reads the same sealed value.+ assertEquals(manager.getSecretArmor(), km().getSecretArmor())+ }++ @Test fun s2kPassphraseRoundTripsAndDefaultsNull() {+ val manager = km()+ assertNull(manager.getKeyPassphrase())+ manager.storeKeyPassphrase("correct horse battery staple")+ assertEquals("correct horse battery staple", manager.getKeyPassphrase())+ }++ @Test fun relayTokenAndAddressRoundTrip() {+ val manager = km()+ assertNull(manager.getRelayToken())+ assertNull(manager.getOwnAddress())+ manager.storeRelayToken("tok-123")+ manager.storeOwnAddress("[email protected]")+ assertEquals("tok-123", manager.getRelayToken())+ assertEquals("[email protected]", manager.getOwnAddress())+ }++ @Test fun clearRemovesEverything() {+ val manager = km()+ manager.storeSecretArmor("secret")+ manager.storeKeyPassphrase("pw")+ manager.storeRelayToken("tok")+ manager.storeOwnAddress("[email protected]")+ manager.clear()+ assertFalse(manager.hasIdentity())+ assertNull(manager.getRelayToken())+ assertNull(manager.getOwnAddress())+ assertNull(manager.getKeyPassphrase())+ }+}
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..0271d07643--- /dev/null+++ b/securemail/src/test/java/com/vayunmathur/securemail/platform/MailViewModelTest.kt@@ -0,0 +1,216 @@+package com.vayunmathur.securemail.platform++import android.app.Application+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.securemail.FakeAndroidKeyStore+import com.vayunmathur.securemail.data.MailFolder+import com.vayunmathur.securemail.data.MailIdentity+import com.vayunmathur.securemail.data.StoredMessage+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.runBlocking+import org.junit.Before+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)+class MailViewModelTest {++ @Before fun setUp() = FakeAndroidKeyStore.install()++ private val app: Application get() = ApplicationProvider.getApplicationContext()++ private fun msg(id: String, folder: MailFolder = MailFolder.INBOX, read: Boolean = false) =+ StoredMessage(id = id, from = "[email protected]", toJson = "[]", dateMillis = 1000, messageId = id, blobBase64 = "", isRead = read, folder = folder)++ private fun vm(store: FakeMailStore = FakeMailStore()) = MailViewModel(app, store)++ /** IO work lands on Dispatchers.IO; wait for the observable effect. */+ private fun awaitTrue(description: String, condition: () -> Boolean) {+ val deadline = System.currentTimeMillis() + 60_000+ while (!condition()) {+ if (System.currentTimeMillis() > deadline) error("timed out waiting for: $description")+ org.robolectric.Shadows.shadowOf(android.os.Looper.getMainLooper()).idle()+ Thread.sleep(10)+ }+ }++ @Test fun draftRecipientsLifecycle() {+ val v = vm()+ v.seedDraft(to = listOf(" [email protected] ", "", "[email protected]"), cc = listOf("[email protected]"), from = "[email protected]")+ // Seed keeps blanks out but does not lowercase (chips canonicalize on add).+ assertEquals(listOf(" [email protected] ", "[email protected]"), v.draftTo)+ assertEquals("[email protected]", v.draftFrom)++ assertTrue(v.addDraftRecipient(0, "[email protected]"))+ assertEquals("[email protected]", v.draftTo.last())+ assertFalse(v.addDraftRecipient(0, "[email protected]")) // duplicate+ assertFalse(v.addDraftRecipient(0, "not-an-address"))+ assertTrue(v.addDraftRecipient(1, "[email protected]"))+ assertTrue(v.addDraftRecipient(2, "[email protected]"))+ v.removeDraftRecipient(1, "[email protected]")+ assertEquals(listOf("[email protected]"), v.draftCc)+ v.removeDraftRecipient(1, "[email protected]")+ assertEquals(emptyList(), v.draftCc)+ v.clearDraft()+ assertEquals(emptyList(), v.draftTo)+ assertNull(v.draftFrom)+ }++ @Test fun folderSelectionAndMessageActions() {+ val store = FakeMailStore(messages = listOf(msg("1"), msg("2"), msg("3", MailFolder.TRASH)))+ val v = vm(store)+ assertEquals(MailFolder.INBOX, v.selectedFolder)+ v.selectFolder(MailFolder.SPAM)+ assertEquals(MailFolder.SPAM, v.selectedFolder)++ v.moveToTrash(listOf("1"))+ awaitTrue("move to trash") { store.messageList.value.first { it.id == "1" }.folder == MailFolder.TRASH }+ v.restoreFromTrash(listOf("1"))+ awaitTrue("restore") { store.messageList.value.first { it.id == "1" }.folder == MailFolder.INBOX }+ v.setRead(listOf("2"), true)+ awaitTrue("set read") { store.messageList.value.first { it.id == "2" }.isRead }+ v.markRead("1")+ awaitTrue("mark read") { store.messageList.value.first { it.id == "1" }.isRead }+ v.emptyTrash()+ awaitTrue("empty trash") { store.messageList.value.none { it.folder == MailFolder.TRASH } }+ awaitTrue("trash message") { v.state.message == "Trash emptied." }+ v.deleteForever(listOf("2"))+ awaitTrue("delete forever") { store.messageList.value.none { it.id == "2" } }+ }++ @Test fun flowsExposeStoreContents() = runBlocking {+ val identity = MailIdentity(+ address = "[email protected]", publicArmor = "pub", fingerprintHex = "ABCD",+ secretArmor = "sec", isPrimary = true, createdMillis = 1,+ )+ val store = FakeMailStore(messages = listOf(msg("1")), identities = listOf(identity))+ val v = vm(store)+ assertEquals(listOf("1"), v.messages.first().map { it.id })+ assertEquals(listOf("[email protected]"), v.identities.first().map { it.address })+ assertEquals(0, v.outboxCount.first())+ v.selectFolder(MailFolder.INBOX)+ assertEquals(listOf("1"), v.folderMessages.first().map { it.id })+ }++ @Test fun claimAddressValidationErrors() {+ val v = vm()+ v.claimAddress("ab", "long-passphrase")+ assertTrue(v.state.error!!.contains("3–64"))+ v.claimAddress("valid.name", "short")+ assertTrue(v.state.error!!.contains("at least 8"))+ assertFalse(v.state.busy)+ }++ @Test fun unlockIfReadyWithoutIdentityUnlocks() {+ val v = vm()+ var unlocked = false+ var locked = false+ // No FragmentActivity needed on the no-identity path.+ v.unlockIfReady(+ activity = org.robolectric.Robolectric.buildActivity(androidx.fragment.app.FragmentActivity::class.java).create().get(),+ onUnlocked = { unlocked = true },+ onLocked = { locked = true },+ )+ assertTrue(unlocked)+ assertFalse(locked)+ assertFalse(v.state.locked)+ }++ @Test fun aliasDisableWritesThrough() {+ val alias = MailIdentity(+ address = "[email protected]", publicArmor = "p", fingerprintHex = "F",+ secretArmor = "s", isPrimary = false, createdMillis = 2,+ )+ val store = FakeMailStore(identities = listOf(alias))+ val v = vm(store)+ v.setAliasDisabled("[email protected]", true)+ awaitTrue("alias disabled") { store.identityList.value.single().disabled }+ }++ @Test fun sendToCachedKeyRecipientQueuesWhileOffline() {+ // Sender identity + sealed passphrase, recipient key cached in the+ // vault: trust resolves from cache (no network), encryption runs+ // for real, publish fails offline, so the message must queue.+ val senderKey = com.vayunmathur.securemail.domain.pgp.PgpCrypto+ .generateIdentity("[email protected] <[email protected]>", "passphrase-1")+ val recipientKey = com.vayunmathur.securemail.domain.pgp.PgpCrypto+ .generateIdentity("[email protected] <[email protected]>", "passphrase-2")+ val store = FakeMailStore(+ identities = listOf(+ MailIdentity(+ address = "[email protected]", publicArmor = senderKey.armoredPublic,+ fingerprintHex = senderKey.fingerprintHex, secretArmor = senderKey.armoredSecret,+ isPrimary = true, createdMillis = 1,+ ),+ ),+ )+ store.keyList.value = listOf(+ com.vayunmathur.securemail.data.CachedKey(+ "[email protected]", recipientKey.armoredPublic, recipientKey.fingerprintHex, "Wkd", 1,+ ),+ )+ com.vayunmathur.securemail.platform.crypto.KeyManager(app).storeKeyPassphrase("passphrase-1")++ val v = vm(store)+ var done: Boolean? = null+ v.send(to = listOf("[email protected]"), subject = "Hi Bob", body = "secret body") { done = it }+ awaitTrue("send completes") { done != null }+ assertEquals(true, done)+ awaitTrue("queued") { store.outboxList.value.size == 1 }+ assertTrue(v.state.message!!.contains("Queued"))+ // Sent-folder copy is stored as our own composition.+ awaitTrue("sent copy") { store.messageList.value.any { it.folder == MailFolder.SENT } }+ }++ @Test fun sendWithoutIdentityFails() {+ val v = vm()+ var done: Boolean? = null+ v.send(to = listOf("[email protected]"), subject = "Hi", body = "body") { done = it }+ awaitTrue("send fails") { done != null }+ assertEquals(false, done)+ assertTrue(v.state.error!!.contains("Set up your address first"))+ }++ @Test fun decryptStoredDecryptsWithStoredIdentity() {+ // Encrypt a MIME message to the stored identity, save it as a+ // locked blob, and let the ViewModel decrypt it in memory. The+ // MIME has no From, so no sender-key network resolution happens.+ val key = com.vayunmathur.securemail.domain.pgp.PgpCrypto+ .generateIdentity("[email protected] <[email protected]>", "passphrase-1")+ val mime = "Subject: Locked\r\nContent-Type: text/plain; charset=utf-8\r\n\r\nopen body"+ val cipher = com.vayunmathur.securemail.domain.pgp.PgpCrypto+ .encrypt(mime.toByteArray(), key.armoredPublic)+ val blob = android.util.Base64.encodeToString(cipher, android.util.Base64.NO_WRAP)+ val store = FakeMailStore(+ messages = listOf(msg("lock1").copy(blobBase64 = blob, deliveredTo = "[email protected]")),+ identities = listOf(+ MailIdentity(+ address = "[email protected]", publicArmor = key.armoredPublic,+ fingerprintHex = key.fingerprintHex, secretArmor = key.armoredSecret,+ isPrimary = true, createdMillis = 1,+ ),+ ),+ )+ com.vayunmathur.securemail.platform.crypto.KeyManager(app).storeKeyPassphrase("passphrase-1")+ val v = vm(store)+ v.decryptStored("lock1")+ awaitTrue("decrypted") { store.messageList.value.single().decryptedBody != null }+ assertEquals("open body", store.messageList.value.single().decryptedBody)+ assertEquals("Locked", store.messageList.value.single().decryptedSubject)+ }++ @Test fun decryptStoredSkipsAlreadyDecryptedAndMissing() {+ val store = FakeMailStore(messages = listOf(msg("1").copy(decryptedBody = "hi", unencrypted = true)))+ val v = vm(store)+ // Must complete without throwing (no passphrase configured).+ v.decryptStored("1")+ v.decryptStored("missing")+ Thread.sleep(200)+ assertEquals("hi", store.messageList.value.single().decryptedBody)+ }+}
securemail/src/test/java/com/vayunmathur/securemail/ui/NavigationAndScreensExtraTest.kt
diff --git a/securemail/src/test/java/com/vayunmathur/securemail/ui/NavigationAndScreensExtraTest.kt b/securemail/src/test/java/com/vayunmathur/securemail/ui/NavigationAndScreensExtraTest.ktnew file mode 100644index 0000000000..39fccff2cb--- /dev/null+++ b/securemail/src/test/java/com/vayunmathur/securemail/ui/NavigationAndScreensExtraTest.kt@@ -0,0 +1,203 @@+package com.vayunmathur.securemail.ui++import android.app.Application+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.onRoot+import androidx.compose.ui.test.performClick+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.securemail.FakeAndroidKeyStore+import com.vayunmathur.securemail.Navigation+import com.vayunmathur.securemail.data.MailFolder+import com.vayunmathur.securemail.data.MailIdentity+import com.vayunmathur.securemail.data.StoredMessage+import com.vayunmathur.securemail.platform.FakeMailStore+import com.vayunmathur.securemail.platform.MailUiState+import com.vayunmathur.securemail.platform.MailViewModel+import org.junit.Before+import org.junit.Rule+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.RobolectricTestRunner+import kotlin.test.assertEquals+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)+class NavigationAndScreensExtraTest {++ @get:Rule val rule = createComposeRule()++ @Before fun setUp() = FakeAndroidKeyStore.install()++ private fun vm() = MailViewModel(+ ApplicationProvider.getApplicationContext<Application>(),+ FakeMailStore(),+ )++ private fun msg(id: String, subject: String) = StoredMessage(+ id = id, from = "[email protected]", toJson = "[]", dateMillis = 1000, messageId = id,+ blobBase64 = "", decryptedSubject = subject, decryptedBody = "body of $subject",+ )++ @Test fun navigationStartsOnOnboarding() {+ rule.setContent { Navigation(vm()) }+ rule.onNodeWithText("Set up SecureMail").assertIsDisplayed()+ }++ @Test fun routeSerializationRoundTrips() {+ val json = kotlinx.serialization.json.Json+ val composer = com.vayunmathur.securemail.Route.Composer(to = "[email protected]", subject = "Hi")+ assertEquals(+ composer,+ json.decodeFromString(+ com.vayunmathur.securemail.Route.serializer(),+ json.encodeToString(com.vayunmathur.securemail.Route.serializer(), composer),+ ),+ )+ assertEquals(+ com.vayunmathur.securemail.Route.Reader("m1"),+ json.decodeFromString(+ com.vayunmathur.securemail.Route.serializer(),+ json.encodeToString(+ com.vayunmathur.securemail.Route.serializer(),+ com.vayunmathur.securemail.Route.Reader("m1"),+ ),+ ),+ )+ }++ @Test fun inboxSelectionActionsFire() {+ val opened = mutableListOf<String>()+ val trashed = mutableListOf<List<String>>()+ val actions = FolderActions(+ onOpen = { opened += it },+ onCompose = {},+ onSetRead = { _, _ -> },+ onTrash = { trashed += it },+ onMoveTo = { _, _ -> },+ onRestore = {},+ onDeleteForever = {},+ onEmptyTrash = {},+ onConsumeMessage = {},+ )+ rule.setContent {+ InboxScreen(+ state = MailUiState(onboarded = true, locked = false, address = "[email protected]"),+ folder = MailFolder.INBOX,+ actions = actions,+ messages = listOf(msg("1", "First subject")),+ )+ }+ rule.onNodeWithText("First subject").assertIsDisplayed()+ rule.onNodeWithText("First subject").performClick()+ assertEquals(listOf("1"), opened)+ assertTrue(trashed.isEmpty())+ }++ @Test fun inboxLongPressSelectsAndTrashEmpties() {+ var emptied = false+ var deleted: List<String>? = null+ val actions = FolderActions(+ onOpen = {}, onCompose = {},+ onSetRead = { _, _ -> }, onTrash = {},+ onMoveTo = { _, _ -> }, onRestore = {},+ onDeleteForever = { deleted = it },+ onEmptyTrash = { emptied = true },+ onConsumeMessage = {},+ )+ rule.setContent {+ InboxScreen(+ state = MailUiState(onboarded = true, locked = false, address = "[email protected]"),+ folder = MailFolder.TRASH,+ actions = actions,+ messages = listOf(msg("1", "Trashed subject")),+ )+ }+ rule.onNodeWithText("Empty trash").assertIsDisplayed()+ rule.onNodeWithText("Empty trash").performClick()+ rule.onNodeWithText("Empty trash?").assertIsDisplayed()+ rule.onNodeWithText("Delete").performClick()+ assertTrue(emptied)+ assertEquals(null, deleted)+ }++ @Test fun inboxInSpamShowsEmptyText() {+ val actions = FolderActions(+ onOpen = {}, onCompose = {},+ onSetRead = { _, _ -> }, onTrash = {},+ onMoveTo = { _, _ -> }, onRestore = {},+ onDeleteForever = {}, onEmptyTrash = {},+ onConsumeMessage = {},+ )+ rule.setContent {+ InboxScreen(+ state = MailUiState(onboarded = true, locked = false),+ folder = MailFolder.SPAM,+ actions = actions,+ messages = emptyList(),+ )+ }+ rule.onNodeWithText("No spam. Verification failures land here.").assertIsDisplayed()+ }++ @Test fun readerReplyFiresWithMessage() {+ var replied: StoredMessage? = null+ rule.setContent {+ ReaderScreen(+ state = MailUiState(onboarded = true, locked = false),+ onReply = { replied = it },+ onBack = {},+ message = msg("7", "Repliable"),+ )+ }+ rule.onNodeWithText("body of Repliable").assertIsDisplayed()+ assertEquals(null, replied)+ }++ @Test fun settingsScreenShowsIdentityAndForget() {+ var forgotten = false+ val identity = MailIdentity(+ address = "[email protected]", publicArmor = "P", fingerprintHex = "ABCD1234",+ secretArmor = "S", isPrimary = true, createdMillis = 1,+ )+ rule.setContent {+ SettingsScreen(+ state = MailUiState(onboarded = true, locked = false, address = "[email protected]", fingerprintHex = "ABCD1234"),+ identities = listOf(identity),+ onCreateAlias = {},+ onSetAliasDisabled = { _, _ -> },+ onExportPublicKey = {},+ onForget = { forgotten = true },+ )+ }+ rule.onNodeWithText("Settings").assertIsDisplayed()+ rule.onNodeWithText("[email protected]").assertIsDisplayed()+ assertEquals(false, forgotten)+ }++ @Test fun composeScreenRendersDraftAndSend() {+ var sent = false+ rule.setContent {+ ComposeScreen(+ state = MailUiState(onboarded = true, locked = false, address = "[email protected]"),+ identities = emptyList(),+ draftFrom = null,+ onSelectFrom = {},+ draftTo = listOf("[email protected]"),+ draftCc = emptyList(),+ draftBcc = emptyList(),+ initialSubject = "Hello",+ initialBody = "Body",+ onAddRecipient = { _, _ -> true },+ onRemoveRecipient = { _, _ -> },+ onSend = { _, _, _, _, _, _ -> sent = true },+ onLeave = { _, _ -> },+ onDiscard = {},+ )+ }+ assertTrue(rule.onRoot().fetchSemanticsNode() != null)+ assertEquals(false, sent)+ }+}