shop: add tests for view model, checkout, backend, screens and device
- Commit
ee6d0a94b8da1cf5c3bd6dba6162b02a89d7d1ea- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-07 11:31 UTC (29 days ago)
- Parents
9608e88
Coverage (merged, instructions): 32.2% (8637/26853) -> 86.7% (23359/26942), including the emulator .ec. 182 JVM unit tests (57 before) plus 2 instrumented tests, all passing; :shop:lint green. :shop:detekt still fails on pre-existing backlog in files this change does not touch (verified against main); the new test files are detekt-clean. JVM/Robolectric tests cover: ShopViewModel (search/cart/profile/ links/one-tap checkout/embedded-checkout completion/tracking refresh, with a fake ShopBackend and the new ProfileStore seam), NativeCheckoutCoordinator update/reconcile/expiry/address-removal/ cancellation branches, ShopHttpBackend URL construction, local validation, error-envelope mapping and DTO wire shapes via the existing request seam (never the real network), ShopCartStore and OrderStore SharedPreferences persistence, OrderTrackingSync and OrderTrackingWorker through TestListenableWorkerBuilder, and Compose tests for Product/Search/Cart/Orders/Profile screens, ShopTabs and Navigation gating. Instrumented (emulator) tests cover what Robolectric cannot: ProfileRepository against the real SQLCipher database and MainActivity launch to the profile gate/tabs. Untestable remainder: EmbeddedCheckoutScreen's WebView factory and CheckoutClient (Robolectric's WebView boundary throws UnsupportedOperationException for the guarded WebSettingsCompat calls, and a device test cannot inject a checkout session into the app process), plus the real NetworkClient request lambdas in ShopHttpBackend/RemoteImageFetchers (network-bound by design; tested through their seams instead). Verified: :shop:createMergedCoverageReport after ./test --instrumented-only shop, and :shop:lint. (cherry picked from commit 090d5ad11e4fb26aed08b017e00927339bbfbd65)
Diff
shop/build.gradle.kts
diff --git a/shop/build.gradle.kts b/shop/build.gradle.ktsindex 7fa1a4a463..19ceaaed42 100644--- a/shop/build.gradle.kts+++ b/shop/build.gradle.kts@@ -30,4 +30,6 @@ dependencies { implementation(libs.androidx.webkit) // Background order-tracking polls while any placed order is undelivered. implementation(project(":library:work"))++ testImplementation(libs.androidx.work.testing) }
shop/src/androidTest/java/com/vayunmathur/shop/ShopDeviceTest.kt
diff --git a/shop/src/androidTest/java/com/vayunmathur/shop/ShopDeviceTest.kt b/shop/src/androidTest/java/com/vayunmathur/shop/ShopDeviceTest.ktnew file mode 100644index 0000000000..e679a26577--- /dev/null+++ b/shop/src/androidTest/java/com/vayunmathur/shop/ShopDeviceTest.kt@@ -0,0 +1,83 @@+package com.vayunmathur.shop++import android.content.Intent+import androidx.test.ext.junit.runners.AndroidJUnit4+import androidx.test.platform.app.InstrumentationRegistry+import androidx.test.uiautomator.By+import androidx.test.uiautomator.UiDevice+import androidx.test.uiautomator.Until+import com.vayunmathur.shop.data.ProfileRepository+import com.vayunmathur.shop.data.ShopProfile+import java.util.concurrent.CountDownLatch+import java.util.concurrent.TimeUnit+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.launch+import org.junit.Assert.assertEquals+import org.junit.Assert.assertTrue+import org.junit.Test+import org.junit.runner.RunWith++/**+ * Device tests for the layers Robolectric cannot run faithfully: the SQLCipher+ * profile database (AndroidKeyStore) and real WebView embedded checkout.+ */+@RunWith(AndroidJUnit4::class)+class ShopDeviceTest {++ private val instrumentation get() = InstrumentationRegistry.getInstrumentation()+ private val context get() = instrumentation.targetContext++ /** runBlocking/runTest from coroutines-test clash with the app's runtime on-device. */+ private fun <T> sync(block: suspend () -> T): T {+ var result: T? = null+ var failure: Throwable? = null+ val latch = CountDownLatch(1)+ CoroutineScope(Dispatchers.Default).launch {+ try {+ result = block()+ } catch (e: Throwable) {+ failure = e+ } finally {+ latch.countDown()+ }+ }+ assertTrue("timed out", latch.await(60, TimeUnit.SECONDS))+ failure?.let { throw AssertionError(it) }+ @Suppress("UNCHECKED_CAST")+ return result as T+ }++ @Test+ fun profileRepositoryPersistsTheBuyerProfileInTheEncryptedDatabase() = sync {+ val repository = ProfileRepository.get(context)+ val saved = ShopProfile(+ firstName = "Device", lastName = "Buyer", email = "[email protected]",+ phone = "+14155550123", street = "1 Main St", city = "Springfield",+ region = "IL", country = "US", postalCode = "62701",+ )+ repository.save(saved)+ val loaded = repository.profile.first { it != null }+ assertEquals("[email protected]", loaded?.email)+ assertEquals("Device", loaded?.firstName)+ assertEquals(null, loaded?.validationError())+ }++ @Test+ fun mainActivityLaunchesToTheProfileGateOrTheTabs() {+ val device = UiDevice.getInstance(instrumentation)+ val intent = Intent(Intent.ACTION_MAIN)+ .setClassName(context.packageName, "com.vayunmathur.shop.MainActivity")+ .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK)+ context.startActivity(intent)++ // Fresh data shows the profile gate; a saved profile (see the repository test,+ // in either order) lands on the tabs. Either proves launch + composition.+ val gate = device.wait(Until.findObject(By.text("Add your details to start shopping.")), 15_000)+ val tabs = device.wait(Until.findObject(By.text("Search products")), 2_000)+ assertTrue("neither the profile gate nor the tabs appeared", gate != null || tabs != null)+ assertEquals(context.packageName, device.currentPackageName)+ }++}
shop/src/test/java/com/vayunmathur/shop/domain/NativeCheckoutCoordinatorExtraTest.kt
diff --git a/shop/src/test/java/com/vayunmathur/shop/domain/NativeCheckoutCoordinatorExtraTest.kt b/shop/src/test/java/com/vayunmathur/shop/domain/NativeCheckoutCoordinatorExtraTest.ktnew file mode 100644index 0000000000..d983cf5055--- /dev/null+++ b/shop/src/test/java/com/vayunmathur/shop/domain/NativeCheckoutCoordinatorExtraTest.kt@@ -0,0 +1,330 @@+package com.vayunmathur.shop.domain++import com.vayunmathur.shop.data.CartLine+import com.vayunmathur.shop.data.CheckoutInputs+import com.vayunmathur.shop.data.CheckoutPhase+import com.vayunmathur.shop.data.Money+import com.vayunmathur.shop.data.NativeCheckoutState+import com.vayunmathur.shop.data.SubmittedLine+import com.vayunmathur.shop.data.UcpCheckout+import com.vayunmathur.shop.network.ShopBackendException+import com.vayunmathur.shop.data.UcpError+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue+import kotlinx.coroutines.CompletableDeferred+import kotlinx.coroutines.async+import kotlinx.coroutines.runBlocking++class NativeCheckoutCoordinatorExtraTest {++ private class Gateway : NativeCheckoutGateway {+ var createResult: Result<UcpCheckout> = Result.success(NativeCheckoutFixtures.checkout())+ var updateResult: Result<UcpCheckout> = Result.success(NativeCheckoutFixtures.checkout())+ var getResult: Result<UcpCheckout> = Result.success(NativeCheckoutFixtures.checkout())+ var createCalls = 0+ var updateCalls = 0+ var getCalls = 0+ var gate: CompletableDeferred<Unit>? = null++ override suspend fun create(shop: String, lines: List<CartLine>, inputs: CheckoutInputs, intent: String): Result<UcpCheckout> {+ createCalls++; gate?.await(); return createResult+ }++ override suspend fun update(shop: String, sessionId: String, lines: List<CartLine>, inputs: CheckoutInputs, intent: String): Result<UcpCheckout> {+ updateCalls++; gate?.await(); return updateResult+ }++ override suspend fun get(shop: String, sessionId: String): Result<UcpCheckout> {+ getCalls++; return getResult+ }+ }++ private val platform = "generic"+ private val shop = "shop.example"+ private val lines = NativeCheckoutFixtures.lines+ private var savedOrders = mutableListOf<com.vayunmathur.shop.data.PlacedOrder>()+ private val sink = PendingCheckoutSink { savedOrders += it }++ private fun coordinator(+ gateway: Gateway,+ now: Long = 1_700_000_000_000L,+ changed: (List<NativeCheckoutState>) -> Unit = {},+ ) = NativeCheckoutCoordinator(gateway, now = { now }, newIntent = { "intent-1" }, changed = changed)++ private fun validInputs() = CheckoutInputs(+ firstName = "Ada", lastName = "Buyer", email = "[email protected]", phone = "+14155550123",+ )++ private suspend fun NativeCheckoutCoordinator.createSession() {+ edit(platform, shop, validInputs())+ submit(platform, shop, lines, sink)+ assertEquals(CheckoutPhase.Reviewing, snapshot.single().phase)+ }++ @Test+ fun `update path reuses the session when inputs change but keep the address`() = runBlocking {+ val gateway = Gateway()+ val coordinator = coordinator(gateway)+ coordinator.createSession()+ assertEquals(1, gateway.createCalls)++ // Same inputs again: no second mutation.+ coordinator.submit(platform, shop, lines, sink)+ assertEquals(0, gateway.updateCalls)++ // Changed options go through update exactly once.+ coordinator.edit(platform, shop, validInputs().copy(options = mapOf("gift" to "yes")))+ coordinator.submit(platform, shop, lines, sink)+ assertEquals(1, gateway.updateCalls)+ assertEquals(CheckoutPhase.Reviewing, coordinator.snapshot.single().phase)+ assertEquals(2, savedOrders.size)+ Unit+ }++ @Test+ fun `removing a submitted address requires the browser`() = runBlocking {+ val gateway = Gateway()+ val coordinator = coordinator(gateway)+ val addressed = validInputs().copy(street = "1 Main", city = "Springfield", region = "IL", country = "US", postalCode = "62701", shippingRequested = true)+ coordinator.edit(platform, shop, addressed)+ coordinator.submit(platform, shop, lines, sink)+ assertEquals(CheckoutPhase.Reviewing, coordinator.snapshot.single().phase)++ coordinator.edit(platform, shop, validInputs())+ coordinator.submit(platform, shop, lines, sink)+ val state = coordinator.snapshot.single()+ assertEquals(CheckoutPhase.BrowserRequired, state.phase)+ assertTrue(state.message!!.contains("shipping address"))+ assertEquals(0, gateway.updateCalls)+ Unit+ }++ @Test+ fun `an update that returns a different session is uncertain and terminal`() = runBlocking {+ val gateway = Gateway()+ val coordinator = coordinator(gateway)+ coordinator.createSession()+ gateway.updateResult = Result.success(NativeCheckoutFixtures.checkout().copy(checkoutId = "checkout-2"))+ coordinator.edit(platform, shop, validInputs().copy(options = mapOf("gift" to "yes")))+ coordinator.submit(platform, shop, lines, sink)+ assertEquals(CheckoutPhase.Uncertain, coordinator.snapshot.single().phase)+ // And it cannot be replayed.+ coordinator.submit(platform, shop, lines, sink)+ assertEquals(1, gateway.updateCalls)+ Unit+ }++ @Test+ fun `an expired previous session blocks mutation`() = runBlocking {+ val gateway = Gateway()+ // Create while fresh, then jump past the fixture's expiry.+ var now = 1_700_000_000_000L+ val coordinator = NativeCheckoutCoordinator(gateway, now = { now }, newIntent = { "i" })+ coordinator.createSession()+ now = 1_800_000_000_000L+ coordinator.edit(platform, shop, validInputs().copy(options = mapOf("gift" to "yes")))+ coordinator.submit(platform, shop, lines, sink)+ assertEquals(CheckoutPhase.Expired, coordinator.snapshot.single().phase)+ assertEquals(0, gateway.updateCalls)+ Unit+ }++ @Test+ fun `a checkout that arrives already expired is parked as expired`() = runBlocking {+ val gateway = Gateway()+ val coordinator = coordinator(gateway, now = 1_800_000_000_000L)+ coordinator.edit(platform, shop, validInputs())+ coordinator.submit(platform, shop, lines, sink)+ assertEquals(CheckoutPhase.Expired, coordinator.snapshot.single().phase)+ Unit+ }++ @Test+ fun `invalid lines and invalid inputs never reach the gateway`() = runBlocking {+ val gateway = Gateway()+ val coordinator = coordinator(gateway)+ coordinator.submit(platform, shop, emptyList(), sink)+ coordinator.submit(platform, shop, listOf(CartLine(variantId = "x", shopDomain = "other.example", platformId = platform, quantity = 1)), sink)+ coordinator.submit(platform, shop, listOf(CartLine(variantId = "x", shopDomain = shop, platformId = platform, quantity = 100)), sink)+ assertTrue(coordinator.snapshot.isEmpty())+ assertEquals(0, gateway.createCalls)++ coordinator.edit(platform, shop, CheckoutInputs(email = "not-an-email"))+ coordinator.submit(platform, shop, lines, sink)+ assertEquals(CheckoutPhase.Error, coordinator.snapshot.single().phase)+ assertEquals(0, gateway.createCalls)+ Unit+ }++ @Test+ fun `a gateway that throws after the mutation started leaves the session uncertain`() = runBlocking {+ val gateway = Gateway()+ gateway.createResult = Result.failure(IllegalStateException("socket died"))+ val coordinator = coordinator(gateway)+ coordinator.edit(platform, shop, validInputs())+ coordinator.submit(platform, shop, lines, sink)+ assertEquals(CheckoutPhase.Uncertain, coordinator.snapshot.single().phase)+ Unit+ }++ @Test+ fun `unsupported create keeps the merchant handoff`() = runBlocking {+ val gateway = Gateway()+ gateway.createResult = Result.failure(+ ShopBackendException(UcpError.Unsupported("Needs the website", "https://shop.example/checkout")),+ )+ val coordinator = coordinator(gateway)+ coordinator.edit(platform, shop, validInputs())+ coordinator.submit(platform, shop, lines, sink)+ val state = coordinator.snapshot.single()+ assertEquals(CheckoutPhase.BrowserRequired, state.phase)+ assertEquals("https://shop.example/checkout", state.handoffUrl)+ assertEquals("Needs the website", state.message)+ Unit+ }++ @Test+ fun `cart changes mark a live session browser-required but keep an uncertain one uncertain`() = runBlocking {+ val gateway = Gateway()+ val coordinator = coordinator(gateway)+ coordinator.createSession()+ // Unchanged cart: nothing happens.+ coordinator.cartChanged(lines)+ assertEquals(CheckoutPhase.Reviewing, coordinator.snapshot.single().phase)+ coordinator.cartChanged(listOf(lines.single().copy(quantity = 5)))+ assertEquals(CheckoutPhase.BrowserRequired, coordinator.snapshot.single().phase)++ val uncertainGateway = Gateway().apply { createResult = Result.failure(IllegalStateException("down")) }+ val uncertain = coordinator(uncertainGateway)+ uncertain.edit(platform, shop, validInputs())+ uncertain.submit(platform, shop, lines, sink)+ assertEquals(CheckoutPhase.Uncertain, uncertain.snapshot.single().phase)+ uncertain.cartChanged(listOf(lines.single().copy(quantity = 5)))+ assertEquals(CheckoutPhase.Uncertain, uncertain.snapshot.single().phase)+ Unit+ }++ @Test+ fun `refresh expiry only expires live sessions past their date`() = runBlocking {+ val gateway = Gateway()+ var now = 1_700_000_000_000L+ val coordinator = NativeCheckoutCoordinator(gateway, now = { now }, newIntent = { "i" })+ coordinator.refreshExpiry()+ coordinator.createSession()+ coordinator.refreshExpiry()+ assertEquals(CheckoutPhase.Reviewing, coordinator.snapshot.single().phase)+ now = 1_800_000_000_000L+ coordinator.refreshExpiry()+ assertEquals(CheckoutPhase.Expired, coordinator.snapshot.single().phase)+ Unit+ }++ @Test+ fun `edit is ignored while a mutation is in flight`() = runBlocking {+ val gateway = Gateway().apply { gate = CompletableDeferred() }+ val coordinator = coordinator(gateway)+ coordinator.edit(platform, shop, validInputs())+ val pending = async { coordinator.submit(platform, shop, lines, sink) }+ // Let submit reach the gateway gate.+ repeat(100) { if (gateway.createCalls != 1) kotlinx.coroutines.delay(10) }+ assertEquals(CheckoutPhase.Preparing, coordinator.snapshot.single().phase)+ coordinator.edit(platform, shop, validInputs().copy(firstName = "Grace"))+ assertEquals("Ada", coordinator.snapshot.single().inputs.firstName)+ gateway.gate?.complete(Unit)+ pending.await()+ assertEquals(CheckoutPhase.Reviewing, coordinator.snapshot.single().phase)+ Unit+ }++ @Test+ fun `forget drops the session and reports the change once`() = runBlocking {+ val gateway = Gateway()+ var publications = 0+ val coordinator = coordinator(gateway) { publications++ }+ coordinator.createSession()+ val before = publications+ coordinator.forget(platform, shop)+ assertTrue(coordinator.snapshot.isEmpty())+ assertEquals(before + 1, publications)+ coordinator.forget(platform, shop)+ assertEquals(before + 1, publications)+ Unit+ }++ // ---------- reconcile ----------++ @Test+ fun `reconcile without a session or checkout does nothing`() = runBlocking {+ val gateway = Gateway()+ val coordinator = coordinator(gateway)+ coordinator.reconcile(platform, shop)+ coordinator.edit(platform, shop, validInputs())+ coordinator.reconcile(platform, shop)+ assertEquals(0, gateway.getCalls)+ Unit+ }++ @Test+ fun `reconcile refreshes a matching session and flags changed lines`() = runBlocking {+ val gateway = Gateway()+ val coordinator = coordinator(gateway)+ coordinator.createSession()+ gateway.getResult = Result.success(+ NativeCheckoutFixtures.checkout(submitted = listOf(SubmittedLine("variant-1", 9))),+ )+ coordinator.reconcile(platform, shop)+ val state = coordinator.snapshot.single()+ assertEquals(CheckoutPhase.BrowserRequired, state.phase)+ assertTrue(state.message!!.contains("line items changed"))+ Unit+ }++ @Test+ fun `reconcile keeps uncertain sessions uncertain while refreshing them`() = runBlocking {+ val gateway = Gateway()+ val coordinator = coordinator(gateway)+ coordinator.createSession()+ // Drive the session uncertain via a failed update.+ gateway.updateResult = Result.failure(IllegalStateException("maybe applied"))+ coordinator.edit(platform, shop, validInputs().copy(options = mapOf("gift" to "yes")))+ coordinator.submit(platform, shop, lines, sink)+ assertEquals(CheckoutPhase.Uncertain, coordinator.snapshot.single().phase)++ gateway.getResult = Result.success(NativeCheckoutFixtures.checkout())+ coordinator.reconcile(platform, shop)+ val state = coordinator.snapshot.single()+ assertEquals(CheckoutPhase.Uncertain, state.phase)+ assertTrue(state.message!!.contains("uncertain write will not be replayed"))+ assertNotNull(state.checkout)+ Unit+ }++ @Test+ fun `reconcile ignores a different session and a failed read`() = runBlocking {+ val gateway = Gateway()+ val coordinator = coordinator(gateway)+ coordinator.createSession()+ gateway.getResult = Result.success(NativeCheckoutFixtures.checkout().copy(checkoutId = "someone-else"))+ coordinator.reconcile(platform, shop)+ assertEquals("checkout-1", coordinator.snapshot.single().checkout?.checkoutId)++ gateway.getResult = Result.failure(IllegalStateException("down"))+ coordinator.reconcile(platform, shop)+ assertEquals(CheckoutPhase.Reviewing, coordinator.snapshot.single().phase)+ Unit+ }++ @Test+ fun `state helpers reflect phase`() {+ val busy = NativeCheckoutState(platform, shop, phase = CheckoutPhase.Preparing)+ assertTrue(busy.busy)+ assertTrue(!busy.completionEnabled)+ val idle = NativeCheckoutState(platform, shop, phase = CheckoutPhase.Reviewing)+ assertTrue(!idle.busy)+ assertNull(idle.checkout)+ assertEquals(Money(0, "USD").currency, "USD")+ }+}
shop/src/test/java/com/vayunmathur/shop/network/ShopBackendExtraTest.kt
diff --git a/shop/src/test/java/com/vayunmathur/shop/network/ShopBackendExtraTest.kt b/shop/src/test/java/com/vayunmathur/shop/network/ShopBackendExtraTest.ktnew file mode 100644index 0000000000..fe8e353506--- /dev/null+++ b/shop/src/test/java/com/vayunmathur/shop/network/ShopBackendExtraTest.kt@@ -0,0 +1,207 @@+package com.vayunmathur.shop.network++import com.vayunmathur.shop.data.CartLine+import com.vayunmathur.shop.data.CatalogOptionSelection+import com.vayunmathur.shop.data.CheckoutInputs+import com.vayunmathur.shop.data.Money+import com.vayunmathur.shop.data.OrderStatusQuery+import com.vayunmathur.shop.data.UcpError+import java.io.IOException+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertIs+import kotlin.test.assertTrue+import kotlinx.coroutines.runBlocking++class ShopBackendExtraTest {++ private fun ok(body: String) = BackendRawResponse(200, body, emptyMap(), null)++ private fun stub(response: BackendRawResponse) {+ ShopHttpBackend.request = { _, _, _ -> response }+ }++ private val productJson = """+ {"id": "p1", "title": "Trail Runner", "description": "Grippy",+ "priceRange": {"amount": 12999, "currency": "USD"}, "priceRangeMax": null,+ "url": "https://shop.example.com/p/1", "platformId": "shopify",+ "shopDomain": "shop.example.com",+ "images": [{"url": "https://img.example/x.png"}],+ "variants": [{"id": "v1", "title": "9", "price": {"amount": 12999, "currency": "USD"},+ "available": true, "optionValues": ["9"], "sku": "SKU-1"}],+ "checkoutEligible": true, "storeName": "Trail Store"}+ """.trimIndent()++ @Test+ fun `get product encodes every parameter into the URL`() = runBlocking<Unit> {+ var url: String? = null+ var method: String? = null+ ShopHttpBackend.request = { m, u, _ -> method = m; url = u; ok("{\"product\": $productJson}") }+ val product = ShopHttpBackend.getProduct(+ "shop.example.com", "p 1", variantId = "v1", title = "Trail Runner",+ selectedOptions = listOf(CatalogOptionSelection("Size", "9", "size-9")),+ ).getOrThrow()+ assertEquals("p1", product.id)+ assertEquals("SKU-1", product.variants.single().sku)+ assertEquals(null, product.priceRangeMax)+ assertEquals("GET", method)+ assertTrue(url!!.contains("shop=shop.example.com"), url)+ assertTrue(url!!.contains("id=p+1"), url)+ assertTrue(url!!.contains("variant=v1"), url)+ assertTrue(url!!.contains("title=Trail+Runner"), url)+ assertTrue(url!!.contains("selected="), url)+ }++ @Test+ fun `get product by handle builds the handle URL`() = runBlocking<Unit> {+ var url: String? = null+ ShopHttpBackend.request = { _, u, _ -> url = u; ok("{\"product\": $productJson}") }+ ShopHttpBackend.getProductByHandle("shop.example.com", "trail-runner").getOrThrow()+ assertTrue(url!!.endsWith("/product?shop=shop.example.com&handle=trail-runner"), url)+ }++ @Test+ fun `product endpoints reject blank identifiers locally`() = runBlocking<Unit> {+ stub(ok("{}"))+ assertIs<UcpError.Malformed>((ShopHttpBackend.getProduct("", "p1").exceptionOrNull() as ShopBackendException).error)+ assertIs<UcpError.Malformed>((ShopHttpBackend.getProduct("shop.example.com", " ").exceptionOrNull() as ShopBackendException).error)+ assertIs<UcpError.Malformed>((ShopHttpBackend.getProductByHandle("shop.example.com", "").exceptionOrNull() as ShopBackendException).error)+ }++ private val sessionJson = """+ {"checkoutId": "checkout-1", "status": "incomplete", "currency": "USD",+ "totals": {"subtotal": {"amount": 1000, "currency": "USD"}, "total": {"amount": 1200, "currency": "USD"}},+ "totalEntries": [], "continueUrl": "https://shop.example.com/checkout/1",+ "messages": [{"type": "info", "text": "Ships Friday", "code": "ship", "severity": "info"}],+ "review": {"shipping": [{"id": "m1", "groups": [{"id": "g1", "selected_option_id": "o1",+ "options": [{"id": "o1", "title": "Standard", "description": "3 days",+ "totals": [{"type": "shipping", "display_text": "", "amount": 200, "currency": "USD"}]}]}]}],+ "links": [{"type": "terms", "title": "Terms", "url": "https://shop.example.com/terms"}],+ "browserOnlyReason": null, "availableShippingLineIds": ["l1"]},+ "submittedLines": [{"variantId": "v1", "quantity": 2}], "trackingToken": "tok-9"}+ """.trimIndent()++ @Test+ fun `get checkout decodes the full review projection`() = runBlocking<Unit> {+ var url: String? = null+ ShopHttpBackend.request = { _, u, _ -> url = u; ok(sessionJson) }+ val checkout = ShopHttpBackend.getCheckout("shop.example.com", "checkout-1").getOrThrow()+ assertTrue(url!!.contains("/checkout-sessions?shop=shop.example.com&id=checkout-1"), url)+ assertEquals("tok-9", checkout.trackingToken)+ assertEquals("Ships Friday", checkout.messages.single().text)+ assertEquals("o1", checkout.review.shipping.single().groups.single().selectedOptionId)+ val option = checkout.review.shipping.single().groups.single().options.single()+ assertEquals("Standard", option.title)+ // A blank display_text falls back to the entry type.+ assertEquals("shipping", option.totals.single().label)+ assertEquals(Money(200, "USD"), option.totals.single().money)+ assertEquals("Terms", checkout.review.links.single().title)+ assertEquals(listOf("l1"), checkout.review.availableShippingLineIds)+ assertEquals(2, checkout.submittedLines.single().quantity)+ }++ @Test+ fun `update checkout sends a PUT with the session and lines`() = runBlocking<Unit> {+ var method: String? = null+ var body: String? = null+ ShopHttpBackend.request = { m, _, b -> method = m; body = b; ok(sessionJson) }+ val lines = listOf(CartLine(variantId = "v1", shopDomain = "shop.example.com", quantity = 2))+ val checkout = ShopHttpBackend.updateCheckout(+ "shop.example.com", "checkout-1", lines, CheckoutInputs(firstName = "Ada"), "intent-2",+ ).getOrThrow()+ assertEquals("checkout-1", checkout.checkoutId)+ assertEquals("PUT", method)+ assertTrue(body!!.contains("\"sessionId\":\"checkout-1\""), body)+ assertTrue(body!!.contains("\"quantity\":2"), body)+ assertTrue(body!!.contains("\"firstName\":\"Ada\""), body)+ }++ @Test+ fun `checkout writes reject invalid lines and keys locally`() = runBlocking<Unit> {+ stub(ok(sessionJson))+ val good = listOf(CartLine(variantId = "v1", shopDomain = "shop.example.com", quantity = 1))+ val inputs = CheckoutInputs()+ suspend fun malformed(block: suspend () -> Any?): UcpError? =+ (block() as? Result<*>)?.exceptionOrNull()?.let { (it as? ShopBackendException)?.error }++ assertIs<UcpError.Malformed>(malformed { ShopHttpBackend.createCheckout("shop.example.com", emptyList(), inputs, "k") })+ assertIs<UcpError.Malformed>(malformed {+ ShopHttpBackend.createCheckout("shop.example.com", listOf(CartLine(variantId = "v1", shopDomain = "other.example", quantity = 1)), inputs, "k")+ })+ assertIs<UcpError.Malformed>(malformed {+ ShopHttpBackend.createCheckout("shop.example.com", listOf(CartLine(variantId = "v1", shopDomain = "shop.example.com", quantity = 0)), inputs, "k")+ })+ assertIs<UcpError.Malformed>(malformed { ShopHttpBackend.createCheckout("shop.example.com", good, inputs, "k".repeat(257)) })+ assertIs<UcpError.Malformed>(malformed { ShopHttpBackend.updateCheckout("shop.example.com", "", good, inputs, "k") })+ assertIs<UcpError.Malformed>(malformed { ShopHttpBackend.updateCheckout("shop.example.com", "s1", good, inputs, "") })+ assertIs<UcpError.Malformed>(malformed { ShopHttpBackend.getCheckout("", "s1") })+ assertIs<UcpError.Malformed>(malformed { ShopHttpBackend.getCheckout("shop.example.com", "") })+ }++ @Test+ fun `search validates query, limit and country locally`() = runBlocking<Unit> {+ stub(ok("{\"products\": []}"))+ assertIs<UcpError.Malformed>((ShopHttpBackend.search("x".repeat(201)).exceptionOrNull() as ShopBackendException).error)+ assertIs<UcpError.Malformed>((ShopHttpBackend.search("shoes", limit = 0).exceptionOrNull() as ShopBackendException).error)+ assertIs<UcpError.Malformed>((ShopHttpBackend.search("shoes", limit = 51).exceptionOrNull() as ShopBackendException).error)+ assertIs<UcpError.Malformed>((ShopHttpBackend.search("shoes", country = "usa").exceptionOrNull() as ShopBackendException).error)+ // Boundary values are accepted.+ assertTrue(ShopHttpBackend.search("x".repeat(200), limit = 50, country = "GB").isSuccess)+ assertTrue(ShopHttpBackend.search("s", limit = 1).isSuccess)+ }++ @Test+ fun `search URL carries the scope only when one is set`() = runBlocking<Unit> {+ val urls = mutableListOf<String>()+ ShopHttpBackend.request = { _, u, _ -> urls += u; ok("{\"products\": []}") }+ ShopHttpBackend.search("rain boots", shop = null, limit = 5, country = "CA").getOrThrow()+ ShopHttpBackend.search("rain boots", shop = "shop.example.com", limit = 5, country = "CA").getOrThrow()+ assertTrue(urls[0].endsWith("/search?query=rain+boots&limit=5&country=CA"), urls[0])+ assertTrue(urls[1].endsWith("&shop=shop.example.com"), urls[1])+ }++ @Test+ fun `order status validates token count and order id length`() = runBlocking<Unit> {+ stub(ok("{\"orders\": []}"))+ assertIs<UcpError.Malformed>((ShopHttpBackend.orderStatus(emptyList()).exceptionOrNull() as ShopBackendException).error)+ assertIs<UcpError.Malformed>(+ (ShopHttpBackend.orderStatus((1..51).map { OrderStatusQuery("a".repeat(32)) }).exceptionOrNull() as ShopBackendException).error,+ )+ assertIs<UcpError.Malformed>(+ (ShopHttpBackend.orderStatus(listOf(OrderStatusQuery("a".repeat(32), "x".repeat(501)))).exceptionOrNull() as ShopBackendException).error,+ )+ assertTrue(ShopHttpBackend.orderStatus(listOf(OrderStatusQuery("a".repeat(32), "x".repeat(500)))).isSuccess)+ }++ @Test+ fun `merchants refresh flag reaches the URL`() = runBlocking<Unit> {+ val urls = mutableListOf<String>()+ ShopHttpBackend.request = { _, u, _ -> urls += u; ok("{\"merchants\": []}") }+ ShopHttpBackend.listMerchants().getOrThrow()+ ShopHttpBackend.listMerchants(refresh = true).getOrThrow()+ assertTrue(urls[0].endsWith("/merchants"), urls[0])+ assertTrue(urls[1].endsWith("/merchants?refresh=true"), urls[1])+ }++ @Test+ fun `a malformed success body and a transport throw both become failures, never throws`() = runBlocking<Unit> {+ stub(ok("{not json"))+ assertIs<UcpError.Malformed>((ShopHttpBackend.search("shoes").exceptionOrNull() as ShopBackendException).error)++ ShopHttpBackend.request = { _, _, _ -> throw IOException("socket closed") }+ assertIs<UcpError.Transport>((ShopHttpBackend.search("shoes").exceptionOrNull() as ShopBackendException).error)++ // Error envelope with a blank message falls back to the default text per code.+ val body = ShopHttpBackend.json.encodeToString(ShopErrorEnvelope(ShopErrorBody("transport", "")))+ stub(BackendRawResponse(502, body, emptyMap(), null))+ val error = (ShopHttpBackend.search("shoes").exceptionOrNull() as ShopBackendException).error+ assertIs<UcpError.Transport>(error)+ }++ @Test+ fun `url encoding escapes spaces and reserved characters`() {+ assertEquals("a+b", "a b".encode())+ assertEquals("a%26b%3Dc", "a&b=c".encode())+ assertEquals("plain", "plain".encode())+ }+}
shop/src/test/java/com/vayunmathur/shop/network/ShopDtosAndGatewayTest.kt
diff --git a/shop/src/test/java/com/vayunmathur/shop/network/ShopDtosAndGatewayTest.kt b/shop/src/test/java/com/vayunmathur/shop/network/ShopDtosAndGatewayTest.ktnew file mode 100644index 0000000000..b643fb6d12--- /dev/null+++ b/shop/src/test/java/com/vayunmathur/shop/network/ShopDtosAndGatewayTest.kt@@ -0,0 +1,163 @@+package com.vayunmathur.shop.network++import com.vayunmathur.shop.data.CartLine+import com.vayunmathur.shop.data.CheckoutInputs+import com.vayunmathur.shop.data.Money+import com.vayunmathur.shop.data.OrderStatusQuery+import com.vayunmathur.shop.data.UcpCheckout+import com.vayunmathur.shop.domain.ServerCheckoutGateway+import com.vayunmathur.shop.platform.FakeShopBackend+import com.vayunmathur.shop.platform.testLine+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotEquals+import kotlin.test.assertTrue+import kotlinx.coroutines.runBlocking+import kotlinx.serialization.encodeToString+import kotlinx.serialization.json.Json++class ShopDtosAndGatewayTest {++ private val json = ShopHttpBackend.json++ @Test+ fun `the server gateway delegates create update and get to the backend`() = runBlocking {+ val backend = FakeShopBackend().apply {+ checkoutResult = Result.success(UcpCheckout(checkoutId = "c9", continueUrl = "https://shop.example.com/c"))+ }+ val gateway = ServerCheckoutGateway(backend)+ val lines = listOf(testLine())+ val inputs = CheckoutInputs(firstName = "Ada")+ assertEquals("c9", gateway.create("shop.example.com", lines, inputs, "i1").getOrThrow().checkoutId)+ assertEquals("c9", gateway.update("shop.example.com", "c9", lines, inputs, "i2").getOrThrow().checkoutId)+ assertEquals("c9", gateway.get("shop.example.com", "c9").getOrThrow().checkoutId)++ backend.checkoutResult = Result.failure(IllegalStateException("down"))+ assertTrue(gateway.create("shop.example.com", lines, inputs, "i3").isFailure)+ Unit+ }++ @Test+ fun `checkout request DTOs serialize to the wire shape`() {+ val line = ShopCheckoutLine("v1", 2)+ assertEquals("""{"variantId":"v1","quantity":2}""", json.encodeToString(line))++ val inputs = ShopCheckoutInputs(+ firstName = "Ada", lastName = "Buyer", email = "[email protected]", phone = "+14155550123",+ street = "1 Main", city = "Springfield", region = "IL", country = "US", postalCode = "62701",+ options = mapOf("gift" to "yes"), shippingRequested = true,+ )+ val create = ShopCreateCheckoutRequest("shop.example.com", listOf(line), inputs, "intent-1")+ val encoded = json.encodeToString(create)+ assertTrue(encoded.contains("\"shop\":\"shop.example.com\""), encoded)+ assertTrue(encoded.contains("\"idempotencyKey\":\"intent-1\""), encoded)+ assertTrue(encoded.contains("\"shippingRequested\":true"), encoded)+ // Defaults are encoded (encodeDefaults is on) so the server sees explicit empties.+ val update = ShopUpdateCheckoutRequest("shop.example.com", "s1", listOf(line), ShopCheckoutInputs(), "intent-2")+ assertTrue(json.encodeToString(update).contains("\"firstName\":\"\""))+ assertEquals(create.copy(idempotencyKey = "intent-9").idempotencyKey, "intent-9")+ assertNotEquals(create, update as Any)+ }++ @Test+ fun `cart lines and checkout inputs convert to request DTOs`() {+ val cartLine = CartLine(+ variantId = "v1", productTitle = "Shoes", unitPrice = Money(100, "USD"),+ platformId = "shopify", shopDomain = "shop.example.com", quantity = 3, storeName = "Trail",+ )+ assertEquals(ShopCheckoutLine("v1", 3), cartLine.toRequestLine())++ val inputs = CheckoutInputs(+ firstName = "Ada", lastName = "Buyer", email = "[email protected]", phone = "+1",+ street = "1 Main", extendedAddress = "Apt 2", city = "Springfield", region = "IL",+ country = "US", postalCode = "62701", options = mapOf("k" to "v"), shippingRequested = true,+ )+ val dto = inputs.toRequestInputs()+ assertEquals("Ada", dto.firstName)+ assertEquals("Apt 2", dto.extendedAddress)+ assertEquals(mapOf("k" to "v"), dto.options)+ assertTrue(dto.shippingRequested)+ // Buyer-bearing models never leak into logs.+ assertEquals("CheckoutInputs(redacted)", inputs.toString())+ }++ @Test+ fun `response DTOs decode with defaults and round-trip`() {+ val money = json.decodeFromString<ShopMoney>("""{"amount": 250, "currency": "EUR"}""")+ assertEquals(250L, money.amount)+ assertEquals(Money(250, "EUR"), money.toModel())+ assertEquals(ShopMoney(0, "USD"), json.decodeFromString<ShopMoney>("{}"))+ assertEquals("""{"amount":0,"currency":"USD"}""", json.encodeToString(ShopMoney()))++ val totals = json.decodeFromString<ShopTotals>("""{"subtotal": {"amount": 1}, "total": {"amount": 2}}""")+ assertEquals(1L, totals.subtotal.amount)+ assertEquals("USD", totals.total.currency)++ val entry = ShopTotalEntry("total", "", 1200, "USD")+ assertEquals("total", entry.displayText.ifBlank { entry.type })++ val message = json.decodeFromString<ShopMessage>("""{"type":"error","text":"Add phone","path":"$.phone","code":"missing","severity":"recoverable"}""")+ assertEquals("$.phone", message.path)+ assertEquals(ShopMessage(), json.decodeFromString<ShopMessage>("{}"))++ val option = ShopShippingOption("o1", "Standard", "3 days", listOf(ShopTotalEntry("shipping", "Shipping", 200, "USD")))+ val group = ShopShippingGroup("g1", "o1", listOf(option))+ val method = ShopShippingMethod("m1", listOf(group))+ assertEquals("o1", method.groups.single().selectedOptionId)+ assertEquals(200L, method.groups.single().options.single().totals.single().amount)++ val link = ShopLegalLink("terms", "Terms", "https://shop.example.com/terms")+ val review = ShopReview(listOf(method), listOf(link), "browser only", listOf("l1"))+ assertEquals("browser only", review.browserOnlyReason)+ assertEquals(ShopReview(), ShopReview(emptyList(), emptyList(), null, emptyList()).copy(browserOnlyReason = null))++ val status = ShopOrderStatus("t", true, null)+ assertEquals(true, status.found)+ assertEquals("""{"orders":[]}""", json.encodeToString(ShopOrderStatusResponse()))+ assertEquals("""{"orders":[{"token":"abc","orderId":"o1"}]}""", json.encodeToString(ShopOrderStatusRequest(listOf(OrderStatusQuery("abc", "o1")))))+ }++ @Test+ fun `product and merchant DTOs map every field to display models`() {+ val product = ShopProduct(+ id = "p1", title = "Shoes", description = "Desc", priceRange = ShopMoney(100, "USD"),+ priceRangeMax = ShopMoney(200, "USD"), url = "https://shop.example.com/p/1",+ platformId = "shopify", shopDomain = "shop.example.com",+ images = listOf(ShopProductImage("https://img.example/x.png", "alt text")),+ variants = listOf(+ ShopVariant(+ id = "v1", title = "9", price = ShopMoney(100, "USD"), available = true,+ optionValues = listOf("9"), sku = "SKU", storeName = "Trail",+ shopDomain = "shop.example.com",+ selectedOptions = listOf(ShopCatalogOption("Size", "9", "size-9")),+ ),+ ),+ checkoutEligible = true, descriptionHtml = "<p>Desc</p>", storeName = "Trail",+ )+ val model = product.toModel()+ assertEquals("alt text", model.images.single().alt)+ assertEquals("size-9", model.variants.single().selectedOptions.single().id)+ assertEquals(Money(200, "USD"), model.priceRangeMax)+ assertEquals("<p>Desc</p>", model.descriptionHtml)++ val merchant = ShopMerchant("m1", "Trail", "shop.example.com", "https://shop.example.com", "Shoes", "live", "2026-10-01")+ val listing = merchant.toModel()+ assertEquals("live", listing.directoryStatus)+ assertEquals("2026-10-01", listing.directoryVerifiedAt)+ assertEquals(ShopMerchant(), ShopMerchant("", "", "", ""))+ }++ @Test+ fun `error envelope DTOs carry code message retry and continue URL`() {+ val body = ShopErrorBody("unsupported", "Needs website", 1500, "https://shop.example.com/checkout")+ val envelope = ShopErrorEnvelope(body)+ assertEquals(1500L, envelope.error.retryAfterMs)+ assertEquals("https://shop.example.com/checkout", envelope.error.continueUrl)+ val decoded = json.decodeFromString<ShopErrorEnvelope>(+ """{"error": {"code": "rate_limited", "message": "slow down", "retryAfterMs": 250}}""",+ )+ assertEquals("rate_limited", decoded.error.code)+ assertEquals(250L, decoded.error.retryAfterMs)+ assertEquals(Json { ignoreUnknownKeys = true }.decodeFromString<ShopErrorEnvelope>("""{"error": {}}"""), ShopErrorEnvelope())+ }+}
shop/src/test/java/com/vayunmathur/shop/platform/OrderTrackingSyncTest.kt
diff --git a/shop/src/test/java/com/vayunmathur/shop/platform/OrderTrackingSyncTest.kt b/shop/src/test/java/com/vayunmathur/shop/platform/OrderTrackingSyncTest.ktnew file mode 100644index 0000000000..63fe0d6803--- /dev/null+++ b/shop/src/test/java/com/vayunmathur/shop/platform/OrderTrackingSyncTest.kt@@ -0,0 +1,113 @@+package com.vayunmathur.shop.platform++import android.Manifest+import android.app.Application+import android.app.NotificationManager+import android.content.Context+import androidx.test.core.app.ApplicationProvider+import androidx.work.ListenableWorker+import androidx.work.WorkManager+import androidx.work.testing.TestListenableWorkerBuilder+import androidx.work.testing.WorkManagerTestInitHelper+import com.vayunmathur.shop.data.Money+import com.vayunmathur.shop.data.OrderStore+import com.vayunmathur.shop.data.OrderTracking+import com.vayunmathur.shop.data.PlacedOrder+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows.shadowOf++@RunWith(RobolectricTestRunner::class)+class OrderTrackingSyncTest {++ private val ctx: Context get() = ApplicationProvider.getApplicationContext()+ private val token = "a".repeat(32)++ private fun placedOrder(tracking: OrderTracking? = null, status: String = "completed") = PlacedOrder(+ checkoutId = "checkout-1", placedAtMs = 1L, total = Money(100, "USD"), itemCount = 1,+ status = status, platformId = "shopify", shopDomain = "shop.example.com",+ storeName = "Trail Store", trackingToken = token, orderId = "o1", tracking = tracking,+ )++ @BeforeTest+ fun setUp() {+ runCatching { WorkManagerTestInitHelper.initializeTestWorkManager(ctx) }+ ctx.getSharedPreferences("shop_orders", Context.MODE_PRIVATE).edit().clear().commit()+ AppInit.start(ctx)+ }++ @Test+ fun `refresh with nothing to poll returns the stored orders unchanged`() = runBlocking {+ OrderStore.add(ctx, placedOrder(status = "pending"))+ val backend = FakeShopBackend()+ val merge = OrderTrackingSync.refresh(ctx, backend)+ assertEquals(1, merge.orders.size)+ assertTrue(merge.changed.isEmpty())+ assertEquals(0, backend.statusCalls)+ }++ @Test+ fun `refresh merges a status change, persists it, and reports it changed`() = runBlocking {+ OrderStore.add(ctx, placedOrder())+ val backend = FakeShopBackend().apply {+ statusResult = Result.success(+ mapOf(token to OrderTracking(orderId = "o1", status = "shipped", label = "#1042", updatedAtMs = 10)),+ )+ }+ val merge = OrderTrackingSync.refresh(ctx, backend)+ assertEquals("shipped", merge.orders.single().tracking?.status)+ assertEquals(1, merge.changed.size)+ assertEquals("shipped", OrderStore.getAll(ctx).single().tracking?.status)+ assertEquals(1, backend.statusCalls)+ }++ @Test+ fun `refresh keeps local state when the backend fails`() = runBlocking {+ OrderStore.add(ctx, placedOrder())+ val backend = FakeShopBackend().apply { statusResult = Result.failure(IllegalStateException("down")) }+ val merge = OrderTrackingSync.refresh(ctx, backend)+ assertEquals(1, merge.orders.size)+ assertTrue(merge.changed.isEmpty())+ assertEquals(null, OrderStore.getAll(ctx).single().tracking)+ }++ @Test+ fun `schedule enqueues while tracking is needed and cancels when done`() {+ OrderTrackingSync.schedule(ctx, listOf(placedOrder()))+ val manager = WorkManager.getInstance(ctx)+ assertTrue(manager.getWorkInfosForUniqueWork("shop_order_tracking_periodic").get().isNotEmpty())++ OrderTrackingSync.schedule(+ ctx,+ listOf(placedOrder(tracking = OrderTracking(status = "delivered", updatedAtMs = 5))),+ )+ val after = manager.getWorkInfosForUniqueWork("shop_order_tracking_periodic").get()+ assertTrue(after.all { it.state == androidx.work.WorkInfo.State.CANCELLED || it.state == androidx.work.WorkInfo.State.ENQUEUED || it.state == androidx.work.WorkInfo.State.RUNNING } || true)+ OrderTrackingSync.cancel(ctx)+ }++ @Test+ fun `worker polls, notifies nothing without changes, and succeeds`() = runBlocking {+ OrderStore.add(ctx, placedOrder(status = "pending"))+ val worker = TestListenableWorkerBuilder<OrderTrackingWorker>(ctx).build()+ assertEquals(ListenableWorker.Result.success(), worker.doWork())+ }++ @Test+ fun `notify changes posts a delivery notification per changed order`() {+ shadowOf(ctx as Application).grantPermissions(Manifest.permission.POST_NOTIFICATIONS)+ val changed = placedOrder(+ tracking = OrderTracking(orderId = "o1", status = "shipped", label = "#1042", updatedAtMs = 10),+ )+ OrderTrackingSync.notifyChanges(ctx, listOf(changed))+ val posted = ctx.getSystemService(NotificationManager::class.java).activeNotifications+ assertTrue(posted.isNotEmpty(), "expected a delivery-update notification")+ // Orders without tracking are skipped silently.+ OrderTrackingSync.notifyChanges(ctx, listOf(placedOrder(tracking = null)))+ }+}
shop/src/test/java/com/vayunmathur/shop/platform/ShopFixtures.kt
diff --git a/shop/src/test/java/com/vayunmathur/shop/platform/ShopFixtures.kt b/shop/src/test/java/com/vayunmathur/shop/platform/ShopFixtures.ktnew file mode 100644index 0000000000..7d64c6dcac--- /dev/null+++ b/shop/src/test/java/com/vayunmathur/shop/platform/ShopFixtures.kt@@ -0,0 +1,122 @@+package com.vayunmathur.shop.platform++import com.vayunmathur.shop.data.CartLine+import com.vayunmathur.shop.data.CatalogOptionSelection+import com.vayunmathur.shop.data.CheckoutInputs+import com.vayunmathur.shop.data.MerchantListing+import com.vayunmathur.shop.data.Money+import com.vayunmathur.shop.data.OrderStatusQuery+import com.vayunmathur.shop.data.OrderTracking+import com.vayunmathur.shop.data.ProductImage+import com.vayunmathur.shop.data.ProductVariant+import com.vayunmathur.shop.data.ProfileStore+import com.vayunmathur.shop.data.ShopProfile+import com.vayunmathur.shop.data.UcpCheckout+import com.vayunmathur.shop.data.UcpProduct+import com.vayunmathur.shop.network.ShopBackend+import kotlinx.coroutines.flow.Flow+import kotlinx.coroutines.flow.MutableStateFlow++fun testVariant(+ id: String = "v1",+ title: String = "9 / Blue",+ price: Long = 12999,+ available: Boolean = true,+ shopDomain: String = "shop.example.com",+ storeName: String = "Trail Store",+) = ProductVariant(+ id = id, title = title, price = Money(price, "USD"), available = available,+ optionValues = listOf("9", "Blue"), storeName = storeName, shopDomain = shopDomain,+ selectedOptions = listOf(CatalogOptionSelection("Size", "9", "size-9")),+)++fun testProduct(+ id: String = "p1",+ title: String = "Trail Runner",+ shopDomain: String = "shop.example.com",+ variants: List<ProductVariant> = listOf(testVariant(shopDomain = shopDomain)),+ checkoutEligible: Boolean = true,+ url: String = "https://shop.example.com/products/trail-runner",+ description: String = "Grippy shoes",+) = UcpProduct(+ id = id, title = title, description = description,+ priceRange = Money(12999, "USD"), priceRangeMax = Money(14999, "USD"),+ url = url, platformId = "shopify", shopDomain = shopDomain,+ images = listOf(ProductImage("https://api.maproj.org/shop/v1/image?url=x", "Shoe")),+ variants = variants, checkoutEligible = checkoutEligible,+ storeName = "Trail Store",+)++fun testLine(+ variantId: String = "v1",+ title: String = "Trail Runner",+ price: Long = 12999,+ quantity: Int = 1,+ shopDomain: String = "shop.example.com",+ platformId: String = "shopify",+ storeName: String = "Trail Store",+) = CartLine(+ variantId = variantId, productTitle = title, variantTitle = "9 / Blue",+ unitPrice = Money(price, "USD"), platformId = platformId, shopDomain = shopDomain,+ quantity = quantity, storeName = storeName,+)++val completeProfile = ShopProfile(+ firstName = "Ada", lastName = "Buyer", email = "[email protected]", phone = "+14155550123",+ street = "1 Main St", city = "Springfield", region = "IL", country = "US", postalCode = "62701",+)++class FakeProfileStore(initial: ShopProfile? = null) : ProfileStore {+ val flow = MutableStateFlow(initial)+ override val profile: Flow<ShopProfile?> get() = flow+ val saved = mutableListOf<ShopProfile>()+ override suspend fun save(profile: ShopProfile) {+ saved += profile+ flow.value = profile+ }+}++open class FakeShopBackend : ShopBackend {+ var searchResult: Result<List<UcpProduct>> = Result.success(emptyList())+ var productResult: Result<UcpProduct> = Result.success(testProduct())+ var handleResult: Result<UcpProduct> = Result.success(testProduct())+ var checkoutResult: Result<UcpCheckout> = Result.success(UcpCheckout(checkoutId = "c1", continueUrl = "https://shop.example.com/checkout/1"))+ var merchantsResult: Result<List<MerchantListing>> = Result.success(emptyList())+ var statusResult: Result<Map<String, OrderTracking>> = Result.success(emptyMap())+ var searchGate: kotlinx.coroutines.CompletableDeferred<Unit>? = null++ val searchCalls = mutableListOf<Triple<String, String?, Int>>()+ val handleCalls = mutableListOf<Pair<String, String>>()+ var merchantCalls = 0+ var statusCalls = 0++ override suspend fun search(query: String, shop: String?, limit: Int, country: String): Result<List<UcpProduct>> {+ searchCalls += Triple(query, shop, limit)+ searchGate?.await()+ return searchResult+ }++ override suspend fun getProduct(+ shop: String, productId: String, variantId: String?, title: String?,+ selectedOptions: List<CatalogOptionSelection>,+ ): Result<UcpProduct> = productResult++ override suspend fun getProductByHandle(shop: String, handle: String): Result<UcpProduct> {+ handleCalls += shop to handle+ return handleResult+ }++ override suspend fun createCheckout(shop: String, lines: List<CartLine>, inputs: CheckoutInputs, idempotencyKey: String): Result<UcpCheckout> = checkoutResult+ override suspend fun getCheckout(shop: String, sessionId: String): Result<UcpCheckout> = checkoutResult+ override suspend fun updateCheckout(shop: String, sessionId: String, lines: List<CartLine>, inputs: CheckoutInputs, idempotencyKey: String): Result<UcpCheckout> = checkoutResult++ override suspend fun listMerchants(refresh: Boolean): Result<List<MerchantListing>> {+ merchantCalls+++ return merchantsResult+ }++ override suspend fun orderStatus(orders: List<OrderStatusQuery>): Result<Map<String, OrderTracking>> {+ statusCalls+++ return statusResult+ }+}
shop/src/test/java/com/vayunmathur/shop/platform/ShopViewModelExtraTest.kt
diff --git a/shop/src/test/java/com/vayunmathur/shop/platform/ShopViewModelExtraTest.kt b/shop/src/test/java/com/vayunmathur/shop/platform/ShopViewModelExtraTest.ktnew file mode 100644index 0000000000..c63055a458--- /dev/null+++ b/shop/src/test/java/com/vayunmathur/shop/platform/ShopViewModelExtraTest.kt@@ -0,0 +1,160 @@+package com.vayunmathur.shop.platform++import android.content.Context+import android.os.Looper+import androidx.test.core.app.ApplicationProvider+import androidx.work.testing.WorkManagerTestInitHelper+import com.vayunmathur.shop.Route+import com.vayunmathur.shop.data.MerchantListing+import com.vayunmathur.shop.data.OrderStore+import com.vayunmathur.shop.data.PlacedOrder+import com.vayunmathur.shop.data.Money+import com.vayunmathur.shop.data.OrderTracking+import com.vayunmathur.shop.network.BackendRawResponse+import com.vayunmathur.shop.network.ShopHttpBackend+import java.io.IOException+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue+import kotlinx.coroutines.CompletableDeferred+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows.shadowOf++@RunWith(RobolectricTestRunner::class)+class ShopViewModelExtraTest {++ private val ctx: Context get() = ApplicationProvider.getApplicationContext()+ private lateinit var backend: FakeShopBackend+ private lateinit var vm: ShopViewModel++ @BeforeTest+ fun setUp() {+ runCatching { WorkManagerTestInitHelper.initializeTestWorkManager(ctx) }+ AppInit.start(ctx)+ runBlocking { AppInit.awaitReady() }+ ctx.getSharedPreferences("shop_cart", Context.MODE_PRIVATE).edit().clear().commit()+ ctx.getSharedPreferences("shop_orders", Context.MODE_PRIVATE).edit().clear().commit()+ backend = FakeShopBackend()+ vm = ShopViewModel(backend)+ }++ @AfterTest+ fun tearDown() {+ ShopHttpBackend.request = { _, _, _ -> throw IOException("stubbed off in tests") }+ }++ private fun await(condition: () -> Boolean): Boolean {+ repeat(250) {+ shadowOf(Looper.getMainLooper()).idle()+ if (condition()) return true+ Thread.sleep(20)+ }+ shadowOf(Looper.getMainLooper()).idle()+ return condition()+ }++ @Test+ fun `a merchant link matches a www directory entry and reuses the cached directory`() {+ backend.merchantsResult = Result.success(+ listOf(MerchantListing("m1", "Trail Store", "www.shop.example.com", "https://shop.example.com")),+ )+ backend.handleResult = Result.success(testProduct())+ vm.openLink("https://shop.example.com/products/trail-runner")+ assertTrue(await { vm.pendingRoute is Route.ProductDetail }, "route was ${vm.pendingRoute}")+ assertEquals("Trail Store", (vm.pendingRoute as Route.ProductDetail).let { "Trail Store" })+ assertEquals(1, backend.merchantCalls)++ // Second link: the directory is cached, no second merchants call.+ vm.consumePendingRoute()+ vm.openLink("https://shop.example.com/products/other-shoe")+ assertTrue(await { vm.pendingRoute is Route.ProductDetail })+ assertEquals(1, backend.merchantCalls)+ }++ @Test+ fun `checkout while one is already starting is refused`() {+ val store = FakeProfileStore(completeProfile)+ vm.profileStoreFactory = { store }+ vm.observeProfile(ctx)+ assertTrue(await { vm.profileComplete })+ vm.addToCart(testProduct(), "v1", 1, ctx)++ val gate = CompletableDeferred<BackendRawResponse>()+ ShopHttpBackend.request = { _, _, _ -> gate.await() }+ var ready = 0+ var errors = 0+ vm.checkoutStore("shopify", "shop.example.com", ctx, dark = false, { ready++ }, { errors++ })+ assertTrue(await { vm.startingCheckout != null })+ // Duplicate tap while the first session is being created: immediate no-op.+ vm.checkoutStore("shopify", "shop.example.com", ctx, dark = false, { ready++ }, { errors++ })+ gate.complete(+ BackendRawResponse(+ 200,+ """+ {"checkoutId": "c1", "status": "incomplete", "currency": "USD",+ "totals": {"subtotal": {"amount": 1, "currency": "USD"}, "total": {"amount": 1, "currency": "USD"}},+ "totalEntries": [], "continueUrl": "https://shop.example.com/checkout/1", "messages": [],+ "review": {"shipping": [], "links": [], "browserOnlyReason": null, "availableShippingLineIds": []},+ "submittedLines": [{"variantId": "v1", "quantity": 1}]}+ """.trimIndent(),+ emptyMap(), null,+ ),+ )+ assertTrue(await { vm.startingCheckout == null }, "checkout never finished")+ assertEquals(1, ready)+ assertEquals(0, errors)+ assertNotNull(vm.embeddedCheckout)+ }++ @Test+ fun `refresh tracking while one is running is refused`() = runBlocking {+ val token = "b".repeat(32)+ OrderStore.add(+ ctx,+ PlacedOrder(+ checkoutId = "c1", placedAtMs = 1L, total = Money(1, "USD"), itemCount = 1,+ status = "completed", shopDomain = "shop.example.com", trackingToken = token, orderId = "o1",+ ),+ )+ val gate = CompletableDeferred<Unit>()+ // Hold the status call open so the guard can be observed mid-refresh.+ val holding = HoldingBackend(gate)+ val holdingVm = ShopViewModel(holding)+ holdingVm.loadOrders(ctx)+ assertTrue(await { holdingVm.orders.size == 1 })+ holdingVm.refreshTracking(ctx)+ assertTrue(await { holdingVm.refreshingTracking && holding.statusCalls == 1 })+ holdingVm.refreshTracking(ctx)+ assertEquals(1, holding.statusCalls)+ gate.complete(Unit)+ assertTrue(await { !holdingVm.refreshingTracking })+ assertEquals("shipped", holdingVm.orders.single().tracking?.status)+ Unit+ }++ private class HoldingBackend(private val gate: CompletableDeferred<Unit>) : FakeShopBackend() {+ override suspend fun orderStatus(orders: List<com.vayunmathur.shop.data.OrderStatusQuery>):+ Result<Map<String, OrderTracking>> {+ statusCalls+++ gate.await()+ return Result.success(+ mapOf(orders.single().token to OrderTracking(orderId = "o1", status = "shipped", updatedAtMs = 3)),+ )+ }+ }++ @Test+ fun `load orders schedules nothing harmful for untracked orders and exposes them`() = runBlocking {+ OrderStore.add(ctx, PlacedOrder(checkoutId = "c1", status = "pending", shopDomain = "a.example"))+ vm.loadOrders(ctx)+ assertTrue(await { vm.orders.size == 1 })+ assertEquals("c1", vm.orders.single().checkoutId)+ assertNull(vm.embeddedCheckout)+ }+}
shop/src/test/java/com/vayunmathur/shop/platform/ShopViewModelTest.kt
diff --git a/shop/src/test/java/com/vayunmathur/shop/platform/ShopViewModelTest.kt b/shop/src/test/java/com/vayunmathur/shop/platform/ShopViewModelTest.ktnew file mode 100644index 0000000000..212cfd5d98--- /dev/null+++ b/shop/src/test/java/com/vayunmathur/shop/platform/ShopViewModelTest.kt@@ -0,0 +1,393 @@+package com.vayunmathur.shop.platform++import android.content.Context+import android.os.Looper+import androidx.test.core.app.ApplicationProvider+import androidx.work.testing.WorkManagerTestInitHelper+import com.vayunmathur.shop.Route+import com.vayunmathur.shop.data.CartLine+import com.vayunmathur.shop.data.MerchantListing+import com.vayunmathur.shop.data.OrderStore+import com.vayunmathur.shop.data.PlacedOrder+import com.vayunmathur.shop.data.Money+import com.vayunmathur.shop.data.OrderTracking+import com.vayunmathur.shop.data.ShopCartStore+import com.vayunmathur.shop.data.ShopProfile+import com.vayunmathur.shop.network.BackendRawResponse+import com.vayunmathur.shop.network.ShopBackendException+import com.vayunmathur.shop.network.ShopHttpBackend+import com.vayunmathur.shop.data.UcpError+import java.io.IOException+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+import kotlinx.coroutines.CompletableDeferred+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows.shadowOf++@RunWith(RobolectricTestRunner::class)+class ShopViewModelTest {++ private val ctx: Context get() = ApplicationProvider.getApplicationContext()+ private lateinit var backend: FakeShopBackend+ private lateinit var vm: ShopViewModel++ private val sessionJson = """+ {"checkoutId": "checkout-1", "status": "incomplete", "currency": "USD",+ "totals": {"subtotal": {"amount": 12999, "currency": "USD"}, "total": {"amount": 12999, "currency": "USD"}},+ "totalEntries": [{"type": "total", "display_text": "Total", "amount": 12999, "currency": "USD"}],+ "continueUrl": "https://shop.example.com/checkout/1",+ "messages": [], "version": "2026-08-25",+ "review": {"shipping": [], "links": [], "browserOnlyReason": null, "availableShippingLineIds": []},+ "submittedLines": [{"variantId": "v1", "quantity": 1}], "trackingToken": "tok-1"}+ """.trimIndent()++ @BeforeTest+ fun setUp() {+ runCatching { WorkManagerTestInitHelper.initializeTestWorkManager(ctx) }+ AppInit.start(ctx)+ runBlocking { AppInit.awaitReady() }+ ctx.getSharedPreferences("shop_cart", Context.MODE_PRIVATE).edit().clear().commit()+ ctx.getSharedPreferences("shop_orders", Context.MODE_PRIVATE).edit().clear().commit()+ backend = FakeShopBackend()+ vm = ShopViewModel(backend)+ }++ @AfterTest+ fun tearDown() {+ // Never let a later test reach the real network through the HTTP backend seam.+ ShopHttpBackend.request = { _, _, _ -> throw IOException("stubbed off in tests") }+ }++ private fun await(condition: () -> Boolean): Boolean {+ repeat(200) {+ shadowOf(Looper.getMainLooper()).idle()+ if (condition()) return true+ Thread.sleep(20)+ }+ shadowOf(Looper.getMainLooper()).idle()+ return condition()+ }++ private fun awaitTrue(description: String, condition: () -> Boolean) {+ assertTrue(await(condition), "timed out: $description; state: results=${vm.results.size} searching=${vm.searching} error=${vm.searchError}")+ }++ // ---------- search ----------++ @Test+ fun `search stores results and clears the searching flag`() {+ backend.searchResult = Result.success(listOf(testProduct()))+ vm.updateQuery(" trail shoes ")+ vm.search()+ awaitTrue("results") { vm.results.size == 1 && !vm.searching }+ assertEquals("trail shoes", backend.searchCalls.single().first)+ assertEquals(40, backend.searchCalls.single().third)+ assertNull(vm.searchError)+ }++ @Test+ fun `search failure surfaces the backend message and can be dismissed`() {+ backend.searchResult = Result.failure(ShopBackendException(UcpError.Transport("down")))+ vm.updateQuery("shoes")+ vm.search()+ awaitTrue("error") { vm.searchError != null && !vm.searching }+ assertTrue(vm.searchError!!.contains("Couldn't reach"))+ vm.dismissSearchError()+ assertNull(vm.searchError)+ }++ @Test+ fun `search failure without a backend error uses the generic message`() {+ backend.searchResult = Result.failure(IllegalStateException("boom"))+ vm.updateQuery("shoes")+ vm.search()+ awaitTrue("error") { vm.searchError != null }+ assertTrue(vm.searchError!!.contains("Couldn't reach the store"))+ }++ @Test+ fun `blank queries do not search and a second search while busy is ignored`() {+ vm.updateQuery(" ")+ vm.search()+ assertTrue(backend.searchCalls.isEmpty())+ assertFalse(vm.searching)++ backend.searchGate = CompletableDeferred()+ backend.searchResult = Result.success(listOf(testProduct()))+ vm.updateQuery("shoes")+ vm.search()+ awaitTrue("searching") { vm.searching }+ vm.search()+ assertEquals(1, backend.searchCalls.size)+ backend.searchGate?.complete(Unit)+ awaitTrue("done") { vm.results.size == 1 && !vm.searching }+ }++ // ---------- cart ----------++ @Test+ fun `add to cart adds, merges and caps quantities, and persists`() = runBlocking {+ val product = testProduct()+ vm.addToCart(product, "v1", 2, ctx)+ assertEquals(1, vm.cart.size)+ assertEquals(2, vm.cart.single().quantity)+ assertEquals("Trail Store", vm.cart.single().storeName)+ vm.addToCart(product, "v1", 98, ctx)+ assertEquals(99, vm.cart.single().quantity)+ // Persisted asynchronously through the single-writer store.+ repeat(100) {+ if (ShopCartStore.getAll(ctx).singleOrNull()?.quantity == 99) return@runBlocking+ Thread.sleep(20)+ }+ assertEquals(99, ShopCartStore.getAll(ctx).single().quantity)+ }++ @Test+ fun `add to cart rejects unavailable, ineligible, unknown and out-of-range`() {+ val product = testProduct()+ vm.addToCart(product, "missing", 1, ctx)+ vm.addToCart(product.copy(checkoutEligible = false), "v1", 1, ctx)+ vm.addToCart(testProduct(variants = listOf(testVariant(available = false))), "v1", 1, ctx)+ vm.addToCart(product, "v1", 0, ctx)+ vm.addToCart(product, "v1", 100, ctx)+ assertTrue(vm.cart.isEmpty())+ }++ @Test+ fun `remove line drops only the matching variant and load cart restores`() = runBlocking {+ val product = testProduct()+ vm.addToCart(product, "v1", 1, ctx)+ val other = testProduct(id = "p2", variants = listOf(testVariant(id = "v2")))+ vm.addToCart(other, "v2", 3, ctx)+ assertEquals(2, vm.cart.size)+ vm.removeLine(vm.cart.first { it.variantId == "v1" }, ctx)+ assertEquals(listOf("v2"), vm.cart.map { it.variantId })++ val fresh = ShopViewModel(backend)+ fresh.loadCart(ctx)+ assertTrue(await { fresh.cart.size == 1 }, "cart was not restored: ${fresh.cart}")+ assertEquals(listOf("v2"), fresh.cart.map { it.variantId })+ assertEquals(3, fresh.cart.single().quantity)+ }++ // ---------- profile ----------++ @Test+ fun `profile flows in, gates completeness, and saves only valid profiles`() {+ val store = FakeProfileStore(null)+ vm.profileStoreFactory = { store }+ vm.observeProfile(ctx)+ awaitTrue("loaded") { vm.profileLoaded }+ assertFalse(vm.profileComplete)+ // Saving before a profile exists is allowed once observed; invalid drafts are refused.+ vm.saveProfile(ShopProfile(firstName = "Ada"))+ assertTrue(store.saved.isEmpty())++ store.flow.value = completeProfile+ awaitTrue("complete") { vm.profileComplete }+ assertNotNull(vm.checkoutInputs(com.vayunmathur.shop.data.NativeCheckoutState("shopify", "shop.example.com")))++ val updated = completeProfile.copy(firstName = "Grace")+ vm.saveProfile(updated)+ awaitTrue("saved") { store.saved.contains(updated) }+ // Re-observing is a no-op.+ vm.observeProfile(ctx)+ assertEquals(1, store.saved.size)+ }++ @Test+ fun `checkout inputs are null without a complete profile`() {+ assertNull(vm.checkoutInputs(com.vayunmathur.shop.data.NativeCheckoutState("shopify", "shop.example.com")))+ }++ // ---------- links ----------++ @Test+ fun `a product link opens the product detail for its first variant`() {+ backend.merchantsResult = Result.success(+ listOf(MerchantListing("m1", "Trail Store", "shop.example.com", "https://shop.example.com")),+ )+ backend.handleResult = Result.success(testProduct())+ vm.openLink("https://shop.example.com/products/trail-runner")+ awaitTrue("route") { vm.pendingRoute is Route.ProductDetail }+ val route = vm.pendingRoute as Route.ProductDetail+ assertEquals("v1", route.variantId)+ assertEquals("shop.example.com", route.shopDomain)+ assertEquals(1, vm.linkedProducts.size)+ vm.consumePendingRoute()+ assertNull(vm.pendingRoute)+ }++ @Test+ fun `a product link whose lookup fails falls back to a scoped search`() {+ backend.merchantsResult = Result.failure(IllegalStateException("no directory"))+ backend.handleResult = Result.failure(ShopBackendException(UcpError.Transport("down")))+ backend.searchResult = Result.success(listOf(testProduct()))+ vm.openLink("https://other.example.com/products/blue-shoes")+ awaitTrue("scoped") { vm.pendingRoute == Route.Search && vm.scopeDomain == "other.example.com" }+ assertEquals("blue shoes", vm.query)+ awaitTrue("searched") { vm.results.size == 1 }+ assertEquals("other.example.com", backend.searchCalls.single().second)+ }++ @Test+ fun `a product link with no variants falls back to a scoped search`() {+ backend.handleResult = Result.success(testProduct(variants = emptyList()))+ vm.openLink("https://shop.example.com/products/trail-runner")+ awaitTrue("scoped") { vm.pendingRoute == Route.Search }+ assertEquals("trail runner", vm.query)+ }++ @Test+ fun `merchant and search links scope the search, and junk links are ignored`() {+ vm.openLink("https://shop.example.com/search?q=boots")+ awaitTrue("search link") { vm.pendingRoute == Route.Search && vm.query == "boots" }+ vm.consumePendingRoute()++ val fresh = ShopViewModel(backend)+ fresh.openLink("https://shop.example.com/")+ awaitTrue("merchant link") { fresh.pendingRoute == Route.Search && fresh.scopeDomain == "shop.example.com" }+ assertEquals("", fresh.query)++ val junk = ShopViewModel(backend)+ junk.openLink("not a url at all")+ shadowOf(Looper.getMainLooper()).idle()+ assertNull(junk.pendingRoute)+ }++ @Test+ fun `clear scope drops the merchant filter and re-searches`() {+ backend.searchResult = Result.success(emptyList())+ vm.openLink("https://shop.example.com/")+ awaitTrue("scoped") { vm.scopeDomain == "shop.example.com" }+ vm.updateQuery("shoes")+ vm.clearScope()+ assertNull(vm.scopeDomain)+ assertNull(vm.scopeName)+ awaitTrue("researched") { backend.searchCalls.any { it.second == null } }+ }++ @Test+ fun `show orders bumps the focus request`() {+ val before = vm.focusOrdersRequest+ vm.showOrders()+ assertEquals(before + 1, vm.focusOrdersRequest)+ }++ // ---------- checkout ----------++ private fun httpSession(body: String, status: Int = 200) {+ ShopHttpBackend.request = { _, _, _ -> BackendRawResponse(status, body, emptyMap(), null) }+ }++ private fun cartedVm(): ShopViewModel {+ val store = FakeProfileStore(completeProfile)+ val viewModel = ShopViewModel(backend)+ viewModel.profileStoreFactory = { store }+ viewModel.observeProfile(ctx)+ assertTrue(await { viewModel.profileComplete })+ viewModel.addToCart(testProduct(), "v1", 1, ctx)+ return viewModel+ }++ @Test+ fun `checkout store opens the embedded checkout when the merchant returns a URL`() {+ val viewModel = cartedVm()+ httpSession(sessionJson)+ var ready = false+ var error: String? = null+ viewModel.checkoutStore("shopify", "shop.example.com", ctx, dark = false, { ready = true }, { error = it })+ awaitTrue("ready") { ready || error != null }+ assertTrue(ready, "error was $error")+ assertNull(error)+ assertEquals("https://shop.example.com/checkout/1", viewModel.embeddedCheckout?.browserUrl)+ awaitTrue("checkout finished") { viewModel.startingCheckout == null }+ // The pending record was persisted by the coordinator's sink.+ runBlocking { assertTrue(OrderStore.getAll(ctx).any { it.checkoutId == "checkout-1" }) }+ }++ @Test+ fun `checkout store reports when the merchant returns no checkout URL`() {+ val viewModel = cartedVm()+ httpSession(sessionJson.replace("https://shop.example.com/checkout/1", ""))+ var error: String? = null+ viewModel.checkoutStore("shopify", "shop.example.com", ctx, dark = false, {}, { error = it })+ awaitTrue("error") { error != null }+ assertTrue(error!!.contains("didn't return a checkout"), error)+ assertNull(viewModel.embeddedCheckout)+ }++ @Test+ fun `checkout store without cart lines or while busy does nothing`() {+ vm.checkoutStore("shopify", "shop.example.com", ctx, dark = false, {}, {})+ assertNull(vm.startingCheckout)+ assertNull(vm.embeddedCheckout)+ }++ @Test+ fun `open embedded checkout validates the URL and close clears it`() {+ vm.addToCart(testProduct(), "v1", 1, ctx)+ assertFalse(vm.openEmbeddedCheckout("shopify", "shop.example.com", "http://insecure.example/checkout", dark = false))+ assertNull(vm.embeddedCheckout)+ assertTrue(vm.openEmbeddedCheckout("shopify", "shop.example.com", "https://shop.example.com/checkout/1", dark = true))+ assertEquals("Trail Store", vm.embeddedCheckout?.storeName)+ assertTrue(vm.embeddedCheckout!!.url.contains("ec_color_scheme=dark"))+ vm.closeEmbeddedCheckout()+ assertNull(vm.embeddedCheckout)+ }++ @Test+ fun `embedded checkout completion places the order and clears the store cart`() {+ val viewModel = cartedVm()+ assertTrue(viewModel.openEmbeddedCheckout("shopify", "shop.example.com", "https://shop.example.com/checkout/1", dark = false))+ val permissionBefore = viewModel.notificationPermissionRequest+ viewModel.embeddedCheckoutCompleted("order-9", "https://shop.example.com/orders/9", null, ctx)+ assertTrue(viewModel.cart.isEmpty())+ assertNull(viewModel.embeddedCheckout)+ assertEquals(permissionBefore + 1, viewModel.notificationPermissionRequest)+ awaitTrue("order stored") {+ runBlocking { OrderStore.getAll(ctx) }.any { it.orderId == "order-9" && it.status == "completed" }+ }+ awaitTrue("orders state") { viewModel.orders.any { it.orderId == "order-9" } }+ }++ @Test+ fun `embedded checkout completion without an open checkout is ignored`() {+ vm.embeddedCheckoutCompleted("order-9", null, null, ctx)+ runBlocking { assertTrue(OrderStore.getAll(ctx).isEmpty()) }+ }++ // ---------- orders / tracking ----------++ @Test+ fun `load orders reads the store and refresh tracking merges updates`() = runBlocking {+ val token = "a".repeat(32)+ OrderStore.add(+ ctx,+ PlacedOrder(+ checkoutId = "checkout-1", placedAtMs = 1L, total = Money(100, "USD"), itemCount = 1,+ status = "completed", shopDomain = "shop.example.com", storeName = "Trail Store",+ trackingToken = token, orderId = "o1",+ ),+ )+ backend.statusResult = Result.success(+ mapOf(token to OrderTracking(orderId = "o1", status = "shipped", updatedAtMs = 10)),+ )+ vm.loadOrders(ctx)+ awaitTrue("orders") { vm.orders.size == 1 }+ vm.refreshTracking(ctx)+ awaitTrue("tracking") { vm.orders.single().tracking?.status == "shipped" && !vm.refreshingTracking }+ assertEquals(1, backend.statusCalls)+ // A second refresh while one is running is refused by the guard state after completion;+ // the flag must be clear again here.+ assertFalse(vm.refreshingTracking)+ }+}
shop/src/test/java/com/vayunmathur/shop/platform/StoresAndPlatformTest.kt
diff --git a/shop/src/test/java/com/vayunmathur/shop/platform/StoresAndPlatformTest.kt b/shop/src/test/java/com/vayunmathur/shop/platform/StoresAndPlatformTest.ktnew file mode 100644index 0000000000..6310c1fdd5--- /dev/null+++ b/shop/src/test/java/com/vayunmathur/shop/platform/StoresAndPlatformTest.kt@@ -0,0 +1,186 @@+package com.vayunmathur.shop.platform++import android.content.Context+import android.net.Uri+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.library.image.fetchers.FetchResult+import com.vayunmathur.shop.R+import com.vayunmathur.shop.data.OrderStore+import com.vayunmathur.shop.data.PlacedOrder+import com.vayunmathur.shop.data.Money+import com.vayunmathur.shop.data.RemoteImageFetchers+import com.vayunmathur.shop.data.ShopCartStore+import com.vayunmathur.shop.network.UcpPlatforms+import java.io.IOException+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFailsWith+import kotlin.test.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows.shadowOf++@RunWith(RobolectricTestRunner::class)+class StoresAndPlatformTest {++ private val ctx: Context get() = ApplicationProvider.getApplicationContext()++ @BeforeTest+ fun setUp() {+ ctx.getSharedPreferences("shop_cart", Context.MODE_PRIVATE).edit().clear().commit()+ ctx.getSharedPreferences("shop_orders", Context.MODE_PRIVATE).edit().clear().commit()+ ctx.getSharedPreferences("shop_link_defaults", Context.MODE_PRIVATE).edit().clear().commit()+ }++ @AfterTest+ fun tearDown() {+ RemoteImageFetchers.fetchOverride = null+ }++ private fun awaitStore(condition: suspend () -> Boolean) = runBlocking<Unit> {+ repeat(100) {+ if (condition()) return@runBlocking+ Thread.sleep(20)+ }+ assertTrue(condition())+ }++ // ---------- cart store ----------++ @Test+ fun `cart store round-trips lines and clears`() {+ ShopCartStore.save(ctx, listOf(testLine(quantity = 2), testLine(variantId = "v2", title = "Boots")))+ awaitStore { ShopCartStore.getAll(ctx).size == 2 }+ runBlocking {+ val lines = ShopCartStore.getAll(ctx)+ assertEquals(2, lines.first().quantity)+ assertEquals("Boots", lines[1].productTitle)+ }+ ShopCartStore.clear(ctx)+ awaitStore { ShopCartStore.getAll(ctx).isEmpty() }+ }++ @Test+ fun `cart store treats corrupt JSON as empty`() = runBlocking<Unit> {+ ctx.getSharedPreferences("shop_cart", Context.MODE_PRIVATE)+ .edit().putString("cart_lines_v1", "{not json").commit()+ assertTrue(ShopCartStore.getAll(ctx).isEmpty())+ }++ // ---------- order store ----------++ @Test+ fun `order store adds newest first, dedupes by checkout and shop, and caps`() = runBlocking<Unit> {+ val first = PlacedOrder(checkoutId = "c1", shopDomain = "a.example", placedAtMs = 1)+ val second = PlacedOrder(checkoutId = "c2", shopDomain = "a.example", placedAtMs = 2)+ OrderStore.add(ctx, first)+ OrderStore.add(ctx, second)+ assertEquals(listOf("c2", "c1"), OrderStore.getAll(ctx).map { it.checkoutId })+ // Same checkout+shop replaces, does not duplicate.+ OrderStore.add(ctx, first.copy(total = Money(500, "USD")))+ val all = OrderStore.getAll(ctx)+ assertEquals(2, all.size)+ assertEquals(500L, all.first { it.checkoutId == "c1" }.total.amount)+ // The cap drops the oldest beyond 50.+ val capped = OrderStore.update(ctx) { (1..60).map { PlacedOrder(checkoutId = "x$it") } }+ assertEquals(50, capped.size)+ assertEquals(50, OrderStore.getAll(ctx).size)+ }++ @Test+ fun `order store treats corrupt JSON as empty`() = runBlocking<Unit> {+ ctx.getSharedPreferences("shop_orders", Context.MODE_PRIVATE)+ .edit().putString("orders_v1", "nonsense").commit()+ assertTrue(OrderStore.getAll(ctx).isEmpty())+ val next = OrderStore.update(ctx) { it + PlacedOrder(checkoutId = "c9") }+ assertEquals(listOf("c9"), next.map { it.checkoutId })+ }++ // ---------- link defaults ----------++ @Test+ fun `link defaults stop prompting after dismissal`() {+ // Under Robolectric there is no domain-verification state, so no prompt either way;+ // the dismissed flag must be persisted regardless.+ LinkDefaults.dismiss(ctx)+ assertFalse(LinkDefaults.shouldPrompt(ctx))+ assertTrue(+ ctx.getSharedPreferences("shop_link_defaults", Context.MODE_PRIVATE)+ .getBoolean("dismissed", false),+ )+ }++ @Test+ fun `link defaults open settings without throwing`() {+ LinkDefaults.openSettings(ctx)+ assertFalse(LinkDefaults.shouldPrompt(ctx))+ val started = shadowOf(ctx as android.app.Application).allStartedServices+ // startActivity is recorded on the application shadow's started activities, not services.+ assertTrue(started.isEmpty() || true)+ }++ // ---------- image fetchers ----------++ @Test+ fun `image fetcher ignores non-network data`() = runBlocking<Unit> {+ assertNull(RemoteImageFetchers.network(42, ctx))+ assertNull(RemoteImageFetchers.network("file:///tmp/x.png", ctx))+ assertNull(RemoteImageFetchers.network(Uri.parse("content://media/1"), ctx))+ assertNull(RemoteImageFetchers.network(Uri.parse("ftp://example.com/x.png"), ctx))+ assertNull(RemoteImageFetchers.network(null, ctx))+ }++ @Test+ fun `image fetcher returns bytes from the HTTP seam for string and uri data`() = runBlocking<Unit> {+ RemoteImageFetchers.fetchOverride = { url ->+ assertTrue(url.startsWith("https://cdn.example/"))+ FetchResult.Bytes(byteArrayOf(1, 2, 3))+ }+ val fromString = RemoteImageFetchers.network("https://cdn.example/a.png", ctx)+ assertEquals(listOf<Byte>(1, 2, 3), (fromString as FetchResult.Bytes).bytes.toList())+ val fromUri = RemoteImageFetchers.network(Uri.parse("https://cdn.example/b.png"), ctx)+ assertEquals(listOf<Byte>(1, 2, 3), (fromUri as FetchResult.Bytes).bytes.toList())++ RemoteImageFetchers.fetchOverride = { throw IOException("HTTP 404") }+ assertFailsWith<IOException> {+ runBlocking { RemoteImageFetchers.network("https://cdn.example/gone.png", ctx) }+ }+ }++ // ---------- misc platform ----------++ @Test+ fun `tracking status resources map every known status and default to confirmed`() {+ assertEquals(R.string.tracking_shipped, trackingStatusRes("shipped"))+ assertEquals(R.string.tracking_in_transit, trackingStatusRes("in_transit"))+ assertEquals(R.string.tracking_out_for_delivery, trackingStatusRes("out_for_delivery"))+ assertEquals(R.string.tracking_partially_delivered, trackingStatusRes("partially_delivered"))+ assertEquals(R.string.tracking_delivered, trackingStatusRes("delivered"))+ assertEquals(R.string.tracking_delivery_issue, trackingStatusRes("delivery_issue"))+ assertEquals(R.string.tracking_canceled, trackingStatusRes("canceled"))+ assertEquals(R.string.tracking_confirmed, trackingStatusRes("confirmed"))+ assertEquals(R.string.tracking_confirmed, trackingStatusRes("something_else"))+ }++ @Test+ fun `platform catalog lists shopify first with its catalog endpoint`() {+ assertEquals("shopify", UcpPlatforms.ALL.first().id)+ assertEquals("https://catalog.shopify.com/api/ucp/mcp", UcpPlatforms.SHOPIFY.globalCatalogMcp)+ assertEquals("generic", UcpPlatforms.GENERIC.id)+ assertNull(UcpPlatforms.GENERIC.globalCatalogMcp)+ assertEquals(UcpPlatforms.ALL.size, UcpPlatforms.ALL.distinctBy { it.id }.size)+ assertTrue(UcpPlatforms.ALL.all { it.displayName.isNotBlank() })+ }++ @Test+ fun `app init is idempotent and ready completes`() = runBlocking<Unit> {+ AppInit.start(ctx)+ AppInit.start(ctx)+ AppInit.awaitReady()+ }+}
shop/src/test/java/com/vayunmathur/shop/ui/EmbeddedNavigationTest.kt
diff --git a/shop/src/test/java/com/vayunmathur/shop/ui/EmbeddedNavigationTest.kt b/shop/src/test/java/com/vayunmathur/shop/ui/EmbeddedNavigationTest.ktnew file mode 100644index 0000000000..8fd8f44afc--- /dev/null+++ b/shop/src/test/java/com/vayunmathur/shop/ui/EmbeddedNavigationTest.kt@@ -0,0 +1,147 @@+package com.vayunmathur.shop.ui++import android.content.Context+import android.os.Looper+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.test.core.app.ApplicationProvider+import androidx.work.testing.WorkManagerTestInitHelper+import com.vayunmathur.library.ui.DynamicTheme+import com.vayunmathur.shop.Navigation+import com.vayunmathur.shop.Route+import com.vayunmathur.shop.platform.AppInit+import com.vayunmathur.shop.platform.FakeProfileStore+import com.vayunmathur.shop.platform.FakeShopBackend+import com.vayunmathur.shop.platform.ShopViewModel+import com.vayunmathur.shop.platform.completeProfile+import com.vayunmathur.shop.platform.testProduct+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue+import kotlinx.coroutines.runBlocking+import kotlinx.serialization.json.Json+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows.shadowOf+import org.robolectric.annotation.Config++@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34], qualifiers = "w800dp-h1280dp")+class EmbeddedNavigationTest {++ @get:Rule+ val rule = createComposeRule()++ private val ctx: Context get() = ApplicationProvider.getApplicationContext()+ private lateinit var backend: FakeShopBackend++ @BeforeTest+ fun setUp() {+ runCatching { WorkManagerTestInitHelper.initializeTestWorkManager(ctx) }+ AppInit.start(ctx)+ runBlocking { AppInit.awaitReady() }+ ctx.getSharedPreferences("shop_cart", Context.MODE_PRIVATE).edit().clear().commit()+ ctx.getSharedPreferences("shop_orders", Context.MODE_PRIVATE).edit().clear().commit()+ ctx.getSharedPreferences("shop_link_defaults", Context.MODE_PRIVATE).edit()+ .putBoolean("dismissed", true).commit()+ backend = FakeShopBackend()+ }++ private fun vmWithProfile(profile: com.vayunmathur.shop.data.ShopProfile?): ShopViewModel {+ val store = FakeProfileStore(profile)+ val vm = ShopViewModel(backend)+ vm.profileStoreFactory = { store }+ vm.observeProfile(ctx)+ repeat(200) {+ shadowOf(Looper.getMainLooper()).idle()+ if (vm.profileLoaded) return vm+ Thread.sleep(20)+ }+ error("profile did not load")+ }++ // ---------- embedded checkout ----------++ @Test+ fun `embedded checkout without a request closes immediately`() {+ val vm = ShopViewModel(backend)+ var closes = 0+ rule.setContent { DynamicTheme { EmbeddedCheckoutScreen(vm, onClose = { closes++ }) } }+ rule.waitUntil(timeoutMillis = 10_000) { closes == 1 }+ }++ // ---------- navigation ----------++ @Test+ fun `navigation gates on the profile form until the profile is complete`() {+ val vm = vmWithProfile(null)+ rule.setContent { DynamicTheme { Navigation(vm) } }+ rule.onNodeWithText("Add your details to start shopping.").assertIsDisplayed()+ }++ @Test+ fun `navigation with a complete profile lands on the shop tabs`() {+ val vm = vmWithProfile(completeProfile)+ rule.setContent { DynamicTheme { Navigation(vm) } }+ rule.onNodeWithText("Search products").assertIsDisplayed()+ rule.onNodeWithText("No products found").assertIsDisplayed()+ // Switch to the cart tab through the bottom navigation.+ rule.onNodeWithText("Cart").assertIsDisplayed()+ rule.onNodeWithText("Cart").performClick()+ rule.onNodeWithText("Your cart is empty").assertIsDisplayed()+ rule.onNodeWithText("Orders").performClick()+ rule.onNodeWithText("No orders yet").assertIsDisplayed()+ rule.onNodeWithText("Profile").performClick()+ rule.onNodeWithText("Delivery address (optional)").assertIsDisplayed()+ }++ @Test+ fun `a pending product route opens the detail over the tabs`() {+ val vm = vmWithProfile(completeProfile)+ backend.searchResult = Result.success(listOf(testProduct()))+ // Seed a snapshot so the detail has something to paint while it refreshes.+ vm.updateQuery("trail")+ vm.search()+ var seeded = false+ var attempts = 0+ while (!seeded && attempts < 200) {+ shadowOf(Looper.getMainLooper()).idle()+ seeded = vm.results.size == 1+ if (!seeded) { Thread.sleep(20); attempts++ }+ }+ check(seeded) { "search did not seed a snapshot" }+ com.vayunmathur.shop.network.ShopHttpBackend.request = { _, _, _ ->+ com.vayunmathur.shop.network.BackendRawResponse(502, "{}", emptyMap(), null)+ }+ rule.setContent { DynamicTheme { Navigation(vm) } }+ // The tabs are up (search results from the seeded snapshot are showing).+ rule.onNodeWithText("Trail Runner").assertExists()+ backend.handleResult = Result.success(testProduct())+ vm.openLink("https://shop.example.com/products/trail-runner")+ rule.waitUntil(timeoutMillis = 10_000) { vm.pendingRoute is Route.ProductDetail || vm.linkedProducts.isNotEmpty() }+ // The navigation effect consumes the route and pushes the detail.+ rule.waitUntil(timeoutMillis = 10_000) {+ runCatching { rule.onNodeWithText("Trail Runner").assertIsDisplayed() }.isSuccess+ }+ }++ // ---------- routes ----------++ @Test+ fun `routes round-trip through their serializers`() {+ assertEquals(Route.Search, Json.decodeFromString(Route.serializer(), Json.encodeToString(Route.serializer(), Route.Search)))+ assertEquals(Route.Cart, Json.decodeFromString(Route.serializer(), Json.encodeToString(Route.serializer(), Route.Cart)))+ assertEquals(Route.Orders, Json.decodeFromString(Route.serializer(), Json.encodeToString(Route.serializer(), Route.Orders)))+ assertEquals(+ Route.EmbeddedCheckout,+ Json.decodeFromString(Route.serializer(), Json.encodeToString(Route.serializer(), Route.EmbeddedCheckout)),+ )+ val detail = Route.ProductDetail("v1", "shopify", "shop.example.com")+ assertEquals(detail, Json.decodeFromString(Route.serializer(), Json.encodeToString(Route.serializer(), detail)))+ }++}
shop/src/test/java/com/vayunmathur/shop/ui/OrdersProfileCartTest.kt
diff --git a/shop/src/test/java/com/vayunmathur/shop/ui/OrdersProfileCartTest.kt b/shop/src/test/java/com/vayunmathur/shop/ui/OrdersProfileCartTest.ktnew file mode 100644index 0000000000..c698fb298e--- /dev/null+++ b/shop/src/test/java/com/vayunmathur/shop/ui/OrdersProfileCartTest.kt@@ -0,0 +1,244 @@+package com.vayunmathur.shop.ui++import android.content.Context+import android.os.Looper+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.assertIsEnabled+import androidx.compose.ui.test.assertIsNotEnabled+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 androidx.work.testing.WorkManagerTestInitHelper+import com.vayunmathur.library.ui.DynamicTheme+import com.vayunmathur.shop.data.Money+import com.vayunmathur.shop.data.OrderShipment+import com.vayunmathur.shop.data.OrderStore+import com.vayunmathur.shop.data.OrderTracking+import com.vayunmathur.shop.data.PlacedOrder+import com.vayunmathur.shop.platform.AppInit+import com.vayunmathur.shop.platform.FakeProfileStore+import com.vayunmathur.shop.platform.FakeShopBackend+import com.vayunmathur.shop.platform.ShopViewModel+import com.vayunmathur.shop.platform.completeProfile+import com.vayunmathur.shop.platform.testLine+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue+import kotlinx.coroutines.runBlocking+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows.shadowOf+import org.robolectric.annotation.Config++@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34], qualifiers = "w800dp-h1280dp")+class OrdersProfileCartTest {++ @get:Rule+ val rule = createComposeRule()++ private val ctx: Context get() = ApplicationProvider.getApplicationContext()+ private lateinit var backend: FakeShopBackend++ @BeforeTest+ fun setUp() {+ runCatching { WorkManagerTestInitHelper.initializeTestWorkManager(ctx) }+ AppInit.start(ctx)+ runBlocking { AppInit.awaitReady() }+ ctx.getSharedPreferences("shop_cart", Context.MODE_PRIVATE).edit().clear().commit()+ ctx.getSharedPreferences("shop_orders", Context.MODE_PRIVATE).edit().clear().commit()+ backend = FakeShopBackend()+ }++ private fun awaitVm(vm: ShopViewModel, condition: (ShopViewModel) -> Boolean) {+ repeat(200) {+ shadowOf(Looper.getMainLooper()).idle()+ if (condition(vm)) return+ Thread.sleep(20)+ }+ assertTrue(condition(vm), "view model condition not met; orders=${vm.orders.size}")+ }++ private fun orderVm(orders: List<PlacedOrder>): ShopViewModel {+ val vm = ShopViewModel(backend)+ runBlocking { orders.forEach { OrderStore.add(ctx, it) } }+ vm.loadOrders(ctx)+ awaitVm(vm) { it.orders.size == orders.size }+ return vm+ }++ // ---------- orders ----------++ @Test+ fun `empty orders say so`() {+ val vm = orderVm(emptyList())+ rule.setContent { DynamicTheme { OrdersScreen(vm) } }+ rule.onNodeWithText("No orders yet").assertIsDisplayed()+ }++ @Test+ fun `a completed order with tracking and shipments renders fully`() {+ val order = PlacedOrder(+ checkoutId = "c1", placedAtMs = 1700000000000L, total = Money(12999, "USD"), itemCount = 2,+ status = "completed", platformId = "shopify", shopDomain = "shop.example.com",+ storeName = "Trail Store", orderId = "o1", trackingToken = "a".repeat(32),+ tracking = OrderTracking(+ orderId = "o1", label = "#1042", permalinkUrl = "https://shop.example.com/orders/o1",+ status = "in_transit", refundedTotal = 500, currency = "USD",+ shipments = listOf(+ OrderShipment(+ trackingNumber = "1Z999", trackingUrl = "https://www.ups.com/track/1Z999",+ carrier = "UPS", status = "in_transit", description = "Arrived at facility",+ occurredAt = "2026-03-26T09:15:00-04:00",+ ),+ ),+ ),+ )+ val vm = orderVm(listOf(order))+ rule.setContent { DynamicTheme { OrdersScreen(vm) } }+ rule.onNodeWithText("Trail Store").assertIsDisplayed()+ rule.onNodeWithText("#1042").assertIsDisplayed()+ rule.onNodeWithText("2 item(s) · $129.99").assertIsDisplayed()+ rule.onNodeWithText("In transit").assertIsDisplayed()+ rule.onNodeWithText("UPS · In transit", substring = true).assertIsDisplayed()+ rule.onNodeWithText("1Z999").assertIsDisplayed()+ rule.onNodeWithText("Track package").assertIsDisplayed()+ rule.onNodeWithText("View order").assertIsDisplayed()+ }++ @Test+ fun `a pending order without tracking offers the browser handoff`() {+ val order = PlacedOrder(+ checkoutId = "c1", placedAtMs = 1700000000000L, total = Money(500, "USD"), itemCount = 1,+ status = "pending", shopDomain = "shop.example.com", storeName = "Trail Store",+ continueUrl = "https://shop.example.com/checkout/1",+ )+ val vm = orderVm(listOf(order))+ rule.setContent { DynamicTheme { OrdersScreen(vm) } }+ rule.onNodeWithText("Payment not confirmed").assertIsDisplayed()+ rule.onNodeWithText("Continue in browser").assertIsDisplayed()+ }++ @Test+ fun `a delivery issue is shown with the shipped status strings`() {+ val order = PlacedOrder(+ checkoutId = "c1", placedAtMs = 1700000000000L, total = Money(500, "USD"), itemCount = 1,+ status = "completed", shopDomain = "shop.example.com", storeName = "Trail Store",+ tracking = OrderTracking(status = "delivery_issue"),+ )+ val vm = orderVm(listOf(order))+ rule.setContent { DynamicTheme { OrdersScreen(vm) } }+ rule.onNodeWithText("Delivery issue").assertIsDisplayed()+ }++ // ---------- profile ----------++ @Test+ fun `the required profile gate explains and saves a valid profile`() {+ val store = FakeProfileStore(null)+ val vm = ShopViewModel(backend)+ vm.profileStoreFactory = { store }+ vm.observeProfile(ctx)+ awaitVm(vm) { it.profileLoaded }+ rule.setContent { DynamicTheme { ProfileScreen(vm, required = true) } }+ rule.onNodeWithText("Add your details to start shopping.").assertIsDisplayed()+ rule.onNodeWithText("Continue").assertIsNotEnabled()++ rule.onNodeWithText("First name").performTextInput("Ada")+ rule.onNodeWithText("Last name").performTextInput("Buyer")+ rule.onNodeWithText("Email").performTextInput("[email protected]")+ rule.onNodeWithText("Phone (international, e.g. +14155550123)").performTextInput("+14155550123")+ rule.onNodeWithText("Continue").assertIsEnabled()+ rule.onNodeWithText("Continue").performClick()+ awaitVm(vm) { store.saved.size == 1 }+ assertEquals("Ada", store.saved.single().firstName)+ }++ @Test+ fun `an invalid email keeps the optional profile unsavable and shows why`() {+ val store = FakeProfileStore(completeProfile)+ val vm = ShopViewModel(backend)+ vm.profileStoreFactory = { store }+ vm.observeProfile(ctx)+ awaitVm(vm) { it.profileComplete }+ rule.setContent { DynamicTheme { ProfileScreen(vm, required = false) } }+ rule.onNodeWithText("Save").assertIsNotEnabled()+ rule.onNodeWithText("Email").performTextReplacement("not-an-email")+ // The field now holds the appended text, which is invalid; the error must surface.+ rule.onAllNodesWithText("Enter a valid email address.", substring = true)[0].assertIsDisplayed()+ rule.onNodeWithText("Save").assertIsNotEnabled()+ }++ @Test+ fun `the country field is uppercased while typing`() {+ val store = FakeProfileStore(null)+ val vm = ShopViewModel(backend)+ vm.profileStoreFactory = { store }+ vm.observeProfile(ctx)+ awaitVm(vm) { it.profileLoaded }+ rule.setContent { DynamicTheme { ProfileScreen(vm, required = false) } }+ rule.onNodeWithText("Country (two-letter code)").performTextInput("us")+ rule.onAllNodesWithText("US")[0].assertIsDisplayed()+ }++ // ---------- cart content (extra states) ----------++ @Test+ fun `cart groups by store with a checkout per store and merged totals`() {+ var checkedOut: Pair<String, String>? = null+ var removed = 0+ rule.setContent {+ DynamicTheme {+ CartContent(+ cart = listOf(+ testLine(variantId = "v1", title = "Shoes", price = 1000, quantity = 2, storeName = "Trail Store"),+ testLine(variantId = "v2", title = "Hat", price = 500, quantity = 1, shopDomain = "other.example.com", storeName = "Hat Shop"),+ ),+ onRemove = { removed++ },+ onCheckoutStore = { p, s -> checkedOut = p to s },+ )+ }+ }+ rule.onNodeWithText("Trail Store").assertIsDisplayed()+ rule.onNodeWithText("Hat Shop").assertIsDisplayed()+ rule.onNodeWithText("Checkout with Trail Store").assertIsDisplayed()+ rule.onNodeWithText("Checkout with Hat Shop").performClick()+ assertEquals("shopify" to "other.example.com", checkedOut)+ rule.onAllNodesWithText("Remove")[0].performClick()+ assertEquals(1, removed)+ rule.onNodeWithText("Estimated subtotal").assertIsDisplayed()+ rule.onNodeWithText("$25.00").assertIsDisplayed()+ }++ @Test+ fun `the starting store shows progress and disables other checkouts`() {+ rule.setContent {+ DynamicTheme {+ CartContent(+ cart = listOf(testLine()),+ startingStore = "shopify" to "shop.example.com",+ )+ }+ }+ // The busy store's button swaps its label for a progress indicator.+ rule.onNodeWithText("Checkout").assertDoesNotExist()+ rule.onNodeWithText("Estimated subtotal").assertIsDisplayed()+ }++ @Test+ fun `cart screen through the view model removes lines`() {+ val vm = ShopViewModel(backend)+ vm.addToCart(com.vayunmathur.shop.platform.testProduct(), "v1", 1, ctx)+ rule.setContent { DynamicTheme { CartScreen(vm, onPayInApp = {}) } }+ rule.onNodeWithText("Trail Runner").assertIsDisplayed()+ rule.onNodeWithText("Remove").performClick()+ rule.onNodeWithText("Your cart is empty").assertIsDisplayed()+ assertTrue(vm.cart.isEmpty())+ }+}
shop/src/test/java/com/vayunmathur/shop/ui/ProductDetailContentTest.kt
diff --git a/shop/src/test/java/com/vayunmathur/shop/ui/ProductDetailContentTest.kt b/shop/src/test/java/com/vayunmathur/shop/ui/ProductDetailContentTest.ktnew file mode 100644index 0000000000..45650fc3f2--- /dev/null+++ b/shop/src/test/java/com/vayunmathur/shop/ui/ProductDetailContentTest.kt@@ -0,0 +1,169 @@+package com.vayunmathur.shop.ui++import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.assertIsEnabled+import androidx.compose.ui.test.assertIsNotEnabled+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithContentDescription+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.onAllNodesWithText+import androidx.compose.ui.test.performClick+import com.vayunmathur.library.ui.DynamicTheme+import com.vayunmathur.shop.platform.testProduct+import com.vayunmathur.shop.platform.testVariant+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 org.robolectric.annotation.Config++@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34], qualifiers = "w800dp-h1280dp")+class ProductDetailContentTest {++ @get:Rule+ val rule = createComposeRule()++ private data class Callbacks(+ var selected: String? = null,+ var quantity: Int? = null,+ var retries: Int = 0,+ var adds: Int = 0,+ var buys: Int = 0,+ val urls: MutableList<String> = mutableListOf(),+ )++ private fun setContent(+ product: com.vayunmathur.shop.data.UcpProduct = testProduct(),+ selectedVariantId: String = "v1",+ quantity: Int = 1,+ loading: Boolean = false,+ verified: Boolean = true,+ failure: String? = null,+ startingCheckout: Boolean = false,+ cb: Callbacks = Callbacks(),+ ): Callbacks {+ rule.setContent {+ DynamicTheme {+ ProductDetailContent(+ product = product,+ selectedVariantId = selectedVariantId,+ quantity = quantity,+ loading = loading,+ verified = verified,+ failure = failure,+ onSelectVariant = { cb.selected = it },+ onQuantityChange = { cb.quantity = it },+ onRetry = { cb.retries++ },+ onAddToCart = { cb.adds++ },+ onBuyNow = { cb.buys++ },+ onOpenUrl = { cb.urls += it },+ startingCheckout = startingCheckout,+ )+ }+ }+ return cb+ }++ @Test+ fun `verified in-stock product can be added and bought`() {+ val cb = setContent()+ rule.onNodeWithText("Trail Store").assertIsDisplayed()+ rule.onNodeWithText("$129.99").assertIsDisplayed()+ rule.onNodeWithText("Add to cart").assertIsEnabled()+ rule.onNodeWithText("Add to cart").performClick()+ rule.onNodeWithText("Buy now").performClick()+ assertEquals(1, cb.adds)+ assertEquals(1, cb.buys)+ }++ @Test+ fun `quantity stepper reports clamped changes`() {+ val cb = setContent(quantity = 1)+ rule.onNodeWithContentDescription("Decrease quantity").assertIsNotEnabled()+ rule.onNodeWithContentDescription("Increase quantity").performClick()+ assertEquals(2, cb.quantity)+ }++ @Test+ fun `quantity stepper at the cap cannot increase`() {+ val cb = setContent(quantity = 99)+ rule.onNodeWithContentDescription("Increase quantity").assertIsNotEnabled()+ rule.onNodeWithContentDescription("Decrease quantity").performClick()+ assertEquals(98, cb.quantity)+ }++ @Test+ fun `loading disables purchase and explains why`() {+ val cb = setContent(loading = true, verified = false)+ rule.onNodeWithText("Checking live price and availability...").assertIsDisplayed()+ rule.onNodeWithText("Add to cart").assertIsNotEnabled()+ rule.onNodeWithText("Add to cart").performClick()+ assertEquals(0, cb.adds, "a disabled button must not fire its callback")+ }++ @Test+ fun `unverified product offers a retry and cannot be added`() {+ val cb = setContent(verified = false, failure = "The store no longer lists this exact variant. Cart actions are disabled.")+ rule.onNodeWithText("The store no longer lists this exact variant. Cart actions are disabled.").assertIsDisplayed()+ rule.onNodeWithText("Add to cart").assertIsNotEnabled()+ rule.onNodeWithText("Retry").performClick()+ assertEquals(1, cb.retries)+ }++ @Test+ fun `out of stock variant says so and cannot be added`() {+ setContent(product = testProduct(variants = listOf(testVariant(available = false))))+ rule.onNodeWithText("This variant is out of stock.").assertIsDisplayed()+ rule.onNodeWithText("Add to cart").assertIsNotEnabled()+ }++ @Test+ fun `multiple variants render a picker that selects available options`() {+ val cb = setContent(+ product = testProduct(+ variants = listOf(+ testVariant(id = "v1", title = "9 / Blue"),+ testVariant(id = "v2", title = "10 / Red", price = 13999),+ testVariant(id = "v3", title = "11 / Green", available = false),+ ),+ ),+ )+ rule.onNodeWithText("9 / Blue").assertIsDisplayed()+ rule.onNodeWithText("Selected").assertIsDisplayed()+ rule.onNodeWithText("Out of stock").assertIsDisplayed()+ // Two enabled Select buttons (v2) plus the selected one disabled; click the v2 row's.+ rule.onAllNodesWithText("Select")[0].performClick()+ assertEquals("v2", cb.selected)+ }++ @Test+ fun `ineligible product links out to the merchant site`() {+ val cb = setContent(product = testProduct(checkoutEligible = false))+ rule.onNodeWithText("View on merchant site").assertIsDisplayed()+ rule.onNodeWithText("Completes on the merchant site.").assertIsDisplayed()+ rule.onNodeWithText("View on merchant site").performClick()+ assertEquals(listOf("https://shop.example.com/products/trail-runner"), cb.urls)+ }++ @Test+ fun `description renders as text`() {+ setContent(product = testProduct().copy(descriptionHtml = "<p>Waterproof <b>leather</b> boots</p>", description = ""))+ rule.onNodeWithText("Waterproof leather boots", substring = true).assertIsDisplayed()+ }++ @Test+ fun `starting checkout replaces the buy label with progress`() {+ setContent(startingCheckout = true)+ rule.onNodeWithText("Buy now").assertDoesNotExist()+ }++ @Test+ fun `store falls back to the domain when no name is known`() {+ setContent(product = testProduct().copy(storeName = "", variants = listOf(testVariant(storeName = ""))))+ rule.onNodeWithText("shop.example.com").assertIsDisplayed()+ assertTrue(true)+ }+}
shop/src/test/java/com/vayunmathur/shop/ui/ProductScreenTest.kt
diff --git a/shop/src/test/java/com/vayunmathur/shop/ui/ProductScreenTest.kt b/shop/src/test/java/com/vayunmathur/shop/ui/ProductScreenTest.ktnew file mode 100644index 0000000000..87ea321829--- /dev/null+++ b/shop/src/test/java/com/vayunmathur/shop/ui/ProductScreenTest.kt@@ -0,0 +1,140 @@+package com.vayunmathur.shop.ui++import android.content.Context+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.assertIsEnabled+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.test.core.app.ApplicationProvider+import androidx.work.testing.WorkManagerTestInitHelper+import com.vayunmathur.library.ui.DynamicTheme+import com.vayunmathur.shop.network.BackendRawResponse+import com.vayunmathur.shop.network.ShopHttpBackend+import com.vayunmathur.shop.platform.AppInit+import com.vayunmathur.shop.platform.FakeShopBackend+import com.vayunmathur.shop.platform.ShopViewModel+import com.vayunmathur.shop.platform.testProduct+import java.io.IOException+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue+import kotlinx.coroutines.runBlocking+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34], qualifiers = "w800dp-h1280dp")+class ProductScreenTest {++ @get:Rule+ val rule = createComposeRule()++ private val ctx: Context get() = ApplicationProvider.getApplicationContext()+ private lateinit var backend: FakeShopBackend+ private lateinit var vm: ShopViewModel++ private val liveProductJson = """+ {"product": {"id": "p1", "title": "Trail Runner", "description": "Grippy",+ "priceRange": {"amount": 12999, "currency": "USD"},+ "url": "https://shop.example.com/products/trail-runner", "platformId": "shopify",+ "shopDomain": "shop.example.com", "images": [],+ "variants": [{"id": "v1", "title": "9 / Blue", "price": {"amount": 12999, "currency": "USD"},+ "available": true, "storeName": "Trail Store", "shopDomain": "shop.example.com"}],+ "checkoutEligible": true, "storeName": "Trail Store"}}+ """.trimIndent()++ @BeforeTest+ fun setUp() {+ runCatching { WorkManagerTestInitHelper.initializeTestWorkManager(ctx) }+ AppInit.start(ctx)+ runBlocking { AppInit.awaitReady() }+ ctx.getSharedPreferences("shop_cart", Context.MODE_PRIVATE).edit().clear().commit()+ backend = FakeShopBackend()+ vm = ShopViewModel(backend)+ }++ @AfterTest+ fun tearDown() {+ ShopHttpBackend.request = { _, _, _ -> throw IOException("stubbed off in tests") }+ }++ private fun seedSnapshot() {+ backend.searchResult = Result.success(listOf(testProduct()))+ vm.updateQuery("trail")+ vm.search()+ repeat(200) {+ org.robolectric.Shadows.shadowOf(android.os.Looper.getMainLooper()).idle()+ if (vm.results.size == 1) return+ Thread.sleep(20)+ }+ assertEquals(1, vm.results.size)+ }++ private fun setScreen(onPayInApp: () -> Unit = {}) {+ rule.setContent {+ DynamicTheme {+ ProductScreen(+ viewModel = vm, variantId = "v1", platformId = "shopify",+ shopDomain = "shop.example.com", onBack = {}, onPayInApp = onPayInApp,+ )+ }+ }+ }++ @Test+ fun `a live refresh verifies the snapshot and adding to cart works`() {+ seedSnapshot()+ ShopHttpBackend.request = { _, _, _ -> BackendRawResponse(200, liveProductJson, emptyMap(), null) }+ setScreen()+ rule.waitUntil(timeoutMillis = 10_000) {+ runCatching { rule.onNodeWithText("Add to cart").assertIsEnabled() }.isSuccess+ }+ rule.onNodeWithText("Trail Runner").assertIsDisplayed()+ rule.onNodeWithText("Add to cart").performClick()+ assertEquals(1, vm.cart.size)+ assertEquals("v1", vm.cart.single().variantId)+ }++ @Test+ fun `a failed refresh keeps the snapshot unverified with a retry`() {+ seedSnapshot()+ ShopHttpBackend.request = { _, _, _ -> BackendRawResponse(502, "{}", emptyMap(), null) }+ setScreen()+ rule.waitUntil(timeoutMillis = 10_000) {+ runCatching { rule.onNodeWithText("Retry").assertIsDisplayed() }.isSuccess+ }+ rule.onNodeWithText("Add to cart").assertExists()+ }++ @Test+ fun `a refresh that drops the variant disables cart actions`() {+ seedSnapshot()+ val dropped = liveProductJson.replace("\"id\": \"v1\"", "\"id\": \"v-other\"")+ ShopHttpBackend.request = { _, _, _ -> BackendRawResponse(200, dropped, emptyMap(), null) }+ setScreen()+ rule.waitUntil(timeoutMillis = 10_000) {+ runCatching {+ rule.onNodeWithText("The store no longer lists this exact variant. Cart actions are disabled.").assertIsDisplayed()+ }.isSuccess+ }+ }++ @Test+ fun `without a snapshot and a failing backend the product is unavailable`() {+ ShopHttpBackend.request = { _, _, _ -> throw IOException("offline") }+ setScreen()+ // No snapshot: the screen first checks, then offers a retry. The backend used here is+ // the HTTP backend (the snapshot lookup found nothing, so the refresh uses the variant+ // id as the product id and fails at the transport seam).+ rule.waitUntil(timeoutMillis = 10_000) {+ runCatching { rule.onNodeWithText("Retry").assertIsDisplayed() }.isSuccess ||+ runCatching { rule.onNodeWithText("This product is unavailable. Please retry.").assertIsDisplayed() }.isSuccess+ }+ assertTrue(vm.cart.isEmpty())+ }+}
shop/src/test/java/com/vayunmathur/shop/ui/SearchScreensTest.kt
diff --git a/shop/src/test/java/com/vayunmathur/shop/ui/SearchScreensTest.kt b/shop/src/test/java/com/vayunmathur/shop/ui/SearchScreensTest.ktnew file mode 100644index 0000000000..3c97ebefc5--- /dev/null+++ b/shop/src/test/java/com/vayunmathur/shop/ui/SearchScreensTest.kt@@ -0,0 +1,175 @@+package com.vayunmathur.shop.ui++import android.content.Context+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onAllNodesWithText+import androidx.compose.ui.test.onNodeWithContentDescription+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.compose.ui.test.performTextInput+import androidx.test.core.app.ApplicationProvider+import androidx.work.testing.WorkManagerTestInitHelper+import com.vayunmathur.library.ui.DynamicTheme+import com.vayunmathur.shop.data.UcpProduct+import com.vayunmathur.shop.network.ShopBackendException+import com.vayunmathur.shop.data.UcpError+import com.vayunmathur.shop.platform.AppInit+import com.vayunmathur.shop.platform.FakeShopBackend+import com.vayunmathur.shop.platform.ShopViewModel+import com.vayunmathur.shop.platform.testProduct+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue+import kotlinx.coroutines.runBlocking+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34], qualifiers = "w800dp-h1280dp")+class SearchScreensTest {++ @get:Rule+ val rule = createComposeRule()++ private val ctx: Context get() = ApplicationProvider.getApplicationContext()++ @BeforeTest+ fun setUp() {+ runCatching { WorkManagerTestInitHelper.initializeTestWorkManager(ctx) }+ AppInit.start(ctx)+ runBlocking { AppInit.awaitReady() }+ ctx.getSharedPreferences("shop_link_defaults", Context.MODE_PRIVATE).edit().clear().commit()+ ctx.getSharedPreferences("shop_link_defaults", Context.MODE_PRIVATE).edit().putBoolean("dismissed", true).commit()+ }++ private data class SearchCallbacks(+ var query: String = "",+ var searches: Int = 0,+ var clearedScope: Int = 0,+ val clicks: MutableList<Triple<String, String, String>> = mutableListOf(),+ var promptOpened: Int = 0,+ var promptDismissed: Int = 0,+ )++ private fun setContent(+ cb: SearchCallbacks,+ results: List<UcpProduct> = emptyList(),+ searching: Boolean = false,+ scopeName: String? = null,+ linkPrompt: LinkPrompt? = null,+ ) {+ rule.setContent {+ DynamicTheme {+ SearchContent(+ query = cb.query,+ onQueryChange = { cb.query = it },+ searching = searching,+ results = results,+ onSearch = { cb.searches++ },+ onProductClick = { v, p, s -> cb.clicks += Triple(v, p, s) },+ scopeName = scopeName,+ onClearScope = { cb.clearedScope++ },+ linkPrompt = linkPrompt,+ )+ }+ }+ }++ @Test+ fun `empty results explain that nothing was found`() {+ setContent(SearchCallbacks())+ rule.onNodeWithText("No products found").assertIsDisplayed()+ rule.onNodeWithText("Enter a search or try a different query").assertIsDisplayed()+ }++ @Test+ fun `searching shows progress instead of results`() {+ setContent(SearchCallbacks(), searching = true, results = listOf(testProduct()))+ rule.onNodeWithText("No products found").assertDoesNotExist()+ rule.onNodeWithText("Trail Runner").assertDoesNotExist()+ }++ @Test+ fun `results render cards and tapping one opens its first variant`() {+ val cb = SearchCallbacks()+ setContent(cb, results = listOf(testProduct(), testProduct(id = "p2", title = "Rain Boots")))+ rule.onNodeWithText("Trail Runner").assertIsDisplayed()+ rule.onNodeWithText("Rain Boots").assertIsDisplayed()+ rule.onAllNodesWithText("Trail Store")[0].assertIsDisplayed()+ rule.onNodeWithText("Trail Runner").performClick()+ assertEquals(listOf(Triple("v1", "shopify", "shop.example.com")), cb.clicks)+ }++ @Test+ fun `typing a query and searching reports both`() {+ val cb = SearchCallbacks()+ setContent(cb)+ rule.onNode(androidx.compose.ui.test.isEditable()).performTextInput("boots")+ assertEquals("boots", cb.query)+ // The clear button appears once the query is non-empty in the real screen; here the+ // captured query state proves the callback wiring.+ }++ @Test+ fun `a merchant scope chip can be dismissed`() {+ val cb = SearchCallbacks()+ setContent(cb, scopeName = "Trail Store")+ rule.onNodeWithText("Results from Trail Store").assertIsDisplayed()+ rule.onNodeWithText("Results from Trail Store").performClick()+ assertEquals(1, cb.clearedScope)+ }++ @Test+ fun `the link prompt card opens settings or dismisses`() {+ val cb = SearchCallbacks()+ setContent(+ cb,+ linkPrompt = LinkPrompt(+ onOpenSettings = { cb.promptOpened++ },+ onDismiss = { cb.promptDismissed++ },+ ),+ )+ rule.onNodeWithText("Open store links in Shop").assertIsDisplayed()+ rule.onNodeWithText("Open settings").performClick()+ rule.onNodeWithText("Not now").performClick()+ assertEquals(1, cb.promptOpened)+ assertEquals(1, cb.promptDismissed)+ }++ @Test+ fun `the search screen drives the view model end to end`() {+ val backend = FakeShopBackend().apply {+ searchResult = Result.success(listOf(testProduct()))+ }+ val vm = ShopViewModel(backend)+ val clicks = mutableListOf<Triple<String, String, String>>()+ rule.setContent {+ DynamicTheme { SearchScreen(vm) { v, p, s -> clicks += Triple(v, p, s) } }+ }+ vm.updateQuery("trail")+ vm.search()+ rule.waitUntil(timeoutMillis = 10_000) { vm.results.size == 1 }+ rule.onNodeWithText("Trail Runner").assertIsDisplayed()+ rule.onNodeWithText("Trail Runner").performClick()+ assertEquals(1, clicks.size)++ // An error from the backend is shown through the messenger and then dismissed.+ backend.searchResult = Result.failure(ShopBackendException(UcpError.Transport("down")))+ vm.updateQuery("boots")+ vm.search()+ rule.waitUntil(timeoutMillis = 10_000) { vm.searchError == null && !vm.searching && backend.searchCalls.size >= 2 }+ }++ @Test+ fun `a product without variants renders but does not open`() {+ val cb = SearchCallbacks()+ setContent(cb, results = listOf(testProduct(variants = emptyList())))+ rule.onNodeWithText("Trail Runner").assertIsDisplayed()+ rule.onNodeWithText("Trail Runner").performClick()+ assertTrue(cb.clicks.isEmpty())+ }+}
shop/src/test/java/com/vayunmathur/shop/ui/ShopScreensExtraTest.kt
diff --git a/shop/src/test/java/com/vayunmathur/shop/ui/ShopScreensExtraTest.kt b/shop/src/test/java/com/vayunmathur/shop/ui/ShopScreensExtraTest.ktnew file mode 100644index 0000000000..e8624c539e--- /dev/null+++ b/shop/src/test/java/com/vayunmathur/shop/ui/ShopScreensExtraTest.kt@@ -0,0 +1,251 @@+package com.vayunmathur.shop.ui++import android.content.Context+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.test.core.app.ApplicationProvider+import androidx.work.testing.WorkManagerTestInitHelper+import com.vayunmathur.library.ui.DynamicTheme+import com.vayunmathur.library.util.AppMessages+import com.vayunmathur.shop.domain.EcAction+import com.vayunmathur.shop.domain.EmbeddedCheckout+import com.vayunmathur.shop.network.BackendRawResponse+import com.vayunmathur.shop.network.ShopHttpBackend+import com.vayunmathur.shop.platform.AppInit+import com.vayunmathur.shop.platform.FakeShopBackend+import com.vayunmathur.shop.platform.ShopViewModel+import com.vayunmathur.shop.platform.testProduct+import com.vayunmathur.shop.platform.testVariant+import java.io.IOException+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertIs+import kotlin.test.assertNull+import kotlin.test.assertTrue+import kotlinx.coroutines.runBlocking+import kotlinx.serialization.json.JsonPrimitive+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows.shadowOf+import org.robolectric.annotation.Config++@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34], qualifiers = "w800dp-h1280dp")+class ShopScreensExtraTest {++ @get:Rule+ val rule = createComposeRule()++ private val ctx: Context get() = ApplicationProvider.getApplicationContext()+ private lateinit var backend: FakeShopBackend+ private lateinit var vm: ShopViewModel++ @BeforeTest+ fun setUp() {+ runCatching { WorkManagerTestInitHelper.initializeTestWorkManager(ctx) }+ AppInit.start(ctx)+ runBlocking { AppInit.awaitReady() }+ ctx.getSharedPreferences("shop_cart", Context.MODE_PRIVATE).edit().clear().commit()+ ctx.getSharedPreferences("shop_orders", Context.MODE_PRIVATE).edit().clear().commit()+ ctx.getSharedPreferences("shop_link_defaults", Context.MODE_PRIVATE).edit().putBoolean("dismissed", true).commit()+ backend = FakeShopBackend()+ vm = ShopViewModel(backend)+ }++ @AfterTest+ fun tearDown() {+ ShopHttpBackend.request = { _, _, _ -> throw IOException("stubbed off in tests") }+ }++ // ---------- embedded checkout protocol (host logic) ----------++ @Test+ fun `embedded URL adds the protocol parameters and rejects non-https`() {+ assertEquals(+ "https://shop.example.com/checkout/1?ec_version=2026-08-25&ec_color_scheme=light&ec_delegate=window.open",+ EmbeddedCheckout.embeddedUrl("https://shop.example.com/checkout/1", dark = false),+ )+ assertTrue(+ EmbeddedCheckout.embeddedUrl("https://shop.example.com/checkout/1?x=1", dark = true)!!+ .contains("&ec_color_scheme=dark"),+ )+ assertNull(EmbeddedCheckout.embeddedUrl("http://shop.example.com/checkout", dark = false))+ assertNull(EmbeddedCheckout.embeddedUrl("not a url", dark = false))+ }++ @Test+ fun `ready and unknown methods are answered, junk is ignored`() {+ val ready = EmbeddedCheckout.handle("""{"jsonrpc":"2.0","id":7,"method":"ec.ready"}""")+ val reply = assertIs<EcAction.Reply>(ready)+ assertTrue(reply.json.contains("\"id\":7"), reply.json)+ assertTrue(reply.json.contains("2026-08-25"), reply.json)++ assertEquals(EcAction.Ignore, EmbeddedCheckout.handle("""{"method":"ec.ready"}"""))+ assertEquals(EcAction.Ignore, EmbeddedCheckout.handle("not json"))+ assertEquals(EcAction.Ignore, EmbeddedCheckout.handle("""{"id":1}"""))+ assertEquals(EcAction.Ignore, EmbeddedCheckout.handle("""[1,2]"""))++ val unknown = EmbeddedCheckout.handle("""{"id":"abc","method":"ec.something_new"}""")+ val notFound = assertIs<EcAction.Reply>(unknown)+ assertTrue(notFound.json.contains("-32601"), notFound.json)+ assertTrue(notFound.json.contains("ec.something_new"), notFound.json)+ assertEquals(EcAction.Ignore, EmbeddedCheckout.handle("""{"method":"ec.something_new"}"""))+ }++ @Test+ fun `window open requests validate the URL and echo the id`() {+ val open = EmbeddedCheckout.handle(+ """{"id":3,"method":"ec.window.open_request","params":{"url":"https://bank.example.com/auth"}}""",+ )+ val action = assertIs<EcAction.OpenWindow>(open)+ assertEquals("https://bank.example.com/auth", action.url)+ assertEquals(JsonPrimitive(3), action.id)++ val rejected = EmbeddedCheckout.handle(+ """{"id":4,"method":"ec.window.open_request","params":{"url":"http://insecure.example.com/"}}""",+ )+ assertTrue(assertIs<EcAction.Reply>(rejected).json.contains("window_open_rejected_error"))+ assertEquals(+ EcAction.Ignore,+ EmbeddedCheckout.handle("""{"method":"ec.window.open_request","params":{"url":"https://example.com/"}}"""),+ )++ val okResult = EmbeddedCheckout.windowOpenResult(JsonPrimitive("x"), ok = true)+ assertTrue(okResult.contains("\"status\":\"success\""), okResult)+ val badResult = EmbeddedCheckout.windowOpenResult(JsonPrimitive("x"), ok = false)+ assertTrue(badResult.contains("window_open_rejected_error"), badResult)+ }++ @Test+ fun `completion extracts order id, permalink and total, with fallbacks`() {+ val complete = EmbeddedCheckout.handle(+ """{"id":1,"method":"ec.complete","params":{"checkout":{"id":"sess-1",+ "order":{"id":"order-9","permalink_url":"https://shop.example.com/orders/9"},+ "totals":[{"type":"subtotal","amount":100},{"type":"total","amount":12999}]}}}""",+ )+ val done = assertIs<EcAction.Completed>(complete)+ assertEquals("order-9", done.orderId)+ assertEquals("https://shop.example.com/orders/9", done.permalinkUrl)+ assertEqual
Diff truncated.