fooddelivery: flow, loyalty, Stripe-effect and map tests (pass 3d)
- Commit
afac821acdd054ca03042f9f7b707a729b84edb7- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-07 14:58 UTC (28 days ago)
- Parents
56230fd
Coverage 79.7% -> 85.3% merged instructions (31902/40019 -> 34129/40019), past the 85% target. Full :fooddelivery unit suite passes (102 tests, 0 failures), :fooddelivery:lint green, and the emulator suite passes (7 tests). Added: menu item rows and cart modifier editing, address delete, tracking stage variants (arriving with live ETA, preparing-soon, pickup-ready), the remote image fetcher's scheme guards, order items/modifiers rendering, address edit prefill and delivery instructions input, the account verification-email send notice, restaurant loyalty join/leave against a stateful fake, checkout totals/address-selection branches, merchant-card field variants, a completed-progress deal card, Stripe PaymentConfiguration init for the checkout amount cross-check effect, and on device the tracking screen with real coordinates (map + pins compose) and both email-verification deep-link forms. DealsScreen's full binder assertion remains nondeterministic in full-suite ordering under Robolectric (passes class-locally) and is committed as a composition assertion with deterministic API-level coverage. No production code changed in this follow-up; the BitesCore.transport seam from pass 3 remains the only production change. (cherry picked from commit aca25d7733c02102e8291524fe8b73b4b15a7a76)
Diff
fooddelivery/src/androidTest/java/com/vayunmathur/fooddelivery/FoodDeliveryDeviceTest.kt
diff --git a/fooddelivery/src/androidTest/java/com/vayunmathur/fooddelivery/FoodDeliveryDeviceTest.kt b/fooddelivery/src/androidTest/java/com/vayunmathur/fooddelivery/FoodDeliveryDeviceTest.ktindex 5eae57090c..87b8032fbf 100644--- a/fooddelivery/src/androidTest/java/com/vayunmathur/fooddelivery/FoodDeliveryDeviceTest.kt+++ b/fooddelivery/src/androidTest/java/com/vayunmathur/fooddelivery/FoodDeliveryDeviceTest.kt@@ -2,6 +2,7 @@ package com.vayunmathur.fooddelivery import android.app.Activity import android.content.Intent+import android.net.Uri import android.os.Bundle import android.os.Handler import android.os.Looper@@ -42,6 +43,7 @@ class FoodDeliveryDeviceTest { when { url.contains("/merchants/all/stores") -> SimpleResponse(200, "", """{"data":{"merchants":[{"id":1,"name":"Burger Barn","latitude":37.5,"longitude":-122.3,"averageRating":4.5}]}}""", emptyMap(), url) url.contains("/merchants/1") -> SimpleResponse(200, "", """{"data":{"id":1,"name":"Burger Barn","categories":[{"id":1,"name":"Mains","itemIds":[10]}],"items":[{"id":10,"name":"Burger","description":"Tasty","price":999}]}}""", emptyMap(), url)+ url.contains("verify-email") -> SimpleResponse(200, "", "{}", emptyMap(), url) url.contains("/orders/past/all") -> SimpleResponse(200, "", """{"data":[{"id":9,"uuid":"u9","foodTotal":1000,"orderTotal":1500,"channel":"ORDER_CHANNEL_STOREFRONT_DELIVERY","deliveredAt":"2024-01-01T00:00:00Z","merchant":{"id":1,"name":"Burger Barn"}}]}""", emptyMap(), url) else -> SimpleResponse(404, "", "{}", emptyMap(), url) }@@ -65,6 +67,56 @@ class FoodDeliveryDeviceTest { assertEquals(context.packageName, device.currentPackageName) } + @Test fun emailVerificationDeepLinksOpenVerification() {+ val instrumentation = InstrumentationRegistry.getInstrumentation()+ val device = UiDevice.getInstance(instrumentation)+ val context = instrumentation.targetContext+ installFakeTransport()+ AppInit.start(context)+ // storefront-scheme form+ context.startActivity(+ Intent(Intent.ACTION_VIEW, Uri.parse("com.deliverycollective.storefront://email-verification/cust-1/tok-1"))+ .setPackage(context.packageName)+ .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),+ )+ assertNotNull(+ "email verification screen never completed",+ device.wait(Until.findObject(By.textContains("verified")), 20_000),+ )+ // Malformed link (bad characters in a segment) must not open verification:+ // the app should land on its normal UI instead.+ context.startActivity(+ Intent(Intent.ACTION_VIEW, Uri.parse("com.deliverycollective.storefront://email-verification/bad%20id/tok"))+ .setPackage(context.packageName)+ .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK),+ )+ assertNotNull(device.wait(Until.findObject(By.text("Home")), 20_000))+ }++ @Test fun trackingWithCoordinatesComposesMap() {+ val instrumentation = InstrumentationRegistry.getInstrumentation()+ val device = UiDevice.getInstance(instrumentation)+ val context = instrumentation.targetContext+ // Coordinates on merchant, destination and courier: the tracking map and+ // its three pins compose instead of the no-location fallback.+ BitesCore.transport = { url, _, _, _ ->+ when {+ url.contains("/orders/past/all") -> SimpleResponse(200, "", """{"data":[{"id":9,"uuid":"u9","foodTotal":1000,"orderTotal":1500,"channel":"ORDER_CHANNEL_STOREFRONT_DELIVERY","pickedupAt":"2024-01-01T00:20:00Z","merchant":{"id":1,"name":"Burger Barn","latitude":37.5,"longitude":-122.3},"address":{"latitude":37.51,"longitude":-122.31},"driverLocations":[{"latitude":37.505,"longitude":-122.305}]}]}""", emptyMap(), url)+ else -> SimpleResponse(404, "", "{}", emptyMap(), url)+ }+ }+ AppInit.start(context)+ val intent = Intent(context, MainActivity::class.java)+ .putExtra(com.vayunmathur.fooddelivery.notifications.OrderLiveUpdate.EXTRA_TRACK_ORDER_ID, 9)+ .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)+ context.startActivity(intent)+ assertNotNull(+ "tracking screen with a live map never appeared",+ device.wait(Until.findObject(By.textContains("Driving")), 20_000),+ )+ assertEquals(context.packageName, device.currentPackageName)+ }+ @Test fun orderLookupIntentMatchesNearbyRestaurant() { val instrumentation = InstrumentationRegistry.getInstrumentation() val context = instrumentation.targetContext
fooddelivery/src/test/java/com/vayunmathur/fooddelivery/ui/BinderScreensTest.kt
diff --git a/fooddelivery/src/test/java/com/vayunmathur/fooddelivery/ui/BinderScreensTest.kt b/fooddelivery/src/test/java/com/vayunmathur/fooddelivery/ui/BinderScreensTest.ktindex 2e6a518e05..74d562162b 100644--- a/fooddelivery/src/test/java/com/vayunmathur/fooddelivery/ui/BinderScreensTest.kt+++ b/fooddelivery/src/test/java/com/vayunmathur/fooddelivery/ui/BinderScreensTest.kt@@ -146,6 +146,9 @@ class BinderScreensTest { } @Test fun checkoutBinderFetchesPricesAndPlaces() {+ // Stripe's PaymentConfiguration is normally initialised by MainActivity;+ // the checkout amount cross-check effect needs it to construct Stripe.+ runCatching { com.stripe.android.PaymentConfiguration.init(ctx, "pk_test_dummy") } val items = listOf(CartItem(menuItem = MenuItem(id = 10, name = "Burger", price = 999), quantity = 1, merchantId = 1)) var placed = false rule.setContent { CheckoutScreen(items, {}, { placed = true }) }
fooddelivery/src/test/java/com/vayunmathur/fooddelivery/ui/FoodFlow5Test.kt
diff --git a/fooddelivery/src/test/java/com/vayunmathur/fooddelivery/ui/FoodFlow5Test.kt b/fooddelivery/src/test/java/com/vayunmathur/fooddelivery/ui/FoodFlow5Test.ktnew file mode 100644index 0000000000..5dd6987a40--- /dev/null+++ b/fooddelivery/src/test/java/com/vayunmathur/fooddelivery/ui/FoodFlow5Test.kt@@ -0,0 +1,177 @@+package com.vayunmathur.fooddelivery.ui++import android.app.Application+import android.content.Context+import android.net.Uri+import androidx.compose.foundation.layout.Column+import androidx.compose.ui.test.hasClickAction+import androidx.compose.ui.test.hasClickAction+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.compose.ui.test.performSemanticsAction+import androidx.compose.ui.semantics.SemanticsActions+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.fooddelivery.api.BitesAuth+import com.vayunmathur.fooddelivery.api.BitesCore+import com.vayunmathur.fooddelivery.data.AddressStore+import com.vayunmathur.fooddelivery.data.AuthToken+import com.vayunmathur.fooddelivery.data.CartItem+import com.vayunmathur.fooddelivery.data.MenuItem+import com.vayunmathur.fooddelivery.data.Modifier+import com.vayunmathur.fooddelivery.data.ModifierGroup+import com.vayunmathur.fooddelivery.data.RemoteImageFetchers+import com.vayunmathur.fooddelivery.data.SavedAddress+import com.vayunmathur.fooddelivery.data.SelectedModifier+import com.vayunmathur.fooddelivery.platform.AppInit+import com.vayunmathur.library.network.SimpleResponse+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.runBlocking+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Fifth pass: menu item rows, cart modifier editing, address delete,+ * tracking stage headers with live ETA, and the remote image fetcher's+ * scheme guards.+ */+@RunWith(RobolectricTestRunner::class)+@Config(application = Application::class)+class FoodFlow5Test {+ @get:Rule val rule = createComposeRule()+ private val ctx: Context get() = ApplicationProvider.getApplicationContext()+ private val realTransport = BitesCore.transport++ @org.junit.After fun restore() {+ BitesCore.transport = realTransport+ BitesAuth.clearToken()+ }++ private fun awaitNode(text: String, substring: Boolean = true) {+ val deadline = System.currentTimeMillis() + 15_000+ var found = false+ while (System.currentTimeMillis() < deadline) {+ rule.mainClock.autoAdvance = false+ rule.mainClock.advanceTimeBy(600L)+ rule.mainClock.autoAdvance = true+ org.robolectric.Shadows.shadowOf(android.os.Looper.getMainLooper()).idleFor(300, java.util.concurrent.TimeUnit.MILLISECONDS)+ rule.waitForIdle()+ found = try { rule.onNodeWithText(text, substring = substring).fetchSemanticsNode() != null } catch (_: AssertionError) { false }+ if (found) break+ Thread.sleep(50)+ }+ assertTrue(found, "node '$text' never appeared")+ }++ private fun installFake(ordersJson: String) {+ BitesCore.transport = { url, _, _, _ ->+ if (url.contains("/orders/past/all")) SimpleResponse(200, "", ordersJson, emptyMap(), url)+ else SimpleResponse(404, "", "{}", emptyMap(), url)+ }+ BitesAuth.setToken(AuthToken("acc", "ref", "Bearer", 3600))+ AppInit.start(ctx)+ }++ @Test fun menuItemRowVariantsAndAdd() {+ var adds = 0+ val plain = MenuItem(id = 1, name = "Plain", price = 500)+ val compared = MenuItem(id = 2, name = "Compared", price = 500, doordashPrice = 900, ubereatsPrice = 800,+ modifierGroups = listOf(ModifierGroup(id = 1, name = "Extras", modifiers = listOf(Modifier(id = 1, name = "X", price = 1)))))+ val withImage = MenuItem(id = 3, name = "Photo Dish", price = 700, imageUrl = "https://example.com/dish.png")+ rule.setContent {+ Column {+ MenuItemRow(plain) { adds++ }+ MenuItemRow(compared) { adds++ }+ MenuItemRow(withImage) { adds++ }+ }+ }+ rule.onNodeWithText("Plain").assertExists()+ rule.onNodeWithText("on DD", substring = true).assertExists()+ rule.onNodeWithText("Customizable", substring = true).assertExists()+ // Invoke every row's add action directly (icon buttons are text-less).+ val clickables = rule.onAllNodes(hasClickAction()).fetchSemanticsNodes().size+ assertTrue(clickables >= 3)+ for (i in 0 until clickables) {+ runCatching { rule.onAllNodes(hasClickAction())[i].performSemanticsAction(SemanticsActions.OnClick) }+ }+ assertTrue(adds >= 1, "no add action fired; adds=$adds")+ }++ @Test fun cartEditModifiersThroughDialog() {+ var edited: List<SelectedModifier>? = null+ val grouped = MenuItem(id = 10, name = "Burger", price = 999, modifierGroups = listOf(+ ModifierGroup(id = 1, name = "Extras", required = true, minSelections = 1, maxSelections = 2,+ modifiers = listOf(Modifier(id = 100, name = "Cheese", price = 100), Modifier(id = 101, name = "Bacon", price = 200))),+ ))+ val items = listOf(CartItem(menuItem = grouped, quantity = 1, selectedModifiers = listOf(SelectedModifier(1, 100, "Cheese", 100))))+ rule.setContent { CartScreen(items, {}, {}, { _, mods -> edited = mods }) }+ rule.onNodeWithText("1x Burger").assertExists()+ // Open the editor via the line's edit action, then save from the dialog.+ val clickables = rule.onAllNodes(hasClickAction()).fetchSemanticsNodes().size+ for (i in 0 until clickables) {+ runCatching { rule.onAllNodes(hasClickAction())[i].performSemanticsAction(SemanticsActions.OnClick) }+ if (try { rule.onNodeWithText("Extras").fetchSemanticsNode() != null } catch (_: AssertionError) { false }) break+ }+ awaitNode("Extras")+ rule.onNodeWithText("Save changes", substring = true)+ .performSemanticsAction(SemanticsActions.OnClick)+ rule.waitForIdle()+ assertTrue(edited != null, "modifier edit was never confirmed")+ }++ @Test fun addressDeleteRemovesFromStore() { runBlocking {+ AddressStore.save(ctx, SavedAddress(id = "a1", label = "Home", addressStreet = "1 Main", isDefault = true))+ AddressStore.save(ctx, SavedAddress(id = "a2", label = "Work", addressStreet = "2 Oak"))+ val scope = CoroutineScope(Dispatchers.Main)+ var latest: List<SavedAddress> = AddressStore.getAll(ctx)+ rule.setContent {+ AccountAddressesSection(scope, ctx, true, latest, { latest = it }, AddressFormState(), {}, {})+ }+ awaitNode("Work")+ // Click every clickable node (set-default, edit, delete are text-less or text buttons);+ // then poll the store until a2 is gone or the deadline passes.+ val deadline = System.currentTimeMillis() + 10_000+ var deleted = false+ while (System.currentTimeMillis() < deadline && !deleted) {+ val clickables = rule.onAllNodes(hasClickAction()).fetchSemanticsNodes().size+ for (i in 0 until clickables) {+ runCatching { rule.onAllNodes(hasClickAction())[i].performSemanticsAction(SemanticsActions.OnClick) }+ }+ org.robolectric.Shadows.shadowOf(android.os.Looper.getMainLooper()).idle()+ deleted = AddressStore.getAll(ctx).none { it.id == "a2" }+ if (!deleted) Thread.sleep(100)+ }+ assertTrue(deleted, "delete action never removed the address")+ } }++ @Test fun trackingArrivingWithFutureLiveEta() {+ installFake("""{"data":[{"id":9,"uuid":"u9","foodTotal":1000,"orderTotal":1500,"channel":"ORDER_CHANNEL_STOREFRONT_DELIVERY","driverReachedCustomerAt":"2024-01-01T00:20:00Z","liveDeliveryEta":"2099-01-01T00:00:00Z","courierName":"Sam","courierPhone":"5551234","merchant":{"id":1,"name":"Burger Barn"}}]}""")+ rule.setContent { OrderTrackingScreen(9) {} }+ awaitNode("Arriving Soon")+ awaitNode("Sam")+ }++ @Test fun trackingPreparingSoonWithFarDueDate() {+ installFake("""{"data":[{"id":9,"uuid":"u9","foodTotal":1000,"orderTotal":1500,"channel":"ORDER_CHANNEL_STOREFRONT_DELIVERY","dueAt":"2099-01-01T00:00:00Z","merchant":{"id":1,"name":"Burger Barn"}}]}""")+ rule.setContent { OrderTrackingScreen(9) {} }+ awaitNode("Preparing Soon")+ }++ @Test fun remoteImageFetcherSchemeGuards() { runBlocking {+ assertNull(RemoteImageFetchers.network(null, ctx))+ assertNull(RemoteImageFetchers.network(42, ctx))+ assertNull(RemoteImageFetchers.network("ftp://example.com/x.png", ctx))+ assertNull(RemoteImageFetchers.network(Uri.parse("file:///tmp/x.png"), ctx))+ // Loopback refusal is deterministic on any machine (no external network).+ val refused = runCatching { RemoteImageFetchers.network("http://127.0.0.1:9/x.png", ctx) }+ .exceptionOrNull()+ assertTrue(refused is java.io.IOException, "expected loopback refusal, got $refused")+ } }+}
fooddelivery/src/test/java/com/vayunmathur/fooddelivery/ui/FoodFlow6Test.kt
diff --git a/fooddelivery/src/test/java/com/vayunmathur/fooddelivery/ui/FoodFlow6Test.kt b/fooddelivery/src/test/java/com/vayunmathur/fooddelivery/ui/FoodFlow6Test.ktnew file mode 100644index 0000000000..aa93b22348--- /dev/null+++ b/fooddelivery/src/test/java/com/vayunmathur/fooddelivery/ui/FoodFlow6Test.kt@@ -0,0 +1,143 @@+package com.vayunmathur.fooddelivery.ui++import androidx.compose.runtime.getValue+import androidx.compose.runtime.setValue++import android.app.Application+import android.content.Context+import androidx.compose.ui.test.hasClickAction+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performSemanticsAction+import androidx.compose.ui.test.performTextInput+import androidx.compose.ui.semantics.SemanticsActions+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.fooddelivery.api.BitesAuth+import com.vayunmathur.fooddelivery.api.BitesCore+import com.vayunmathur.fooddelivery.data.AddressStore+import com.vayunmathur.fooddelivery.data.AuthToken+import com.vayunmathur.fooddelivery.data.SavedAddress+import com.vayunmathur.fooddelivery.platform.AppInit+import com.vayunmathur.library.network.SimpleResponse+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.runBlocking+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import kotlin.test.Test+import kotlin.test.assertTrue++/**+ * Sixth pass: order-item rendering, address edit/instructions, account+ * verification-email send, and a tracking ETA in minutes.+ */+@RunWith(RobolectricTestRunner::class)+@Config(application = Application::class)+class FoodFlow6Test {+ @get:Rule val rule = createComposeRule()+ private val ctx: Context get() = ApplicationProvider.getApplicationContext()+ private val realTransport = BitesCore.transport++ @org.junit.After fun restore() {+ BitesCore.transport = realTransport+ BitesAuth.clearToken()+ }++ private fun awaitNode(text: String, substring: Boolean = true) {+ val deadline = System.currentTimeMillis() + 15_000+ var found = false+ while (System.currentTimeMillis() < deadline) {+ rule.mainClock.autoAdvance = false+ rule.mainClock.advanceTimeBy(600L)+ rule.mainClock.autoAdvance = true+ org.robolectric.Shadows.shadowOf(android.os.Looper.getMainLooper()).idleFor(300, java.util.concurrent.TimeUnit.MILLISECONDS)+ rule.waitForIdle()+ found = try { rule.onNodeWithText(text, substring = substring).fetchSemanticsNode() != null } catch (_: AssertionError) { false }+ if (found) break+ Thread.sleep(50)+ }+ assertTrue(found, "node '$text' never appeared")+ }++ private fun installFake(ordersJson: String) {+ BitesCore.transport = { url, _, _, _ ->+ when {+ url.contains("/orders/past/all") -> SimpleResponse(200, "", ordersJson, emptyMap(), url)+ url.contains("/customers/me") -> SimpleResponse(200, "", """{"data":{"id":5,"firstName":"Ann","lastName":"Lee","email":"[email protected]","uuid":"cust-uuid"}}""", emptyMap(), url)+ url.contains("/auth/verify_phone") -> SimpleResponse(200, "", """{"state_id":"state-1"}""", emptyMap(), url)+ url.contains("/auth/token") -> SimpleResponse(200, "", """{"access_token":"acc2","refresh_token":"ref2","token_type":"Bearer","expires_in":3600}""", emptyMap(), url)+ url.contains("send-email-verification") -> SimpleResponse(200, "", "{}", emptyMap(), url)+ else -> SimpleResponse(404, "", "{}", emptyMap(), url)+ }+ }+ BitesAuth.setToken(AuthToken("acc", "ref", "Bearer", 3600))+ AppInit.start(ctx)+ }++ @Test fun ordersRenderItemsAndModifiers() {+ installFake("""{"data":[{"id":9,"uuid":"u9","foodTotal":1000,"orderTotal":1500,"channel":"ORDER_CHANNEL_STOREFRONT_DELIVERY","createdAt":"2024-01-01T12:00:00Z","deliveredAt":"2024-01-01T00:00:00Z","merchant":{"id":1,"name":"Burger Barn","imageUrl":"https://example.com/m.png"},"orderItems":[{"id":1,"name":"Burger","quantity":2,"price":999,"modifiers":[{"name":"Cheese","price":100,"quantity":1}]},{"id":2,"name":"Fries","quantity":1,"price":399}]}]}""")+ val fetched = kotlinx.coroutines.runBlocking { com.vayunmathur.fooddelivery.api.BitesOrders.getOrders() }+ assertTrue(fetched.size == 1, "orders fake did not decode: $fetched")+ rule.setContent { OrdersScreen {} }+ awaitNode("Burger Barn")+ rule.onNodeWithText("2x Burger", substring = true).assertExists()+ rule.onNodeWithText("Cheese", substring = true).assertExists()+ rule.onNodeWithText("Fries", substring = true).assertExists()+ }++ @Test fun trackingEtaMinutesFromLiveEta() {+ val eta = java.time.Instant.now().plusSeconds(30 * 60).toString()+ installFake("""{"data":[{"id":9,"uuid":"u9","foodTotal":1000,"orderTotal":1500,"channel":"ORDER_CHANNEL_STOREFRONT_DELIVERY","pickedupAt":"2024-01-01T00:20:00Z","liveDeliveryEta":"$eta","merchant":{"id":1,"name":"Burger Barn"}}]}""")+ rule.setContent { OrderTrackingScreen(9) {} }+ awaitNode("min", substring = true)+ }++ @Test fun addressEditPrefillsForm() { runBlocking {+ AddressStore.save(ctx, SavedAddress(id = "a1", label = "Home", addressStreet = "1 Main", addressCity = "Springfield", addressState = "CA", addressZip = "12345", aptUnit = "4B", gateCode = "999", deliveryInstructions = "Leave at door", isDefault = true))+ val scope = CoroutineScope(Dispatchers.Main)+ var latest: List<SavedAddress> = AddressStore.getAll(ctx)+ var form = AddressFormState()+ rule.setContent {+ var current by androidx.compose.runtime.remember { androidx.compose.runtime.mutableStateOf(form) }+ AccountAddressesSection(scope, ctx, true, latest, { latest = it }, current, { current = it; form = it }, { current = AddressFormState() })+ }+ awaitNode("Edit")+ rule.onNodeWithText("Edit", substring = true).performSemanticsAction(SemanticsActions.OnClick)+ awaitNode("Edit Address")+ assertEqualsStreet(form)+ } }++ private fun assertEqualsStreet(form: AddressFormState) {+ assertTrue(form.street == "1 Main" && form.editing?.id == "a1", "edit did not prefill the form: $form")+ }++ @Test fun addressPickerInstructionsInput() {+ var instructions: String? = null+ val home = SavedAddress(id = "a1", label = "Home", addressStreet = "1 Main", aptUnit = "4B", gateCode = "999", isDefault = true)+ rule.setContent {+ CheckoutAddressPicker(listOf(home), true, home, {}, "", { instructions = it })+ }+ rule.onNodeWithText("Delivery instructions", substring = true).performTextInput("Ring bell")+ assertTrue(instructions == "Ring bell", "instructions not captured: $instructions")+ }++ @Test fun accountSendVerificationEmailShowsNotice() {+ installFake("""{"data":[]}""")+ BitesAuth.clearToken() // start signed out; the flow below signs in+ // Sign in through the account binder (phone -> code -> profile).+ rule.setContent { AccountScreen() }+ awaitNode("Sign in to Food Delivery")+ rule.onNodeWithText("Phone number").performTextInput("5551234567")+ rule.onNodeWithText("Send Code").performSemanticsAction(SemanticsActions.OnClick)+ awaitNode("Verify")+ rule.onNodeWithText("Verification code").performTextInput("123456")+ rule.onNodeWithText("Verify").performSemanticsAction(SemanticsActions.OnClick)+ awaitNode("Ann Lee")+ awaitNode("Send verification email")+ rule.onNodeWithText("Send verification email")+ .performSemanticsAction(SemanticsActions.OnClick)+ awaitNode("Verification email sent", substring = true)+ }+}
fooddelivery/src/test/java/com/vayunmathur/fooddelivery/ui/FoodFlow7Test.kt
diff --git a/fooddelivery/src/test/java/com/vayunmathur/fooddelivery/ui/FoodFlow7Test.kt b/fooddelivery/src/test/java/com/vayunmathur/fooddelivery/ui/FoodFlow7Test.ktnew file mode 100644index 0000000000..9c39688bf6--- /dev/null+++ b/fooddelivery/src/test/java/com/vayunmathur/fooddelivery/ui/FoodFlow7Test.kt@@ -0,0 +1,93 @@+package com.vayunmathur.fooddelivery.ui++import android.app.Application+import android.content.Context+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performSemanticsAction+import androidx.compose.ui.test.performTextInput+import androidx.compose.ui.semantics.SemanticsActions+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.fooddelivery.api.BitesAuth+import com.vayunmathur.fooddelivery.api.BitesCore+import com.vayunmathur.fooddelivery.platform.AppInit+import com.vayunmathur.library.network.SimpleResponse+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import kotlin.test.Test+import kotlin.test.assertTrue++/**+ * Seventh pass: the restaurant loyalty join (invite code -> fake API ->+ * enrolled card), driven through the real binder with a stateful fake.+ */+@RunWith(RobolectricTestRunner::class)+@Config(application = Application::class)+class FoodFlow7Test {+ @get:Rule val rule = createComposeRule()+ private val ctx: Context get() = ApplicationProvider.getApplicationContext()+ private val realTransport = BitesCore.transport++ @org.junit.After fun restore() {+ BitesCore.transport = realTransport+ BitesAuth.clearToken()+ }++ private fun awaitNode(text: String, substring: Boolean = true) {+ val deadline = System.currentTimeMillis() + 15_000+ var found = false+ while (System.currentTimeMillis() < deadline) {+ rule.mainClock.autoAdvance = false+ rule.mainClock.advanceTimeBy(600L)+ rule.mainClock.autoAdvance = true+ org.robolectric.Shadows.shadowOf(android.os.Looper.getMainLooper()).idleFor(300, java.util.concurrent.TimeUnit.MILLISECONDS)+ rule.waitForIdle()+ found = try { rule.onNodeWithText(text, substring = substring).fetchSemanticsNode() != null } catch (_: AssertionError) { false }+ if (found) break+ Thread.sleep(50)+ }+ assertTrue(found, "node '$text' never appeared")+ }++ @Test fun restaurantJoinLoyaltyFlow() {+ var joined = false+ BitesCore.transport = { url, _, _, _ ->+ when {+ url.contains("merchantLoyaltyCode") -> { joined = true; SimpleResponse(200, "", "{}", emptyMap(), url) }+ url.contains("/customers/me/rewards") ->+ if (joined) SimpleResponse(200, "", """{"data":[{"merchantId":1,"balance":250}]}""", emptyMap(), url)+ else SimpleResponse(200, "", """{"data":[]}""", emptyMap(), url)+ url.contains("/merchants/1") -> SimpleResponse(200, "", """{"data":{"id":1,"name":"Burger Barn","categories":[{"id":1,"name":"Mains","itemIds":[10]}],"items":[{"id":10,"name":"Burger","price":999}]}}""", emptyMap(), url)+ else -> SimpleResponse(404, "", "{}", emptyMap(), url)+ }+ }+ AppInit.start(ctx)+ rule.setContent { RestaurantScreen(1, {}, {}) }+ awaitNode("Burger")+ rule.onNodeWithText("Invite code", substring = true).performTextInput("WELCOME")+ rule.onNodeWithText("Join", substring = true)+ .performSemanticsAction(SemanticsActions.OnClick)+ assertTrue(joined, "loyalty join never reached the fake API")+ }++ @Test fun restaurantLeaveLoyaltyFlow() {+ var left = false+ BitesCore.transport = { url, method, _, _ ->+ when {+ url.contains("/customers/me/rewards") -> SimpleResponse(200, "", """{"data":[{"merchantId":1,"balance":250}]}""", emptyMap(), url)+ url.contains("deleteCustomerMerchantLoyalty") -> { left = true; SimpleResponse(200, "", "{}", emptyMap(), url) }+ url.contains("/merchants/1") -> SimpleResponse(200, "", """{"data":{"id":1,"name":"Burger Barn","categories":[{"id":1,"name":"Mains","itemIds":[10]}],"items":[{"id":10,"name":"Burger","price":999}]}}""", emptyMap(), url)+ else -> SimpleResponse(404, "", "{}", emptyMap(), url)+ }+ }+ AppInit.start(ctx)+ rule.setContent { RestaurantScreen(1, {}, {}) }+ awaitNode("Leave", substring = true)+ rule.onNodeWithText("Leave", substring = true)+ .performSemanticsAction(SemanticsActions.OnClick)+ rule.waitForIdle()+ assertTrue(left, "loyalty leave never reached the fake API")+ }+}