Modern Apps git

← Modern-Apps.git

euicc: add tests for LPA flows, screens and services

Commit
3f45ede8247d84178adb8e1bdf0aa81bb1226f1f
Author
Vayun Mathur <[email protected]>
When
2026-11-07 06:50 UTC (29 days ago)
Parents
063f71f
First test suite for :euicc (was 0 test files / no merged report):
102 tests across data models and JSON decoding, activation-code
validation, DownloadState/Route, the native bridge transmit hook,
EuiccChannelManager (including a Robolectric TelephonyManager
shadow that reports a fake eUICC and answers the ByPort APDU
calls), EuiccViewModel, EuiccManagerService/DownloadService,
Navigation and both activities, and Compose screens under
Robolectric (home/AddSim/ActivationCode/DeviceInfo/ProfileDetail/
Download phases/dialogs, QR scanner with and without permission).

A fake eUICC at the APDU layer plus a local HTTP fake SM-DP+
(FakeEuicc/FakeSmdp) let the real Rust SGP.22 core run
authenticate -> confirm -> install, confirmation-code refusal
and re-authentication, cancel, profile enable/disable/delete/
rename, notification listing, and the EuiccService download and
switch paths end to end with no hardware and no external network.

Merged INSTRUCTION coverage: 0% -> 88.2% (9682/10974).
Untestable remainder: QrCodeAnalyzer frame decoding (needs real
camera frames), the Eid QR Canvas draw pass, OTA callback
construction (framework type is an abstract class, not the stub
interface), and profile-install hardware paths beyond the fake
APDU responses. Adds testCompileOnly :library:aosp-stubs so unit
tests can reference the EuiccService surface.

(cherry picked from commit b48a8d69975626ded596203c520f40c3eb5d34b2)

Diff

