fooddelivery: wave-3 coverage for models, API, main flow (#45)
- Commit
e57dc7ce80b332d8227e5eb54d18e2171cc65fa8- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-16 13:44 UTC (19 days ago)
- Parents
be51aa3
Wave 3 of the fooddelivery coverage push. Baseline merged JaCoCo INSTRUCTION coverage was 32,197 covered / 8,531 missed; the top uncovered classes were MainActivityKt (1,266 missed), the order tracking screen (969), RestaurantScreen (608), CheckoutScreen (476) and OrderLookupIntent (281, fully uncovered). New tests (45, no smoke filler, no @Ignore, no weakened assertions): - FoodWave3ModelsTest: CartItem totals with per-unit modifier quantities, Order component/display totals with missing fees, stage derivation from haversine driver distance (arriving vs driving), ETA as the later of live/due, DealProgress threshold/fraction edges, CustomerSavings fallback, checkout wire shape (encodeDefaults keeps isMobile/isPickup/tips, explicitNulls omits promo/schedule/drive-thru), CheckoutResponse serviceability shapes, serialization round-trips for the remaining models, and parseIsoMillis calendar/clock edges (leap years incl. 1900/2000, fractional truncation, and the documented java.time fallback tolerances for 24:00, a trailing fraction dot, and junk after the Z). - FoodWave3ApiTest: the remaining Bites* surface against a fake BitesCore.transport - merchant by-name/reporting, deals listing variants, customer/order mutation failure branches (5xx and IOException both degrade to false/null/empty), unwrap with and without the data envelope, auth headers with and without a token, encodeTokenForStorage expiry embedding, and the refresh rules (already-rotated token returned, no refresh token signs out, 408/429/503 are transient and neither retry nor sign out, malformed refresh body keeps the session). - FoodWave3ScreensTest: RestaurantContent search debounce and availability/inactive-category filtering, MenuItemRow DoorDash comparison variants, MerchantRewardsCard join (trimmed code) and leave, HomeContent merchant-card branches, DealsScreen progress/unlocked rendering and merchant-click rules, and all CheckoutTotals branches (fetching, no tax quote, rewards row, display/subtotal total fallbacks). - FoodWave3MainActivityTest: canAddFromSameMerchant and pushDetail rules, OrderLookupIntent nearest normalised-name matching with radius and failure degradation, and MainActivity launches for plain, restaurant deep-link, track-order and email-verification intents including malformed new-intents. - FoodWave3MainComposeTest: the real MainActivity composition - a walk across all five tabs, the cross-merchant pending-cart dialog replacing the seeded cart on confirm, the cart-to- checkout navigation entry, and the orders-to-tracking entry. Dead code: a caller scan of fooddelivery/src/main found no provably dead code (only framework entry points and DTOs used through serialization), so nothing was deleted. Coverage after: 35,883 covered / 4,845 missed INSTRUCTION, a gain of +3,686 covered instructions over baseline. Verified: - :fooddelivery:createMergedCoverageReport with the coverage ignore-failures init script, before and after. - :fooddelivery:testDevUnitTest :fooddelivery:detekt :fooddelivery:lint without the init script: BUILD SUCCESSFUL, no pre-existing failures.
Diff
fooddelivery/src/test/java/com/vayunmathur/fooddelivery/FoodWave3MainActivityTest.kt
diff --git a/fooddelivery/src/test/java/com/vayunmathur/fooddelivery/FoodWave3MainActivityTest.kt b/fooddelivery/src/test/java/com/vayunmathur/fooddelivery/FoodWave3MainActivityTest.ktnew file mode 100644index 0000000000..51c7d72933--- /dev/null+++ b/fooddelivery/src/test/java/com/vayunmathur/fooddelivery/FoodWave3MainActivityTest.kt@@ -0,0 +1,205 @@+package com.vayunmathur.fooddelivery++import android.app.Application+import android.content.Context+import android.content.Intent+import android.net.Uri+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.fooddelivery.api.BitesAuth+import com.vayunmathur.fooddelivery.api.BitesCore+import com.vayunmathur.fooddelivery.data.AuthToken+import com.vayunmathur.fooddelivery.data.CartItem+import com.vayunmathur.fooddelivery.data.MenuItem+import com.vayunmathur.fooddelivery.intents.OrderLookupIntent+import com.vayunmathur.fooddelivery.notifications.OrderLiveUpdate+import com.vayunmathur.fooddelivery.platform.AppInit+import com.vayunmathur.library.intents.fooddelivery.OrderLookupRequest+import com.vayunmathur.library.network.SimpleResponse+import com.vayunmathur.library.util.NavBackStack+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue+import kotlinx.coroutines.runBlocking+import org.junit.After+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import kotlin.test.Test++/** Wave-3: MainActivity routing helpers, deep-link intents, and order lookup. */+@RunWith(RobolectricTestRunner::class)+@Config(application = Application::class)+class FoodWave3MainActivityTest {++ private val ctx: Context get() = ApplicationProvider.getApplicationContext()+ private val realTransport = BitesCore.transport++ @After fun restore() {+ BitesCore.transport = realTransport+ BitesAuth.clearToken()+ }++ private fun installMerchants() {+ BitesCore.transport = { url, _, _, _ ->+ when {+ url.contains("/merchants/all/stores") -> SimpleResponse(+ 200, "",+ """{"data":{"merchants":[+ {"id":7,"name":"Joe's Cafe","latitude":37.0,"longitude":-122.0},+ {"id":8,"name":"Joes Cafe Express","latitude":37.01,"longitude":-122.0},+ {"id":9,"name":"Far Away Diner","latitude":38.0,"longitude":-122.0}+ ]}}""",+ emptyMap(), url,+ )+ url.contains("/orders/past/all") -> SimpleResponse(200, "", """{"data":[]}""", emptyMap(), url)+ url.contains("/merchants/") -> SimpleResponse(+ 200, "", """{"data":{"id":7,"name":"Joe's Cafe","items":[],"categories":[]}}""",+ emptyMap(), url,+ )+ url.contains("/customers/me/rewards") -> SimpleResponse(200, "", """{"data":[]}""", emptyMap(), url)+ url.contains("/customers/verify-email") -> SimpleResponse(200, "", "{}", emptyMap(), url)+ else -> SimpleResponse(404, "", "{}", emptyMap(), url)+ }+ }+ BitesAuth.setToken(AuthToken("acc", "ref", "Bearer", 3600))+ AppInit.start(ctx)+ }++ private fun idleLoops(times: Int = 8) {+ repeat(times) {+ org.robolectric.Shadows.shadowOf(android.os.Looper.getMainLooper())+ .idleFor(300, java.util.concurrent.TimeUnit.MILLISECONDS)+ Thread.sleep(20)+ }+ }++ @Test fun canAddFromSameMerchantRules() {+ val burger = MenuItem(id = 1, name = "Burger", price = 100)+ fun line(merchant: Int) = CartItem(menuItem = burger, merchantId = merchant)+ assertTrue(emptyList<CartItem>().canAddFromSameMerchant(line(7)))+ assertTrue(listOf(line(0)).canAddFromSameMerchant(line(7)))+ assertTrue(listOf(line(7)).canAddFromSameMerchant(line(0)))+ assertTrue(listOf(line(7)).canAddFromSameMerchant(line(7)))+ assertFalse(listOf(line(7)).canAddFromSameMerchant(line(8)))+ }++ @Test fun pushDetailReplacesSameClassOnly() {+ val stack = NavBackStack(arrayOf<Route>(Route.Main()))+ with(stack) { pushDetail(Route.Restaurant(1)) }+ assertEquals(2, stack.backStack.size)+ // A second restaurant replaces the first instead of stacking.+ with(stack) { pushDetail(Route.Restaurant(2)) }+ assertEquals(2, stack.backStack.size)+ assertEquals(2, (stack.last() as Route.Restaurant).id)+ // A different destination class stacks normally.+ with(stack) { pushDetail(Route.OrderTracking(9)) }+ assertEquals(3, stack.backStack.size)+ with(stack) { pushDetail(Route.OrderTracking(10)) }+ assertEquals(3, stack.backStack.size)+ assertEquals(10, (stack.last() as Route.OrderTracking).orderId)+ // Checkout is an object destination; pushing it after tracking stacks.+ with(stack) { pushDetail(Route.Checkout) }+ assertEquals(4, stack.backStack.size)+ }++ @Test fun orderLookupMatchesNearestNormalisedName() { runBlocking {+ installMerchants()+ val intent = Robolectric.buildActivity(OrderLookupIntent::class.java).create().get()+ // "JOE'S CAFE!!" normalises to "joescafe": exact match wins over the+ // farther prefix match, and the far diner is outside the radius anyway.+ val hit = intent.performCalculation(OrderLookupRequest(name = "JOE'S CAFE!!", lat = 37.0, lng = -122.0))+ assertTrue(hit.available)+ assertEquals(7, hit.merchantId)+ assertEquals("fooddelivery://restaurant/7", hit.deepLink)+ // Containment in the other direction also matches.+ val contained = intent.performCalculation(OrderLookupRequest(name = "Cafe", lat = 37.0, lng = -122.0))+ assertTrue(contained.available)+ // Unknown name and blank name are not orderable.+ val miss = intent.performCalculation(OrderLookupRequest(name = "Sushi Place", lat = 37.0, lng = -122.0))+ assertFalse(miss.available)+ assertEquals(0, miss.merchantId)+ assertEquals("", miss.deepLink)+ val blank = intent.performCalculation(OrderLookupRequest(name = " ", lat = 37.0, lng = -122.0))+ assertFalse(blank.available)+ // A query a degree away matches nothing within 800 m.+ val far = intent.performCalculation(OrderLookupRequest(name = "Joe's Cafe", lat = 39.0, lng = -122.0))+ assertFalse(far.available)+ } }++ @Test fun orderLookupDegradesWhenCatalogFails() { runBlocking {+ BitesCore.transport = { _, _, _, _ -> throw java.io.IOException("down") }+ AppInit.start(ctx)+ val intent = Robolectric.buildActivity(OrderLookupIntent::class.java).create().get()+ val result = intent.performCalculation(OrderLookupRequest(name = "Joe's Cafe", lat = 37.0, lng = -122.0))+ assertFalse(result.available)+ assertEquals(0, result.merchantId)+ } }++ @Test fun mainActivityPlainLaunchComposesTabs() {+ installMerchants()+ val controller = Robolectric.buildActivity(MainActivity::class.java, Intent(ctx, MainActivity::class.java))+ .create().start().resume()+ idleLoops()+ assertFalse(controller.get().isFinishing)+ controller.pause().stop().destroy()+ }++ @Test fun mainActivityRestaurantDeepLinkLaunch() {+ installMerchants()+ val intent = Intent(ctx, MainActivity::class.java).apply {+ data = Uri.parse("fooddelivery://restaurant/7")+ }+ val controller = Robolectric.buildActivity(MainActivity::class.java, intent).create().start().resume()+ idleLoops()+ assertFalse(controller.get().isFinishing)+ controller.pause().stop().destroy()+ }++ @Test fun mainActivityTrackOrderLaunch() {+ installMerchants()+ val intent = Intent(ctx, MainActivity::class.java).apply {+ putExtra(OrderLiveUpdate.EXTRA_TRACK_ORDER_ID, 9)+ }+ val controller = Robolectric.buildActivity(MainActivity::class.java, intent).create().start().resume()+ idleLoops()+ assertFalse(controller.get().isFinishing)+ controller.pause().stop().destroy()+ }++ @Test fun mainActivityEmailVerificationLaunchesAndNewIntents() {+ installMerchants()+ val intent = Intent(ctx, MainActivity::class.java).apply {+ data = Uri.parse("https://withbites.com/email-verification/cust-1/tok_ABC-123")+ }+ val controller = Robolectric.buildActivity(MainActivity::class.java, intent).create().start().resume()+ idleLoops()+ val activity = controller.get()+ // New intents: valid storefront form, then every malformed shape, which+ // must be ignored rather than crash or re-route.+ controller.newIntent(Intent(ctx, MainActivity::class.java).apply {+ data = Uri.parse("com.deliverycollective.storefront://email-verification/cust2/tok2")+ })+ controller.newIntent(Intent(ctx, MainActivity::class.java).apply {+ data = Uri.parse("https://withbites.com/email-verification/only-one")+ })+ controller.newIntent(Intent(ctx, MainActivity::class.java).apply {+ data = Uri.parse("https://withbites.com/email-verification/bad%20seg/tok")+ })+ controller.newIntent(Intent(ctx, MainActivity::class.java).apply {+ data = Uri.parse("fooddelivery://restaurant/0")+ })+ controller.newIntent(Intent(ctx, MainActivity::class.java).apply {+ data = Uri.parse("fooddelivery://other/7")+ })+ controller.newIntent(Intent(ctx, MainActivity::class.java).apply {+ data = Uri.parse("other://restaurant/7")+ })+ controller.newIntent(Intent(ctx, MainActivity::class.java).apply {+ putExtra(OrderLiveUpdate.EXTRA_TRACK_ORDER_ID, -5)+ })+ idleLoops()+ assertFalse(activity.isFinishing)+ controller.pause().stop().destroy()+ }+}
fooddelivery/src/test/java/com/vayunmathur/fooddelivery/api/FoodWave3ApiTest.kt
diff --git a/fooddelivery/src/test/java/com/vayunmathur/fooddelivery/api/FoodWave3ApiTest.kt b/fooddelivery/src/test/java/com/vayunmathur/fooddelivery/api/FoodWave3ApiTest.ktnew file mode 100644index 0000000000..92170b4422--- /dev/null+++ b/fooddelivery/src/test/java/com/vayunmathur/fooddelivery/api/FoodWave3ApiTest.kt@@ -0,0 +1,262 @@+package com.vayunmathur.fooddelivery.api++import android.app.Application+import com.vayunmathur.fooddelivery.data.AuthToken+import com.vayunmathur.fooddelivery.data.CheckoutCartItem+import com.vayunmathur.fooddelivery.data.CheckoutRequest+import com.vayunmathur.fooddelivery.data.Customer+import com.vayunmathur.fooddelivery.data.FeedbackRequest+import com.vayunmathur.library.network.SimpleResponse+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue+import kotlinx.coroutines.runBlocking+import org.junit.After+import org.junit.Before+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import kotlin.test.Test++/** Wave-3: remaining Bites* endpoints, failure branches, and refresh-token rules. */+@RunWith(RobolectricTestRunner::class)+@Config(application = Application::class)+class FoodWave3ApiTest {++ data class Recorded(val url: String, val method: String, val headers: Map<String, String>, val body: String?)++ private val recorded = mutableListOf<Recorded>()+ private var handler: (Recorded) -> SimpleResponse = { resp(404, "{}") }+ private val realTransport = BitesCore.transport++ private fun resp(status: Int, body: String, url: String = "") =+ SimpleResponse(status, "", body, emptyMap(), url)++ private fun on(match: String, status: Int, body: String) {+ val previous = handler+ handler = { req -> if (req.url.contains(match)) resp(status, body, req.url) else previous(req) }+ }++ @Before fun installFake() {+ recorded.clear()+ handler = { resp(404, "{}") }+ BitesCore.transport = { url, method, headers, body ->+ val req = Recorded(url, method, headers, body)+ recorded += req+ handler(req)+ }+ BitesAuth.onTokenUpdated = null+ BitesAuth.onTokenCleared = null+ BitesAuth.clearToken()+ }++ @After fun restore() {+ BitesCore.transport = realTransport+ BitesAuth.clearToken()+ }++ private fun lastRequest(match: String): Recorded = recorded.last { it.url.contains(match) }++ @Test fun merchantByNameReportingAndNoParamsUrl() { runBlocking {+ on("/merchants/storefront/", 200, """{"data":{"id":8,"name":"Alias Place"}}""")+ on("/merchants/reporting/", 200, "csv-report")+ assertEquals("Alias Place", BitesMerchants.getMerchantByName("alias-place")!!.name)+ assertEquals("csv-report", BitesMerchants.getMerchantReporting(8))+ BitesCore.transport = { url, _, _, _ -> resp(404, "{}", url) }+ assertNull(BitesMerchants.getMerchantReporting(8))+ BitesCore.transport = { _, _, _, _ -> throw java.io.IOException("down") }+ assertNull(BitesMerchants.getMerchantReporting(8))+ assertNull(BitesMerchants.getMerchantByName("x"))+ // No coordinates: the merchants URL carries no query string at all.+ BitesCore.transport = { url, method, headers, body ->+ recorded += Recorded(url, method, headers, body)+ resp(200, """{"data":{"merchants":[]}}""", url)+ }+ assertTrue(BitesMerchants.getMerchants().isEmpty())+ assertFalse(lastRequest("/merchants/all/stores").url.contains("?"))+ assertTrue(lastRequest("/merchants/all/stores").url.contains("/merchants/all/stores"))+ } }++ @Test fun dealsListingVariantsAndFailures() { runBlocking {+ // Generic registrations first: later `on` handlers are checked first.+ on("/deals", 200, """{"data":[{"id":4,"title":"Every"}]}""")+ on("/deals/merchant/7", 200, """{"data":[{"id":3,"title":"All"}]}""")+ on("/deals/merchant/7/active", 200, """{"data":[{"id":2,"title":"Active"}]}""")+ on("/deals/active", 200, """{"data":[{"id":1,"title":"Near"}]}""")+ val near = BitesDeals.getDeals(lat = 1.5, lng = 2.5)+ assertEquals("Near", near.single().title)+ assertTrue(lastRequest("/deals/active").url.contains("lat=1.5"))+ assertTrue(lastRequest("/deals/active").url.contains("lng=2.5"))+ assertTrue(lastRequest("/deals/active").url.contains("radius=8"))+ assertEquals("Active", BitesDeals.getActiveDealsByMerchant(7).single().title)+ assertEquals("All", BitesDeals.getDealsByMerchant(7).single().title)+ assertEquals("Every", BitesDeals.getAllDeals().single().title)+ BitesCore.transport = { _, _, _, _ -> throw java.io.IOException("down") }+ assertTrue(BitesDeals.getDeals().isEmpty())+ assertNull(BitesDeals.getDealProgress(1))+ BitesCore.transport = { url, _, _, _ -> resp(500, "boom", url) }+ assertTrue(BitesDeals.getAllDeals().isEmpty())+ assertNull(BitesDeals.getDealById(4))+ } }++ @Test fun customerReadAndMutationFailureBranches() { runBlocking {+ on("/customers/getReferrals", 200, """{"data":[{"id":1,"code":"REF1","referredById":5}]}""")+ on("/orders/me/savings", 500, "boom")+ assertEquals("REF1", BitesCustomers.getReferrals().single().code)+ assertNull(BitesCustomers.getCustomerSavings())+ // Every one-shot mutation maps a server failure to false, not an exception.+ BitesCore.transport = { url, _, _, _ -> resp(500, "boom", url) }+ assertNull(BitesCustomers.createOrUpdateCustomer(Customer(id = 1)))+ assertFalse(BitesCustomers.deleteCustomer())+ assertFalse(BitesCustomers.registerPushNotification("t", "u"))+ assertFalse(BitesCustomers.createReferral("u", 1))+ assertFalse(BitesCustomers.sendEmailVerification("[email protected]"))+ assertFalse(BitesCustomers.verifyEmailToken("c", "t"))+ assertFalse(BitesCustomers.createCustomerMerchantLoyalty("CODE", 1))+ assertFalse(BitesCustomers.deleteCustomerMerchantLoyalty(1))+ // And a transport failure takes the same path.+ BitesCore.transport = { _, _, _, _ -> throw java.io.IOException("down") }+ assertFalse(BitesCustomers.deleteCustomer())+ assertFalse(BitesCustomers.registerPushNotification("t", "u"))+ assertFalse(BitesCustomers.createReferral("u", 1))+ assertFalse(BitesCustomers.sendEmailVerification("[email protected]"))+ assertFalse(BitesCustomers.verifyEmailToken("c", "t"))+ assertFalse(BitesCustomers.createCustomerMerchantLoyalty("CODE", 1))+ assertFalse(BitesCustomers.deleteCustomerMerchantLoyalty(1))+ assertNull(BitesCustomers.getCustomer())+ assertNull(BitesCustomers.createOrUpdateCustomer(Customer(id = 1)))+ assertTrue(BitesCustomers.getReferrals().isEmpty())+ } }++ @Test fun orderReadAndMutationFailureBranches() { runBlocking {+ on("/orders/9/feedback", 200, """{"data":{"id":3,"orderId":9,"rating":4,"tips":100}}""")+ on("/merchants/7/checkout", 200, """{"data":{"clientSecret":"secret-1","order":{"id":11,"foodTotal":1000},"serviceable":{"ok":true}}}""")+ val feedback = BitesOrders.getFeedback("9")+ assertEquals(4, feedback!!.rating)+ val checkout = BitesOrders.checkout(+ 7,+ CheckoutRequest(+ cartItems = listOf(CheckoutCartItem(itemId = 1, quantity = 1)),+ tips = 300, promoCode = "SAVE",+ ),+ )+ assertEquals("secret-1", checkout!!.clientSecret)+ assertEquals(11, checkout.order!!.id)+ assertTrue(checkout.isServiceable)+ assertTrue(lastRequest("/checkout").body!!.contains("SAVE"))+ // Failures degrade to null/false/empty.+ BitesCore.transport = { url, _, _, _ -> resp(500, "boom", url) }+ assertNull(BitesOrders.getOrderByEmail("tok"))+ assertNull(BitesOrders.getOrderRewards("u9"))+ assertFalse(BitesOrders.pickUpOrder("u9"))+ assertFalse(BitesOrders.submitFeedback("u9", FeedbackRequest(orderId = 9, rating = 5)))+ assertNull(BitesOrders.checkout(7, CheckoutRequest(cartItems = emptyList())))+ assertNull(BitesOrders.getFeedback("9"))+ BitesCore.transport = { _, _, _, _ -> throw java.io.IOException("down") }+ assertNull(BitesOrders.getOrderByEmail("tok"))+ assertNull(BitesOrders.getOrderRewards("u9"))+ assertFalse(BitesOrders.pickUpOrder("u9"))+ assertFalse(BitesOrders.submitFeedback("u9", FeedbackRequest(orderId = 9)))+ assertNull(BitesOrders.checkout(7, CheckoutRequest(cartItems = emptyList())))+ assertTrue(BitesOrders.getOrders().isEmpty())+ BitesCore.transport = { url, _, _, _ -> resp(200, "not json", url) }+ assertTrue(BitesOrders.getOrders().isEmpty())+ assertNull(BitesRewards.getPlatformSavings())+ } }++ @Test fun rewardsFailureBranches() { runBlocking {+ BitesCore.transport = { _, _, _, _ -> throw java.io.IOException("down") }+ assertTrue(BitesRewards.getRewards().isEmpty())+ assertTrue(BitesRewards.getCustomerMerchantRewards().isEmpty())+ assertNull(BitesRewards.getPlatformSavings())+ BitesCore.transport = { url, _, _, _ -> resp(500, "boom", url) }+ assertTrue(BitesRewards.getRewards().isEmpty())+ } }++ @Test fun coreUnwrapHeadersAndTokenStorage() { runBlocking {+ // unwrap falls back to the root object when there is no data envelope.+ val direct = BitesCore.unwrap("""{"id":5,"firstName":"Solo"}""", Customer.serializer())+ assertEquals("Solo", direct!!.firstName)+ val enveloped = BitesCore.unwrap("""{"message":"ok","data":{"id":6}}""", Customer.serializer())+ assertEquals(6, enveloped!!.id)+ // No stored token: headers carry no Authorization entry.+ val anon = BitesCore.authHeaders()+ assertFalse(anon.containsKey("Authorization"))+ assertEquals("application/json", anon["Content-Type"])+ // A fresh (unexpired) token is returned without any refresh traffic.+ BitesAuth.setToken(AuthToken("fresh-acc", "ref", "Bearer", 3600))+ recorded.clear()+ assertEquals("fresh-acc", BitesCore.getAccessToken())+ assertTrue(recorded.isEmpty())+ assertEquals("Bearer fresh-acc", BitesCore.authHeaders()["Authorization"])+ // encodeTokenForStorage embeds the absolute expiry alongside the token fields.+ val stored = BitesCore.encodeTokenForStorage(AuthToken("acc", "ref", "Bearer", 60), 123456L)+ assertTrue(stored.contains("\"access_token\":\"acc\""), stored)+ assertTrue(stored.contains("\"expires_at_ms\":123456"), stored)+ // Restoring a payload without the expiry key leaves the expiry unknown (0).+ BitesAuth.restoreToken("""{"access_token":"zz","refresh_token":"rr"}""")+ assertEquals("zz", BitesCore.storedToken!!.accessToken)+ assertEquals(0L, BitesCore.expiresAtMs)+ // setToken(null) clears the in-memory token without firing the update callback.+ var updates = 0+ BitesAuth.onTokenUpdated = { updates++ }+ BitesAuth.setToken(null)+ assertFalse(BitesAuth.isLoggedIn())+ assertEquals(0, updates)+ } }++ @Test fun refreshRotationAndSignOutRules() { runBlocking {+ // A caller holding a stale token gets the already-rotated current token.+ BitesAuth.setToken(AuthToken("current-acc", "ref-cur", "Bearer", 3600))+ val rotated = BitesCore.refreshToken(AuthToken("stale-acc", "ref-old", "Bearer", 3600))+ assertEquals("current-acc", rotated!!.accessToken)+ // No refresh token at all: refresh signs the user out.+ BitesAuth.setToken(AuthToken("solo-acc", "", "Bearer", 3600))+ BitesCore.expiresAtMs = System.currentTimeMillis() + 3600_000+ assertNull(BitesCore.refreshToken(AuthToken("solo-acc", "", "Bearer", 3600)))+ assertFalse(BitesAuth.isLoggedIn())+ // Timeout (408) and rate-limit (429) rejections are transient: session kept.+ for (status in listOf(408, 429, 503)) {+ BitesAuth.setToken(AuthToken("old-acc", "ref-1", "Bearer", 3600))+ BitesCore.expiresAtMs = 1+ var dataCalls = 0+ BitesCore.transport = { url, _, _, _ ->+ when {+ url.contains("/auth/token") -> resp(status, "{}", url)+ else -> { dataCalls++; resp(401, "{}", url) }+ }+ }+ assertNull(BitesMerchants.getMerchantDetail(5))+ assertEquals(1, dataCalls, "status $status must not retry after transient refresh failure")+ assertTrue(BitesAuth.isLoggedIn(), "status $status must keep the session")+ }+ // A malformed refresh success body is a failure, not a sign-out.+ BitesAuth.setToken(AuthToken("old-acc", "ref-1", "Bearer", 3600))+ BitesCore.expiresAtMs = 1+ BitesCore.transport = { url, _, _, _ ->+ if (url.contains("/auth/token")) resp(200, "not json", url) else resp(401, "{}", url)+ }+ assertNull(BitesMerchants.getMerchantDetail(5))+ assertTrue(BitesAuth.isLoggedIn())+ } }++ @Test fun authPhoneStateIdVariantsAndFailures() { runBlocking {+ on("/auth/verify_phone", 200, """{"stateId":"camel-7"}""")+ assertEquals("camel-7", BitesAuth.verifyPhone("555 0100"))+ assertTrue(lastRequest("/auth/verify_phone").body!!.contains("+5550100"))+ // A non-object success body yields no state id.+ BitesCore.transport = { url, _, _, _ -> resp(200, """["x"]""", url) }+ assertNull(BitesAuth.verifyPhone("555"))+ BitesCore.transport = { _, _, _, _ -> throw java.io.IOException("down") }+ assertNull(BitesAuth.verifyPhone("555"))+ assertNull(BitesAuth.exchangeOtpCodeForToken("s", "123456"))+ // expiresIn=0 leaves a previously recorded expiry untouched.+ BitesAuth.setToken(AuthToken("acc", "ref", "Bearer", 3600))+ val expiry = BitesCore.expiresAtMs+ assertTrue(expiry > 0)+ BitesAuth.setToken(AuthToken("acc2", "ref2", "Bearer", 0))+ assertEquals(expiry, BitesCore.expiresAtMs)+ assertEquals("acc2", BitesCore.storedToken!!.accessToken)+ } }+}
fooddelivery/src/test/java/com/vayunmathur/fooddelivery/data/FoodWave3ModelsTest.kt
diff --git a/fooddelivery/src/test/java/com/vayunmathur/fooddelivery/data/FoodWave3ModelsTest.kt b/fooddelivery/src/test/java/com/vayunmathur/fooddelivery/data/FoodWave3ModelsTest.ktnew file mode 100644index 0000000000..1e1a705da6--- /dev/null+++ b/fooddelivery/src/test/java/com/vayunmathur/fooddelivery/data/FoodWave3ModelsTest.kt@@ -0,0 +1,267 @@+package com.vayunmathur.fooddelivery.data++import com.vayunmathur.fooddelivery.api.BitesCore+import kotlinx.serialization.builtins.serializer+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNotEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue+import kotlinx.serialization.json.JsonObject+import kotlinx.serialization.json.JsonPrimitive++/** Wave-3: model derived values, ISO parsing edges, and checkout wire shape. */+class FoodWave3ModelsTest {++ @Test fun merchantAddressAndImageFallbackBranches() {+ assertEquals("1 Main", Merchant(addressStreet = "1 Main").address)+ assertEquals(", Springfield", Merchant(addressCity = "Springfield").address)+ assertEquals("1 Main, IL", Merchant(addressStreet = "1 Main", addressState = "IL").address)+ val noBrand = Merchant(imageUrl = "", logoUrl = "")+ assertEquals("", noBrand.displayImage)+ assertEquals("", noBrand.displayLogo)+ val own = Merchant(+ imageUrl = "own-img", logoUrl = "own-logo",+ brand = Brand(logoUrl = "brand-logo", imageUrl = "brand-img"),+ averageRating = 4.5, totalRatings = 12, rewardsPercentage = 5.0,+ )+ assertEquals("own-img", own.displayImage)+ assertEquals("own-logo", own.displayLogo)+ assertEquals(4.5, own.displayRating)+ assertEquals(12, own.displayTotalRatings)+ assertEquals(5.0, own.displayRewardsPercentage)+ }++ @Test fun menuAndModifierPriceConversions() {+ assertEquals("thumb", MenuItem(imageUrl = null, thumbnailUrl = "thumb").displayImage)+ assertEquals("img", MenuItem(imageUrl = "img", thumbnailUrl = "thumb").displayImage)+ assertEquals("", MenuItem().displayImage)+ assertNull(MenuItem().doordashPriceDollars)+ assertEquals(12.5, MenuItem(doordashPrice = 1250).doordashPriceDollars)+ assertEquals(9.99, MenuItem(price = 999).priceDollars)+ assertEquals(2.5, MerchantItem(price = 250).priceDollars)+ assertEquals(1.25, Modifier(price = 125).priceDollars)+ assertEquals(3.0, Deal(discountAmount = 300).discountAmountDollars)+ assertEquals(0.75, SelectedModifier(price = 75).priceDollars)+ assertEquals(4.2, OrderItem(price = 420).priceDollars)+ }++ @Test fun dealProgressThresholdEdges() {+ val p = DealProgress(ordersCount = 3, isComplete = false)+ assertTrue(p.isUnlocked(3))+ assertTrue(p.isUnlocked(2))+ assertFalse(p.isUnlocked(4))+ assertFalse(DealProgress(ordersCount = 9).isUnlocked(0))+ assertTrue(DealProgress(ordersCount = 0, isComplete = true).isUnlocked(0))+ assertEquals(0, p.remaining(2))+ assertEquals(2, p.remaining(5))+ assertEquals(0f, p.fraction(0))+ assertEquals(0f, p.fraction(-1))+ assertEquals(1f, DealProgress(ordersCount = 9).fraction(3))+ assertEquals(0.5f, DealProgress(ordersCount = 1).fraction(2))+ }++ @Test fun customerAndSavingsDisplayValues() {+ assertEquals("Ann", Customer(firstName = "Ann").displayName)+ assertEquals("Lee", Customer(lastName = "Lee").displayName)+ assertEquals("", Customer().displayName)+ assertEquals(12.34, Customer(totalCustomerSavings = 1234).savingsDollars)+ // customerSavings wins; the legacy total is only a fallback when it is zero.+ assertEquals(5.0, CustomerSavings(customerSavings = 500, totalCustomerSavings = 999).customerSavingsDollars)+ assertEquals(9.99, CustomerSavings(customerSavings = 0, totalCustomerSavings = 999).customerSavingsDollars)+ assertEquals(0.0, CustomerSavings().customerSavingsDollars)+ assertEquals(1.5, PlatformSavings(totalCustomerSavings = 150).customerSavingsDollars)+ assertEquals(2.5, MerchantRewards(balance = 250).balanceDollars)+ }++ @Test fun orderComponentTotalsWithMissingFees() {+ val o = Order(foodTotal = 1000, deliveryFee = 200, fees = null, taxes = 80, tips = 100)+ assertEquals(13.8, o.componentTotal)+ assertEquals(13.8, o.displayTotal)+ assertEquals(10.0, o.foodTotalDollars)+ assertEquals(0.8, o.taxesDollars)+ assertEquals(1.0, o.tipsDollars)+ assertEquals(2.0, o.deliveryFeeDollars)+ assertFalse(o.isDone)+ // Pickup completion is driven by pickedupAt, delivery by deliveredAt.+ assertFalse(Order(channel = "P", deliveredAt = "2024-01-01T00:00:00Z").isDone)+ assertFalse(Order(+ channel = "ORDER_CHANNEL_STOREFRONT_DELIVERY",+ pickedupAt = "2024-01-01T00:00:00Z",+ ).isDone)+ }++ @Test fun orderStageFromDriverDistance() {+ val dest = OrderAddress(latitude = 40.0, longitude = -73.0)+ val far = Order(+ channel = "ORDER_CHANNEL_STOREFRONT_DELIVERY", address = dest,+ driverLocations = listOf(DriverLocation(latitude = 41.0, longitude = -73.0)),+ )+ val dist = far.driverDistanceMiles!!+ assertTrue(dist > 60.0, "one degree of latitude should be ~69 miles, was $dist")+ assertEquals(OrderStage.DRIVING, far.stage)+ // The last usable fix wins; trailing fixes without coordinates are skipped.+ val mixed = Order(+ channel = "ORDER_CHANNEL_STOREFRONT_DELIVERY", address = dest,+ driverLocations = listOf(+ DriverLocation(latitude = 41.0, longitude = -73.0),+ DriverLocation(latitude = 40.0, longitude = -73.0),+ DriverLocation(latitude = null, longitude = null),+ ),+ )+ assertEquals(40.0, mixed.driverPosition?.latitude)+ assertEquals(0.0, mixed.driverDistanceMiles!!, 0.001)+ assertEquals(OrderStage.ARRIVING, mixed.stage)+ // Missing either endpoint means no distance and no proximity stage.+ assertNull(Order(driverLocations = listOf(DriverLocation(1.0, 2.0))).driverDistanceMiles)+ assertNull(Order(address = OrderAddress()).driverDistanceMiles)+ assertNull(Order(+ address = OrderAddress(latitude = null, longitude = -73.0),+ driverLocations = listOf(DriverLocation(40.0, -73.0)),+ ).driverDistanceMiles)+ }++ @Test fun orderEtaCombinations() {+ val past = "2024-01-01T00:00:00Z"+ val future = "2999-01-01T00:00:00Z"+ assertEquals(parseIsoMillis(past), Order(liveDeliveryEta = past).etaMillis)+ assertEquals(parseIsoMillis(future), Order(dueAt = future).etaMillis)+ assertEquals(parseIsoMillis(future), Order(liveDeliveryEta = past, dueAt = future).etaMillis)+ assertEquals(parseIsoMillis(future), Order(liveDeliveryEta = future, dueAt = past).etaMillis)+ assertNull(Order(liveDeliveryEta = "junk", dueAt = "junk").etaMillis)+ // Delivered beats every other signal.+ assertEquals(OrderStage.DELIVERED, Order(+ deliveredAt = past, driverReachedCustomerAt = past,+ channel = "ORDER_CHANNEL_STOREFRONT_DELIVERY",+ ).stage)+ assertEquals("Arriving Soon", OrderStage.ARRIVING.label)+ assertEquals("Driving to you", OrderStage.DRIVING.label)+ assertEquals("Ready for Pickup", OrderStage.READY.label)+ assertEquals("Preparing Soon", OrderStage.PREPARING_SOON.label)+ assertEquals("Preparing", OrderStage.PREPARING.label)+ }++ @Test fun cartLineTotalsWithNestedModifierQuantities() {+ val item = MenuItem(id = 1, price = 500)+ val cart = CartItem(+ menuItem = item, quantity = 3,+ selectedModifiers = listOf(+ SelectedModifier(name = "Extra", price = 100, quantity = 2),+ SelectedModifier(name = "Free", price = 0, quantity = 5),+ ),+ )+ // (500 + 100*2 + 0*5) * 3 / 100 = 21.0+ assertEquals(21.0, cart.totalPrice)+ assertEquals(0.0, CartItem(menuItem = item, quantity = 0).totalPrice)+ assertNotEquals(cart.lineId, CartItem(menuItem = item).lineId)+ assertEquals("line-x", cart.copy(lineId = "line-x").lineId)+ }++ @Test fun checkoutResponseServiceabilityShape() {+ assertFalse(CheckoutResponse().isServiceable)+ assertFalse(CheckoutResponse(serviceable = JsonPrimitive(true)).isServiceable)+ assertFalse(CheckoutResponse(serviceable = JsonPrimitive("yes")).isServiceable)+ assertTrue(CheckoutResponse(serviceable = JsonObject(emptyMap())).isServiceable)+ assertTrue(CheckoutResponse(+ serviceable = kotlinx.serialization.json.JsonArray(emptyList()),+ ).isServiceable)+ }++ @Test fun checkoutRequestWireShapeKeepsDefaultsAndOmitsNulls() {+ val req = CheckoutRequest(+ cartItems = listOf(CheckoutCartItem(itemId = 7, quantity = 2)),+ tips = 0,+ )+ val encoded = BitesCore.json.encodeToString(CheckoutRequest.serializer(), req)+ // encodeDefaults: the reference always sends these flags, even at defaults.+ assertTrue(encoded.contains("\"isMobile\":true"), encoded)+ assertTrue(encoded.contains("\"isPickup\":false"), encoded)+ assertTrue(encoded.contains("\"tips\":0"), encoded)+ // explicitNulls=false: unset optional fields stay off the wire.+ assertFalse(encoded.contains("promoCode"), encoded)+ assertFalse(encoded.contains("scheduledDate"), encoded)+ assertFalse(encoded.contains("isDriveThru"), encoded)+ val decoded = BitesCore.json.decodeFromString<CheckoutRequest>(encoded)+ assertEquals(req, decoded)+ assertEquals(7, decoded.cartItems.single().itemId)+ }++ @Test fun serializationRoundTripsForRemainingModels() {+ val json = BitesCore.json+ val feedback = Feedback(id = 1, orderId = 9, rating = 5, feedback = "great", tips = 200, createdAt = "2024-01-01T00:00:00Z")+ assertEquals(feedback, json.decodeFromString<Feedback>(json.encodeToString(Feedback.serializer(), feedback)))+ assertNotEquals(feedback, feedback.copy(rating = 1))+ val promo = Promotion(id = 2, name = "BOGO", description = "buy one get one")+ assertEquals(promo, json.decodeFromString<Promotion>(json.encodeToString(Promotion.serializer(), promo)))+ val rewards = MerchantRewards(+ merchantId = 7, balance = 250,+ expiryBatches = listOf(RewardExpiryBatch(amount = 100, date = "2025-01-01")),+ merchant = RewardMerchant(name = "Greens", logoUrl = "logo", addressCity = "Springfield"),+ )+ val rewardsBack = json.decodeFromString<MerchantRewards>(json.encodeToString(MerchantRewards.serializer(), rewards))+ assertEquals(rewards, rewardsBack)+ assertEquals("Greens", rewardsBack.merchant?.name)+ assertEquals(100, rewardsBack.expiryBatches.single().amount)+ val referral = Referral(id = 3, referredById = 5, uuid = "u", orderId = 9, code = "ABC", status = "ACTIVE", createdAt = "2024-01-01T00:00:00Z")+ assertEquals(referral, json.decodeFromString<Referral>(json.encodeToString(Referral.serializer(), referral)))+ val reward = Reward(id = 4, title = "Free fries", description = "desc", pointsRequired = 100, merchantName = "Greens")+ assertEquals(reward, json.decodeFromString<Reward>(json.encodeToString(Reward.serializer(), reward)))+ val merchantItemOrder = OrderItem(+ id = 5, name = "Burger", quantity = 2, price = 999,+ modifiers = listOf(OrderItemModifier(name = "Cheese", price = 100, quantity = 2, modifierGroupName = "Extras")),+ specialInstructions = "no onion",+ )+ val itemBack = json.decodeFromString<OrderItem>(json.encodeToString(OrderItem.serializer(), merchantItemOrder))+ assertEquals(merchantItemOrder, itemBack)+ assertEquals("Extras", itemBack.modifiers.single().modifierGroupName)+ val om = OrderMerchant(id = 6, name = "Greens", latitude = 1.5, longitude = 2.5, phone = "555")+ assertEquals(om, json.decodeFromString<OrderMerchant>(json.encodeToString(OrderMerchant.serializer(), om)))+ val auth = AuthToken(accessToken = "a", refreshToken = "r", tokenType = "Bearer", expiresIn = 60)+ val authJson = json.encodeToString(AuthToken.serializer(), auth)+ assertTrue(authJson.contains("\"access_token\":\"a\""), authJson)+ assertEquals(auth, json.decodeFromString<AuthToken>(authJson))+ val saved = SavedAddress(id = "a1", label = "Home", isDefault = true, latitude = 3.0)+ assertEquals(saved, json.decodeFromString<SavedAddress>(json.encodeToString(SavedAddress.serializer(), saved)))+ val wrapper = MerchantsWrapper(merchants = listOf(Merchant(id = 1, name = "A")))+ assertEquals("A", json.decodeFromString<MerchantsWrapper>(+ json.encodeToString(MerchantsWrapper.serializer(), wrapper),+ ).merchants.single().name)+ val envelope = ApiResponse(message = "ok", data = 42)+ assertEquals(42, json.decodeFromString<ApiResponse<Int>>(+ json.encodeToString(ApiResponse.serializer(Int.serializer()), envelope),+ ).data)+ }++ @Test fun isoParsingCalendarAndClockEdges() {+ // Leap-day rules: 2024 and 2000 are leap years, 2023 and 1900 are not.+ assertEquals(parseIsoMillis("2024-02-29T12:00:00Z"), java.time.Instant.parse("2024-02-29T12:00:00Z").toEpochMilli())+ assertNull(parseIsoMillis("2023-02-29T12:00:00Z"))+ assertEquals(parseIsoMillis("2000-02-29T00:00:00Z"), java.time.Instant.parse("2000-02-29T00:00:00Z").toEpochMilli())+ assertNull(parseIsoMillis("1900-02-29T00:00:00Z"))+ assertNull(parseIsoMillis("2024-04-31T00:00:00Z"))+ assertNull(parseIsoMillis("2024-01-32T00:00:00Z"))+ assertNull(parseIsoMillis("2024-00-10T00:00:00Z"))+ assertNull(parseIsoMillis("2024-01-00T00:00:00Z"))+ // The java.time fallback accepts 24:00 as the end of the day.+ assertEquals(1704153600000L, parseIsoMillis("2024-01-01T24:00:00Z"))+ assertNull(parseIsoMillis("2024-01-01T00:60:00Z"))+ assertNull(parseIsoMillis("2024-01-01T00:00:60Z"))+ // Fractional seconds are truncated/padded to millis.+ assertEquals(500L, parseIsoMillis("1970-01-01T00:00:00.5Z")!! - parseIsoMillis("1970-01-01T00:00:00Z")!!)+ assertEquals(50L, parseIsoMillis("1970-01-01T00:00:00.05Z")!!)+ assertEquals(123L, parseIsoMillis("1970-01-01T00:00:00.123456Z")!!)+ // The java.time fallback tolerates a trailing fraction dot after the Z is stripped.+ assertEquals(1704067200000L, parseIsoMillis("2024-01-01T00:00:00.Z"))+ // No suffix, blank and malformed separators.+ assertEquals(0L, parseIsoMillis("1970-01-01T00:00:00"))+ assertNull(parseIsoMillis(" "))+ assertNull(parseIsoMillis("2024/01/01T00:00:00Z"))+ assertNull(parseIsoMillis("2024-01-01 00:00:00Z"))+ // Likewise, junk after the Z is stripped by the same fallback.+ assertEquals(1704067200000L, parseIsoMillis("2024-01-01T00:00:00Zjunk"))+ assertNull(parseIsoMillis("short"))+ // An explicit offset still parses through the java.time fallback.+ assertEquals(0L, parseIsoMillis("1970-01-01T01:00:00+01:00"))+ }+}
fooddelivery/src/test/java/com/vayunmathur/fooddelivery/ui/FoodWave3MainComposeTest.kt
diff --git a/fooddelivery/src/test/java/com/vayunmathur/fooddelivery/ui/FoodWave3MainComposeTest.kt b/fooddelivery/src/test/java/com/vayunmathur/fooddelivery/ui/FoodWave3MainComposeTest.ktnew file mode 100644index 0000000000..68571b6441--- /dev/null+++ b/fooddelivery/src/test/java/com/vayunmathur/fooddelivery/ui/FoodWave3MainComposeTest.kt@@ -0,0 +1,181 @@+package com.vayunmathur.fooddelivery.ui++import android.app.Application+import android.content.Context+import androidx.compose.ui.test.hasAnySibling+import androidx.compose.ui.test.hasAnyDescendant+import androidx.compose.ui.test.hasClickAction+import androidx.compose.ui.test.hasText+import androidx.compose.ui.test.junit4.createAndroidComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.compose.ui.test.hasScrollAction+import androidx.compose.ui.test.performScrollToIndex+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.fooddelivery.MainActivity+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.library.network.SimpleResponse+import kotlin.test.assertTrue+import kotlinx.coroutines.runBlocking+import org.junit.After+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import kotlin.test.Test++/**+ * Wave-3: the real MainActivity composition — tab pager, navigation entries,+ * cart-restore and the cross-merchant pending-cart dialog.+ */+@RunWith(RobolectricTestRunner::class)+@Config(application = Application::class)+class FoodWave3MainComposeTest {+ @get:Rule val rule = createAndroidComposeRule<MainActivity>()+ private val ctx: Context get() = ApplicationProvider.getApplicationContext()+ private val realTransport = BitesCore.transport++ init {+ BitesCore.transport = { url, _, _, _ ->+ when {+ url.contains("/merchants/all/stores") -> SimpleResponse(+ 200, "",+ """{"data":{"merchants":[{"id":7,"name":"Burger Barn","latitude":37.0,"longitude":-122.0}]}}""",+ emptyMap(), url,+ )+ url.contains("/merchants/7") -> SimpleResponse(+ 200, "",+ """{"data":{"id":7,"name":"Burger Barn","categories":[{"id":1,"name":"Mains","itemIds":[10]}],"items":[{"id":10,"name":"Burger","price":999}]}}""",+ emptyMap(), url,+ )+ url.contains("/checkout") -> SimpleResponse(+ 200, "",+ """{"data":{"clientSecret":"pi_secret","order":{"id":11,"uuid":"u11","foodTotal":999,"taxes":80},"serviceable":{"ok":true}}}""",+ emptyMap(), url,+ )+ url.contains("/orders/past/all") -> SimpleResponse(+ 200, "",+ """{"data":[{"id":9,"uuid":"u9","foodTotal":1000,"channel":"ORDER_CHANNEL_STOREFRONT_DELIVERY","merchant":{"id":7,"name":"Burger Barn"}}]}""",+ emptyMap(), url,+ )+ url.contains("/orders/u11/rewards") -> SimpleResponse(+ 200, "", """{"data":{"rewardsAvailable":0,"rewardsRate":0.0}}""", emptyMap(), url,+ )+ url.contains("/customers/me/rewards") -> SimpleResponse(200, "", """{"data":[]}""", emptyMap(), url)+ url.contains("/customers/me") -> SimpleResponse(+ 200, "", """{"data":{"id":5,"uuid":"cu1","firstName":"Ann","lastName":"Lee","email":"[email protected]"}}""",+ emptyMap(), url,+ )+ url.contains("/deals") -> SimpleResponse(+ 200, "", """{"data":[{"id":1,"title":"Main Deal","merchantId":7,"isActive":true}]}""",+ emptyMap(), url,+ )+ url.contains("/orders/me/savings") -> SimpleResponse(+ 200, "", """{"data":{"customerSavings":500,"orderCount":2}}""", emptyMap(), url,+ )+ else -> SimpleResponse(404, "", "{}", emptyMap(), url)+ }+ }+ BitesAuth.setToken(AuthToken("acc", "ref", "Bearer", 3600))+ runBlocking {+ AddressStore.save(+ ctx,+ SavedAddress(+ id = "home", label = "Home", addressStreet = "1 Main",+ latitude = 37.0, longitude = -122.0, isDefault = true,+ ),+ )+ }+ // A cart from a different merchant (99), so adding from merchant 7+ // must go through the pending-cart dialog. Seeded synchronously in+ // the store's own prefs shape (CartStore.save is fire-and-forget).+ ctx.getSharedPreferences("fooddelivery_cart", Context.MODE_PRIVATE).edit()+ .putString(+ "cart_items_v2",+ """[{"menuItem":{"id":1,"name":"Seed Burger","price":500},"quantity":1,"merchantId":99,"merchantName":"Other Place","lineId":"seed-1"}]""",+ ).commit()+ }++ @After fun restore() {+ BitesCore.transport = realTransport+ BitesAuth.clearToken()+ }++ private fun awaitNode(text: String, substring: Boolean = true) {+ val deadline = System.currentTimeMillis() + 20_000+ var found = false+ while (System.currentTimeMillis() < deadline) {+ 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 tabsWalkComposesEveryTab() {+ awaitNode("Burger Barn")+ rule.onNodeWithText("Cart").performClick()+ awaitNode("Seed Burger")+ rule.onNodeWithText("Deals").performClick()+ awaitNode("Main Deal")+ rule.onNodeWithText("Orders").performClick()+ awaitNode("Track order")+ rule.onNodeWithText("Account").performClick()+ awaitNode("Ann Lee")+ }++ @Test fun pendingCartDialogReplacesCartOnConfirm() {+ awaitNode("Burger Barn")+ rule.onNodeWithText("Burger Barn").performClick()+ awaitNode("Burger Barn")+ // Scroll the menu list so the Burger row composes.+ rule.onNode(hasScrollAction()).performScrollToIndex(5)+ rule.waitForIdle()+ // The menu row's add button: the clickable node on the same row as,+ // and to the right of, the item name (it carries no text of its own).+ val burgerBounds = rule.onNodeWithText("Burger", useUnmergedTree = true)+ .fetchSemanticsNode().boundsInRoot+ val clickables = rule.onAllNodes(hasClickAction(), useUnmergedTree = true)+ val nodes = clickables.fetchSemanticsNodes()+ val addIndex = nodes.indexOfFirst { node ->+ val b = node.boundsInRoot+ kotlin.math.abs((b.top + b.bottom) / 2 - (burgerBounds.top + burgerBounds.bottom) / 2) < 80 &&+ b.left > burgerBounds.right+ }+ assertTrue(addIndex >= 0, "no clickable node on the Burger row")+ clickables[addIndex].performClick()+ awaitNode("Start a new cart?")+ rule.onNodeWithText("Start new cart").performClick()+ // Back out to the tabs and open the cart: Burger is the cart now.+ rule.activity.onBackPressedDispatcher.onBackPressed()+ rule.waitForIdle()+ rule.onNodeWithText("Cart").performClick()+ // The cart now holds the Burger line, not the seeded Other Place line.+ awaitNode("Checkout")+ rule.onNodeWithText("Seed Burger").assertDoesNotExist()+ rule.onNodeWithText("1x Burger").fetchSemanticsNode()+ }++ @Test fun cartTabCheckoutEntryComposesCheckout() {+ rule.onNodeWithText("Cart").performClick()+ awaitNode("Seed Burger")+ rule.onNodeWithText("Checkout").performClick()+ awaitNode("Place Order")+ }++ @Test fun ordersTabTrackEntryComposesTracking() {+ rule.onNodeWithText("Orders").performClick()+ awaitNode("Track order")+ rule.onNodeWithText("Track order").performClick()+ awaitNode("Preparing")+ }+}
fooddelivery/src/test/java/com/vayunmathur/fooddelivery/ui/FoodWave3ScreensTest.kt
diff --git a/fooddelivery/src/test/java/com/vayunmathur/fooddelivery/ui/FoodWave3ScreensTest.kt b/fooddelivery/src/test/java/com/vayunmathur/fooddelivery/ui/FoodWave3ScreensTest.ktnew file mode 100644index 0000000000..6067146581--- /dev/null+++ b/fooddelivery/src/test/java/com/vayunmathur/fooddelivery/ui/FoodWave3ScreensTest.kt@@ -0,0 +1,321 @@+package com.vayunmathur.fooddelivery.ui++import android.app.Application+import android.content.Context+import androidx.compose.foundation.layout.Column+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.hasClickAction+import androidx.compose.ui.test.hasAnyDescendant+import androidx.compose.ui.test.hasText+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.onAllNodesWithText+import androidx.compose.ui.test.assertCountEquals+import androidx.compose.ui.test.performClick+import androidx.compose.ui.test.performSemanticsAction+import androidx.compose.ui.test.performTextInput+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.fooddelivery.api.BitesAuth+import com.vayunmathur.fooddelivery.api.BitesCore+import com.vayunmathur.fooddelivery.data.AuthToken+import com.vayunmathur.fooddelivery.data.CartItem+import com.vayunmathur.fooddelivery.data.Deal+import com.vayunmathur.fooddelivery.data.MenuCategory+import com.vayunmathur.fooddelivery.data.MenuItem+import com.vayunmathur.fooddelivery.data.Merchant+import com.vayunmathur.fooddelivery.data.MerchantDetail+import com.vayunmathur.fooddelivery.data.MerchantRewards+import com.vayunmathur.fooddelivery.data.Modifier+import com.vayunmathur.fooddelivery.data.ModifierGroup+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 kotlin.test.assertEquals+import kotlin.test.assertTrue+import org.junit.After+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import kotlin.test.Test++/** Wave-3: restaurant/home/deals/checkout section branches not hit by earlier flows. */+@RunWith(RobolectricTestRunner::class)+@Config(application = Application::class)+class FoodWave3ScreensTest {+ @get:Rule val rule = createComposeRule()+ private val ctx: Context get() = ApplicationProvider.getApplicationContext()+ private val realTransport = BitesCore.transport++ @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) {+ 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 idle(seconds: Long = 1) {+ org.robolectric.Shadows.shadowOf(android.os.Looper.getMainLooper())+ .idleFor(seconds, java.util.concurrent.TimeUnit.SECONDS)+ rule.waitForIdle()+ }++ @Test fun restaurantRichContentFiltersAndSearches() {+ val items = listOf(+ MenuItem(id = 10, name = "Burger", description = "Beef patty", price = 999),+ MenuItem(id = 11, name = "Shake", description = "Vanilla shake", price = 499),+ MenuItem(id = 12, name = "Ghost", description = "Unavailable", price = 100, isAvailable = false),+ MenuItem(id = 13, name = "SoldOut", description = "Gone", price = 100, isInStock = false),+ )+ val detail = MerchantDetail(+ id = 1, name = "Burger Barn", imageUrl = "",+ merchantTags = listOf("Burgers", "Shakes"), averageRating = 4.5, totalRatings = 42,+ nextOpenWindow = "Opens at 9 AM", rewardsPercentage = 5.0,+ categories = listOf(+ MenuCategory(id = 2, name = "Drinks", sortOrder = 2, itemIds = listOf(11)),+ MenuCategory(id = 1, name = "Mains", sortOrder = 1, itemIds = listOf(10, 12, 13)),+ MenuCategory(id = 3, name = "Hidden", sortOrder = 0, isActive = false, itemIds = listOf(10)),+ ),+ items = items,+ )+ rule.setContent {+ RestaurantContent(detail, rewards = MerchantRewards(merchantId = 1, balance = 0), onAddItem = { _, _ -> })+ }+ rule.onNodeWithText("Burger Barn").assertIsDisplayed()+ rule.onNodeWithText("4.5 (42)").assertExists()+ rule.onNodeWithText("Opens at 9 AM").assertExists()+ // Unavailable / out-of-stock / inactive-category rows never render.+ rule.onNodeWithText("Ghost").assertDoesNotExist()+ rule.onNodeWithText("SoldOut").assertDoesNotExist()+ // Search settles through the debounce, then only the matching row remains.+ rule.onNodeWithText("Search menu").performTextInput("shake")+ // The menu re-filter is debounced on the compose clock, not the wall clock.+ rule.mainClock.autoAdvance = false+ rule.mainClock.advanceTimeBy(2_000L)+ rule.mainClock.autoAdvance = true+ rule.waitForIdle()+ awaitNode("Shake")+ rule.onNodeWithText("Burger", substring = false).assertDoesNotExist()+ }++ @Test fun restaurantEmptyMenuShowsNoMatchMessage() {+ val detail = MerchantDetail(+ id = 1, name = "Empty Place",+ categories = listOf(MenuCategory(id = 1, name = "Mains", itemIds = listOf(99))),+ items = emptyList(),+ )+ rule.setContent { RestaurantContent(detail) }+ rule.onNodeWithText("No menu items", substring = true).assertExists()+ }++ @Test fun menuItemRowPlainVariantAndAddClick() {+ var adds = 0+ val plain = MenuItem(id = 1, name = "Fries", description = "", price = 399, doordashPrice = 299)+ rule.setContent { MenuItemRow(plain) { adds++ } }+ rule.onNodeWithText("Fries").assertIsDisplayed()+ rule.onNodeWithText("$3.99").assertExists()+ // DoorDash price below ours is not shown as a comparison.+ rule.onNodeWithText("on DD", substring = true).assertDoesNotExist()+ rule.onNode(hasClickAction()).performClick()+ assertEquals(1, adds)+ }++ @Test fun menuItemRowFancyVariant() {+ val fancy = MenuItem(+ id = 2, name = "Burger", description = "Beef", price = 999, doordashPrice = 1299,+ imageUrl = "https://example.com/b.jpg",+ modifierGroups = listOf(+ ModifierGroup(id = 1, name = "Extras", modifiers = listOf(Modifier(id = 1, name = "Cheese", price = 100))),+ ),+ )+ rule.setContent { MenuItemRow(fancy) {} }+ rule.onNodeWithText("$12.99 on DD").assertExists()+ rule.onNodeWithText("Customizable").assertExists()+ }++ @Test fun merchantRewardsJoinTrimsAndClears() {+ var joined: String? = null+ var left = false+ rule.setContent {+ MerchantRewardsCard(rewards = null, onJoin = { joined = it }, onLeave = { left = true })+ }+ rule.onNodeWithText("No rewards", substring = true).assertExists()+ rule.onNodeWithText("Invite code").performTextInput(" CODE9 ")+ rule.onNodeWithText("Join").performClick()+ assertEquals("CODE9", joined)+ assertTrue(!left)+ }++ @Test fun merchantRewardsLeaveFires() {+ var left = false+ rule.setContent {+ MerchantRewardsCard(+ rewards = MerchantRewards(merchantId = 1, balance = 250),+ onJoin = {}, onLeave = { left = true },+ )+ }+ rule.onNodeWithText("$2.50", substring = true).assertExists()+ rule.onNodeWithText("Leave", substring = true).performClick()+ assertTrue(left)+ }++ @Test fun homeMerchantCardBranchVariants() {+ val closed = Merchant(+ id = 1, name = "Closed Cafe", isOpen = false, closingTime = "",+ addressCity = "Springfield", addressStreet = "1 Main", addressState = "IL",+ doordashMarkup = 500, doordashMarkupComparison = 300,+ )+ val open = Merchant(+ id = 2, name = "Open Diner", isOpen = true, nextOpenWindow = "Open until 10 PM",+ imageUrl = "https://example.com/o.jpg", logoUrl = "https://example.com/l.jpg",+ averageRating = 3.5, distance = 1.25, rewardsPercentage = 10.0,+ doordashMarkup = 200, doordashMarkupComparison = 700, merchantTags = listOf("Diner"),+ )+ rule.setContent { HomeContent(listOf(closed, open), onMerchantClick = {}) }+ rule.onNodeWithText("Closed Cafe").assertExists()+ rule.onNodeWithText("Closed").assertExists()+ rule.onNodeWithText("Open Diner").assertExists()+ rule.onNodeWithText("Open until 10 PM").assertExists()+ rule.onNodeWithText("1.3 mi").assertExists()+ rule.onNodeWithText("Save $5 vs DoorDash").assertExists()+ rule.onNodeWithText("3.5").assertExists()+ }++ @Test fun dealsScreenRendersProgressAndClickRules() {+ BitesCore.transport = { url, _, _, _ ->+ when {+ url.contains("/deals/1/progress") ->+ SimpleResponse(200, "", """{"data":{"ordersCount":2,"isComplete":true}}""", emptyMap(), url)+ url.contains("/deals/2/progress") ->+ SimpleResponse(200, "", """{"data":{"ordersCount":1,"isComplete":false}}""", emptyMap(), url)+ url.contains("/deals") -> SimpleResponse(+ 200, "",+ """{"data":[+ {"id":1,"title":"Unlocked Deal","merchantId":7,"merchantName":"Greens","description":"Done","image":"https://example.com/d.jpg","discountAmount":500,"minOrderCount":2,"isActive":true},+ {"id":2,"title":"Percent Deal","merchantId":0,"merchantName":"","discountPercent":25.0,"minOrderCount":4,"isActive":true},+ {"id":3,"title":"Inactive Deal","merchantId":9,"isActive":false}+ ]}""",+ emptyMap(), url,+ )+ else -> SimpleResponse(404, "", "{}", emptyMap(), url)+ }+ }+ BitesAuth.setToken(AuthToken("acc", "ref", "Bearer", 3600))+ AppInit.start(ctx)+ var clicked = -1+ rule.setContent { DealsScreen { clicked = it } }+ awaitNode("Unlocked Deal")+ rule.onNodeWithText("Inactive Deal").assertDoesNotExist()+ rule.onNodeWithText("$5.00 off").assertExists()+ rule.onNodeWithText("25% off").assertExists()+ rule.onNodeWithText("Unlocked Deal").performClick()+ assertEquals(7, clicked)+ // A deal without a merchant opens nothing.+ rule.onNodeWithText("Percent Deal").performClick()+ assertEquals(7, clicked)+ }++ @Test fun checkoutTotalsFetchingBranch() {+ rule.setContent {+ CheckoutTotals(20.0, true, null, null, null, null, 0.0, null, null)+ }+ rule.onNodeWithText("$20.00").assertExists()+ rule.onNodeWithText("Tax").assertDoesNotExist()+ }++ @Test fun checkoutTotalsNoTaxQuoteBranch() {+ rule.setContent {+ CheckoutTotals(20.0, false, null, null, null, null, 0.0, null, null)+ }+ rule.onNodeWithText("$20.00").assertExists()+ rule.onNodeWithText("Total", substring = true).assertDoesNotExist()+ }++ @Test fun checkoutTotalsRewardsAndDisplayFallback() {+ // Zero fees are hidden, rewards show as a negative row, and the total+ // falls back to displayTotal when payTotal is absent.+ rule.setContent {+ CheckoutTotals(+ subtotal = 20.0, fetchingPrices = false, taxesDollars = 2.0,+ deliveryFeeDollars = 0.0, feesDollars = 0.0, tipsDollars = 0.0,+ rewardsApplied = 1.5, payTotal = null, displayTotal = 20.5,+ )+ }+ rule.onNodeWithText("Rewards").assertExists()+ rule.onNodeWithText("$20.50").assertExists()+ rule.onNodeWithText("Delivery fee").assertDoesNotExist()+ }++ @Test fun checkoutTotalsSubtotalFallback() {+ // Both totals absent: the subtotal itself is the displayed total.+ rule.setContent {+ CheckoutTotals(33.0, false, 3.0, 2.0, 1.0, 4.0, 0.0, null, null)+ }+ // Subtotal and total rows both read $33.00 in this fallback.+ rule.onAllNodesWithText("$33.00").assertCountEquals(2)+ rule.onNodeWithText("Delivery fee").assertExists()+ rule.onNodeWithText("Service fees").assertExists()+ }++ @Test fun checkoutSectionInteractionsWave3() {+ var tip = -1+ var promo = ""+ var dealSel: Int? = 99+ var selected: SavedAddress? = null+ var instructions = ""+ val addr = SavedAddress(+ id = "a1", label = "", addressStreet = "1 Main St",+ aptUnit = "4B", gateCode = "1234",+ )+ val items = listOf(+ CartItem(+ menuItem = MenuItem(id = 1, name = "Burger", price = 1000), quantity = 2,+ selectedModifiers = listOf(SelectedModifier(name = "Cheese", price = 100)),+ ),+ )+ rule.setContent {+ Column {+ CheckoutOrderSummary(items)+ CheckoutTipPicker(300) { tip = it }+ CheckoutDealsPicker(+ deals = listOf(Deal(id = 5, title = "Deal Five", description = "")),+ selectedDealId = 5,+ onSelect = { dealSel = it },+ promoCode = promo,+ onPromoChange = { promo = it },+ )+ CheckoutAddressPicker(+ addresses = listOf(addr), addressesLoaded = true, selectedAddress = addr,+ onSelect = { selected = it }, deliveryInstructions = instructions,+ onInstructionsChange = { instructions = it },+ )+ }+ }+ rule.onNodeWithText("2x Burger").assertExists()+ rule.onNodeWithText("Cheese").assertExists()+ rule.onNodeWithText("$5.00").performClick()+ assertEquals(500, tip)+ // Tapping the already-chosen deal clears the selection.+ rule.onNodeWithText("Deal Five").performClick()+ assertEquals(null, dealSel)+ rule.onNodeWithText("Address").assertExists()+ rule.onNode(hasClickAction() and hasAnyDescendant(hasText("1 Main St")), useUnmergedTree = true)+ .performSemanticsAction(androidx.compose.ui.semantics.SemanticsActions.OnClick)+ assertEquals("a1", selected?.id)+ }+}