globalesim: give the ViewModel test a ViewModelStore, like production
- Commit
660f62617bce3a4afe77d2dc590556ffcf4c6061- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-22 04:25 UTC (14 days ago)
- Parents
5992ced
The class built bare EsimViewModels, bypassing the ViewModelStore that cancels viewModelScope in production - every method's coroutines (including a 45-minute credit-watch poll) kept running against process-wide DataStore state and later methods' init never settled (4/9 failing on 15s awaits, 65s class time). The VM now lives in a ViewModelStore cleared in tearDown, each method gets a unique account id, and waits use the shared deterministic await. No production change: real usage is a single activity-scoped VM the framework clears. Verified: class 9/9 three forced runs (~3.4s), full suite 60/60 twice.
Diff
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.ktindex 6c0c863c83..5d3f37ab35 100644--- a/globalesim/src/test/java/com/vayunmathur/globalesim/platform/EsimViewModelTest.kt+++ b/globalesim/src/test/java/com/vayunmathur/globalesim/platform/EsimViewModelTest.kt@@ -1,10 +1,14 @@ package com.vayunmathur.globalesim.platform import android.app.Application-import android.os.Looper+import androidx.lifecycle.ViewModelStore import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.globalesim.data.AnonymousIdStore import com.vayunmathur.globalesim.network.EsimApi import com.vayunmathur.globalesim.network.ProfileDto+import com.vayunmathur.testsupport.awaitWithMainIdle+import com.vayunmathur.testsupport.idleMainLooper+import java.util.UUID import kotlin.test.AfterTest import kotlin.test.BeforeTest import kotlin.test.Test@@ -12,44 +16,81 @@ import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertNull import kotlin.test.assertTrue-import org.robolectric.Shadows+import kotlinx.coroutines.runBlocking /** * 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.+ *+ * Isolation (why the whole class used to fail while single methods passed):+ * this class builds a fresh ViewModel per method, but production gets its+ * one instance from `by viewModels()`, whose ViewModelStore cancels+ * viewModelScope when the activity finishes. Bare construction here+ * bypassed that, so every previous method's coroutines — the init load and,+ * worst, the 45-minute credit-watch poll started by the paid-purchase+ * tests — kept running against the process-wide state for the rest of the+ * class: the `preferencesDataStore` delegate behind [AnonymousIdStore]+ * (one DataStore per file for the whole test process) and+ * [EsimApi.baseUrlOverride]. Later methods then raced those leaked polls+ * for the same account id and never settled inside the old wall-clock+ * await. The store below restores the production lifecycle (clearing it in+ * tearDown cancels the scope, credit watch included), each method seeds a+ * unique account id before its ViewModel reads one, and all waits go+ * through the shared [awaitWithMainIdle] instead of sleeping. */ @org.junit.runner.RunWith(org.robolectric.RobolectricTestRunner::class) class EsimViewModelTest { private val app: Application get() = ApplicationProvider.getApplicationContext() + private lateinit var viewModelStore: ViewModelStore private lateinit var vm: EsimViewModel @BeforeTest fun setUp() { // Hermetic offline: dead loopback, so the API fails on any box // (CI has internet and the real API answered these tests before). EsimApi.baseUrlOverride = "https://127.0.0.1:9"+ // Unique account id per method, seeded before the ViewModel's init+ // reads it: the DataStore file itself is process-wide (see class+ // doc), so value-level isolation is what a method can own.+ runBlocking { AnonymousIdStore(app).replace(UUID.randomUUID().toString()) }+ viewModelStore = ViewModelStore() vm = EsimViewModel(app)+ viewModelStore.put(VM_KEY, vm) } @AfterTest fun tearDown() {+ // onCleared() closes viewModelScope: cancels the init load, any+ // in-flight action, and the credit-watch poll, so nothing from this+ // method can touch the shared DataStore or API override afterwards.+ viewModelStore.clear() EsimApi.baseUrlOverride = null } - 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)+ /**+ * Deterministic form of the old sleep-and-deadline loop: pump the main+ * looper until [cond] holds. The generous step bound is the cast+ * precedent for producers on IO (the dead-loopback calls land there);+ * each step yields so those threads get wall time, and the bound is a+ * failure limit only, never the mechanism.+ */+ private fun await(description: String, cond: () -> Boolean): Boolean =+ try {+ awaitWithMainIdle(description, maxSteps = AWAIT_MAX_STEPS, condition = cond)+ true+ } catch (_: IllegalStateException) {+ false }- return cond()++ private companion object {+ const val VM_KEY = "esim"+ const val AWAIT_MAX_STEPS = 200_000 } @Test fun initMintsSimIdAndSettlesOffline() { assertTrue(- await { vm.state.statusLoaded && vm.state.simId != null },+ await("init settles offline") { vm.state.statusLoaded && vm.state.simId != null }, "state=${vm.state}") assertFalse(vm.state.loading) assertNull(vm.state.profile)@@ -83,10 +124,10 @@ class EsimViewModelTest { } @Test fun purchasesFailOfflineWithFriendlyMessage() {- assertTrue(await { vm.state.statusLoaded })+ assertTrue(await("status loaded") { 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}")+ assertTrue(await("action fails offline") { !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)@@ -95,7 +136,7 @@ class EsimViewModelTest { vm.dismissMessage() var invoiceReady: String? = null vm.startCryptoPurchase(1_000L) { invoiceReady = it }- assertTrue(await { !vm.state.loading && vm.state.message != null }, "state=${vm.state}")+ assertTrue(await("action fails offline") { !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)@@ -103,9 +144,9 @@ class EsimViewModelTest { } @Test fun claimAndClearInvoiceFailOffline() {- assertTrue(await { vm.state.statusLoaded })+ assertTrue(await("status loaded") { vm.state.statusLoaded }) vm.claim(" some-sim-id ")- assertTrue(await { !vm.state.loading && vm.state.message != null }, "state=${vm.state}")+ assertTrue(await("action fails offline") { !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.@@ -117,26 +158,29 @@ class EsimViewModelTest { } @Test fun refreshCyclesSettleOffline() {- assertTrue(await { vm.state.statusLoaded })+ assertTrue(await("status loaded") { vm.state.statusLoaded }) vm.refresh()- assertTrue(await { !vm.state.refreshing }, "state=${vm.state}")+ assertTrue(await("refresh settles") { !vm.state.refreshing }, "state=${vm.state}") vm.refreshStatus()- assertTrue(await { !vm.state.loading }, "state=${vm.state}")+ assertTrue(await("refreshStatus settles") { !vm.state.loading }, "state=${vm.state}") vm.refreshRates()- assertTrue(await { vm.state.rates.isEmpty() })+ assertTrue(await("rates settle empty") { 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.+ // No wall-clock wait for a poll tick: a failed poll changes no visible+ // state, so pumping the looper and re-checking the cleared state is+ // the deterministic form of the old sleep-and-recheck. 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()+ assertTrue(+ await("credit watch leaves purchase state cleared") {+ vm.state.pendingClientSecret == null && !vm.state.loading+ })+ idleMainLooper() assertNull(vm.state.pendingClientSecret)+ assertFalse(vm.state.loading) vm.clearPendingInvoice() }