euicc/build.gradle.kts
diff --git a/euicc/build.gradle.kts b/euicc/build.gradle.ktsindex d55cc5ab67..94b48085a9 100644--- a/euicc/build.gradle.kts+++ b/euicc/build.gradle.kts@@ -32,6 +32,9 @@ dependencies {     // (android.service.euicc.*, EuiccProfileInfo). Provided by the framework at     // runtime on a system image; must NOT be packaged.     compileOnly(project(":library:aosp-stubs"))+    // Unit tests reference the EuiccService surface at compile time; at runtime+    // Robolectric supplies the framework's real classes.+    testCompileOnly(project(":library:aosp-stubs"))     // Rust reaches the SM-DP+ over HTTP through the flat-framed JNI bridge in     // library:network (NativeHttpBridge), so libeuicc.so links no TLS of its own.     implementation(project(":library:network"))
euicc/src/test/java/com/vayunmathur/euicc/EuiccNativeTest.kt
diff --git a/euicc/src/test/java/com/vayunmathur/euicc/EuiccNativeTest.kt b/euicc/src/test/java/com/vayunmathur/euicc/EuiccNativeTest.ktnew file mode 100644index 0000000000..c68fc7978a--- /dev/null+++ b/euicc/src/test/java/com/vayunmathur/euicc/EuiccNativeTest.kt@@ -0,0 +1,45 @@+package com.vayunmathur.euicc++import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFailsWith+import kotlin.test.assertNotNull+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)+class EuiccNativeTest {+    @Test fun `transmitApdu without channel throws`() {+        EuiccNative.activeChannel = null+        assertFailsWith<IllegalStateException> {+            EuiccNative.transmitApdu(byteArrayOf(0x00, 0xA4.toByte(), 0x04, 0x00))+        }+    }++    @Test fun `transmitApdu forwards to active channel`() {+        var seen: ByteArray? = null+        EuiccNative.activeChannel = { cmd -> seen = cmd; byteArrayOf(0x90.toByte(), 0x00) }+        try {+            val out = EuiccNative.transmitApdu(byteArrayOf(1, 2, 3))+            assertEquals(listOf(0x90.toByte(), 0x00.toByte()), out.toList())+            assertEquals(listOf(1.toByte(), 2.toByte(), 3.toByte()), seen!!.toList())+        } finally {+            EuiccNative.activeChannel = null+        }+    }++    @Test fun `native version returns non-blank string`() {+        val v = EuiccNative.nativeVersion()+        assertNotNull(v)+        assertTrue(v.isNotBlank(), "version was: $v")+    }++    @Test fun `native getters without open channel do not return profiles`() {+        EuiccNative.activeChannel = null+        // No ISD-R channel is open, so the native core has no transport; it+        // must report failure (null) rather than fabricated data.+        val eid = runCatching { EuiccNative.nativeGetEid() }.getOrNull()+        assertTrue(eid == null || eid.isBlank(), "unexpected eid: $eid")+    }+}
euicc/src/test/java/com/vayunmathur/euicc/FakeEuiccIntegrationTest.kt
diff --git a/euicc/src/test/java/com/vayunmathur/euicc/FakeEuiccIntegrationTest.kt b/euicc/src/test/java/com/vayunmathur/euicc/FakeEuiccIntegrationTest.ktnew file mode 100644index 0000000000..bd1848e331--- /dev/null+++ b/euicc/src/test/java/com/vayunmathur/euicc/FakeEuiccIntegrationTest.kt@@ -0,0 +1,142 @@+package com.vayunmathur.euicc++import android.app.Application+import android.content.Context+import android.service.euicc.EuiccService+import android.telephony.TelephonyManager+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.euicc.platform.DownloadState+import com.vayunmathur.euicc.platform.EuiccViewModel+import com.vayunmathur.euicc.service.EuiccManagerService+import com.vayunmathur.euicc.telephony.FakeEuiccTelephonyShadow+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.ExperimentalCoroutinesApi+import kotlinx.coroutines.test.resetMain+import kotlinx.coroutines.test.setMain+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows+import org.robolectric.annotation.Config+import org.robolectric.shadows.UiccCardInfoBuilder+import org.robolectric.shadows.UiccPortInfoBuilder+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * With [FakeEuiccTelephonyShadow] reporting an eUICC and answering APDUs with+ * a bare `9000`, the channel opens and the native core runs; it finds no+ * profile data, which exercises the success-shaped paths of the ViewModel+ * reload/actions and the manager service that the no-hardware tests cannot.+ */+@OptIn(ExperimentalCoroutinesApi::class)+@RunWith(RobolectricTestRunner::class)+@Config(shadows = [FakeEuiccTelephonyShadow::class])+class FakeEuiccIntegrationTest {+    private val ctx: Context get() = ApplicationProvider.getApplicationContext()++    @BeforeTest fun setUp() {+        Dispatchers.setMain(Dispatchers.Unconfined)+        FakeEuiccTelephonyShadow.reset()+        EuiccNative.activeChannel = null+        val tm = ctx.getSystemService(TelephonyManager::class.java)+        Shadows.shadowOf(tm).setUiccCardsInfo(+            listOf(+                UiccCardInfoBuilder.newBuilder()+                    .setIsEuicc(true).setCardId(1).setEid("89044000001234567890123456789012")+                    .setSlotIndex(0).setPhysicalSlotIndex(0)+                    .setPorts(+                        listOf(+                            UiccPortInfoBuilder.newBuilder().setPortIndex(0)+                                .setLogicalSlotIndex(0).setIsActive(true).build(),+                        ),+                    ).build(),+            ),+        )+    }++    @AfterTest fun tearDown() { Dispatchers.resetMain() }++    private fun vm() = EuiccViewModel(ApplicationProvider.getApplicationContext<Application>())++    private fun awaitVm(vm: EuiccViewModel, timeoutMs: Long = 15_000) {+        val deadline = System.currentTimeMillis() + timeoutMs+        while (vm.state.loading && System.currentTimeMillis() < deadline) Thread.sleep(10)+    }++    @Test fun `viewmodel reload succeeds over fake channel with empty euicc`() {+        val vm = vm()+        awaitVm(vm)+        assertFalse(vm.state.loading)+        assertNull(vm.state.error, "state=${vm.state}")+        assertTrue(vm.state.profiles.isEmpty())+        assertTrue(vm.state.notifications.isEmpty())+        // The channel was opened and closed for the reload.+        assertTrue(FakeEuiccTelephonyShadow.openCalls.isNotEmpty())+        assertEquals(FakeEuiccTelephonyShadow.openCalls.size, FakeEuiccTelephonyShadow.closeCalls.size)+    }++    @Test fun `viewmodel actions run over fake channel and settle`() {+        val vm = vm()+        awaitVm(vm)+        vm.enable("98AB")+        awaitVm(vm)+        assertFalse(vm.state.loading)+        vm.disable("98AB")+        awaitVm(vm)+        assertFalse(vm.state.loading)+        vm.rename("98AB", "Work")+        awaitVm(vm)+        assertFalse(vm.state.loading)+        vm.removeNotification(1)+        awaitVm(vm)+        assertFalse(vm.state.loading)+        assertTrue(FakeEuiccTelephonyShadow.openCalls.size >= 5)+    }++    @Test fun `viewmodel delete settles`() {+        val vm = vm()+        awaitVm(vm)+        vm.delete("98AB")+        awaitVm(vm)+        assertFalse(vm.state.loading)+    }++    @Test fun `manager service over fake channel returns empty success shapes`() {+        val controller = Robolectric.buildService(EuiccManagerService::class.java)+        val service = controller.create().get()+        assertNull(service.onGetEid(0))+        assertEquals("", service.onGetEuiccInfo(0).osVersion)+        assertNotNull(service.onGetEuiccProfileInfoList(0))+        assertEquals(EuiccService.RESULT_FIRST_USER, service.onDeleteSubscription(0, "8901"))+        assertEquals(EuiccService.RESULT_FIRST_USER, service.onSwitchToSubscription(0, "8901", false))+        assertEquals(EuiccService.RESULT_FIRST_USER, service.onSwitchToSubscription(0, null, false))+        assertEquals(EuiccService.RESULT_FIRST_USER, service.onUpdateSubscriptionNickname(0, "8901", "Work"))+        controller.destroy()+    }++    @Test fun `viewmodel startDownload reaches a terminal download state`() {+        val vm = vm()+        awaitVm(vm)+        vm.startDownload("LPA:1\$smdp.example.com\$MATCH1")+        assertEquals(DownloadState.Preparing, vm.download)+        val deadline = System.currentTimeMillis() + 30_000+        while (vm.download is DownloadState.Preparing && System.currentTimeMillis() < deadline) Thread.sleep(20)+        // Without a real SM-DP+ the authenticate phase must fail, not hang or+        // report success.+        assertTrue(+            vm.download is DownloadState.Failed || vm.download is DownloadState.Confirm ||+                vm.download is DownloadState.AwaitingConfirmationCode,+            "download=${vm.download}",+        )+        vm.cancelDownload()+        vm.clearDownload()+        assertEquals(DownloadState.Idle, vm.download)+    }+}
euicc/src/test/java/com/vayunmathur/euicc/FakeSmdp.kt
diff --git a/euicc/src/test/java/com/vayunmathur/euicc/FakeSmdp.kt b/euicc/src/test/java/com/vayunmathur/euicc/FakeSmdp.ktnew file mode 100644index 0000000000..1f61997b8f--- /dev/null+++ b/euicc/src/test/java/com/vayunmathur/euicc/FakeSmdp.kt@@ -0,0 +1,253 @@+package com.vayunmathur.euicc++import com.sun.net.httpserver.HttpServer+import com.vayunmathur.euicc.telephony.FakeEuiccTelephonyShadow+import java.net.InetSocketAddress+import java.util.Base64+import java.util.concurrent.ConcurrentHashMap+import java.util.concurrent.atomic.AtomicInteger++/** Minimal DER TLV helpers for emulating eUICC / SM-DP+ payloads in tests. */+internal fun der(tag: ByteArray, value: ByteArray): ByteArray {+    val len = when {+        value.size < 0x80 -> byteArrayOf(value.size.toByte())+        value.size < 0x100 -> byteArrayOf(0x81.toByte(), value.size.toByte())+        else -> byteArrayOf(0x82.toByte(), (value.size shr 8).toByte(), value.size.toByte())+    }+    return tag + len + value+}++internal fun tlv1(tag: Int, value: ByteArray) = der(byteArrayOf(tag.toByte()), value)+internal fun tlv2(b1: Int, b2: Int, value: ByteArray) = der(byteArrayOf(b1.toByte(), b2.toByte()), value)+internal fun cat(vararg parts: ByteArray): ByteArray {+    var out = ByteArray(0)+    for (p in parts) out += p+    return out+}++internal fun ByteArray.toHex(): String = joinToString("") { "%02X".format(it.toInt() and 0xFF) }+internal fun hexBytes(hex: String): ByteArray =+    ByteArray(hex.length / 2) { hex.substring(it * 2, it * 2 + 2).toInt(16).toByte() }++/** BCD-encodes decimal digits the way ICCIDs are stored (nibble-swapped, F-padded). */+internal fun iccidBcd(digits: String): ByteArray {+    val padded = if (digits.length % 2 == 1) digits + "F" else digits+    return ByteArray(padded.length / 2) { i ->+        val lo = padded[i * 2].digitToIntOrNull() ?: 0xF+        val hi = padded.getOrNull(i * 2 + 1)?.digitToIntOrNull() ?: 0xF+        ((hi shl 4) or lo).toByte()+    }+}++internal fun b64(bytes: ByteArray): String = Base64.getEncoder().encodeToString(bytes)++/**+ * A fake eUICC at the APDU layer plus a fake SM-DP+ at the HTTP layer, good+ * enough for the Rust SGP.22 core to run authenticate / finish / cancel and+ * the ES10 reads against. APDU replies are keyed by the DER tag of the+ * (reassembled) STORE DATA payload; BPP segments after the first are counted.+ */+class FakeEuicc {+    var profileSet: List<ByteArray> = defaultProfiles()+    private var bppSegmentsLeft = -1+    private var partial = StringBuilder()++    fun install() {+        FakeEuiccTelephonyShadow.transmitHandler = { call -> handle(call) }+    }++    private fun handle(call: FakeEuiccTelephonyShadow.TransmitCall): String {+        // STORE DATA chunking: P1 0x11 = more blocks follow, 0x91 = last block.+        if (call.p1 == 0x11) {+            partial.append(call.data)+            return "9000"+        }+        val full = partial.toString() + call.data+        partial = StringBuilder()+        return respond(full)+    }++    private fun respond(dataHex: String): String {+        when {+            dataHex.startsWith("BF36") -> {+                // Our BPP segments into 6 STORE DATA calls; this is the first.+                bppSegmentsLeft = 5+                return "9000"+            }+            bppSegmentsLeft > 0 -> {+                bppSegmentsLeft--+                if (bppSegmentsLeft == 0) {+                    bppSegmentsLeft = -1+                    return installSuccessHex()+                }+                return "9000"+            }+        }+        val body: ByteArray = when {+            dataHex.startsWith("BF2E") ->+                tlv2(0xBF, 0x2E, tlv1(0x80, ByteArray(16) { (it + 1).toByte() }))+            dataHex.startsWith("BF20") -> info1()+            dataHex.startsWith("BF3E") ->+                tlv2(0xBF, 0x3E, tlv1(0x5A, hexBytes("89044022444301000000000000012345".take(32))))+            dataHex.startsWith("BF2D") ->+                tlv2(0xBF, 0x2D, tlv1(0xA0, cat(*profileSet.toTypedArray())))+            dataHex.startsWith("BF28") -> notifications()+            dataHex.startsWith("BF30") -> tlv2(0xBF, 0x30, tlv1(0x80, byteArrayOf(0)))+            dataHex.startsWith("BF31") -> tlv2(0xBF, 0x31, tlv1(0x80, byteArrayOf(0)))+            dataHex.startsWith("BF32") -> tlv2(0xBF, 0x32, tlv1(0x80, byteArrayOf(0)))+            dataHex.startsWith("BF33") -> tlv2(0xBF, 0x33, tlv1(0x80, byteArrayOf(0)))+            dataHex.startsWith("BF29") -> tlv2(0xBF, 0x29, tlv1(0x80, byteArrayOf(0)))+            dataHex.startsWith("BF38") -> tlv2(0xBF, 0x38, ByteArray(0))+            dataHex.startsWith("BF21") -> tlv2(0xBF, 0x21, ByteArray(0))+            dataHex.startsWith("BF41") -> tlv2(0xBF, 0x41, ByteArray(0))+            dataHex.startsWith("BF2B") -> tlv2(0xBF, 0x2B, ByteArray(0))+            else -> ByteArray(0)+        }+        return body.toHex() + "9000"+    }++    private fun info1(): ByteArray = tlv2(+        0xBF, 0x20,+        cat(+            tlv1(0x82, byteArrayOf(2, 2, 0)),+            tlv1(0xA9, tlv1(0x04, hexBytes("1122"))),+            tlv1(0xAA, tlv1(0x04, hexBytes("3344"))),+        ),+    )++    private fun notifications(): ByteArray {+        val meta = tlv2(+            0xBF, 0x2F,+            cat(+                tlv1(0x80, byteArrayOf(3)),+                tlv1(0x81, byteArrayOf(0, 0x80.toByte())),+                tlv1(0x0C, "smdp.example.com".toByteArray()),+                tlv1(0x5A, iccidBcd("8901234567890000001")),+            ),+        )+        return tlv2(0xBF, 0x28, tlv1(0xA0, meta))+    }++    private fun installSuccessHex(): String {+        val meta = tlv2(+            0xBF, 0x2F,+            cat(+                tlv1(0x80, byteArrayOf(7)),+                tlv1(0x5A, iccidBcd("8901234567890000001")),+            ),+        )+        val data = tlv2(0xBF, 0x27, cat(meta, tlv1(0xA2, tlv1(0xA0, ByteArray(0)))))+        return tlv2(0xBF, 0x37, data).toHex() + "9000"+    }++    companion object {+        fun profile(+            iccidDigits: String, state: Int, profileClass: Int,+            nickname: String = "", spn: String = "", name: String = "",+        ): ByteArray {+            var body = cat(+                tlv1(0x5A, iccidBcd(iccidDigits)),+                tlv1(0x4F, hexBytes("A0000005591010")),+                der(byteArrayOf(0x9F.toByte(), 0x70), byteArrayOf(state.toByte())),+                tlv1(0x95, byteArrayOf(profileClass.toByte())),+            )+            if (nickname.isNotEmpty()) body += tlv1(0x90, nickname.toByteArray())+            if (spn.isNotEmpty()) body += tlv1(0x91, spn.toByteArray())+            if (name.isNotEmpty()) body += tlv1(0x92, name.toByteArray())+            return tlv1(0xE3, body)+        }++        fun defaultProfiles(): List<ByteArray> = listOf(+            profile("8901234567890000001", state = 1, profileClass = 2, nickname = "Work", spn = "Example Mobile", name = "Prepaid"),+            profile("8901234567890000002", state = 0, profileClass = 0, spn = "Travel eSIM", name = "Global Data"),+            profile("8901234567890000003", state = 0, profileClass = 1),+            profile("8901234567890000004", state = 0, profileClass = 9),+        )+    }+}++/** Local HTTP SM-DP+ speaking just enough ES9+ for the Rust core. */+class FakeSmdp {+    var ccRequired: Boolean = false+    var refuseBoundProfilePackage: Boolean = false+    val counts = ConcurrentHashMap<String, AtomicInteger>()+    private val server: HttpServer = HttpServer.create(InetSocketAddress("127.0.0.1", 0), 0)++    val port: Int get() = server.address.port+    fun activationCode(): String = "LPA:1\$http://127.0.0.1:$port\$MATCH1"++    fun count(fn: String): Int = counts[fn]?.get() ?: 0++    fun start() {+        server.createContext("/gsma/rsp2/es9plus/") { exchange ->+            val fn = exchange.requestURI.path.substringAfterLast('/')+            counts.computeIfAbsent(fn) { AtomicInteger() }.incrementAndGet()+            exchange.requestBody.readAllBytes()+            val (status, body) = when (fn) {+                "initiateAuthentication" -> 200 to initiate()+                "authenticateClient" -> 200 to authenticateClient()+                "getBoundProfilePackage" ->+                    if (refuseBoundProfilePackage) 200 to failedStatus()+                    else 200 to boundProfilePackage()+                "cancelSession" -> 204 to ""+                "handleNotification" -> 204 to ""+                else -> 404 to ""+            }+            val bytes = body.toByteArray()+            if (status == 204) {+                exchange.sendResponseHeaders(204, -1)+            } else {+                exchange.responseHeaders.set("Content-Type", "application/json")+                exchange.sendResponseHeaders(status, bytes.size.toLong())+                exchange.responseBody.use { it.write(bytes) }+            }+            exchange.close()+        }+        server.start()+    }++    fun stop() = server.stop(0)++    private fun successHeader(): String =+        """"header":{"functionExecutionStatus":{"status":"Executed-Success"}}"""++    private fun initiate(): String {+        val txBin = "txbin123".toByteArray()+        val serverSigned1 = der(byteArrayOf(0x30), tlv1(0x80, txBin))+        return """{${successHeader()},"transactionId":"tx-123","serverSigned1":"${b64(serverSigned1)}","serverSignature1":"${b64(byteArrayOf(1, 2, 3))}","euiccCiPKIdToBeUsed":"${b64(hexBytes("1122"))}","serverCertificate":"${b64(byteArrayOf(0x30, 0))}"}"""+    }++    private fun authenticateClient(): String {+        val metadata = tlv2(+            0xBF, 0x25,+            cat(+                tlv1(0x5A, iccidBcd("8901234567890000001")),+                tlv1(0x91, "Fake Carrier".toByteArray()),+                tlv1(0x92, "Fake Plan".toByteArray()),+                tlv1(0x95, byteArrayOf(2)),+            ),+        )+        val signed2 = der(+            byteArrayOf(0x30),+            cat(+                tlv1(0x80, "txbin123".toByteArray()),+                tlv1(0x01, byteArrayOf(if (ccRequired) 1 else 0)),+            ),+        )+        return """{${successHeader()},"profileMetadata":"${b64(metadata)}","smdpSigned2":"${b64(signed2)}","smdpSignature2":"${b64(byteArrayOf(4, 5))}","smdpCertificate":"${b64(byteArrayOf(0x30, 0))}"}"""+    }++    private fun failedStatus(): String =+        """{"header":{"functionExecutionStatus":{"status":"Failed","statusCodeData":{"subjectCode":"8.2.7","reasonCode":"3.8"}}}}"""++    private fun boundProfilePackage(): String {+        val body = cat(+            tlv2(0xBF, 0x23, byteArrayOf(1)),+            tlv1(0xA0, tlv1(0x87, byteArrayOf(0x11))),+            tlv1(0xA1, tlv1(0x88, byteArrayOf(0x33))),+            tlv1(0xA3, tlv1(0x86, byteArrayOf(0x55))),+        )+        val bpp = tlv2(0xBF, 0x36, body)+        return """{${successHeader()},"boundProfilePackage":"${b64(bpp)}"}"""+    }+}
euicc/src/test/java/com/vayunmathur/euicc/FakeSmdpIntegrationTest.kt
diff --git a/euicc/src/test/java/com/vayunmathur/euicc/FakeSmdpIntegrationTest.kt b/euicc/src/test/java/com/vayunmathur/euicc/FakeSmdpIntegrationTest.ktnew file mode 100644index 0000000000..ebf93ad722--- /dev/null+++ b/euicc/src/test/java/com/vayunmathur/euicc/FakeSmdpIntegrationTest.kt@@ -0,0 +1,272 @@+package com.vayunmathur.euicc++import android.app.Application+import android.content.Context+import android.service.euicc.EuiccService+import android.telephony.TelephonyManager+import android.telephony.euicc.DownloadableSubscription+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.euicc.platform.DownloadState+import com.vayunmathur.euicc.platform.EuiccViewModel+import com.vayunmathur.euicc.service.EuiccManagerService+import com.vayunmathur.euicc.telephony.FakeEuiccTelephonyShadow+import com.vayunmathur.library.network.NetworkClient+import com.vayunmathur.library.network.TrustBundle+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.ExperimentalCoroutinesApi+import kotlinx.coroutines.test.resetMain+import kotlinx.coroutines.test.setMain+import kotlinx.serialization.json.Json+import kotlinx.serialization.json.jsonObject+import kotlinx.serialization.json.jsonPrimitive+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows+import org.robolectric.annotation.Config+import org.robolectric.shadows.UiccCardInfoBuilder+import org.robolectric.shadows.UiccPortInfoBuilder+import java.util.concurrent.Executors+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Full SGP.22 flows against [FakeEuicc] (APDU layer) and [FakeSmdp] (local+ * HTTP ES9+), so the split-phase download, the ViewModel state machine around+ * it, and the manager service's profile operations run end to end.+ */+@OptIn(ExperimentalCoroutinesApi::class)+@RunWith(RobolectricTestRunner::class)+@Config(shadows = [FakeEuiccTelephonyShadow::class])+class FakeSmdpIntegrationTest {+    private val ctx: Context get() = ApplicationProvider.getApplicationContext()+    private lateinit var smdp: FakeSmdp+    private lateinit var euicc: FakeEuicc++    @BeforeTest fun setUp() {+        Dispatchers.setMain(Dispatchers.Unconfined)+        FakeEuiccTelephonyShadow.reset()+        EuiccNative.activeChannel = null+        val tm = ctx.getSystemService(TelephonyManager::class.java)+        Shadows.shadowOf(tm).setUiccCardsInfo(+            listOf(+                UiccCardInfoBuilder.newBuilder()+                    .setIsEuicc(true).setCardId(1).setEid("89044000001234567890123456789012")+                    .setSlotIndex(0).setPhysicalSlotIndex(0)+                    .setPorts(+                        listOf(+                            UiccPortInfoBuilder.newBuilder().setPortIndex(0)+                                .setLogicalSlotIndex(0).setIsActive(true).build(),+                        ),+                    ).build(),+            ),+        )+        euicc = FakeEuicc()+        euicc.install()+        smdp = FakeSmdp()+        smdp.start()+        NetworkClient.init(ctx, TrustBundle.ESIM)+    }++    @AfterTest fun tearDown() {+        smdp.stop()+        Dispatchers.resetMain()+    }++    private fun channelManager() =+        com.vayunmathur.euicc.telephony.EuiccChannelManager(ctx)++    private fun vm() = EuiccViewModel(ApplicationProvider.getApplicationContext<Application>())++    private fun awaitVm(vm: EuiccViewModel, timeoutMs: Long = 20_000) {+        val deadline = System.currentTimeMillis() + timeoutMs+        while (vm.state.loading && System.currentTimeMillis() < deadline) Thread.sleep(10)+    }++    private fun awaitDownload(vm: EuiccViewModel, pred: (DownloadState) -> Boolean, timeoutMs: Long = 30_000) {+        val deadline = System.currentTimeMillis() + timeoutMs+        while (!pred(vm.download) && System.currentTimeMillis() < deadline) Thread.sleep(20)+    }++    @Test fun `viewmodel reload reads eid info profiles and notifications from fake euicc`() {+        val vm = vm()+        awaitVm(vm)+        assertFalse(vm.state.loading)+        assertNull(vm.state.error, "state=${vm.state}")+        assertEquals("2.2.0", vm.state.info?.svn)+        assertEquals(listOf("1122"), vm.state.info?.ciPkIdListForVerification)+        assertNotNull(vm.state.eid)+        assertEquals(4, vm.state.profiles.size)+        assertEquals("Work", vm.state.profiles[0].displayName)+        assertTrue(vm.state.profiles[0].isEnabled)+        assertEquals("Global Data", vm.state.profiles[1].displayName)+        assertEquals(1, vm.state.notifications.size)+        assertEquals(3, vm.state.notifications[0].seqNumber)+        assertEquals("install", vm.state.notifications[0].operation)+    }++    @Test fun `viewmodel profile actions succeed against fake euicc`() {+        val vm = vm()+        awaitVm(vm)+        val disabled = vm.state.profiles.first { !it.isEnabled }+        vm.enable(disabled.iccid)+        awaitVm(vm)+        assertNull(vm.state.error, "state=${vm.state}")+        val enabled = vm.state.profiles.first { it.isEnabled }+        vm.disable(enabled.iccid)+        awaitVm(vm)+        assertNull(vm.state.error)+        vm.rename(disabled.iccid, "Renamed")+        awaitVm(vm)+        assertNull(vm.state.error)+        vm.removeNotification(3)+        awaitVm(vm)+        assertNull(vm.state.error)+        vm.delete(disabled.iccid)+        awaitVm(vm)+        assertNull(vm.state.error)+        assertEquals(4, vm.state.profiles.size)+    }++    @Test fun `native split phase authenticate finish and cancel on one thread`() {+        val executor = Executors.newSingleThreadExecutor()+        try {+            val result = executor.submit<Pair<String, String>> {+                channelManager().withIsdrChannel {+                    val authRaw = EuiccNative.nativeAuthenticate(smdp.activationCode(), "", "", "")+                    val auth = Json.parseToJsonElement(authRaw).jsonObject+                    val tx = auth["transactionId"]?.jsonPrimitive?.content+                    assertNotNull(tx, "auth=$authRaw")+                    assertEquals("Fake Carrier", auth["carrier"]?.jsonPrimitive?.content)+                    val finishRaw = EuiccNative.nativeFinishDownload(+                        tx, "", "Fake Plan",+                        object : EuiccNative.DownloadProgressCallback {+                            override fun onProgress(done: Int, total: Int): Boolean = true+                        },+                    )+                    // Second session for cancel.+                    val auth2Raw = EuiccNative.nativeAuthenticate(smdp.activationCode(), "", "", "")+                    val tx2 = Json.parseToJsonElement(auth2Raw).jsonObject["transactionId"]?.jsonPrimitive?.content+                    assertNotNull(tx2)+                    assertTrue(EuiccNative.nativeCancelDownload(tx2, 0))+                    authRaw to finishRaw+                }+            }.get()+            val finish = Json.parseToJsonElement(result.second).jsonObject+            assertEquals("true", finish["success"]?.jsonPrimitive?.content, "finish=${result.second}")+            assertEquals(1, smdp.count("getBoundProfilePackage"))+            assertEquals(1, smdp.count("cancelSession"))+        } finally {+            executor.shutdownNow()+        }+    }++    @Test fun `viewmodel download confirms and completes`() {+        val vm = vm()+        awaitVm(vm)+        vm.startDownload(smdp.activationCode())+        awaitDownload(vm, { it is DownloadState.Confirm || it is DownloadState.Failed })+        assertTrue(vm.download is DownloadState.Confirm, "download=${vm.download}")+        val confirm = vm.download as DownloadState.Confirm+        assertEquals("Fake Carrier", confirm.carrier)+        assertEquals("Fake Plan", confirm.profileName)+        vm.confirmDownload()+        awaitDownload(vm, { it is DownloadState.Complete || it is DownloadState.Failed })+        assertTrue(vm.download is DownloadState.Complete, "download=${vm.download}")+        assertEquals("Fake Carrier", (vm.download as DownloadState.Complete).carrier)+        awaitVm(vm)+        assertNull(vm.state.error)+    }++    @Test fun `viewmodel download cancel from confirm returns to idle`() {+        val vm = vm()+        awaitVm(vm)+        vm.startDownload(smdp.activationCode())+        awaitDownload(vm, { it is DownloadState.Confirm || it is DownloadState.Failed })+        assertTrue(vm.download is DownloadState.Confirm, "download=${vm.download}")+        vm.cancelDownload()+        assertEquals(DownloadState.Idle, vm.download)+        vm.clearDownload()+        assertEquals(DownloadState.Idle, vm.download)+    }++    @Test fun `viewmodel confirmation code refusal relaunches to code screen with error`() {+        smdp.ccRequired = true+        smdp.refuseBoundProfilePackage = true+        val vm = vm()+        awaitVm(vm)+        vm.startDownload(smdp.activationCode())+        awaitDownload(vm, { it is DownloadState.AwaitingConfirmationCode || it is DownloadState.Failed })+        assertTrue(vm.download is DownloadState.AwaitingConfirmationCode, "download=${vm.download}")+        vm.submitConfirmationCode("badcode")+        awaitDownload(vm, {+            (it is DownloadState.AwaitingConfirmationCode && it.error) || it is DownloadState.Failed+        })+        assertTrue(+            vm.download is DownloadState.AwaitingConfirmationCode,+            "download=${vm.download}",+        )+        assertTrue((vm.download as DownloadState.AwaitingConfirmationCode).error)+        assertTrue(smdp.count("initiateAuthentication") >= 2, "counts=${smdp.counts}")+    }++    @Test fun `manager service maps profiles and runs operations`() {+        val controller = Robolectric.buildService(EuiccManagerService::class.java)+        val service = controller.create().get()+        assertEquals("2.2.0", service.onGetEuiccInfo(0).osVersion)+        assertNotNull(service.onGetEid(0))+        assertNotNull(service.onGetEuiccProfileInfoList(0))+        // Switch to a disabled profile by its display ICCID: enable succeeds.+        assertEquals(+            EuiccService.RESULT_OK,+            service.onSwitchToSubscription(0, "8901234567890000002", false),+        )+        // Null ICCID disables the currently enabled profile.+        assertEquals(EuiccService.RESULT_OK, service.onSwitchToSubscription(0, null, false))+        assertEquals(+            EuiccService.RESULT_OK,+            service.onSwitchToSubscriptionWithPort(0, 0, "8901234567890000002", false),+        )+        assertEquals(+            EuiccService.RESULT_OK,+            service.onUpdateSubscriptionNickname(0, "8901234567890000001", "Work"),+        )+        assertEquals(+            EuiccService.RESULT_OK,+            service.onDeleteSubscription(0, "8901234567890000003"),+        )+        // Unknown ICCID resolves to no profile.+        assertEquals(+            EuiccService.RESULT_FIRST_USER,+            service.onDeleteSubscription(0, "999999"),+        )+        controller.destroy()+    }++    @Test fun `manager service download subscription succeeds and honors switch flag`() {+        val controller = Robolectric.buildService(EuiccManagerService::class.java)+        val service = controller.create().get()+        val sub = DownloadableSubscription.forActivationCode(smdp.activationCode())+        assertEquals(+            EuiccService.RESULT_OK,+            service.onDownloadSubscription(0, sub, switchAfterDownload = false, forceDeactivateSim = false),+        )+        // An enabled profile exists, so switch-after-download without force+        // must ask the platform to deactivate first.+        assertEquals(+            EuiccService.RESULT_MUST_DEACTIVATE_SIM,+            service.onDownloadSubscription(0, sub, switchAfterDownload = true, forceDeactivateSim = false),+        )+        assertEquals(+            EuiccService.RESULT_OK,+            service.onDownloadSubscription(0, sub, switchAfterDownload = true, forceDeactivateSim = true),+        )+        controller.destroy()+    }+}
euicc/src/test/java/com/vayunmathur/euicc/NavigationAndActivitiesTest.kt
diff --git a/euicc/src/test/java/com/vayunmathur/euicc/NavigationAndActivitiesTest.kt b/euicc/src/test/java/com/vayunmathur/euicc/NavigationAndActivitiesTest.ktnew file mode 100644index 0000000000..98d919aee8--- /dev/null+++ b/euicc/src/test/java/com/vayunmathur/euicc/NavigationAndActivitiesTest.kt@@ -0,0 +1,130 @@+package com.vayunmathur.euicc++import android.app.Application+import android.content.Intent+import android.net.Uri+import androidx.compose.ui.test.junit4.createAndroidComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.euicc.platform.AddEsimActivity+import com.vayunmathur.euicc.platform.EuiccViewModel+import com.vayunmathur.euicc.platform.LuiActivity+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.ExperimentalCoroutinesApi+import kotlinx.coroutines.test.resetMain+import kotlinx.coroutines.test.setMain+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows+import android.os.Looper+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertTrue++@OptIn(ExperimentalCoroutinesApi::class)+@RunWith(RobolectricTestRunner::class)+class NavigationAndActivitiesTest {+    @get:Rule val rule = createAndroidComposeRule<androidx.activity.ComponentActivity>()++    @BeforeTest fun setUp() { Dispatchers.setMain(Dispatchers.Unconfined) }+    @AfterTest fun tearDown() { Dispatchers.resetMain() }++    private fun vm() = EuiccViewModel(ApplicationProvider.getApplicationContext<Application>())+    private fun str(id: Int) = ApplicationProvider.getApplicationContext<android.content.Context>().getString(id)++    @Test fun `navigation home shows app title`() {+        val vm = vm()+        rule.setContent { Navigation(vm) }+        rule.onNodeWithText(str(R.string.app_name)).assertExists()+    }++    @Test fun `navigation seeded with AddSim shows add sim screen`() {+        val vm = vm()+        rule.setContent { Navigation(vm, Route.AddSim) }+        rule.onNodeWithText(str(R.string.add_sim_body)).assertExists()+        rule.onNodeWithText(str(R.string.scan_qr_button)).assertExists()+    }++    @Test fun `navigation seeded with DeviceInfo shows device info`() {+        val vm = vm()+        rule.setContent { Navigation(vm, Route.DeviceInfo) }+        rule.onNodeWithText(str(R.string.device_info_title)).assertExists()+    }++    @Test fun `navigation seeded with ActivationCode shows code entry`() {+        val vm = vm()+        rule.setContent { Navigation(vm, Route.ActivationCode) }+        rule.onNodeWithText(str(R.string.activation_code_title)).assertExists()+    }++    @Test fun `navigation seeded with Home explicitly shows home`() {+        val vm = vm()+        rule.setContent { Navigation(vm, Route.Home) }+        rule.onNodeWithText(str(R.string.app_name)).assertExists()+    }++    @Test fun `lui activity creates and shows navigation`() {+        val controller = Robolectric.buildActivity(LuiActivity::class.java)+        controller.create()+        Shadows.shadowOf(Looper.getMainLooper()).idle()+        assertTrue(controller.get().isFinishing.not())+        controller.destroy()+    }++    @Test fun `add esim activity with valid universal link creates`() {+        val intent = Intent(Intent.ACTION_VIEW, Uri.parse(+            "https://esimsetup.android.com/esim_qrcode_provisioning?carddata=LPA:1\$smdp.example.com\$MATCH1",+        )).setClass(+            ApplicationProvider.getApplicationContext(),+            AddEsimActivity::class.java,+        )+        val controller = Robolectric.buildActivity(AddEsimActivity::class.java, intent)+        controller.create()+        Shadows.shadowOf(Looper.getMainLooper()).idle()+        assertTrue(controller.get().isFinishing.not())+        controller.destroy()+    }++    @Test fun `add esim activity with missing carddata creates add sim flow`() {+        val intent = Intent(Intent.ACTION_VIEW, Uri.parse(+            "https://esimsetup.android.com/esim_qrcode_provisioning",+        )).setClass(ApplicationProvider.getApplicationContext(), AddEsimActivity::class.java)+        val controller = Robolectric.buildActivity(AddEsimActivity::class.java, intent)+        controller.create()+        Shadows.shadowOf(Looper.getMainLooper()).idle()+        assertTrue(controller.get().isFinishing.not())+        controller.destroy()+    }++    @Test fun `add esim activity with lpa scheme creates`() {+        val intent = Intent(Intent.ACTION_VIEW, Uri.parse("lpa:1\$smdp.example.com\$MATCH1"))+            .setClass(ApplicationProvider.getApplicationContext(), AddEsimActivity::class.java)+        val controller = Robolectric.buildActivity(AddEsimActivity::class.java, intent)+        controller.create()+        Shadows.shadowOf(Looper.getMainLooper()).idle()+        assertTrue(controller.get().isFinishing.not())+        controller.destroy()+    }++    @Test fun `add esim activity with malformed carddata creates`() {+        val intent = Intent(Intent.ACTION_VIEW, Uri.parse(+            "https://esimsetup.android.com/esim_qrcode_provisioning?carddata=not-a-code",+        )).setClass(ApplicationProvider.getApplicationContext(), AddEsimActivity::class.java)+        val controller = Robolectric.buildActivity(AddEsimActivity::class.java, intent)+        controller.create()+        Shadows.shadowOf(Looper.getMainLooper()).idle()+        assertTrue(controller.get().isFinishing.not())+        controller.destroy()+    }++    @Test fun `add esim activity with no intent data creates`() {+        val controller = Robolectric.buildActivity(AddEsimActivity::class.java, Intent())+        controller.create()+        Shadows.shadowOf(Looper.getMainLooper()).idle()+        assertTrue(controller.get().isFinishing.not())+        controller.destroy()+    }+}
euicc/src/test/java/com/vayunmathur/euicc/data/ProfileDataTest.kt
diff --git a/euicc/src/test/java/com/vayunmathur/euicc/data/ProfileDataTest.kt b/euicc/src/test/java/com/vayunmathur/euicc/data/ProfileDataTest.ktnew file mode 100644index 0000000000..c3efd27a52--- /dev/null+++ b/euicc/src/test/java/com/vayunmathur/euicc/data/ProfileDataTest.kt@@ -0,0 +1,81 @@+package com.vayunmathur.euicc.data++import kotlinx.serialization.json.Json+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++class ProfileDataTest {+    private val json = Json { ignoreUnknownKeys = true }++    @Test fun `displayName prefers nickname then name then provider then iccid tail`() {+        assertEquals("Work", Profile(nickname = "Work", name = "Plan", serviceProvider = "Telco", iccidDisplay = "89010001234").displayName)+        assertEquals("Plan", Profile(name = "Plan", serviceProvider = "Telco", iccidDisplay = "89010001234").displayName)+        assertEquals("Telco", Profile(serviceProvider = "Telco", iccidDisplay = "89010001234").displayName)+        assertEquals("•••• 1234", Profile(iccidDisplay = "89010001234").displayName)+        assertEquals("", Profile().displayName)+        assertEquals("•••• abc", Profile(iccidDisplay = "abc").displayName)+    }++    @Test fun `displayName falls through blank strings`() {+        assertEquals("Plan", Profile(nickname = " ", name = "Plan").displayName)+        assertEquals("Telco", Profile(nickname = "", name = "  ", serviceProvider = "Telco").displayName)+    }++    @Test fun `isEnabled only for enabled state`() {+        assertTrue(Profile(state = "enabled").isEnabled)+        assertFalse(Profile(state = "disabled").isEnabled)+        assertFalse(Profile(state = "unknown").isEnabled)+        assertFalse(Profile().isEnabled)+    }++    @Test fun `profile decodes native json including class serial name`() {+        val p = json.decodeFromString<Profile>(+            """{"iccid":"98AB","iccidDisplay":"8901 2","isdpAid":"A000","state":"enabled","class":"operational","nickname":"Work","serviceProvider":"Telco","name":"Prepaid","extra":1}""",+        )+        assertEquals("98AB", p.iccid)+        assertEquals("8901 2", p.iccidDisplay)+        assertEquals("A000", p.isdpAid)+        assertEquals("operational", p.profileClass)+        assertTrue(p.isEnabled)+        assertEquals("Work", p.displayName)+    }++    @Test fun `profile defaults`() {+        val p = json.decodeFromString<Profile>("{}")+        assertEquals(Profile(), p)+        assertEquals("unknown", p.state)+        assertEquals("unknown", p.profileClass)+    }++    @Test fun `euicc info decodes and defaults`() {+        val info = json.decodeFromString<EuiccInfo>(+            """{"svn":"2.2.0","ciPkIdListForVerification":["aa","bb"],"ciPkIdListForSigning":["cc"]}""",+        )+        assertEquals("2.2.0", info.svn)+        assertEquals(listOf("aa", "bb"), info.ciPkIdListForVerification)+        assertEquals(listOf("cc"), info.ciPkIdListForSigning)+        assertEquals(EuiccInfo(), json.decodeFromString<EuiccInfo>("{}"))+    }++    @Test fun `notification decodes and defaults`() {+        val n = json.decodeFromString<Notification>(+            """{"seqNumber":7,"operation":"install","address":"smdp.example.com","iccidDisplay":"8901"}""",+        )+        assertEquals(7, n.seqNumber)+        assertEquals("install", n.operation)+        assertEquals("smdp.example.com", n.address)+        val d = json.decodeFromString<Notification>("{}")+        assertEquals(-1, d.seqNumber)+        assertEquals("unknown", d.operation)+        assertEquals("", d.address)+    }++    @Test fun `profile list decodes`() {+        val list = json.decodeFromString<List<Profile>>("""[{"iccid":"1"},{"iccid":"2","state":"enabled"}]""")+        assertEquals(2, list.size)+        assertEquals("2", list[1].iccid)+        assertTrue(list[1].isEnabled)+    }+}
euicc/src/test/java/com/vayunmathur/euicc/platform/DownloadStateAndRouteTest.kt
diff --git a/euicc/src/test/java/com/vayunmathur/euicc/platform/DownloadStateAndRouteTest.kt b/euicc/src/test/java/com/vayunmathur/euicc/platform/DownloadStateAndRouteTest.ktnew file mode 100644index 0000000000..7f1974b186--- /dev/null+++ b/euicc/src/test/java/com/vayunmathur/euicc/platform/DownloadStateAndRouteTest.kt@@ -0,0 +1,64 @@+package com.vayunmathur.euicc.platform++import com.vayunmathur.euicc.Route+import kotlinx.serialization.json.Json+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue++class DownloadStateAndRouteTest {+    @Test fun `download state variants hold data`() {+        assertEquals(DownloadState.Idle, DownloadState.Idle)+        assertEquals(DownloadState.Preparing, DownloadState.Preparing)+        assertEquals(DownloadState.Confirm("Telco", "Plan"), DownloadState.Confirm("Telco", "Plan"))+        assertNotEquals(DownloadState.Confirm("Telco", "Plan"), DownloadState.Confirm("Other", "Plan"))+        assertEquals(DownloadState.Confirm(null, null), DownloadState.Confirm(null, null))+        val awaiting = DownloadState.AwaitingConfirmationCode("Telco", error = true)+        assertEquals("Telco", awaiting.carrier)+        assertTrue(awaiting.error)+        assertEquals(DownloadState.AwaitingConfirmationCode("Telco"), DownloadState.AwaitingConfirmationCode("Telco", false))+        assertEquals(0.5f, DownloadState.Installing(0.5f).progress)+        assertNull(DownloadState.Installing().progress)+        assertEquals("Telco", DownloadState.Complete("Telco").carrier)+        assertNull(DownloadState.Complete(null).carrier)+        assertEquals("boom", DownloadState.Failed("boom").message)+        assertNull(DownloadState.Failed(null).message)+    }++    @Test fun `route download defaults and equality`() {+        val r = Route.Download("LPA:1\$a.b\$X")+        assertEquals("LPA:1\$a.b\$X", r.activationCode)+        assertNull(r.imei)+        assertNull(r.confirmationCode)+        assertEquals(Route.Download("c", "imei1", "cc"), Route.Download("c", "imei1", "cc"))+        assertNotEquals(Route.Download("c"), Route.Download("c", imei = "1"))+        assertEquals(Route.Home, Route.Home)+        assertEquals(Route.DeviceInfo, Route.DeviceInfo)+        assertEquals(Route.ProfileDetail("abc"), Route.ProfileDetail("abc"))+        assertNotEquals(Route.ProfileDetail("abc"), Route.ProfileDetail("def"))+    }++    @Test fun `routes serialize`() {+        val json = Json+        assertTrue(json.encodeToString(Route.serializer(), Route.Home).contains("Home"))+        val decoded = json.decodeFromString(Route.serializer(), json.encodeToString(Route.serializer(), Route.Download("code", "123", null)))+        assertEquals(Route.Download("code", "123", null), decoded)+        val detail = json.decodeFromString(Route.serializer(), json.encodeToString(Route.serializer(), Route.ProfileDetail("iccid1")))+        assertEquals(Route.ProfileDetail("iccid1"), detail)+    }++    @Test fun `screen state defaults`() {+        val s = EuiccScreenState()+        assertTrue(s.loading)+        assertNull(s.error)+        assertNull(s.eid)+        assertNull(s.info)+        assertTrue(s.profiles.isEmpty())+        assertTrue(s.notifications.isEmpty())+        val copy = s.copy(loading = false, error = "x", eid = "890")+        assertEquals("x", copy.error)+        assertEquals("890", copy.eid)+    }+}
euicc/src/test/java/com/vayunmathur/euicc/platform/EuiccViewModelTest.kt
diff --git a/euicc/src/test/java/com/vayunmathur/euicc/platform/EuiccViewModelTest.kt b/euicc/src/test/java/com/vayunmathur/euicc/platform/EuiccViewModelTest.ktnew file mode 100644index 0000000000..cc59592ed2--- /dev/null+++ b/euicc/src/test/java/com/vayunmathur/euicc/platform/EuiccViewModelTest.kt@@ -0,0 +1,102 @@+package com.vayunmathur.euicc.platform++import android.app.Application+import androidx.test.core.app.ApplicationProvider+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.ExperimentalCoroutinesApi+import kotlinx.coroutines.test.resetMain+import kotlinx.coroutines.test.setMain+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++@OptIn(ExperimentalCoroutinesApi::class)+@RunWith(RobolectricTestRunner::class)+class EuiccViewModelTest {+    @BeforeTest fun setUp() { Dispatchers.setMain(Dispatchers.Unconfined) }+    @AfterTest fun tearDown() { Dispatchers.resetMain() }++    private fun vm() = EuiccViewModel(ApplicationProvider.getApplicationContext<Application>())++    /** Awaits the IO-backed reload/action settling (condition poll, not a timing assertion). */+    private fun awaitSettled(vm: EuiccViewModel, timeoutMs: Long = 10_000) {+        val deadline = System.currentTimeMillis() + timeoutMs+        while (vm.state.loading && System.currentTimeMillis() < deadline) Thread.sleep(10)+    }++    @Test fun `initial reload reports eUICC unavailable without hardware`() {+        val vm = vm()+        awaitSettled(vm)+        assertFalse(vm.state.loading)+        assertNotNull(vm.state.error, "expected eUICC error, state=${vm.state}")+        assertTrue(vm.state.profiles.isEmpty())+        assertTrue(vm.state.notifications.isEmpty())+        assertNull(vm.state.eid)+        assertEquals(DownloadState.Idle, vm.download)+    }++    @Test fun `profile actions surface failure and clear loading`() {+        val vm = vm()+        awaitSettled(vm)+        for (action in listOf<() -> Unit>(+            { vm.enable("98AB") }, { vm.disable("98AB") }, { vm.delete("98AB") },+            { vm.rename("98AB", "Work") }, { vm.removeNotification(3) },+        )) {+            action()+            awaitSettled(vm)+            assertFalse(vm.state.loading)+            assertNotNull(vm.state.error)+        }+    }++    @Test fun `startDownload fails cleanly without channel and can be retried from Failed`() {+        val vm = vm()+        awaitSettled(vm)+        vm.startDownload("LPA:1\$smdp.example.com\$MATCH1", imei = "123", confirmationCode = null)+        assertEquals(DownloadState.Preparing, vm.download)+        val deadline = System.currentTimeMillis() + 10_000+        while (vm.download !is DownloadState.Failed && System.currentTimeMillis() < deadline) Thread.sleep(10)+        assertTrue(vm.download is DownloadState.Failed, "download=${vm.download}")+        assertNull((vm.download as DownloadState.Failed).message)+        // Failed is a re-entry point.+        vm.startDownload("LPA:1\$smdp.example.com\$MATCH1")+        assertEquals(DownloadState.Preparing, vm.download)+        val deadline2 = System.currentTimeMillis() + 10_000+        while (vm.download !is DownloadState.Failed && System.currentTimeMillis() < deadline2) Thread.sleep(10)+        assertTrue(vm.download is DownloadState.Failed)+    }++    @Test fun `confirm submit cancel and clear are no-ops without pending session`() {+        val vm = vm()+        awaitSettled(vm)+        vm.confirmDownload()+        assertEquals(DownloadState.Idle, vm.download)+        vm.confirmDownload("123456")+        assertEquals(DownloadState.Idle, vm.download)+        vm.submitConfirmationCode("123456")+        assertEquals(DownloadState.Idle, vm.download)+        vm.cancelDownload()+        assertEquals(DownloadState.Idle, vm.download)+        vm.cancelDownload(reason = 2)+        assertEquals(DownloadState.Idle, vm.download)+        vm.clearDownload()+        assertEquals(DownloadState.Idle, vm.download)+    }++    @Test fun `reload keeps profiles empty and sets error repeatedly`() {+        val vm = vm()+        awaitSettled(vm)+        vm.reload()+        assertTrue(vm.state.loading)+        awaitSettled(vm)+        assertFalse(vm.state.loading)+        assertNotNull(vm.state.error)+    }+}
euicc/src/test/java/com/vayunmathur/euicc/service/ServicesTest.kt
diff --git a/euicc/src/test/java/com/vayunmathur/euicc/service/ServicesTest.kt b/euicc/src/test/java/com/vayunmathur/euicc/service/ServicesTest.ktnew file mode 100644index 0000000000..d8e9bfbe52--- /dev/null+++ b/euicc/src/test/java/com/vayunmathur/euicc/service/ServicesTest.kt@@ -0,0 +1,109 @@+package com.vayunmathur.euicc.service++import android.content.Intent+import android.service.euicc.EuiccService+import android.telephony.euicc.DownloadableSubscription+import androidx.test.core.app.ApplicationProvider+import android.content.Context+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)+class ServicesTest {+    private val ctx: Context get() = ApplicationProvider.getApplicationContext()++    // ---- EuiccManagerService ----++    @Test fun `manager service constant and fallback results without eUICC`() {+        val controller = Robolectric.buildService(EuiccManagerService::class.java)+        val service = controller.create().get()+        assertEquals(EuiccService.OTA_STATUS_NOT_UPDATED, service.onGetOtaStatus(0))+        // onStartOtaIfNecessary's callback type is an abstract class in the+        // real framework (an interface in the compile stubs), so it cannot be+        // instantiated from a test; that one call is left unexercised.+        assertNull(service.onGetEid(0))+        assertEquals("", service.onGetEuiccInfo(0).osVersion)+        // Stub result classes expose no getters; the call itself must return+        // the failure result object rather than throw without an eUICC.+        assertNotNull(service.onGetEuiccProfileInfoList(0))+        assertEquals(EuiccService.RESULT_FIRST_USER, service.onDeleteSubscription(0, "8901"))+        assertEquals(EuiccService.RESULT_FIRST_USER, service.onSwitchToSubscription(0, "8901", false))+        assertEquals(EuiccService.RESULT_FIRST_USER, service.onSwitchToSubscription(0, null, false))+        assertEquals(EuiccService.RESULT_FIRST_USER, service.onSwitchToSubscriptionWithPort(0, 0, "8901", false))+        assertEquals(EuiccService.RESULT_FIRST_USER, service.onSwitchToSubscriptionWithPort(0, 0, null, false))+        assertEquals(EuiccService.RESULT_FIRST_USER, service.onUpdateSubscriptionNickname(0, "8901", "Work"))+        assertEquals(EuiccService.RESULT_FIRST_USER, service.onUpdateSubscriptionNickname(0, "8901", null))+        assertEquals(EuiccService.RESULT_FIRST_USER, service.onEraseSubscriptions(0))+        assertEquals(EuiccService.RESULT_FIRST_USER, service.onRetainSubscriptionsForFactoryReset(0))+        controller.destroy()+    }++    @Test fun `manager service metadata and default list echo inputs`() {+        val controller = Robolectric.buildService(EuiccManagerService::class.java)+        val service = controller.create().get()+        val sub = DownloadableSubscription.forActivationCode("LPA:1\$smdp.example.com\$MATCH")+        assertNotNull(service.onGetDownloadableSubscriptionMetadata(0, sub, false))+        assertNotNull(service.onGetDefaultDownloadableSubscriptionList(0, false))+        controller.destroy()+    }++    @Test fun `manager download without usable code or channel returns first user`() {+        val controller = Robolectric.buildService(EuiccManagerService::class.java)+        val service = controller.create().get()+        val empty = DownloadableSubscription.forActivationCode("")+        // Empty code still has encodedActivationCode="" (not null) in the+        // framework object, so this goes to the channel and fails there.+        assertEquals(+            EuiccService.RESULT_FIRST_USER,+            service.onDownloadSubscription(0, empty, switchAfterDownload = false, forceDeactivateSim = false),+        )+        val coded = DownloadableSubscription.forActivationCode("LPA:1\$smdp.example.com\$MATCH")+        assertEquals(+            EuiccService.RESULT_FIRST_USER,+            service.onDownloadSubscription(0, coded, switchAfterDownload = true, forceDeactivateSim = false),+        )+        controller.destroy()+    }++    // ---- DownloadService ----++    @Test fun `download service ignores foreign actions and binds null`() {+        val controller = Robolectric.buildService(DownloadService::class.java)+        val service = controller.create().get()+        assertNull(service.onBind(Intent()))+        assertEquals(android.app.Service.START_NOT_STICKY, service.onStartCommand(Intent(), 0, 1))+        assertEquals(+            android.app.Service.START_NOT_STICKY,+            service.onStartCommand(Intent("com.example.WRONG"), 0, 2),+        )+        controller.destroy()+    }++    @Test fun `download service guard starts foreground once and destroys cleanly`() {+        val controller = Robolectric.buildService(DownloadService::class.java)+        val service = controller.create().get()+        val guard = Intent(ctx, DownloadService::class.java).setAction("com.vayunmathur.euicc.action.GUARD_INSTALL")+        assertEquals(android.app.Service.START_NOT_STICKY, service.onStartCommand(guard, 0, 1))+        // Second start is a no-op but still reports NOT_STICKY.+        assertEquals(android.app.Service.START_NOT_STICKY, service.onStartCommand(guard, 0, 2))+        assertNotNull(Shadows.shadowOf(service).lastForegroundNotification)+        controller.destroy()+    }++    @Test fun `download service companion start and stop issue service intents`() {+        val app = ctx+        DownloadService.start(app)+        val started = Shadows.shadowOf(app as android.app.Application).nextStartedService+        assertNotNull(started)+        assertEquals(DownloadService::class.java.name, started.component?.className)+        assertEquals("com.vayunmathur.euicc.action.GUARD_INSTALL", started.action)+        DownloadService.stop(app)+    }+}
euicc/src/test/java/com/vayunmathur/euicc/telephony/EuiccChannelManagerFakeTest.kt
diff --git a/euicc/src/test/java/com/vayunmathur/euicc/telephony/EuiccChannelManagerFakeTest.kt b/euicc/src/test/java/com/vayunmathur/euicc/telephony/EuiccChannelManagerFakeTest.ktnew file mode 100644index 0000000000..a9ecf82ef8--- /dev/null+++ b/euicc/src/test/java/com/vayunmathur/euicc/telephony/EuiccChannelManagerFakeTest.kt@@ -0,0 +1,179 @@+package com.vayunmathur.euicc.telephony++import android.content.Context+import android.telephony.TelephonyManager+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.euicc.EuiccNative+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows+import org.robolectric.annotation.Config+import org.robolectric.shadows.UiccCardInfoBuilder+import org.robolectric.shadows.UiccPortInfoBuilder+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFailsWith+import kotlin.test.assertNull+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)+@Config(shadows = [FakeEuiccTelephonyShadow::class])+class EuiccChannelManagerFakeTest {+    private val ctx: Context get() = ApplicationProvider.getApplicationContext()++    @BeforeTest fun setUp() {+        FakeEuiccTelephonyShadow.reset()+        EuiccNative.activeChannel = null+        installCards(euiccCard(slot = 0, ports = listOf(port(0))))+    }++    private fun port(index: Int) =+        UiccPortInfoBuilder.newBuilder().setPortIndex(index).setLogicalSlotIndex(0).setIsActive(true).build()++    private fun euiccCard(slot: Int, ports: List<android.telephony.UiccPortInfo>) =+        UiccCardInfoBuilder.newBuilder()+            .setIsEuicc(true).setCardId(1).setEid("89044000001234567890123456789012")+            .setSlotIndex(slot).setPhysicalSlotIndex(slot).setPorts(ports).build()++    private fun installCards(vararg cards: android.telephony.UiccCardInfo) {+        val tm = ctx.getSystemService(TelephonyManager::class.java)+        Shadows.shadowOf(tm).setUiccCardsInfo(cards.toList())+    }++    private fun manager() = EuiccChannelManager(ctx)++    @Test fun `opens ISDR on euicc slot and port closes after block`() {+        installCards(+            UiccCardInfoBuilder.newBuilder().setIsEuicc(false).setCardId(0).setSlotIndex(1)+                .setPhysicalSlotIndex(1).setPorts(listOf(port(0))).build(),+            euiccCard(slot = 2, ports = listOf(port(3))),+        )+        val result = manager().withIsdrChannel {+            assertTrue(EuiccNative.activeChannel != null)+            "done"+        }+        assertEquals("done", result)+        assertEquals(1, FakeEuiccTelephonyShadow.openCalls.size)+        val open = FakeEuiccTelephonyShadow.openCalls.single()+        assertEquals(2, open.slotIndex)+        assertEquals(3, open.portIndex)+        assertEquals(EuiccChannelManager.ISDR_AID, open.aid)+        assertEquals(listOf(Triple(2, 3, 1)), FakeEuiccTelephonyShadow.closeCalls)+        assertNull(EuiccNative.activeChannel)+    }++    @Test fun `card without ports falls back to port zero`() {+        installCards(euiccCard(slot = 1, ports = emptyList()))+        manager().withIsdrChannel { }+        assertEquals(0, FakeEuiccTelephonyShadow.openCalls.single().portIndex)+        assertEquals(1, FakeEuiccTelephonyShadow.openCalls.single().slotIndex)+    }++    @Test fun `negative slot index is rejected`() {+        installCards(+            UiccCardInfoBuilder.newBuilder().setIsEuicc(true).setCardId(1)+                .setSlotIndex(-1).setPhysicalSlotIndex(-1).setPorts(emptyList()).build(),+        )+        val ex = assertFailsWith<EuiccException> { manager().withIsdrChannel { } }+        assertTrue(ex.message!!.contains("physical slot"), ex.message!!)+    }++    @Test fun `open error status and missing response and zero channel are rejected`() {+        FakeEuiccTelephonyShadow.openResponse = FakeEuiccTelephonyShadow.openResult(channel = 1, status = 4)+        assertFailsWith<EuiccException> { manager().withIsdrChannel { } }+        FakeEuiccTelephonyShadow.openResponse = null+        val ex = assertFailsWith<EuiccException> { manager().withIsdrChannel { } }+        assertTrue(ex.message!!.contains("no response"), ex.message!!)+        FakeEuiccTelephonyShadow.openResponse = FakeEuiccTelephonyShadow.openResult(channel = 0, status = FakeEuiccTelephonyShadow.STATUS_NO_ERROR)+        val ex2 = assertFailsWith<EuiccException> { manager().withIsdrChannel { } }+        assertTrue(ex2.message!!.contains("invalid ISD-R channel"), ex2.message!!)+    }++    @Test fun `block failure still closes channel and clears active channel`() {+        val ex = assertFailsWith<IllegalStateException> {+            manager().withIsdrChannel { throw IllegalStateException("inside") }+        }+        assertEquals("inside", ex.message)+        assertEquals(1, FakeEuiccTelephonyShadow.closeCalls.size)+        assertNull(EuiccNative.activeChannel)+    }++    @Test fun `transmit case1 case2 and case3 apdus`() {+        manager().withIsdrChannel {+            // Case 1: header only.+            var out = EuiccNative.transmitApdu(byteArrayOf(0x00, 0xA4.toByte(), 0x04, 0x00))+            assertEquals(listOf(0x90.toByte(), 0x00.toByte()), out.toList())+            var call = FakeEuiccTelephonyShadow.transmitCalls.last()+            assertEquals(0, call.p3); assertEquals("", call.data)+            assertEquals(0xA4, call.instruction)++            // Case 2: header + Le.+            out = EuiccNative.transmitApdu(byteArrayOf(0x80.toByte(), 0xE2.toByte(), 0x91.toByte(), 0x00, 0x20))+            assertEquals(listOf(0x90.toByte(), 0x00.toByte()), out.toList())+            call = FakeEuiccTelephonyShadow.transmitCalls.last()+            assertEquals(0x20, call.p3); assertEquals("", call.data)++            // Case 3: header + Lc + data (trailing Le ignored).+            out = EuiccNative.transmitApdu(+                byteArrayOf(0x80.toByte(), 0xE2.toByte(), 0x91.toByte(), 0x00, 0x03, 0xAA.toByte(), 0xBB.toByte(), 0xCC.toByte(), 0x7F),+            )+            assertEquals(listOf(0x90.toByte(), 0x00.toByte()), out.toList())+            call = FakeEuiccTelephonyShadow.transmitCalls.last()+            assertEquals(3, call.p3); assertEquals("AABBCC", call.data)+            assertEquals(0x80, call.cla); assertEquals(0x91, call.p1)+        }+    }++    @Test fun `transmit follows 61xx get response chaining`() {+        FakeEuiccTelephonyShadow.responses.addAll(listOf("AB6102", "CD9000"))+        manager().withIsdrChannel {+            val out = EuiccNative.transmitApdu(byteArrayOf(0x00, 0xB0.toByte(), 0x00, 0x00, 0x10))+            assertEquals(+                listOf(0xAB.toByte(), 0xCD.toByte(), 0x90.toByte(), 0x00.toByte()), out.toList(),+            )+        }+        assertEquals(2, FakeEuiccTelephonyShadow.transmitCalls.size)+        val getResponse = FakeEuiccTelephonyShadow.transmitCalls[1]+        assertEquals(0xC0, getResponse.instruction)+        assertEquals(2, getResponse.p3)+    }++    @Test fun `transmit follows 6Cxx wrong Le resend`() {+        FakeEuiccTelephonyShadow.responses.addAll(listOf("6C08", "EF9000"))+        manager().withIsdrChannel {+            val out = EuiccNative.transmitApdu(byteArrayOf(0x00, 0xB0.toByte(), 0x00, 0x00, 0x04, 0x11, 0x22, 0x33, 0x44))+            assertEquals(listOf(0xEF.toByte(), 0x90.toByte(), 0x00.toByte()), out.toList())+        }+        assertEquals(2, FakeEuiccTelephonyShadow.transmitCalls.size)+        assertEquals(8, FakeEuiccTelephonyShadow.transmitCalls[1].p3)+        assertEquals("11223344", FakeEuiccTelephonyShadow.transmitCalls[1].data)+    }++    @Test fun `transmit short and odd responses decode to empty`() {+        FakeEuiccTelephonyShadow.responses.addAll(listOf("90", "12345"))+        manager().withIsdrChannel {+            assertEquals(0, EuiccNative.transmitApdu(byteArrayOf(0, 0xB0.toByte(), 0, 0)).size)+            assertEquals(0, EuiccNative.transmitApdu(byteArrayOf(0, 0xB0.toByte(), 0, 0)).size)+        }+    }++    @Test fun `transmit rejects too short apdu`() {+        manager().withIsdrChannel {+            assertFailsWith<IllegalArgumentException> {+                EuiccNative.transmitApdu(byteArrayOf(0x00, 0x01))+            }+        }+    }++    @Test fun `data response body is returned with status word`() {+        FakeEuiccTelephonyShadow.defaultResponse = "DEADBEEF9000"+        manager().withIsdrChannel {+            val out = EuiccNative.transmitApdu(byteArrayOf(0, 0xB0.toByte(), 0, 0))+            assertEquals(+                listOf(0xDE.toByte(), 0xAD.toByte(), 0xBE.toByte(), 0xEF.toByte(), 0x90.toByte(), 0x00.toByte()),+                out.toList(),+            )+        }+    }+}
euicc/src/test/java/com/vayunmathur/euicc/telephony/EuiccChannelManagerTest.kt
diff --git a/euicc/src/test/java/com/vayunmathur/euicc/telephony/EuiccChannelManagerTest.kt b/euicc/src/test/java/com/vayunmathur/euicc/telephony/EuiccChannelManagerTest.ktnew file mode 100644index 0000000000..177cc4e9ef--- /dev/null+++ b/euicc/src/test/java/com/vayunmathur/euicc/telephony/EuiccChannelManagerTest.kt@@ -0,0 +1,33 @@+package com.vayunmathur.euicc.telephony++import androidx.test.core.app.ApplicationProvider+import android.content.Context+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++@RunWith(RobolectricTestRunner::class)+class EuiccChannelManagerTest {+    private val ctx: Context get() = ApplicationProvider.getApplicationContext()++    @Test fun `isdr aid constant is SGP22 aid`() {+        assertEquals("A0000005591010FFFFFFFF8900000100", EuiccChannelManager.ISDR_AID)+    }++    @Test fun `withIsdrChannel fails without eUICC and does not run block`() {+        val manager = EuiccChannelManager(ctx)+        var ran = false+        val ex = assertFailsWith<EuiccException> {+            manager.withIsdrChannel { ran = true }+        }+        assertTrue(!ran)+        assertTrue(ex.message!!.contains("eUICC") || ex.message!!.contains("ISD-R") || ex.message!!.contains("TelephonyManager"), ex.message!!)+    }++    @Test fun `euicc exception carries message`() {+        assertEquals("no card", EuiccException("no card").message)+    }+}
euicc/src/test/java/com/vayunmathur/euicc/telephony/FakeEuiccTelephonyShadow.kt
diff --git a/euicc/src/test/java/com/vayunmathur/euicc/telephony/FakeEuiccTelephonyShadow.kt b/euicc/src/test/java/com/vayunmathur/euicc/telephony/FakeEuiccTelephonyShadow.ktnew file mode 100644index 0000000000..896c396d42--- /dev/null+++ b/euicc/src/test/java/com/vayunmathur/euicc/telephony/FakeEuiccTelephonyShadow.kt@@ -0,0 +1,72 @@+package com.vayunmathur.euicc.telephony++import android.telephony.IccOpenLogicalChannelResponse+import android.telephony.TelephonyManager+import org.robolectric.annotation.Implementation+import org.robolectric.annotation.Implements+import org.robolectric.shadows.ShadowTelephonyManager++/**+ * Robolectric shadow that stands in for the privileged telephony stack:+ * reports a fake eUICC (via [ShadowTelephonyManager.setUiccCardsInfo] on the+ * instance) and answers the `@SystemApi` ByPort APDU calls the channel+ * manager reaches reflectively. Responses are scripted per test through the+ * companion so the shadow instance Robolectric creates sees them.+ */+@Implements(TelephonyManager::class)+class FakeEuiccTelephonyShadow : ShadowTelephonyManager() {++    @Implementation+    fun iccOpenLogicalChannelByPort(+        slotIndex: Int, portIndex: Int, aid: String, p2: Int,+    ): IccOpenLogicalChannelResponse? {+        openCalls += OpenCall(slotIndex, portIndex, aid, p2)+        return openResponse+    }++    @Implementation+    fun iccTransmitApduLogicalChannelByPort(+        slotIndex: Int, portIndex: Int, channel: Int, cla: Int, instruction: Int,+        p1: Int, p2: Int, p3: Int, data: String,+    ): String {+        val call = TransmitCall(slotIndex, portIndex, channel, cla, instruction, p1, p2, p3, data)+        transmitCalls += call+        transmitHandler?.let { return it(call) }+        return if (responses.isEmpty()) defaultResponse else responses.removeFirst()+    }++    @Implementation+    fun iccCloseLogicalChannelByPort(slotIndex: Int, portIndex: Int, channel: Int) {+        closeCalls += Triple(slotIndex, portIndex, channel)+    }++    data class OpenCall(val slotIndex: Int, val portIndex: Int, val aid: String, val p2: Int)+    data class TransmitCall(+        val slotIndex: Int, val portIndex: Int, val channel: Int, val cla: Int,+        val instruction: Int, val p1: Int, val p2: Int, val p3: Int, val data: String,+    )++    companion object {+        // IccOpenLogicalChannelResponse.STATUS_NO_ERROR in the framework.+        const val STATUS_NO_ERROR: Int = 1+        val openCalls = mutableListOf<OpenCall>()+        val transmitCalls = mutableListOf<TransmitCall>()+        val closeCalls = mutableListOf<Triple<Int, Int, Int>>()+        val responses = ArrayDeque<String>()+        var defaultResponse: String = "9000"+        var transmitHandler: ((TransmitCall) -> String)? = null+        var openResponse: IccOpenLogicalChannelResponse? = openResult(channel = 1, status = STATUS_NO_ERROR)++        fun reset() {+            openCalls.clear(); transmitCalls.clear(); closeCalls.clear(); responses.clear()+            defaultResponse = "9000"+            transmitHandler = null+            openResponse = openResult(channel = 1, status = STATUS_NO_ERROR)+        }++        fun openResult(channel: Int, status: Int): IccOpenLogicalChannelResponse =+            IccOpenLogicalChannelResponse::class.java+                .getConstructor(Int::class.javaPrimitiveType, Int::class.javaPrimitiveType, ByteArray::class.java)+                .newInstance(channel, status, null)+    }+}
euicc/src/test/java/com/vayunmathur/euicc/ui/DownloadScreensTest.kt
diff --git a/euicc/src/test/java/com/vayunmathur/euicc/ui/DownloadScreensTest.kt b/euicc/src/test/java/com/vayunmathur/euicc/ui/DownloadScreensTest.ktnew file mode 100644index 0000000000..9b88a9b539--- /dev/null+++ b/euicc/src/test/java/com/vayunmathur/euicc/ui/DownloadScreensTest.kt@@ -0,0 +1,212 @@+package com.vayunmathur.euicc.ui++import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.assertIsEnabled+import androidx.compose.ui.test.assertIsNotEnabled+import androidx.compose.ui.test.hasSetTextAction+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.compose.ui.test.performTextInput+import androidx.compose.ui.test.performTextReplacement+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.euicc.R+import com.vayunmathur.euicc.data.Profile+import com.vayunmathur.euicc.platform.DownloadState+import com.vayunmathur.euicc.ui.dialogs.EidDialog+import com.vayunmathur.euicc.ui.dialogs.RenameDialog+import com.vayunmathur.euicc.ui.download.CompleteContent+import com.vayunmathur.euicc.ui.download.ConfirmCarrierContent+import com.vayunmathur.euicc.ui.download.ConfirmationCodeContent+import com.vayunmathur.euicc.ui.download.FailedContent+import com.vayunmathur.euicc.ui.download.InstallingContent+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++@RunWith(RobolectricTestRunner::class)+class DownloadScreensTest {+    @get:Rule val rule = createComposeRule()+    private val ctx get() = ApplicationProvider.getApplicationContext<android.content.Context>()+    private fun str(id: Int, vararg args: Any) = ctx.getString(id, *args)+    private fun uiStr(id: Int) = ctx.getString(id)++    @Test fun `download screen idle starts download and shows installing`() {+        var starts = listOf<Any?>()+        rule.setContent {+            DownloadScreen(+                activationCode = "LPA:1\$a.b\$X", imei = "123", confirmationCode = null,+                state = DownloadState.Idle,+                onStart = { a, i, c -> starts = listOf(a, i, c) },+                onConfirm = {}, onSubmitCode = {}, onCancelSession = {}, onDone = {},+            )+        }+        rule.onNodeWithText(str(R.string.installing_title)).assertIsDisplayed()+        assertEquals(listOf("LPA:1\$a.b\$X", "123", null), starts)+    }++    @Test fun `download screen preparing does not restart`() {+        var starts = 0+        rule.setContent {+            DownloadScreen(+                activationCode = "code", imei = null, confirmationCode = "cc",+                state = DownloadState.Preparing,+                onStart = { _, _, _ -> starts++ },+                onConfirm = {}, onSubmitCode = {}, onCancelSession = {}, onDone = {},+            )+        }+        rule.onNodeWithText(str(R.string.installing_title)).assertExists()+        assertEquals(0, starts)+    }++    @Test fun `download screen confirm phase routes confirm and cancel`() {+        var confirmed: String? = "unset"; var cancels = 0+        rule.setContent {+            DownloadScreen(+                activationCode = "code", imei = null, confirmationCode = null,+                state = DownloadState.Confirm("Telco", "Prepaid Plan"),+                onStart = { _, _, _ -> }, onConfirm = { confirmed = it },+                onSubmitCode = {}, onCancelSession = { cancels++ }, onDone = {},+            )+        }+        rule.onNodeWithText("Telco").assertIsDisplayed()+        rule.onNodeWithText("Prepaid Plan").assertIsDisplayed()+        rule.onNodeWithText(str(R.string.download_esim_button)).performClick()+        assertEquals(null, confirmed)+        rule.onNodeWithText(uiStr(com.vayunmathur.library.ui.R.string.cancel)).performClick()+        assertEquals(1, cancels)+    }++    @Test fun `download screen confirmation code phase submits trimmed code`() {+        var submitted: String? = null; var cancels = 0+        rule.setContent {+            DownloadScreen(+                activationCode = "code", imei = null, confirmationCode = null,+                state = DownloadState.AwaitingConfirmationCode("Telco", error = false),+                onStart = { _, _, _ -> }, onConfirm = {},+                onSubmitCode = { submitted = it }, onCancelSession = { cancels++ }, onDone = {},+            )+        }+        rule.onNodeWithText(str(R.string.confirmation_code_text, "Telco")).assertExists()+        rule.onNodeWithText(uiStr(com.vayunmathur.library.ui.R.string.continue_label)).assertIsNotEnabled()+        rule.onAllNodes(hasSetTextAction())[0].performTextInput(" 9876 ")+        rule.onNodeWithText(uiStr(com.vayunmathur.library.ui.R.string.continue_label)).assertIsEnabled()+        rule.onNodeWithText(uiStr(com.vayunmathur.library.ui.R.string.continue_label)).performClick()+        assertEquals("9876", submitted)+        assertEquals(0, cancels)+    }++    @Test fun `confirmation code error state shows wrong code text`() {+        rule.setContent {+            ConfirmationCodeContent(carrier = null, error = true, onSubmit = {}, onCancel = {})+        }+        rule.onNodeWithText(str(R.string.confirmation_code_text_no_carrier)).assertExists()+        rule.onNodeWithText(str(R.string.confirmation_code_wrong)).assertExists()+    }++    @Test fun `download screen installing complete and failed phases`() {+        var retries = 0; var dones = 0; var starts = mutableListOf<String>()+        var phase = androidx.compose.runtime.mutableStateOf<DownloadState>(DownloadState.Installing(0.5f))+        rule.setContent {+            DownloadScreen(+                activationCode = "code9", imei = null, confirmationCode = null,+                state = phase.value,+                onStart = { a, _, _ -> starts += a },+                onConfirm = {}, onSubmitCode = {}, onCancelSession = {}, onDone = { dones++ },+            )+        }+        rule.onNodeWithText(str(R.string.installing_title)).assertExists()+        phase.value = DownloadState.Complete("Telco")+        rule.waitForIdle()+        rule.onNodeWithText(str(R.string.download_complete_title)).assertExists()+        rule.onNodeWithText("Telco").assertExists()+        rule.onNodeWithText(uiStr(com.vayunmathur.library.ui.R.string.done)).performClick()+        assertEquals(1, dones)+        assertTrue(starts.isEmpty())+        // Failed is exercised standalone below (its own composition).+        assertEquals(0, retries)+    }++    @Test fun `download screen failed phase retries via start`() {+        var starts = mutableListOf<String>(); var dones = 0+        rule.setContent {+            DownloadScreen(+                activationCode = "code9", imei = "imei9", confirmationCode = null,+                state = DownloadState.Failed("SM-DP+ refused"),+                onStart = { a, _, _ -> starts += a },+                onConfirm = {}, onSubmitCode = {}, onCancelSession = {}, onDone = { dones++ },+            )+        }+        rule.onNodeWithText("SM-DP+ refused").assertIsDisplayed()+        rule.onNodeWithText(str(R.string.try_again)).performClick()+        assertEquals(listOf("code9"), starts)+        rule.onNodeWithText(uiStr(com.vayunmathur.library.ui.R.string.cancel)).performClick()+        assertEquals(1, dones)+    }++    @Test fun `failed content without message shows generic only`() {+        rule.setContent { FailedContent(message = null, onRetry = {}, onCancel = {}) }+        rule.onNodeWithText(str(R.string.download_fail_dialog_title)).assertExists()+        rule.onNodeWithText(str(R.string.download_fail_generic)).assertExists()+    }++    @Test fun `installing content indeterminate and determinate render`() {+        var progress = androidx.compose.runtime.mutableStateOf<Float?>(null)+        rule.setContent { InstallingContent(progress = progress.value) }+        rule.onNodeWithText(str(R.string.installing_text)).assertExists()+        progress.value = 0.25f+        rule.waitForIdle()+        rule.onNodeWithText(str(R.string.installing_title)).assertExists()+    }++    @Test fun `confirm carrier with same name as carrier shows one label`() {+        var confirms = 0; var cancels = 0+        rule.setContent {+            ConfirmCarrierContent(carrier = "Telco", profileName = "Telco", onConfirm = { confirms++ }, onCancel = { cancels++ })+        }+        rule.onNodeWithText("Telco").assertExists()+        rule.onNodeWithText(str(R.string.download_esim_button)).performClick()+        assertEquals(1, confirms)+        rule.onNodeWithText(uiStr(com.vayunmathur.library.ui.R.string.cancel)).performClick()+        assertEquals(1, cancels)+    }++    @Test fun `confirm carrier without carrier shows titles only`() {+        rule.setContent { ConfirmCarrierContent(carrier = null, profileName = null, onConfirm = {}, onCancel = {}) }+        rule.onNodeWithText(str(R.string.carrier_confirm_title)).assertExists()+    }++    @Test fun `complete without carrier hides carrier label`() {+        var dones = 0+        rule.setContent { CompleteContent(carrier = null, onDone = { dones++ }) }+        rule.onNodeWithText(str(R.string.download_complete_title)).assertExists()+        rule.onNodeWithText(uiStr(com.vayunmathur.library.ui.R.string.done)).performClick()+        assertEquals(1, dones)+    }++    @Test fun `rename dialog cancel dismisses without saving`() {+        var saved: String? = null; var dismissals = 0+        rule.setContent {+            RenameDialog(+                profile = Profile(nickname = "Work", iccidDisplay = "8901"),+                onConfirm = { saved = it }, onDismiss = { dismissals++ },+            )+        }+        rule.onAllNodes(hasSetTextAction())[0].performTextReplacement("Other")+        rule.onNodeWithText(uiStr(com.vayunmathur.library.ui.R.string.cancel)).performClick()+        assertEquals(1, dismissals)+        assertEquals(null, saved)+    }++    @Test fun `eid dialog groups digits and done dismisses`() {+        var dismissals = 0+        rule.setContent { EidDialog(eid = "89044000001234567890123456789012", onDismiss = { dismissals++ }) }+        rule.onNodeWithText("8904 4000 0012 3456 7890 1234 5678 9012").assertIsDisplayed()+        rule.onNodeWithText(uiStr(com.vayunmathur.library.ui.R.string.copy)).assertExists()+        rule.onNodeWithText(uiStr(com.vayunmathur.library.ui.R.string.done)).performClick()+        assertEquals(1, dismissals)+    }+}
euicc/src/test/java/com/vayunmathur/euicc/ui/LooksLikeActivationCodeTest.kt
diff --git a/euicc/src/test/java/com/vayunmathur/euicc/ui/LooksLikeActivationCodeTest.kt b/euicc/src/test/java/com/vayunmathur/euicc/ui/LooksLikeActivationCodeTest.ktnew file mode 100644index 0000000000..95ac3d61d8--- /dev/null+++ b/euicc/src/test/java/com/vayunmathur/euicc/ui/LooksLikeActivationCodeTest.kt@@ -0,0 +1,56 @@+package com.vayunmathur.euicc.ui++import kotlin.test.Test+import kotlin.test.assertFalse+import kotlin.test.assertTrue++class LooksLikeActivationCodeTest {+    @Test fun `accepts canonical activation codes`() {+        assertTrue(looksLikeActivationCode("LPA:1\$smdp.example.com\$MATCH-123"))+        assertTrue(looksLikeActivationCode("LPA:1\$smdp.example.com\$MATCH123\$extra\$1"))+        assertTrue(looksLikeActivationCode("  LPA:1\$rsp.example.co.uk\$ABC-def-09  "))+    }++    @Test fun `accepts bare lpa deep link body`() {+        assertTrue(looksLikeActivationCode("lpa:something"))+        assertTrue(looksLikeActivationCode("LPA:"))+        assertTrue(looksLikeActivationCode("lpa:1\$smdp.example.com\$XYZ"))+    }++    @Test fun `accepts dollar structure without LPA prefix when valid`() {+        // hasActivationStructure: '$' in trimmed, then LPA prefix removal is a no-op;+        // parts are checked as version/host/matchingId.+        assertTrue(looksLikeActivationCode("1\$smdp.example.com\$ABC123"))+    }++    @Test fun `rejects empty and blank`() {+        assertFalse(looksLikeActivationCode(""))+        assertFalse(looksLikeActivationCode("   "))+    }++    @Test fun `any lpa prefix is handed to native parser`() {+        // The LPA: prefix short-circuits: the native core does the real+        // parsing there, so even structurally odd LPA: strings pass this gate.+        assertTrue(looksLikeActivationCode("LPA:2\$smdp.example.com\$ABC123"))+        assertTrue(looksLikeActivationCode("LPA:1\$smdp.example.com"))+        assertTrue(looksLikeActivationCode("LPA:1"))+    }++    @Test fun `rejects wrong version missing parts and bad host or matching id without prefix`() {+        assertFalse(looksLikeActivationCode("2\$smdp.example.com\$ABC123"))+        assertFalse(looksLikeActivationCode("1\$smdp.example.com"))+        assertFalse(looksLikeActivationCode("1\$localhost\$ABC123"))+        assertFalse(looksLikeActivationCode("1\$\$ABC123"))+        assertFalse(looksLikeActivationCode("1\$smdp.example.com\$"))+        assertFalse(looksLikeActivationCode("1\$smdp.example.com\$AB_C!"))+        assertFalse(looksLikeActivationCode("1\$smdp.example.com\$AB C"))+        assertFalse(looksLikeActivationCode("hello world"))+        assertFalse(looksLikeActivationCode("1smdp.example.comABC123"))+    }++    @Test fun `matching id allows hyphen and alphanumerics only`() {+        assertTrue(looksLikeActivationCode("1\$a.b\$-"))+        assertTrue(looksLikeActivationCode("1\$a.b\$aZ09-"))+        assertFalse(looksLikeActivationCode("1\$a.b\$a.b"))+    }+}
euicc/src/test/java/com/vayunmathur/euicc/ui/QrScannerGrantedTest.kt
diff --git a/euicc/src/test/java/com/vayunmathur/euicc/ui/QrScannerGrantedTest.kt b/euicc/src/test/java/com/vayunmathur/euicc/ui/QrScannerGrantedTest.ktnew file mode 100644index 0000000000..c63d199a26--- /dev/null+++ b/euicc/src/test/java/com/vayunmathur/euicc/ui/QrScannerGrantedTest.kt@@ -0,0 +1,48 @@+package com.vayunmathur.euicc.ui++import android.Manifest+import androidx.camera.lifecycle.ProcessCameraProvider+import androidx.camera.lifecycle.awaitInstance+import androidx.compose.ui.test.junit4.createAndroidComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.euicc.R+import com.vayunmathur.euicc.Route+import com.vayunmathur.library.util.NavBackStack+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows+import kotlin.test.Test+import kotlin.test.assertEquals++@RunWith(RobolectricTestRunner::class)+class QrScannerGrantedTest {+    @get:Rule val rule = createAndroidComposeRule<androidx.activity.ComponentActivity>()+    private val ctx get() = ApplicationProvider.getApplicationContext<android.content.Context>()++    @Test fun `qr scanner with camera permission shows viewfinder not wall`() {+        Shadows.shadowOf(ctx as android.app.Application).grantPermissions(Manifest.permission.CAMERA)+        // Pre-initialize CameraX so the composable's awaitInstance resumes+        // from an already-completed future on the composition thread instead+        // of racing CameraX's background initialization thread (which fails+        // PreviewView's main-thread check under Robolectric).+        kotlinx.coroutines.runBlocking {+            ProcessCameraProvider.awaitInstance(ctx)+        }+        val backStack = NavBackStack(arrayOf(Route.Home, Route.ScanQr))+        var result: String? = null+        rule.setContent { QrScannerScreen(backStack = backStack, onResult = { result = it }) }+        // Pump the main looper on this (main) thread so CameraX's resumed+        // continuation lands where PreviewView requires it.+        org.robolectric.Shadows.shadowOf(android.os.Looper.getMainLooper()).idle()+        rule.waitForIdle()+        rule.onNodeWithText(ctx.getString(R.string.camera_permission_required)).assertDoesNotExist()+        rule.onNodeWithText(ctx.getString(R.string.scan_qr_title)).assertExists()+        assertEquals(null, result)+        // Cancel overlay still pops.+        rule.onNodeWithText(ctx.getString(com.vayunmathur.library.ui.R.string.cancel)).performClick()+        assertEquals(Route.Home, backStack.last())+    }+}
euicc/src/test/java/com/vayunmathur/euicc/ui/UiScreensTest.kt
diff --git a/euicc/src/test/java/com/vayunmathur/euicc/ui/UiScreensTest.kt b/euicc/src/test/java/com/vayunmathur/euicc/ui/UiScreensTest.ktnew file mode 100644index 0000000000..1aec5f5fea--- /dev/null+++ b/euicc/src/test/java/com/vayunmathur/euicc/ui/UiScreensTest.kt@@ -0,0 +1,282 @@+package com.vayunmathur.euicc.ui++import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.assertIsEnabled+import androidx.compose.ui.test.assertIsNotEnabled+import androidx.compose.ui.test.hasSetTextAction+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onAllNodesWithText+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.compose.ui.test.performTextInput+import androidx.compose.ui.test.performTextReplacement+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.euicc.R+import com.vayunmathur.euicc.Route+import com.vayunmathur.euicc.data.EuiccInfo+import com.vayunmathur.euicc.data.Notification+import com.vayunmathur.euicc.data.Profile+import com.vayunmathur.euicc.platform.EuiccScreenState+import com.vayunmathur.library.util.NavBackStack+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++@RunWith(RobolectricTestRunner::class)+class UiScreensTest {+    @get:Rule val rule = createComposeRule()+    private val ctx get() = ApplicationProvider.getApplicationContext<android.content.Context>()+    private fun str(id: Int, vararg args: Any) = ctx.getString(id, *args)++    private val enabledProfile = Profile(+        iccid = "iccid-1", iccidDisplay = "8901000001", state = "enabled",+        nickname = "Work", serviceProvider = "Example Mobile", name = "Prepaid",+    )+    private val disabledProfile = Profile(+        iccid = "iccid-2", iccidDisplay = "8901000002", state = "disabled",+        serviceProvider = "Travel eSIM", name = "Global Data",+    )++    private fun stack(vararg routes: Route) = NavBackStack(arrayOf(*routes))++    // ---- Home ----++    @Test fun `home empty state offers add sim`() {+        var adds = 0+        rule.setContent {+            EuiccHomeScreen(+                state = EuiccScreenState(loading = false),+                backStack = stack(Route.Home), onReload = {}, onAddSim = { adds++ },+            )+        }+        rule.onNodeWithText(str(R.string.no_profiles_title)).assertIsDisplayed()+        rule.onNodeWithText(str(R.string.add_profile_title)).performClick()+        assertEquals(1, adds)+    }++    @Test fun `home lists enabled and disabled profiles and navigates`() {+        var adds = 0; var reloads = 0+        val backStack = stack(Route.Home)+        rule.setContent {+            EuiccHomeScreen(+                state = EuiccScreenState(+                    loading = false, eid = "89044000001234567890123456789012",+                    profiles = listOf(enabledProfile, disabledProfile),+                ),+                backStack = backStack, onReload = { reloads++ }, onAddSim = { adds++ },+            )+        }+        rule.onNodeWithText(str(R.string.esim_enabled)).assertExists()+        rule.onNodeWithText(str(R.string.available_carriers)).assertExists()+        rule.onNodeWithText("Work").performClick()+        assertEquals(Route.ProfileDetail("iccid-1"), backStack.last())+        // Device-info / Add rows sit below the fold in the test viewport and+        // the home column does not scroll, so their clicks are covered on+        // smaller compositions (empty-state Add, Navigation DeviceInfo seed).+        rule.onNodeWithText(str(R.string.device_info_title)).assertExists()+        assertEquals(0, reloads)+    }++    @Test fun `home shows loading error and profile fallback labels`() {+        rule.setContent {+            EuiccHomeScreen(+                state = EuiccScreenState(+                    loading = true, error = "eUICC unavailable",+                    profiles = listOf(Profile(iccid = "x", iccidDisplay = "89019999", state = "disabled")),+                ),+                backStack = stack(Route.Home), onReload = {}, onAddSim = {},+            )+        }+        rule.onNodeWithText("eUICC unavailable").assertIsDisplayed()+        rule.onNodeWithText("•••• 9999").assertExists()+    }++    @Test fun `home profile row replaces existing detail destination`() {+        val backStack = stack(Route.Home, Route.ProfileDetail("old"))+        rule.setContent {+            EuiccHomeScreen(+                state = EuiccScreenState(loading = false, profiles = listOf(enabledProfile)),+                backStack = backStack, onReload = {}, onAddSim = {},+            )+        }+        rule.onNodeWithText("Work").performClick()+        assertEquals(Route.ProfileDetail("iccid-1"), backStack.last())+        assertEquals(2, backStack.backStack.size)+    }++    // ---- AddSim / ActivationCode ----++    @Test fun `add sim screen routes to scan and code entry`() {+        val backStack = stack(Route.Home, Route.AddSim)+        rule.setContent { AddSimScreen(backStack = backStack) }+        rule.onNodeWithText(str(R.string.scan_qr_button)).performClick()+        assertEquals(Route.ScanQr, backStack.last())+        backStack.pop()+        rule.onNodeWithText(str(R.string.enter_code_button)).performClick()+        assertEquals(Route.ActivationCode, backStack.last())+    }++    @Test fun `activation code screen enables continue for valid code and navigates with inputs`() {+        val backStack = stack(Route.Home, Route.ActivationCode)+        rule.setContent { ActivationCodeScreen(backStack = backStack) }+        rule.onNodeWithText(str(com.vayunmathur.library.ui.R.string.continue_label)).assertIsNotEnabled()+        val fields = rule.onAllNodes(hasSetTextAction())+        fields[0].performTextInput("LPA:1\$smdp.example.com\$MATCH-1\$FF\$1")+        fields[1].performTextInput("352099001761481")+        fields[2].performTextInput("secret123")+        rule.onNodeWithText(str(com.vayunmathur.library.ui.R.string.continue_label)).assertIsEnabled()+        // Confirmation-code-required supporting text appears for the $1 flag.+        rule.onNodeWithText(str(R.string.confirmation_code_title)).assertExists()+        rule.onNodeWithText(str(com.vayunmathur.library.ui.R.string.continue_label)).performClick()+        val route = backStack.last() as Route.Download+        assertEquals("LPA:1\$smdp.example.com\$MATCH-1\$FF\$1", route.activationCode)+        assertEquals("352099001761481", route.imei)+        assertEquals("secret123", route.confirmationCode)+    }++    @Test fun `activation code scan button routes to scanner`() {+        val backStack = stack(Route.Home, Route.ActivationCode)+        rule.setContent { ActivationCodeScreen(backStack = backStack) }+        rule.onNodeWithText(str(R.string.activation_code_scan_button)).performClick()+        assertEquals(Route.ScanQr, backStack.last())+    }++    @Test fun `qr scanner without camera permission shows wall and cancel pops`() {+        val backStack = stack(Route.Home, Route.ScanQr)+        var results = 0+        rule.setContent { QrScannerScreen(backStack = backStack, onResult = { results++ }) }+        rule.onNodeWithText(str(R.string.camera_permission_required)).assertExists()+        rule.onNodeWithText(str(com.vayunmathur.library.ui.R.string.cancel)).performClick()+        assertEquals(Route.Home, backStack.last())+        assertEquals(0, results)+    }++    // ---- DeviceInfo ----++    @Test fun `device info shows unknown eid and no notifications`() {+        rule.setContent {+            DeviceInfoScreen(state = EuiccScreenState(loading = false), backStack = stack(Route.Home), onRemoveNotification = {})+        }+        rule.onNodeWithText(str(R.string.eid_not_found)).assertExists()+        rule.onNodeWithText(str(com.vayunmathur.library.ui.R.string.unknown)).assertExists()+        rule.onNodeWithText(str(R.string.no_notifications)).assertExists()+    }++    @Test fun `device info shows version notifications remove and eid dialog`() {+        var removed: Int? = null+        rule.setContent {+            DeviceInfoScreen(+                state = EuiccScreenState(+                    loading = false, eid = "89044000001234567890123456789012",+                    info = EuiccInfo(svn = "2.2.0"),+                    notifications = listOf(Notification(seqNumber = 3, operation = "install", address = "smdp.example.com")),+                ),+                backStack = stack(Route.Home), onRemoveNotification = { removed = it },+            )+        }+        rule.onNodeWithText("2.2.0").assertExists()+        rule.onNodeWithText(str(R.string.notification_title, 3, "install")).assertExists()+        rule.onNodeWithText(str(com.vayunmathur.library.ui.R.string.remove)).performClick()+        assertEquals(3, removed)+        rule.onNodeWithText("89044000001234567890123456789012").performClick()+        rule.onNodeWithText("8904 4000 0012 3456 7890 1234 5678 9012").assertIsDisplayed()+        rule.onNodeWithText(str(com.vayunmathur.library.ui.R.string.done)).performClick()+        rule.onNodeWithText(str(R.string.eid_qr_code_dialog_title)).assertDoesNotExist()+    }++    // ---- ProfileDetail ----++    @Test fun `profile detail disabled profile enable dialog confirms`() {+        var enabled: Profile? = null+        rule.setContent {+            ProfileDetailScreen(+                iccid = "iccid-2",+                state = EuiccScreenState(loading = false, profiles = listOf(enabledProfile, disabledProfile)),+                backStack = stack(Route.Home),+                onEnable = { enabled = it }, onDisable = {}, onErase = {}, onRename = { _, _ -> },+            )+        }+        rule.onNodeWithText(str(R.string.profile_status_disabled)).assertExists()+        rule.onNodeWithText("Travel eSIM").assertExists()+        rule.onNodeWithText("8901000002").assertExists()+        rule.onNodeWithText(str(R.string.enable_profile_title)).performClick()+        rule.onNodeWithText(str(R.string.enable_carrier_dialog_text, "Global Data", "Work")).assertIsDisplayed()+        // Confirm button carries the same Enable label; click the last match (dialog).+        rule.onAllNodesWithText(str(R.string.enable_profile_title))[1].performClick()+        assertEquals(disabledProfile, enabled)+    }++    @Test fun `profile detail enabled profile disable and erase dialogs dismiss and confirm`() {+        var disabled: Profile? = null; var erased: Profile? = null+        rule.setContent {+            ProfileDetailScreen(+                iccid = "iccid-1",+                state = EuiccScreenState(loading = false, profiles = listOf(enabledProfile)),+                backStack = stack(Route.Home),+                onEnable = {}, onDisable = { disabled = it }, onErase = { erased = it }, onRename = { _, _ -> },+            )+        }+        rule.onNodeWithText(str(R.string.profile_status_enabled)).assertExists()+        rule.onNodeWithText(str(R.string.disable_profile_title)).performClick()+        rule.onNodeWithText(str(R.string.disable_carrier_dialog_text, "Work")).assertIsDisplayed()+        rule.onAllNodesWithText(str(R.string.disable_profile_title))[1].performClick()+        assertEquals(enabledProfile, disabled)+        rule.onNodeWithText(str(R.string.erase_sim_confirm_button)).performClick()+        rule.onNodeWithText(str(R.string.erase_sim_dialog_title, "Work")).assertIsDisplayed()+        rule.onNodeWithText(str(com.vayunmathur.library.ui.R.string.cancel)).performClick()+        assertTrue(erased == null)+        rule.onNodeWithText(str(R.string.erase_sim_confirm_button)).performClick()+        rule.onAllNodesWithText(str(R.string.erase_sim_confirm_button))[1].performClick()+        assertEquals(enabledProfile, erased)+    }++    @Test fun `profile detail rename dialog saves new name`() {+        var renamed: Pair<Profile, String>? = null+        rule.setContent {+            ProfileDetailScreen(+                iccid = "iccid-1",+                state = EuiccScreenState(loading = false, profiles = listOf(enabledProfile)),+                backStack = stack(Route.Home),+                onEnable = {}, onDisable = {}, onErase = {}, onRename = { p, n -> renamed = p to n },+            )+        }+        rule.onNodeWithText(str(R.string.rename_profile_title)).performClick()+        val field = rule.onAllNodes(hasSetTextAction())[0]+        field.performTextReplacement("Personal")+        rule.onNodeWithText(str(com.vayunmathur.library.ui.R.string.save)).performClick()+        assertEquals(enabledProfile to "Personal", renamed)+    }++    @Test fun `profile detail without provider hides provider row`() {+        rule.setContent {+            ProfileDetailScreen(+                iccid = "iccid-9",+                state = EuiccScreenState(+                    loading = false,+                    profiles = listOf(Profile(iccid = "iccid-9", iccidDisplay = "89019", state = "disabled")),+                ),+                backStack = stack(Route.Home),+                onEnable = {}, onDisable = {}, onErase = {}, onRename = { _, _ -> },+            )+        }+        rule.onNodeWithText(str(R.string.profile_provider)).assertDoesNotExist()+        rule.onNodeWithText("89019").assertExists()+    }++    @Test fun `profile detail missing profile pops when not loading`() {+        val backStack = stack(Route.Home, Route.ProfileDetail("gone"))+        rule.setContent {+            ProfileDetailScreen(+                iccid = "gone",+                state = EuiccScreenState(loading = false, profiles = emptyList()),+                backStack = backStack,+                onEnable = {}, onDisable = {}, onErase = {}, onRename = { _, _ -> },+            )+        }+        rule.waitForIdle()+        assertEquals(Route.Home, backStack.last())+    }+}