Modern Apps git

← Modern-Apps.git

globalesim: add tests for ViewModel, API, stores and screens

Commit
0825ebe239f5988d56e23ae14f1864e57ac0c381
Author
Vayun Mathur <[email protected]>
When
2026-11-07 06:32 UTC (29 days ago)
Parents
e076899
JVM/Robolectric tests for the travel eSIM storefront: EsimApi URL
building, DTO snake_case wire shapes and offline endpoint failures;
AnonymousIdStore mint/replace over DataStore (including a fresh
files-dir mint) and the StripeKeyStore cache; EsimViewModel offline
behaviour (SIM ID minting, friendly no-connection messages for every
purchase/claim/refresh path, one-shot messages, credit-watch
polling); and Compose tests for Home/TopUp/Claim cards in all
balance states, Pricing search and carrier expansion, the custom
card payment sheet (valid and invalid cards), CardPaymentHost
secret presentation and pay flow, Navigation tabs, and a full
MainActivity launch.

Coverage (merged, whole module): 6.1% -> 86.4% instructions
(8314/9628), above the 85% target. Bugs fixed: none.

Untestable remainder: the payment-success paths that need the
live api.maproj.org service (status application, credit landing,
HTTP status-code message mapping) and Stripe's PaymentLauncher
result callback in MainActivity, which needs a real Stripe
checkout.

Verified with gslot ./gradlew :globalesim:createMergedCoverageReport
(full :globalesim:testDevUnitTest suite passes).

(cherry picked from commit 48b2e6a1ec7acb9108aa3ab1362669ed02ca15d5)

Diff

globalesim/src/test/java/com/vayunmathur/globalesim/data/IdAndKeyStoresTest.kt
diff --git a/globalesim/src/test/java/com/vayunmathur/globalesim/data/IdAndKeyStoresTest.kt b/globalesim/src/test/java/com/vayunmathur/globalesim/data/IdAndKeyStoresTest.ktnew file mode 100644index 0000000000..78a09617f5--- /dev/null+++ b/globalesim/src/test/java/com/vayunmathur/globalesim/data/IdAndKeyStoresTest.kt@@ -0,0 +1,69 @@+package com.vayunmathur.globalesim.data++import androidx.test.core.app.ApplicationProvider+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.test.runTest++/** AnonymousIdStore (DataStore UUID) and StripeKeyStore (SharedPreferences cache). */[email protected](org.robolectric.RobolectricTestRunner::class)+class IdAndKeyStoresTest {++    private val ctx get() = ApplicationProvider.getApplicationContext<android.content.Context>()++    @Test fun anonymousIdMintsOnceAndPersists() = runTest {+        val store = AnonymousIdStore(ctx)+        // Reset any state a sibling test left in the shared store file.+        store.replace(java.util.UUID.randomUUID().toString())+        val first = store.getOrCreate()+        assertTrue(first.isNotBlank())+        // UUIDv4 shape: 8-4-4-4-12 hex with the version nibble.+        assertTrue(Regex("[0-9a-f-]{36}").matches(first), first)+        assertEquals(first, store.getOrCreate())+        assertEquals(first, store.accountId.first())+    }++    @Test fun anonymousIdReplaceAdoptsClaimedId() = runTest {+        val store = AnonymousIdStore(ctx)+        val minted = store.getOrCreate()+        store.replace("claimed-sim-id")+        assertNotEquals(minted, store.accountId.first())+        assertEquals("claimed-sim-id", store.getOrCreate())+        store.replace("second-id")+        assertEquals("second-id", store.accountId.first())+    }++    @Test fun anonymousIdMintsIntoFreshFilesDir() = runTest {+        // A context over a fresh files dir has an empty DataStore, so+        // getOrCreate must take the mint-and-persist branch.+        val freshDir = java.nio.file.Files.createTempDirectory("esim-fresh").toFile()+        val wrapper = object : android.content.ContextWrapper(ctx) {+            override fun getFilesDir(): java.io.File {+                return java.io.File(freshDir, "files").apply { mkdirs() }+            }+            override fun getApplicationContext(): android.content.Context = this+        }+        val store = AnonymousIdStore(wrapper)+        val minted = store.getOrCreate()+        assertTrue(Regex("[0-9a-f-]{36}").matches(minted), minted)+        assertEquals(minted, store.getOrCreate())+        assertEquals(minted, store.accountId.first())+        freshDir.deleteRecursively()+    }++    @Test fun stripeKeyCacheRoundTrip() {+        val store = StripeKeyStore(ctx)+        store.save("")+        assertNull(store.getCached())+        store.save("pk_test_123")+        assertEquals("pk_test_123", store.getCached())+        // A fresh store instance over the same context sees the cached key.+        assertEquals("pk_test_123", StripeKeyStore(ctx).getCached())+        store.save("pk_live_456")+        assertEquals("pk_live_456", store.getCached())+    }+}
globalesim/src/test/java/com/vayunmathur/globalesim/data/api/EsimApiDtoTest.kt
diff --git a/globalesim/src/test/java/com/vayunmathur/globalesim/data/api/EsimApiDtoTest.kt b/globalesim/src/test/java/com/vayunmathur/globalesim/data/api/EsimApiDtoTest.ktnew file mode 100644index 0000000000..6c6e25ef6c--- /dev/null+++ b/globalesim/src/test/java/com/vayunmathur/globalesim/data/api/EsimApiDtoTest.kt@@ -0,0 +1,88 @@+package com.vayunmathur.globalesim.data.api++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue+import kotlinx.coroutines.test.runTest+import kotlinx.serialization.json.Json++/** EsimApi URL building, DTO wire shapes (snake_case), and offline failure behaviour. */+class EsimApiDtoTest {++    private val json = Json { ignoreUnknownKeys = true; isLenient = true }++    @Test fun urlJoinsBaseAndPath() {+        assertEquals("https://api.maproj.org/esim/v1/rates", EsimApi.url("/esim/v1/rates"))+        assertEquals("https://api.maproj.org", EsimApi.BASE_URL)+    }++    @Test fun rateDtoWireShape() {+        val parsed = json.decodeFromString(+            RateDto.serializer(),+            """{"country_code":"PT","country_name":"Portugal","price_per_gb_usd_cents":450,+                "networks":[{"operator":"MEO","price_per_gb_usd_cents":450},+                            {"operator":"NOS","price_per_gb_usd_cents":500}],"unknown_field":1}""")+        assertEquals("PT", parsed.countryCode)+        assertEquals(450L, parsed.pricePerGbUsdCents)+        assertEquals(listOf("MEO", "NOS"), parsed.networks.map { it.operator })+        val bare = json.decodeFromString(+            RateDto.serializer(),+            """{"country_code":"FR","country_name":"France","price_per_gb_usd_cents":300}""")+        assertEquals(emptyList(), bare.networks)+        val encoded = json.encodeToString(RateDto.serializer(), parsed)+        assertTrue(encoded.contains("\"country_code\":\"PT\""), encoded)+        assertTrue(encoded.contains("\"price_per_gb_usd_cents\":450"), encoded)+    }++    @Test fun statusAndProfileDefaults() {+        val empty = json.decodeFromString(StatusResponse.serializer(), "{}")+        assertEquals(null, empty.profile)+        assertEquals(0L, empty.pendingCreditCents)+        assertEquals(false, empty.balanceStale)+        val full = json.decodeFromString(+            StatusResponse.serializer(),+            """{"profile":{"iccid":"8901","status":"active","wallet_usd_cents":1234},+                "pending_invoice_url":"http://pay.example/i","pending_credit_cents":500,+                "balance_stale":true}""")+        assertEquals("8901", full.profile!!.iccid)+        assertEquals("", full.profile!!.activationCode)+        assertEquals(1234L, full.profile!!.walletUsdCents)+        assertEquals(500L, full.pendingCreditCents)+        assertTrue(full.balanceStale)+    }++    @Test fun requestAndResponseShapes() {+        assertTrue(json.encodeToString(AccountRequest.serializer(), AccountRequest("acc-1"))+            .contains("\"account_id\":\"acc-1\""))+        assertTrue(json.encodeToString(+            TransferInRequest.serializer(), TransferInRequest("old", "new"))+            .contains("\"old_account_id\":\"old\""))+        assertTrue(json.encodeToString(+            StripeIntentRequest.serializer(), StripeIntentRequest("a", 1000L))+            .contains("\"amount_cents\":1000"))+        assertEquals("pk_1", json.decodeFromString(StripeKeyResponse.serializer(), """{"publishable_key":"pk_1"}""").publishableKey)+        assertEquals("", json.decodeFromString(StripeKeyResponse.serializer(), "{}").publishableKey)+        assertEquals("cs_1", json.decodeFromString(StripeIntentResponse.serializer(), """{"client_secret":"cs_1"}""").clientSecret)+        val invoice = json.decodeFromString(+            NowPayInvoiceResponse.serializer(),+            """{"invoice_url":"https://pay.example","invoice_id":"inv1","bonus_usd_cents":25,"amount_cents":500,"existing":true}""")+        assertTrue(invoice.existing)+        assertEquals(25L, invoice.bonusUsdCents)+        assertEquals(false, json.decodeFromString(OkResponse.serializer(), "{}").ok)+        assertEquals(true, json.decodeFromString(OkResponse.serializer(), """{"ok":true}""").ok)+        assertEquals(0, json.decodeFromString(RatesResponse.serializer(), "{}").rates.size)+    }++    @Test fun endpointsFailOffline() = runTest {+        // The devserver has no route to api.maproj.org: every call fails as an+        // IOException (never a successful fake), which ViewModels map to the+        // "No connection" message.+        assertTrue(runCatching { EsimApi.rates() }.exceptionOrNull() is java.io.IOException)+        assertTrue(runCatching { EsimApi.status("acc") }.exceptionOrNull() is java.io.IOException)+        assertTrue(runCatching { EsimApi.stripeKey() }.exceptionOrNull() is java.io.IOException)+        assertTrue(runCatching { EsimApi.stripeIntent("acc", 500L) }.exceptionOrNull() is java.io.IOException)+        assertTrue(runCatching { EsimApi.nowPayInvoice("acc", 500L) }.exceptionOrNull() is java.io.IOException)+        assertTrue(runCatching { EsimApi.nowPayCancel("acc") }.exceptionOrNull() is java.io.IOException)+        assertTrue(runCatching { EsimApi.claim("sim", "acc") }.exceptionOrNull() is java.io.IOException)+    }+}
globalesim/src/test/java/com/vayunmathur/globalesim/platform/EsimViewModelTest.kt
diff --git a/globalesim/src/test/java/com/vayunmathur/globalesim/platform/EsimViewModelTest.kt b/globalesim/src/test/java/com/vayunmathur/globalesim/platform/EsimViewModelTest.ktnew file mode 100644index 0000000000..e19c330f54--- /dev/null+++ b/globalesim/src/test/java/com/vayunmathur/globalesim/platform/EsimViewModelTest.kt@@ -0,0 +1,157 @@+package com.vayunmathur.globalesim.platform++import android.app.Application+import android.os.Looper+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.globalesim.data.api.ProfileDto+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue+import org.robolectric.Shadows++/**+ * EsimViewModel offline behaviour: the API is unreachable from tests, so+ * loads settle into the "No connection" message with the anonymous SIM ID+ * minted, and every user action maps failures to its friendly message.+ */[email protected](org.robolectric.RobolectricTestRunner::class)+class EsimViewModelTest {++    private val app: Application get() = ApplicationProvider.getApplicationContext()++    private lateinit var vm: EsimViewModel++    @BeforeTest fun setUp() {+        vm = EsimViewModel(app)+    }++    private fun await(timeoutMs: Long = 15_000, cond: () -> Boolean): Boolean {+        val deadline = System.currentTimeMillis() + timeoutMs+        while (System.currentTimeMillis() < deadline) {+            Shadows.shadowOf(Looper.getMainLooper()).idle()+            if (cond()) return true+            Thread.sleep(20)+        }+        return cond()+    }++    @Test fun initMintsSimIdAndSettlesOffline() {+        assertTrue(+            await { vm.state.statusLoaded && vm.state.simId != null },+            "state=${vm.state}")+        assertFalse(vm.state.loading)+        assertNull(vm.state.profile)+        assertEquals(+            "No connection. Check your internet and try again.", vm.state.message)+        assertTrue(vm.state.rates.isEmpty())+    }++    @Test fun messageOneShotHelpers() {+        vm.notifyMessage("hello")+        assertEquals("hello", vm.state.message)+        vm.dismissMessage()+        assertNull(vm.state.message)+        vm.notifyMessage("again")+        vm.dismissMessage()+        assertNull(vm.state.message)+    }++    @Test fun finishCardPurchaseStates() {+        vm.finishCardPurchase(paid = false)+        assertNull(vm.state.pendingClientSecret)+        assertFalse(vm.state.loading)+        // Paid starts the credit watch (polling offline status in background);+        // the visible state is just cleared secret + not loading.+        vm.finishCardPurchase(paid = true)+        assertNull(vm.state.pendingClientSecret)+        assertFalse(vm.state.loading)+        vm.finishCardPurchaseWithError("Card declined")+        assertEquals("Card declined", vm.state.message)+        assertNull(vm.state.pendingClientSecret)+    }++    @Test fun purchasesFailOfflineWithFriendlyMessage() {+        assertTrue(await { vm.state.statusLoaded })+        var keyCallback: String? = null+        vm.startCardPurchase(1_000L, publishableKey = "pk_test") { keyCallback = it }+        assertTrue(await { !vm.state.loading && vm.state.message != null }, "state=${vm.state}")+        assertEquals(+            "No connection. Check your internet and try again.", vm.state.message)+        assertNull(vm.state.pendingClientSecret)+        assertNull(keyCallback)++        vm.dismissMessage()+        var invoiceReady: String? = null+        vm.startCryptoPurchase(1_000L) { invoiceReady = it }+        assertTrue(await { !vm.state.loading && vm.state.message != null }, "state=${vm.state}")+        assertEquals(+            "No connection. Check your internet and try again.", vm.state.message)+        assertNull(vm.state.pendingInvoiceUrl)+        assertNull(invoiceReady)+    }++    @Test fun claimAndClearInvoiceFailOffline() {+        assertTrue(await { vm.state.statusLoaded })+        vm.claim("  some-sim-id  ")+        assertTrue(await { !vm.state.loading && vm.state.message != null }, "state=${vm.state}")+        assertEquals(+            "No connection. Check your internet and try again.", vm.state.message)+        // SIM ID is not adopted on failure.+        assertTrue(vm.state.simId != "some-sim-id")++        vm.clearPendingInvoice()+        assertNull(vm.state.pendingInvoiceUrl)+        assertFalse(vm.state.loading)+    }++    @Test fun refreshCyclesSettleOffline() {+        assertTrue(await { vm.state.statusLoaded })+        vm.refresh()+        assertTrue(await { !vm.state.refreshing }, "state=${vm.state}")+        vm.refreshStatus()+        assertTrue(await { !vm.state.loading }, "state=${vm.state}")+        vm.refreshRates()+        assertTrue(await { vm.state.rates.isEmpty() })+    }++    @Test fun creditWatchPollsInBackground() {+        // Paid starts the watcher; it polls the (unreachable) status endpoint+        // on its fast cadence without disturbing the cleared purchase state.+        vm.finishCardPurchase(paid = true)+        assertTrue(await(6_000) {+            Shadows.shadowOf(Looper.getMainLooper()).idle()+            vm.state.pendingClientSecret == null && !vm.state.loading+        })+        Thread.sleep(2_500)+        Shadows.shadowOf(Looper.getMainLooper()).idle()+        assertNull(vm.state.pendingClientSecret)+        vm.clearPendingInvoice()+    }++    @Test fun routeAndStateValueSemantics() {+        val encoded = kotlinx.serialization.json.Json.encodeToString(+            com.vayunmathur.globalesim.Route.serializer(),+            com.vayunmathur.globalesim.Route.Tabs)+        assertTrue(encoded.contains("Tabs"), encoded)+        val s = EsimUiState(loading = true, simId = "x")+        assertEquals(s, s.copy())+        assertEquals(s.hashCode(), s.copy().hashCode())+        assertTrue(s.toString().contains("simId=x"))+        assertTrue(s != s.copy(loading = false))+    }++    @Test fun uiStateDefaults() {+        val s = EsimUiState()+        assertFalse(s.loading || s.statusLoaded || s.refreshing)+        assertNull(s.simId)+        assertNull(s.profile)+        assertTrue(s.rates.isEmpty())+        assertEquals(0L, s.pendingCreditCents)+        val profile = ProfileDto(iccid = "8901", status = "active", walletUsdCents = 250L)+        assertEquals("", profile.activationCode)+        assertEquals(250L, profile.walletUsdCents)+    }+}
globalesim/src/test/java/com/vayunmathur/globalesim/ui/CardPaymentHostTest.kt
diff --git a/globalesim/src/test/java/com/vayunmathur/globalesim/ui/CardPaymentHostTest.kt b/globalesim/src/test/java/com/vayunmathur/globalesim/ui/CardPaymentHostTest.ktnew file mode 100644index 0000000000..cd56df0007--- /dev/null+++ b/globalesim/src/test/java/com/vayunmathur/globalesim/ui/CardPaymentHostTest.kt@@ -0,0 +1,118 @@+package com.vayunmathur.globalesim.ui++import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.hasClickAction+import androidx.compose.ui.test.hasSetTextAction+import androidx.compose.ui.test.hasText+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.performSemanticsAction+import androidx.compose.ui.test.performTextInput+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.globalesim.MainActivity+import com.vayunmathur.globalesim.data.StripeKeyStore+import com.vayunmathur.globalesim.data.api.AccountRequest+import com.vayunmathur.globalesim.data.api.NetworkDto+import com.vayunmathur.globalesim.data.api.NowPayInvoiceRequest+import com.vayunmathur.globalesim.data.api.NowPayInvoiceResponse+import com.vayunmathur.globalesim.data.api.OkResponse+import com.vayunmathur.globalesim.data.api.RateDto+import com.vayunmathur.globalesim.data.api.RatesResponse+import com.vayunmathur.globalesim.data.api.StatusResponse+import com.vayunmathur.globalesim.data.api.StripeIntentRequest+import com.vayunmathur.globalesim.data.api.StripeIntentResponse+import com.vayunmathur.globalesim.data.api.StripeKeyResponse+import com.vayunmathur.globalesim.data.api.TransferInRequest+import com.vayunmathur.globalesim.platform.EsimUiState+import com.vayunmathur.library.ui.DynamicTheme+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner++/** CardPaymentHost secret-presentation and sheet pay flow, plus DTO defaults. */+@RunWith(RobolectricTestRunner::class)+class CardPaymentHostTest {++    @get:Rule+    val composeRule = createComposeRule()++    @Test fun pendingSecretPresentedOnceToHoistedCallback() {+        val presented = mutableListOf<String>()+        composeRule.setContent {+            DynamicTheme {+                CardPaymentHost(+                    state = EsimUiState(pendingClientSecret = "secret_123"),+                    launchers = null,+                    sheetAmountCents = null,+                    onDismissSheet = {},+                    onSheetAmountConsumed = {},+                    onStartCardPurchase = { _, _, _ -> },+                    onPresentPaymentSheet = { presented.add(it) })+            }+        }+        composeRule.waitForIdle()+        assertEquals(listOf("secret_123"), presented)+    }++    @Test fun sheetPayFlowStartsPurchaseAndCachesKey() {+        var startedAmount: Long? = null+        composeRule.setContent {+            DynamicTheme {+                CardPaymentHost(+                    state = EsimUiState(),+                    launchers = null,+                    sheetAmountCents = 1500L,+                    onDismissSheet = {},+                    onSheetAmountConsumed = {},+                    onStartCardPurchase = { amount, _, onKey ->+                        startedAmount = amount+                        onKey("pk_test_host")+                    })+            }+        }+        composeRule.onAllNodesWithText("Pay $15.00")[0].assertIsDisplayed()+        composeRule.onAllNodes(hasSetTextAction())[0].performTextInput("4242424242424242")+        composeRule.onAllNodes(hasSetTextAction())[1].performTextInput("12/99")+        composeRule.onAllNodes(hasSetTextAction())[2].performTextInput("123")+        composeRule.onNode(hasText("Pay $15.00") and hasClickAction()).performClick()+        assertEquals(1500L, startedAmount)+        val ctx = ApplicationProvider.getApplicationContext<android.content.Context>()+        assertEquals("pk_test_host", StripeKeyStore(ctx).getCached())+    }++    @Test fun mainActivityLaunchesToPurchaseTab() {+        androidx.test.core.app.ActivityScenario.launch(MainActivity::class.java).use { scenario ->+            composeRule.waitForIdle()+            scenario.onActivity { activity ->+                assertTrue(activity.javaClass == MainActivity::class.java)+            }+            composeRule.onAllNodesWithText("Purchase")[0].assertIsDisplayed()+        }+    }++    @Test fun dtoDefaultsAndCopies() {+        assertEquals("a", AccountRequest("a").accountId)+        assertEquals("old", TransferInRequest("old", "new").copy(newAccountId = "x").oldAccountId)+        assertEquals(0, RatesResponse().rates.size)+        assertEquals("", StripeKeyResponse().publishableKey)+        assertEquals("", StripeIntentResponse().clientSecret)+        assertEquals(500L, StripeIntentRequest("a", 500L).amountCents)+        assertEquals(500L, NowPayInvoiceRequest("a", 500L).amountCents)+        val invoice = NowPayInvoiceResponse()+        assertEquals("", invoice.invoiceUrl)+        assertEquals(false, invoice.existing)+        assertEquals(false, OkResponse().ok)+        assertEquals(null, StatusResponse().profile)+        val rate = RateDto("PT", "Portugal", 100L)+        assertEquals(emptyList(), rate.networks)+        assertEquals(100L, NetworkDto("MEO", 100L).pricePerGbUsdCents)+        assertTrue(RateDto("PT", "Portugal", 100L) == rate)+        assertTrue(RateDto("PT", "Portugal", 100L).hashCode() == rate.hashCode())+        assertTrue(rate.toString().contains("Portugal"))+    }+}
globalesim/src/test/java/com/vayunmathur/globalesim/ui/HomeTopUpComposeTest.kt
diff --git a/globalesim/src/test/java/com/vayunmathur/globalesim/ui/HomeTopUpComposeTest.kt b/globalesim/src/test/java/com/vayunmathur/globalesim/ui/HomeTopUpComposeTest.ktnew file mode 100644index 0000000000..90879b7e05--- /dev/null+++ b/globalesim/src/test/java/com/vayunmathur/globalesim/ui/HomeTopUpComposeTest.kt@@ -0,0 +1,187 @@+package com.vayunmathur.globalesim.ui++import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.hasClickAction+import androidx.compose.ui.test.hasSetTextAction+import androidx.compose.ui.test.performSemanticsAction+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.globalesim.data.api.ProfileDto+import org.robolectric.Shadows+import com.vayunmathur.globalesim.platform.EsimUiState+import com.vayunmathur.library.ui.DynamicTheme+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner++/** HomeScreen states and TopUpCard/ClaimCard interactions. */+@RunWith(RobolectricTestRunner::class)+class HomeTopUpComposeTest {++    @get:Rule+    val composeRule = createComposeRule()++    private fun home(+        state: EsimUiState,+        onClaim: (String) -> Unit = {},+        onStartCryptoPurchase: (Long) -> Unit = {},+    ) {+        composeRule.setContent {+            DynamicTheme {+                HomeScreen(+                    state = state,+                    onStartCardPurchase = { _, _, _ -> },+                    onStartCryptoPurchase = onStartCryptoPurchase,+                    onClearCryptoInvoice = {},+                    onClaim = onClaim,+                    onRefresh = {})+            }+        }+    }++    @Test fun loadingStateShowsPurchaseShell() {+        home(EsimUiState(statusLoaded = false))+        composeRule.onNodeWithText("Purchase").assertIsDisplayed()+    }++    @Test fun noProfileShowsSetupTermsAndClaim() {+        var claimed: String? = null+        home(EsimUiState(statusLoaded = true), onClaim = { claimed = it })+        composeRule.onNodeWithText("One global eSIM for 200+ countries").assertIsDisplayed()+        composeRule.onNodeWithText("$3 one-time setup fee").assertIsDisplayed()+        composeRule.onNodeWithText("Top up amount (USD)").assertIsDisplayed()+        composeRule.onAllNodes(hasSetTextAction())[1].performTextInput("sim-abc")+        composeRule.onNodeWithText("sim-abc").assertExists()+        composeRule.onNode(+            androidx.compose.ui.test.hasText("Claim on this phone") and+                androidx.compose.ui.test.hasClickAction())+            .performSemanticsAction(androidx.compose.ui.semantics.SemanticsActions.OnClick)+        assertEquals("sim-abc", claimed)+    }++    @Test fun pendingCreditShowsCreatingMessage() {+        home(EsimUiState(statusLoaded = true, pendingCreditCents = 500L))+        composeRule.onNodeWithText("Payment received").assertIsDisplayed()+        composeRule.onNodeWithText("Creating your eSIM. This page updates on its own.").assertIsDisplayed()+    }++    @Test fun profileShowsBalanceAndActions() {+        home(+            EsimUiState(+                statusLoaded = true,+                simId = "sim-xyz",+                profile = ProfileDto(+                    iccid = "8901", status = "active", walletUsdCents = 1234L,+                    activationCode = "CODE1", smdpAddress = "smdp.example")))+        composeRule.onNodeWithText("$12.34").assertIsDisplayed()+        composeRule.onNodeWithText("Balance · Active").assertIsDisplayed()+        composeRule.onNodeWithText("Install eSIM").assertIsDisplayed()+        composeRule.onNodeWithText("Copy SIM ID").assertIsDisplayed()+    }++    @Test fun profileStaleUnknownBalanceIsDash() {+        home(+            EsimUiState(+                statusLoaded = true,+                balanceStale = true,+                profile = ProfileDto(iccid = "1", status = "unknown", walletUsdCents = 0L),+                pendingCreditCents = 200L))+        composeRule.onNodeWithText("—").assertIsDisplayed()+        composeRule.onNodeWithText("$2.00 on its way. No need to pay again.").assertIsDisplayed()+    }++    private fun assertStatusLabel(status: String, label: String) {+        home(+            EsimUiState(+                statusLoaded = true,+                profile = ProfileDto(iccid = "1", status = status, walletUsdCents = 100L)))+        composeRule.onNodeWithText(label).assertIsDisplayed()+    }++    @Test fun statusPendingIsActivating() = assertStatusLabel("pending", "Balance · Activating")+    @Test fun statusSuspendedIsPaused() = assertStatusLabel("suspended", "Balance · Paused")+    @Test fun statusTerminated() = assertStatusLabel("terminated", "Balance · Terminated")+    @Test fun statusUnknownIsChecking() = assertStatusLabel("unknown", "Balance · Checking…")+    @Test fun statusCustomIsCapitalized() = assertStatusLabel("weird", "Balance · Weird")++    @Test fun profileInstallAndCopyActions() {+        val ctx = ApplicationProvider.getApplicationContext<android.content.Context>()+        home(+            EsimUiState(+                statusLoaded = true,+                simId = "sim-copy-me",+                profile = ProfileDto(+                    iccid = "8901", status = "active", walletUsdCents = 100L,+                    activationCode = "CODE9", smdpAddress = "smdp.example")))+        composeRule.onNodeWithText("Install eSIM").performClick()+        val intent = Shadows.shadowOf(ctx as android.app.Application).nextStartedActivity+        assertTrue(intent.data.toString().contains("esim_qrcode_provisioning"), "${intent.data}")+        assertTrue(intent.data.toString().contains("LPA:1\$smdp.example\$CODE9"), "${intent.data}")+        composeRule.onNodeWithText("Copy SIM ID").performClick()+        val clipboard = ctx.getSystemService(android.content.ClipboardManager::class.java)+        assertEquals("sim-copy-me", clipboard.primaryClip?.getItemAt(0)?.text?.toString())+    }++    @Test fun topUpAmountValidationAndBuy() {+        var card: Long? = null+        var crypto: Long? = null+        composeRule.setContent {+            DynamicTheme {+                TopUpCard(+                    busy = false,+                    onBuyWithCard = { card = it },+                    onBuyWithCrypto = { crypto = it },+                    pendingInvoiceUrl = null,+                    onClearCryptoInvoice = {})+            }+        }+        // Too small.+        composeRule.onNode(hasSetTextAction()).performTextInput("3")+        composeRule.onNodeWithText("Minimum $5.00 payment.").assertIsDisplayed()+        // Valid amount enables both rails.+        composeRule.onNode(hasSetTextAction()).performTextReplacement("12.50")+        composeRule.onNodeWithText("Card topup").performClick()+        assertEquals(1250L, card)+        composeRule.onNodeWithText("Crypto topup").performClick()+        assertEquals(1250L, crypto)+    }++    @Test fun topUpInvalidAndTooLargeAmounts() {+        composeRule.setContent {+            DynamicTheme {+                TopUpCard(+                    busy = false,+                    onBuyWithCard = {}, onBuyWithCrypto = {},+                    pendingInvoiceUrl = null, onClearCryptoInvoice = {})+            }+        }+        composeRule.onNode(hasSetTextAction()).performTextInput("abc")+        // Non-numeric input filters to blank through QuoteMath parsing; type digits beyond max.+        composeRule.onNode(hasSetTextAction()).performTextReplacement("25")+        composeRule.onNodeWithText("$20.00 max payment.").assertIsDisplayed()+    }++    @Test fun topUpPendingInvoiceRow() {+        var cleared = 0+        composeRule.setContent {+            DynamicTheme {+                TopUpCard(+                    busy = false,+                    onBuyWithCard = {}, onBuyWithCrypto = {},+                    pendingInvoiceUrl = "https://pay.example/invoice",+                    onClearCryptoInvoice = { cleared++ })+            }+        }+        composeRule.onNodeWithText("Reopen checkout").assertIsDisplayed()+        composeRule.onNodeWithText("Cancel").performClick()+        assertEquals(1, cleared)+        assertTrue(true)+    }+}
globalesim/src/test/java/com/vayunmathur/globalesim/ui/PricingSheetComposeTest.kt
diff --git a/globalesim/src/test/java/com/vayunmathur/globalesim/ui/PricingSheetComposeTest.kt b/globalesim/src/test/java/com/vayunmathur/globalesim/ui/PricingSheetComposeTest.ktnew file mode 100644index 0000000000..8d1eddf395--- /dev/null+++ b/globalesim/src/test/java/com/vayunmathur/globalesim/ui/PricingSheetComposeTest.kt@@ -0,0 +1,115 @@+package com.vayunmathur.globalesim.ui++import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.onAllNodesWithText+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 com.vayunmathur.globalesim.Navigation+import com.vayunmathur.globalesim.Route+import com.vayunmathur.globalesim.data.api.NetworkDto+import com.vayunmathur.globalesim.data.api.RateDto+import com.vayunmathur.globalesim.platform.EsimUiState+import com.vayunmathur.globalesim.platform.EsimViewModel+import com.vayunmathur.library.ui.DynamicTheme+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import androidx.test.core.app.ApplicationProvider++/** PricingScreen search/expansion and the CardPaymentSheet form. */+@RunWith(RobolectricTestRunner::class)+class PricingSheetComposeTest {++    @get:Rule+    val composeRule = createComposeRule()++    private fun rate(code: String, name: String, cents: Long, vararg ops: Pair<String, Long>) =+        RateDto(code, name, cents, ops.map { NetworkDto(it.first, it.second) })++    @Test fun pricingEmptyStates() {+        composeRule.setContent {+            DynamicTheme { PricingScreen(state = EsimUiState(), onRefresh = {}) }+        }+        composeRule.onNodeWithText("No rates yet").assertIsDisplayed()+        composeRule.onNodeWithText("Retry").assertIsDisplayed()+    }++    @Test fun pricingSearchFilterAndExpand() {+        val rates = listOf(+            rate("PT", "Portugal", 450L, "MEO" to 450L, "NOS" to 500L),+            rate("FR", "France", 300L))+        composeRule.setContent {+            DynamicTheme { PricingScreen(state = EsimUiState(rates = rates), onRefresh = {}) }+        }+        composeRule.onNodeWithText("Portugal").assertIsDisplayed()+        composeRule.onNodeWithText("from $4.50 / GB").assertIsDisplayed()+        // Expand Portugal to see carriers.+        composeRule.onNodeWithText("Portugal").performClick()+        composeRule.onNodeWithText("MEO", substring = true).assertIsDisplayed()+        // Filter down to France only.+        composeRule.onNode(hasSetTextAction()).performTextInput("fran")+        composeRule.onNodeWithText("France").assertIsDisplayed()+        // No matches state.+        composeRule.onNode(hasSetTextAction()).performTextReplacement("zzzz")+        composeRule.onNodeWithText("No matches").assertIsDisplayed()+    }++    @Test fun pricingExpandWithoutCarriersShowsFallback() {+        val rates = listOf(rate("FR", "France", 300L))+        composeRule.setContent {+            DynamicTheme { PricingScreen(state = EsimUiState(rates = rates), onRefresh = {}) }+        }+        composeRule.onNodeWithText("France").performClick()+        composeRule.onNodeWithText(+            "Carrier breakdown unavailable — charged at $3.00 / GB.").assertIsDisplayed()+    }++    @Test fun cardSheetValidCardPays() {+        var paid: com.vayunmathur.globalesim.domain.CardValidation.ValidCard? = null+        composeRule.setContent {+            DynamicTheme {+                CardPaymentSheet(+                    amountCents = 1000L, busy = false, confirming = false,+                    onPayWithCard = { paid = it }, onDismiss = {})+            }+        }+        composeRule.onAllNodesWithText("Pay $10.00")[0].assertIsDisplayed()+        composeRule.onNodeWithText("Card number").performTextInput("4242424242424242")+        composeRule.onNodeWithText("Expiry").performTextInput("12/99")+        composeRule.onNodeWithText("CVC").performTextInput("123")+        composeRule.onNode(+            androidx.compose.ui.test.hasText("Pay $10.00") and+                androidx.compose.ui.test.hasClickAction()).performClick()+        assertTrue(paid != null, "valid card should pay")+        assertEquals("4242424242424242", paid!!.number.replace(" ", ""))+    }++    @Test fun cardSheetInvalidCardShowsErrors() {+        composeRule.setContent {+            DynamicTheme {+                CardPaymentSheet(+                    amountCents = 500L, busy = false, confirming = false,+                    onPayWithCard = {}, onDismiss = {})+            }+        }+        composeRule.onNodeWithText("Card number").performTextInput("1234")+        composeRule.onAllNodesWithText("Pay $5.00")[0].assertIsDisplayed()+        // Error text appears once the field has been touched.+        composeRule.onNodeWithText("That card number doesn't look right.", substring = true).assertIsDisplayed()+    }++    @Test fun navigationRendersTabsOffline() {+        val app = ApplicationProvider.getApplicationContext<android.app.Application>()+        val vm = EsimViewModel(app)+        composeRule.setContent { DynamicTheme { Navigation(viewModel = vm) } }+        composeRule.onAllNodesWithText("Purchase")[0].assertIsDisplayed()+        assertEquals(Route.Tabs, Route.Tabs)+    }+}