travel: add tests for repository, booking and pages (389 tests)
- Commit
2de9a095d56136e5d95c28785338ebcff1aef328- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-15 23:31 UTC (20 days ago)
- Parents
0376974
New C5 test files only; no production or existing test files changed, so the batch stays integration-clean against parallel CI-fix branches. What: TravelRepository against an in-memory Room database (recent searches, booked trips, frequent flyers/customers); TravelBookingOps and TravelOrderOps over a scripted travelTransport seam (passenger prefill, checkout/price gating, ancillaries and seat maps, cancellation/change/recheckout polling); Robolectric Compose pages for order detail, change, cancellation, confirmation, stay detail/confirmation, passengers, ancillaries and offer review. Coverage (merged JaCoCo INSTRUCTION counter): covered 48,100 -> 54,915 (+6,815), missed 17,677 -> 10,862. Verification: ./gradlew :travel:testDevUnitTest :travel:detekt :travel:lint green; 389 tests, 0 failures. createMergedCoverageReport before/after as above.
Diff
travel/src/test/java/com/vayunmathur/travel/data/TravelRepositoryC5Test.kt
diff --git a/travel/src/test/java/com/vayunmathur/travel/data/TravelRepositoryC5Test.kt b/travel/src/test/java/com/vayunmathur/travel/data/TravelRepositoryC5Test.ktnew file mode 100644index 0000000000..3e4bbc4ce1--- /dev/null+++ b/travel/src/test/java/com/vayunmathur/travel/data/TravelRepositoryC5Test.kt@@ -0,0 +1,104 @@+package com.vayunmathur.travel.data++import androidx.room3.Room+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.library.util.databases+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.test.assertSame+import kotlin.test.assertTrue+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.test.runTest+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++/**+ * The real [TravelRepository] delegates against an in-memory database seeded+ * into the shared `databases` cache (the same seam HealthRepository tests+ * use), so every DAO delegation — not just the fake overrides used to drive+ * ViewModels elsewhere — is exercised end to end.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class TravelRepositoryC5Test {++ private val context = ApplicationProvider.getApplicationContext<android.content.Context>()++ @BeforeTest+ fun open() {+ synchronized(databases) {+ if (databases[TravelDatabase::class] == null) {+ databases[TravelDatabase::class] = Room+ .inMemoryDatabaseBuilder(context, TravelDatabase::class.java)+ .allowMainThreadQueries()+ .build()+ }+ }+ }++ private fun repo() = TravelRepository(context)++ @Test+ fun recentSearches_insertObserveDeleteTrimClear() = runTest {+ val repo = repo()+ repo.clearRecent()+ val first = RecentSearch(vertical = "flights", label = "C5 SFO to JFK")+ repo.insertRecent(first)+ repo.insertRecent(RecentSearch(vertical = "stays", label = "C5 Paris hotels"))+ repo.insertRecent(RecentSearch(vertical = "flights", label = "C5 LAX to ORD"))+ assertEquals(3, repo.observeRecent(10).first().size)+ assertEquals(2, repo.observeRecent(2).first().size)+ repo.deleteRecent(repo.observeRecent(10).first().first { it.label == "C5 SFO to JFK" })+ assertTrue(repo.observeRecent(10).first().none { it.label == "C5 SFO to JFK" })+ repo.trimRecent(keep = 1)+ assertEquals(1, repo.observeRecent(10).first().size)+ repo.clearRecent()+ assertTrue(repo.observeRecent(10).first().isEmpty())+ }++ @Test+ fun bookedTrips_upsertObserveGetDelete() = runTest {+ val repo = repo()+ val trip = BookedTrip(+ orderId = "c5_ord_1", bookingReference = "C5REF1", route = "SFO → JFK",+ departDate = "2027-06-24", amount = "250.00", currency = "USD",+ )+ repo.upsertBookedTrip(trip)+ repo.upsertBookedTrip(trip.copy(amount = "275.00", status = "processing"))+ assertEquals("275.00", repo.getBookedTrip("c5_ord_1")?.amount)+ assertTrue(repo.getAllBookedTrips().any { it.orderId == "c5_ord_1" })+ assertTrue(repo.observeBookedTrips().first().any { it.orderId == "c5_ord_1" })+ assertNull(repo.getBookedTrip("c5_missing"))+ repo.deleteBookedTripById("c5_ord_1")+ assertNull(repo.getBookedTrip("c5_ord_1"))+ }++ @Test+ fun frequentFlyers_upsertObserveGetDelete() = runTest {+ val repo = repo()+ repo.upsertFrequentFlyer(FrequentFlyer(airlineIata = "C5", accountNumber = "998877", airlineName = "C5 Air"))+ assertEquals("998877", repo.getAllFrequentFlyers().first { it.airlineIata == "C5" }.accountNumber)+ assertTrue(repo.observeFrequentFlyers().first().any { it.airlineIata == "C5" })+ repo.deleteFrequentFlyer("C5")+ assertTrue(repo.getAllFrequentFlyers().none { it.airlineIata == "C5" })+ }++ @Test+ fun customers_upsertObserveGetDelete() = runTest {+ val repo = repo()+ repo.upsertCustomer(Customer(id = "c5_cust_1", email = "[email protected]", givenName = "Casey", familyName = "Five"))+ assertEquals("Casey Five", repo.getCustomer("c5_cust_1")?.displayName)+ assertTrue(repo.observeCustomers().first().any { it.id == "c5_cust_1" })+ assertNull(repo.getCustomer("c5_nobody"))+ repo.deleteCustomerById("c5_cust_1")+ assertNull(repo.getCustomer("c5_cust_1"))+ }++ @Test+ fun singleton_getReturnsSameInstance() {+ assertSame(TravelRepository.get(context), TravelRepository.get(context))+ }+}
travel/src/test/java/com/vayunmathur/travel/ui/TravelPagesC5Test.kt
diff --git a/travel/src/test/java/com/vayunmathur/travel/ui/TravelPagesC5Test.kt b/travel/src/test/java/com/vayunmathur/travel/ui/TravelPagesC5Test.ktnew file mode 100644index 0000000000..8c137165e0--- /dev/null+++ b/travel/src/test/java/com/vayunmathur/travel/ui/TravelPagesC5Test.kt@@ -0,0 +1,468 @@+package com.vayunmathur.travel.ui++import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.isToggleable+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.performScrollTo+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.travel.Route+import com.vayunmathur.travel.data.BookedTrip+import com.vayunmathur.travel.data.Customer+import com.vayunmathur.travel.data.FrequentFlyer+import com.vayunmathur.travel.data.RecentSearch+import com.vayunmathur.travel.data.TravelRepository+import com.vayunmathur.travel.network.CancellationDto+import com.vayunmathur.travel.network.ChangeOfferDto+import com.vayunmathur.travel.network.ChangePriceDto+import com.vayunmathur.travel.network.CheckoutDto+import com.vayunmathur.travel.network.OrderDetailDto+import com.vayunmathur.travel.network.SegmentDto+import com.vayunmathur.travel.network.SliceDto+import com.vayunmathur.travel.network.StayBookingHotelDto+import com.vayunmathur.travel.util.CancellationState+import com.vayunmathur.travel.util.ChangeState+import com.vayunmathur.travel.util.CheckoutState+import com.vayunmathur.travel.util.OrderDetailState+import com.vayunmathur.travel.util.TravelViewModel+import com.vayunmathur.travel.util.TripPollState+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue+import kotlinx.coroutines.flow.Flow+import kotlinx.coroutines.flow.MutableStateFlow+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++/**+ * C5 page branches: change-offer pricing variants, cancellation quote/done+ * states, confirmation statuses, hotel order detail, price-change notice,+ * and the date-range dialog.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class TravelPagesC5Test {++ @get:Rule val rule = createComposeRule()++ private class FakeRepo(ctx: android.content.Context) : TravelRepository(ctx) {+ val trips = MutableStateFlow<List<BookedTrip>>(emptyList())+ val customers = MutableStateFlow<List<Customer>>(emptyList())+ val flyers = MutableStateFlow<List<FrequentFlyer>>(emptyList())+ val recents = MutableStateFlow<List<RecentSearch>>(emptyList())+ override fun observeRecent(limit: Int): Flow<List<RecentSearch>> = recents+ override fun observeBookedTrips(): Flow<List<BookedTrip>> = trips+ override fun observeFrequentFlyers(): Flow<List<FrequentFlyer>> = flyers+ override fun observeCustomers(): Flow<List<Customer>> = customers+ override suspend fun getAllFrequentFlyers(): List<FrequentFlyer> = flyers.value+ override suspend fun getAllBookedTrips(): List<BookedTrip> = trips.value+ override suspend fun getBookedTrip(orderId: String): BookedTrip? = trips.value.find { it.orderId == orderId }+ override suspend fun insertRecent(value: RecentSearch) {}+ override suspend fun clearRecent() {}+ override suspend fun trimRecent(keep: Int) {}+ override suspend fun upsertBookedTrip(value: BookedTrip) {+ trips.value = trips.value.filter { it.orderId != value.orderId } + value+ }+ }++ private lateinit var repo: FakeRepo++ @BeforeTest+ fun open() {+ repo = FakeRepo(ApplicationProvider.getApplicationContext())+ com.vayunmathur.travel.network.travelTransport = null+ }++ private fun vm(): TravelViewModel {+ val ctx = ApplicationProvider.getApplicationContext<android.content.Context>()+ return TravelViewModel(ctx as android.app.Application, repo)+ }++ private fun stack() = NavBackStack<Route>(arrayOf(Route.Home))++ private fun slice(origin: String = "SFO", destination: String = "JFK", id: String = "sli_1") = SliceDto(+ id = id, origin = origin, destination = destination,+ departureAt = "2027-06-24T07:15:00", arrivalAt = "2027-06-24T15:50:00",+ segments = listOf(+ SegmentDto(+ id = "seg_$id", carrierIata = "AS", flightNumber = "100",+ origin = origin, destination = destination,+ departureAt = "2027-06-24T07:15:00", arrivalAt = "2027-06-24T15:50:00",+ )+ ),+ )++ private fun order() = OrderDetailDto(+ orderId = "ord_1", bookingReference = "ABC123", totalAmount = "250.00",+ currency = "USD", status = "confirmed",+ slices = listOf(slice(), slice("JFK", "SFO", "sli_2")),+ canChange = true, canCancel = true,+ )++ private fun trip(status: String, failure: String = "", expires: String = "") = BookedTrip(+ orderId = "ord_1", bookingReference = "ABC123", route = "SFO → JFK",+ departDate = "2027-06-24", amount = "250.00", currency = "USD",+ status = status, tripId = "trip_1", failureMessage = failure,+ checkoutExpiresAt = expires,+ )++ // -- Order detail (stateless screen) -------------------------------------++ @Test+ fun orderDetail_hotelCard_rendersAllHotelLines() {+ val hotelOrder = order().copy(+ hotel = StayBookingHotelDto(+ name = "Grand Hotel", address = "1 Main St",+ checkIn = "2027-06-24", checkOut = "2027-06-26",+ roomName = "Deluxe King", boardName = "Breakfast included",+ ),+ ticketNumbers = listOf("0011234567890"),+ )+ rule.setContent {+ OrderDetailScreen(+ state = com.vayunmathur.travel.util.OrderDetailUiState(order = hotelOrder),+ actions = com.vayunmathur.travel.util.OrderDetailActions.Noop,+ )+ }+ rule.onNodeWithText("Grand Hotel").assertIsDisplayed()+ rule.onNodeWithText("1 Main St").performScrollTo().assertIsDisplayed()+ rule.onNodeWithText("2027-06-24 → 2027-06-26").performScrollTo().assertExists()+ rule.onNodeWithText("Deluxe King · Breakfast included").performScrollTo().assertExists()+ rule.onNodeWithText("0011234567890").performScrollTo().assertExists()+ rule.onNodeWithText("Flight 1").performScrollTo().assertExists()+ rule.onNodeWithText("Flight 2").performScrollTo().assertExists()+ }++ @Test+ fun orderDetail_hotelCard_blankFieldsAreOmitted() {+ val hotelOrder = order().copy(hotel = StayBookingHotelDto(name = "Airport Inn"))+ rule.setContent {+ OrderDetailScreen(+ state = com.vayunmathur.travel.util.OrderDetailUiState(order = hotelOrder),+ actions = com.vayunmathur.travel.util.OrderDetailActions.Noop,+ )+ }+ rule.onNodeWithText("Airport Inn").assertIsDisplayed()+ }++ @Test+ fun orderDetail_priceChanged_requiresAcceptBeforePay() {+ var accepted = 0+ var paid = 0+ rule.setContent {+ OrderDetailScreen(+ state = com.vayunmathur.travel.util.OrderDetailUiState(+ order = order(),+ checkout = CheckoutState.Ready(+ CheckoutDto(+ clientSecret = "cs", publishableKey = "pk",+ totalAmount = "300.00", currency = "USD",+ priceChanged = true, originalAmount = "250.00",+ )+ ),+ ),+ actions = object : com.vayunmathur.travel.util.OrderDetailActions {+ override fun acceptNewPrice() { accepted++ }+ override fun completePayment() { paid++ }+ },+ pendingCheckout = true,+ )+ }+ rule.onNodeWithText("Price changed").performScrollTo().assertIsDisplayed()+ rule.onNodeWithText("Accept new price").performScrollTo().assertExists()+ rule.onNode(isToggleable()).performScrollTo().performClick()+ rule.runOnIdle { assertEquals(1, accepted) }+ // The screen is stateless: until the owner re-renders with+ // acceptedNewPrice=true the pay button stays gated, so clicking it+ // must not fire completePayment.+ rule.onNodeWithText("Complete payment").performScrollTo().performClick()+ rule.runOnIdle { assertEquals(0, paid) }+ }++ @Test+ fun orderDetail_checkoutError_showsMessage() {+ rule.setContent {+ OrderDetailScreen(+ state = com.vayunmathur.travel.util.OrderDetailUiState(+ order = order(),+ checkout = CheckoutState.Error("Card setup failed"),+ ),+ actions = com.vayunmathur.travel.util.OrderDetailActions.Noop,+ pendingCheckout = true,+ )+ }+ rule.onNodeWithText("Card setup failed").performScrollTo().assertIsDisplayed()+ }++ // -- Change page ----------------------------------------------------------++ private fun setChange(v: TravelViewModel, change: ChangeState, text: String) {+ val s = stack()+ rule.setContent { ChangePage(s, v, Route.Change("ord_1")) }+ rule.waitUntil(5_000) {+ v.orderDetailMutable.value = OrderDetailState(order = order())+ v.changeMutable.value = change+ rule.onAllNodesWithText(text, substring = true).fetchSemanticsNodes().isNotEmpty()+ }+ }++ @Test+ fun change_notRequested_sliceSelectionAndDateGate() {+ val v = vm()+ setChange(v, ChangeState(), "Pick a flight to change")+ rule.onNodeWithText("Pick a flight to change").assertIsDisplayed()+ rule.onAllNodesWithText("JFK → SFO")[0].performScrollTo().performClick()+ rule.onNodeWithText("Find change options").performScrollTo().assertExists()+ }++ @Test+ fun change_offers_pricingVariants() {+ val v = vm()+ val offers = listOf(+ ChangeOfferDto(id = "c_pay", changeTotalAmount = "50.00", changeTotalCurrency = "USD", slices = listOf(slice()), description = "Same cabin"),+ ChangeOfferDto(id = "c_refund", changeTotalAmount = "-20.00", changeTotalCurrency = "USD", slices = listOf(slice())),+ ChangeOfferDto(id = "c_blank", changeTotalAmount = "", changeTotalCurrency = "USD", slices = listOf(slice())),+ ChangeOfferDto(id = "c_even", changeTotalAmount = "0.00", changeTotalCurrency = "USD", slices = listOf(slice())),+ )+ setChange(+ v,+ ChangeState(requested = true, offers = offers, checkoutUrl = "https://pay.example", polling = true),+ "Change options",+ )+ rule.onNodeWithText("Change options").assertIsDisplayed()+ rule.onNodeWithText("An extra payment is needed to finish this change.", substring = true).assertExists()+ rule.onNodeWithText("Change is processing…").assertExists()+ rule.onAllNodesWithText("Extra to pay", substring = true)[0].performScrollTo().assertExists()+ rule.onAllNodesWithText("Refund", substring = true)[0].performScrollTo().assertExists()+ rule.onAllNodesWithText("No price change", substring = true)[0].performScrollTo().assertExists()+ rule.onNodeWithText("Same cabin").performScrollTo().assertExists()+ }++ @Test+ fun change_offers_pricedOutcomeAndConfirmButton() {+ val v = vm()+ val offers = listOf(+ ChangeOfferDto(id = "c_pay", changeTotalAmount = "50.00", changeTotalCurrency = "USD", slices = listOf(slice())),+ )+ setChange(+ v,+ ChangeState(+ requested = true, offers = offers,+ price = ChangePriceDto(outcome = "pay", amount = "50.00", currency = "USD"),+ pricingOfferId = "c_pay",+ ),+ "Select & confirm",+ )+ rule.onNodeWithText("Select & confirm").performScrollTo().assertIsDisplayed()+ rule.onAllNodesWithText("Extra to pay", substring = true)[0].assertExists()+ }++ @Test+ fun change_loadingErrorAndEmptyStates() {+ val v = vm()+ setChange(v, ChangeState(requested = true, loading = true), "Change flights")+ rule.waitUntil(5_000) {+ v.changeMutable.value = ChangeState(requested = true, error = "Change lookup failed")+ rule.onAllNodesWithText("Change lookup failed").fetchSemanticsNodes().isNotEmpty()+ }+ rule.onNodeWithText("Change lookup failed").assertIsDisplayed()+ rule.waitUntil(5_000) {+ v.changeMutable.value = ChangeState(requested = true)+ rule.onAllNodesWithText("No change options available.").fetchSemanticsNodes().isNotEmpty()+ }+ rule.onNodeWithText("No change options available.").assertIsDisplayed()+ }++ @Test+ fun change_done_showsConfirmation() {+ val v = vm()+ setChange(v, ChangeState(done = true), "Change confirmed")+ rule.onNodeWithText("Change confirmed", substring = true).assertExists()+ }++ // -- Cancellation page ------------------------------------------------------++ private fun setCancellation(v: TravelViewModel, state: CancellationState, text: String) {+ val s = stack()+ rule.setContent { CancellationPage(s, v, Route.Cancel("ord_1")) }+ rule.waitUntil(5_000) {+ v.cancellationMutable.value = state+ rule.onAllNodesWithText(text, substring = true).fetchSemanticsNodes().isNotEmpty()+ }+ }++ @Test+ fun cancellation_quoteWithPenaltyMessageAndPolling() {+ val v = vm()+ setCancellation(+ v,+ CancellationState(+ quote = CancellationDto(+ id = "can_1", orderId = "ord_1", refundAmount = "180.00",+ refundCurrency = "USD", penaltyAmount = "70.00",+ commitable = true, message = "Airline fee applies",+ ),+ polling = true,+ ),+ "Cancel this order?",+ )+ rule.onNodeWithText("Cancel this order?").assertIsDisplayed()+ rule.onNodeWithText("Airline fee applies").performScrollTo().assertExists()+ rule.onNodeWithText("Cancellation is processing…").performScrollTo().assertExists()+ rule.onAllNodesWithText("$180", substring = true)[0].assertExists()+ rule.onAllNodesWithText("$70", substring = true)[0].performScrollTo().assertExists()+ }++ @Test+ fun cancellation_doneShowsRefundDestinationFallback() {+ val v = vm()+ setCancellation(+ v,+ CancellationState(+ done = true,+ quote = CancellationDto(id = "can_1", refundAmount = "200.00", refundCurrency = "USD"),+ ),+ "Order cancelled",+ )+ rule.onNodeWithText("Order cancelled").assertIsDisplayed()+ rule.onAllNodesWithText("original payment", substring = true)[0].assertExists()+ }++ @Test+ fun cancellation_errorWithoutQuote_showsStatusBox() {+ val v = vm()+ setCancellation(v, CancellationState(error = "Quote expired"), "Quote expired")+ rule.onNodeWithText("Quote expired").assertIsDisplayed()+ }++ // -- Confirmation pages ------------------------------------------------------++ @Test+ fun confirmation_failedShowsFailureMessage() {+ repo.trips.value = listOf(trip("failed", failure = "Card declined by issuer"))+ val v = vm()+ rule.setContent { ConfirmationPage(stack(), v, Route.Confirmation("ord_1")) }+ rule.waitUntil(5_000) {+ rule.onAllNodesWithText("Card declined by issuer").fetchSemanticsNodes().isNotEmpty()+ }+ rule.onNodeWithText("Booking failed", substring = true).assertExists()+ rule.onNodeWithText("Card declined by issuer").performScrollTo().assertExists()+ }++ @Test+ fun confirmation_processingAndPartialShowRefresh() {+ repo.trips.value = listOf(trip("processing"))+ val v = vm()+ rule.setContent { ConfirmationPage(stack(), v, Route.Confirmation("ord_1")) }+ rule.onAllNodesWithText("Confirming payment…")[0].assertExists()+ // Swap to partial: refresh button appears for polling statuses.+ repo.trips.value = listOf(trip("partial"))+ rule.waitUntil(5_000) {+ rule.onAllNodesWithText("Refresh status").fetchSemanticsNodes().isNotEmpty()+ }+ rule.onNodeWithText("Refresh status").performScrollTo().assertExists()+ }++ @Test+ fun confirmation_pendingExpiredShowsExpiredNotice() {+ repo.trips.value = listOf(trip("pending_payment", expires = "2000-01-01T00:00:00Z"))+ val v = vm()+ rule.setContent { ConfirmationPage(stack(), v, Route.Confirmation("ord_1")) }+ rule.waitUntil(5_000) {+ rule.onAllNodesWithText("booking session has expired", substring = true).fetchSemanticsNodes().isNotEmpty()+ }+ rule.onAllNodesWithText("Payment pending", substring = true)[0].assertExists()+ }++ @Test+ fun confirmation_pendingWithErrorsShowsBothMessages() {+ repo.trips.value = listOf(trip("pending_payment", expires = "2999-01-01T00:00:00Z"))+ val v = vm()+ rule.setContent { ConfirmationPage(stack(), v, Route.Confirmation("ord_1")) }+ rule.waitUntil(5_000) {+ v.tripPollMutable.value = TripPollState.Error("Poll failed")+ v.checkoutMutable.value = CheckoutState.Error("Checkout failed")+ rule.onAllNodesWithText("Checkout failed").fetchSemanticsNodes().isNotEmpty()+ }+ rule.onNodeWithText("Poll failed").performScrollTo().assertExists()+ rule.onNodeWithText("Checkout failed").assertExists()+ rule.onNodeWithText("Complete payment").performScrollTo().assertExists()+ }++ @Test+ fun confirmation_unknownTripOffersBackToSearch() {+ val v = vm()+ val s = stack()+ rule.setContent { ConfirmationPage(s, v, Route.Confirmation("missing")) }+ rule.onNodeWithText("Trip not found.").assertIsDisplayed()+ rule.onNodeWithText("Back to search").performClick()+ rule.runOnIdle { assertTrue(s.backStack.last() is Route.Home) }+ }++ @Test+ fun confirmation_doneButtonsNavigate() {+ repo.trips.value = listOf(trip("confirmed"))+ val v = vm()+ val s = stack()+ rule.setContent { ConfirmationPage(s, v, Route.Confirmation("ord_1")) }+ rule.onNodeWithText("You're booked!").assertIsDisplayed()+ rule.onNodeWithText("View full itinerary").performScrollTo().performClick()+ rule.runOnIdle { assertTrue(s.backStack.last() is Route.OrderDetail, "last=${s.backStack.last()}") }+ assertEquals("ABC123", repo.trips.value.single().bookingReference)+ }++ @Test+ fun stayConfirmation_pendingAndConfirmedStates() {+ repo.trips.value = listOf(trip("confirmed"))+ val v = vm()+ rule.setContent { StayConfirmationPage(stack(), v, Route.StayConfirmation("ord_1")) }+ rule.onNodeWithText("You're booked!").assertIsDisplayed()+ rule.onNodeWithText("ABC123").assertExists()++ repo.trips.value = listOf(trip("pending_payment", expires = "2999-01-01T00:00:00Z"))+ rule.waitUntil(5_000) {+ v.tripPollMutable.value = TripPollState.Error("Stay poll failed")+ rule.onAllNodesWithText("Complete payment").fetchSemanticsNodes().isNotEmpty()+ }+ rule.onNodeWithText("Complete payment").performScrollTo().assertExists()+ }++ // -- Date range --------------------------------------------------------------++ @Test+ fun dateRangeFields_openDialogAndCancelKeepsValue() {+ var range: Pair<String, String>? = null+ rule.setContent {+ DateRangeFields(+ startLabel = "Depart", endLabel = "Return",+ start = "2027-06-24", end = "2027-06-28",+ onRange = { s, e -> range = s to e },+ )+ }+ rule.onNodeWithText("Depart").assertIsDisplayed()+ rule.onNodeWithText("Depart").performClick()+ rule.onNodeWithText("Select dates").assertExists()+ rule.onNodeWithText("Cancel").performClick()+ rule.runOnIdle { assertEquals(null, range) }+ }++ @Test+ fun dateRangeFields_invalidIsoFallsBackToRawText() {+ rule.setContent {+ DateRangeFields(+ startLabel = "Check-in", endLabel = "Check-out",+ start = "not-a-date", end = "",+ onRange = { _, _ -> },+ allowSameDay = false,+ )+ }+ rule.onNodeWithText("not-a-date").assertIsDisplayed()+ rule.onNodeWithText("Check-out").assertIsDisplayed()+ }+}
travel/src/test/java/com/vayunmathur/travel/ui/TravelPagesC5bTest.kt
diff --git a/travel/src/test/java/com/vayunmathur/travel/ui/TravelPagesC5bTest.kt b/travel/src/test/java/com/vayunmathur/travel/ui/TravelPagesC5bTest.ktnew file mode 100644index 0000000000..521122d950--- /dev/null+++ b/travel/src/test/java/com/vayunmathur/travel/ui/TravelPagesC5bTest.kt@@ -0,0 +1,230 @@+package com.vayunmathur.travel.ui++import androidx.compose.ui.test.assertIsDisplayed+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.performScrollTo+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.travel.Route+import com.vayunmathur.travel.data.BookedTrip+import com.vayunmathur.travel.data.Customer+import com.vayunmathur.travel.data.FrequentFlyer+import com.vayunmathur.travel.data.RecentSearch+import com.vayunmathur.travel.data.TravelRepository+import com.vayunmathur.travel.network.AirlineDto+import com.vayunmathur.travel.network.BaggageDto+import com.vayunmathur.travel.network.ConditionsDto+import com.vayunmathur.travel.network.OfferDto+import com.vayunmathur.travel.network.OfferPassengerDto+import com.vayunmathur.travel.network.PenaltyRuleDto+import com.vayunmathur.travel.network.SegmentDto+import com.vayunmathur.travel.network.ServiceDto+import com.vayunmathur.travel.network.SliceDto+import com.vayunmathur.travel.network.TripAncillariesDto+import com.vayunmathur.travel.util.AncillariesState+import com.vayunmathur.travel.util.BookingState+import com.vayunmathur.travel.util.OfferReviewState+import com.vayunmathur.travel.util.TravelViewModel+import com.vayunmathur.travel.util.initPassengers+import com.vayunmathur.travel.util.prefillFromProfile+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue+import kotlinx.coroutines.flow.Flow+import kotlinx.coroutines.flow.MutableStateFlow+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++/**+ * C5 page branches, part 2: mixed passenger types with identity documents,+ * multi-passenger ancillaries with seat choices, and a round-trip offer+ * review with policies and operating-carrier disclosure.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class TravelPagesC5bTest {++ @get:Rule val rule = createComposeRule()++ private class FakeRepo(ctx: android.content.Context) : TravelRepository(ctx) {+ val trips = MutableStateFlow<List<BookedTrip>>(emptyList())+ val customers = MutableStateFlow<List<Customer>>(emptyList())+ val flyers = MutableStateFlow<List<FrequentFlyer>>(emptyList())+ val recents = MutableStateFlow<List<RecentSearch>>(emptyList())+ override fun observeRecent(limit: Int): Flow<List<RecentSearch>> = recents+ override fun observeBookedTrips(): Flow<List<BookedTrip>> = trips+ override fun observeFrequentFlyers(): Flow<List<FrequentFlyer>> = flyers+ override fun observeCustomers(): Flow<List<Customer>> = customers+ override suspend fun getAllFrequentFlyers(): List<FrequentFlyer> = flyers.value+ override suspend fun getBookedTrip(orderId: String): BookedTrip? = trips.value.find { it.orderId == orderId }+ override suspend fun insertRecent(value: RecentSearch) {}+ override suspend fun clearRecent() {}+ override suspend fun trimRecent(keep: Int) {}+ override suspend fun upsertBookedTrip(value: BookedTrip) {}+ }++ private lateinit var repo: FakeRepo++ @BeforeTest+ fun open() {+ repo = FakeRepo(ApplicationProvider.getApplicationContext())+ com.vayunmathur.travel.network.travelTransport = null+ }++ private fun vm(): TravelViewModel {+ val ctx = ApplicationProvider.getApplicationContext<android.content.Context>()+ return TravelViewModel(ctx as android.app.Application, repo)+ }++ private fun stack() = NavBackStack<Route>(arrayOf(Route.Home))++ private fun segment(id: String, origin: String, destination: String) = SegmentDto(+ id = id, carrier = "Alaska Airlines", carrierIata = "AS", flightNumber = "100",+ origin = origin, destination = destination,+ departureAt = "2027-06-24T07:15:00", arrivalAt = "2027-06-24T15:50:00",+ aircraft = "737-900", cabinClass = "Economy",+ baggages = listOf(BaggageDto(type = "checked", quantity = 1)),+ operatingCarrierIata = "OO",+ )++ private fun offer() = OfferDto(+ offerId = "off_1", totalAmount = "250.00", currency = "USD",+ owner = "Alaska", ownerIata = "AS",+ passengerIds = listOf("pax_1", "pax_2", "pax_3"),+ passengers = listOf(+ OfferPassengerDto(id = "pax_1", type = "adult"),+ OfferPassengerDto(id = "pax_2", type = "child", age = 7),+ OfferPassengerDto(id = "pax_3", type = "infant_without_seat"),+ ),+ passengerIdentityDocumentsRequired = true,+ refundPolicy = "Refundable before departure", changePolicy = "Changes for a fee",+ fareBrand = "Main Cabin",+ conditions = ConditionsDto(+ refundBeforeDeparture = PenaltyRuleDto(allowed = true),+ changeBeforeDeparture = PenaltyRuleDto(allowed = true),+ ),+ slices = listOf(+ SliceDto(+ origin = "SFO", destination = "JFK", durationMinutes = 315, stops = 0,+ departureAt = "2027-06-24T07:15:00", arrivalAt = "2027-06-24T15:50:00",+ segments = listOf(segment("seg_1", "SFO", "JFK")),+ ),+ SliceDto(+ origin = "JFK", destination = "SFO", durationMinutes = 330, stops = 0,+ departureAt = "2027-06-28T09:00:00", arrivalAt = "2027-06-28T12:30:00",+ segments = listOf(segment("seg_2", "JFK", "SFO")),+ ),+ ),+ )++ @Test+ fun passengers_mixedTypes_identityAndMissingDetails() {+ val v = vm()+ repo.customers.value = listOf(+ Customer(id = "c1", email = "[email protected]", givenName = "Jane", familyName = "Doe"),+ )+ v.reviewMutable.value = OfferReviewState(offer = offer())+ v.initPassengers(offer())+ v.bookingMutable.value = BookingState.MissingDetails(+ listOf("passport"), "Passport details are required",+ )+ v.airlinesMutable.value = listOf(AirlineDto(iataCode = "AS", name = "Alaska Airlines"))+ rule.setContent { PassengersPage(stack(), v, Route.Passengers("off_1")) }+ rule.onNodeWithText("Passport details are required").assertIsDisplayed()+ rule.onNodeWithText("Adult 1").performScrollTo().assertExists()+ rule.onNodeWithText("Child (7) 2").performScrollTo().assertExists()+ // "Infant 3" appears twice: the passenger heading and the adult's infant-link chip.+ rule.onAllNodesWithText("Infant 3")[1].performScrollTo().assertExists()+ rule.onAllNodesWithText("Passport number")[0].performScrollTo().assertExists()+ // The saved-profile chip is offered; tapping it prefills via the VM+ // (asserted directly in TravelBookingC5Test, chip wiring in TravelFieldsTest).+ rule.onAllNodesWithText("Jane Doe")[0].performScrollTo().assertExists()+ rule.runOnIdle {+ v.prefillFromProfile("[email protected]", "Jane", "Doe", "555-1")+ assertEquals("[email protected]", v.passengers.value[0].email)+ assertEquals("Jane", v.passengers.value[0].givenName)+ }+ // Booking error branch replaces the missing-details message.+ rule.runOnIdle { v.bookingMutable.value = BookingState.Error("Trip creation failed") }+ rule.onNodeWithText("Trip creation failed").performScrollTo().assertExists()+ rule.runOnIdle { v.bookingMutable.value = BookingState.Loading }+ rule.onNodeWithText("Creating trip…").performScrollTo().assertExists()+ }++ @Test+ fun ancillaries_multiPassenger_seatsAndSummary() {+ val v = vm()+ v.reviewMutable.value = OfferReviewState(offer = offer())+ v.ancillariesMutable.value = AncillariesState(+ ancillaries = TripAncillariesDto(+ services = listOf(+ ServiceDto(id = "bag_1", type = "baggage", title = "Checked bag", totalAmount = "30.00", totalCurrency = "USD", maxQuantity = 3, passengerIds = listOf("pax_2")),+ ServiceDto(id = "ext_1", type = "extra", title = "Priority boarding", totalAmount = "15.00", totalCurrency = "USD", maxQuantity = 1, passengerIds = listOf("pax_1")),+ ServiceDto(id = "seat_1", type = "seat", title = "Seat", totalAmount = "25.00", totalCurrency = "USD", passengerIds = listOf("pax_1")),+ ),+ ),+ )+ v.selectedBaggageMutable.value = mapOf("bag_1" to 2L)+ v.selectedExtrasMutable.value = mapOf("ext_1" to 1L)+ v.selectedSeatsMutable.value = mapOf(+ "seg_1|pax_1" to com.vayunmathur.travel.network.SeatElementDto(+ type = "seat", designator = "14A", available = true, serviceId = "seat_1", totalAmount = "25.00",+ ),+ )+ rule.setContent { AncillariesPage(stack(), v, Route.Ancillaries("off_1")) }+ rule.onNodeWithText("Checked bag").assertIsDisplayed()+ rule.onNodeWithText("Priority boarding").performScrollTo().assertExists()+ rule.onAllNodesWithText("Child 2", substring = true)[0].performScrollTo().assertExists()+ rule.onAllNodesWithText("14A", substring = true)[0].performScrollTo().assertExists()+ rule.onNodeWithText("Continue to checkout").performScrollTo().assertExists()+ // Error branch.+ rule.runOnIdle {+ v.ancillariesMutable.value = v.ancillaries.value.copy(error = "Extras failed to save")+ }+ rule.onNodeWithText("Extras failed to save").performScrollTo().assertExists()+ }++ @Test+ fun ancillaries_seatMapsPending_showsRetryCard() {+ val v = vm()+ v.reviewMutable.value = OfferReviewState(offer = offer())+ v.ancillariesMutable.value = AncillariesState(+ ancillaries = TripAncillariesDto(services = emptyList()),+ seatMapsLoading = true,+ )+ rule.setContent { AncillariesPage(stack(), v, Route.Ancillaries("off_1")) }+ rule.onNodeWithText("Seat maps are still loading", substring = true).performScrollTo().assertExists()+ rule.onNodeWithText("Retry").performScrollTo().assertExists()+ }++ @Test+ fun ancillaries_noOffer_showsEmptyState() {+ val v = vm()+ rule.setContent { AncillariesPage(stack(), v, Route.Ancillaries("off_1")) }+ rule.onNodeWithText("No offer selected.").assertIsDisplayed()+ }++ @Test+ fun offerReview_roundTrip_policiesAndOperatingCarrier() {+ val v = vm()+ v.reviewMutable.value = OfferReviewState(offer = offer())+ val s = stack()+ rule.setContent { OfferReviewPage(s, v, Route.OfferReview("off_1")) }+ rule.onNodeWithText("Alaska").assertIsDisplayed()+ rule.onNodeWithText("Main Cabin").performScrollTo().assertExists()+ rule.onNodeWithText("Refundable").performScrollTo().assertExists()+ rule.onNodeWithText("Outbound").performScrollTo().assertExists()+ rule.onNodeWithText("Return").performScrollTo().assertExists()+ rule.onAllNodesWithText("737-900", substring = true)[0].performScrollTo().assertExists()+ rule.onAllNodesWithText("Operated by", substring = true)[0].performScrollTo().assertExists()+ rule.onNodeWithText("Fare policies").performScrollTo().assertExists()+ rule.onAllNodesWithText("$250", substring = true)[0].performScrollTo().assertExists()+ assertTrue(s.backStack.last() is Route.Home)+ }+}
travel/src/test/java/com/vayunmathur/travel/ui/TravelPagesC5cTest.kt
diff --git a/travel/src/test/java/com/vayunmathur/travel/ui/TravelPagesC5cTest.kt b/travel/src/test/java/com/vayunmathur/travel/ui/TravelPagesC5cTest.ktnew file mode 100644index 0000000000..a84f1fff4c--- /dev/null+++ b/travel/src/test/java/com/vayunmathur/travel/ui/TravelPagesC5cTest.kt@@ -0,0 +1,221 @@+package com.vayunmathur.travel.ui++import androidx.compose.ui.test.assertIsDisplayed+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.performTouchInput+import androidx.compose.ui.test.swipeUp+import androidx.compose.ui.test.performScrollTo+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.travel.Route+import com.vayunmathur.travel.data.BookedTrip+import com.vayunmathur.travel.data.Customer+import com.vayunmathur.travel.data.FrequentFlyer+import com.vayunmathur.travel.data.RecentSearch+import com.vayunmathur.travel.data.TravelRepository+import com.vayunmathur.travel.network.OfferDto+import com.vayunmathur.travel.network.OfferPassengerDto+import com.vayunmathur.travel.network.SegmentDto+import com.vayunmathur.travel.network.SliceDto+import com.vayunmathur.travel.network.StayRateDto+import com.vayunmathur.travel.network.StayRatesDto+import com.vayunmathur.travel.network.StayRoomDto+import com.vayunmathur.travel.util.OfferReviewState+import com.vayunmathur.travel.util.StayRatesState+import com.vayunmathur.travel.util.TravelViewModel+import com.vayunmathur.travel.util.selectedStayRate+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue+import kotlinx.coroutines.flow.Flow+import kotlinx.coroutines.flow.MutableStateFlow+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++/**+ * C5 page branches, part 3: a fully populated stay detail with rate+ * selection, and the offer review's held-price / error / continue+ * branches.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class TravelPagesC5cTest {++ @get:Rule val rule = createComposeRule()++ private class FakeRepo(ctx: android.content.Context) : TravelRepository(ctx) {+ val trips = MutableStateFlow<List<BookedTrip>>(emptyList())+ val customers = MutableStateFlow<List<Customer>>(emptyList())+ val flyers = MutableStateFlow<List<FrequentFlyer>>(emptyList())+ val recents = MutableStateFlow<List<RecentSearch>>(emptyList())+ override fun observeRecent(limit: Int): Flow<List<RecentSearch>> = recents+ override fun observeBookedTrips(): Flow<List<BookedTrip>> = trips+ override fun observeFrequentFlyers(): Flow<List<FrequentFlyer>> = flyers+ override fun observeCustomers(): Flow<List<Customer>> = customers+ override suspend fun getAllFrequentFlyers(): List<FrequentFlyer> = flyers.value+ override suspend fun getBookedTrip(orderId: String): BookedTrip? = trips.value.find { it.orderId == orderId }+ override suspend fun insertRecent(value: RecentSearch) {}+ override suspend fun clearRecent() {}+ override suspend fun trimRecent(keep: Int) {}+ override suspend fun upsertBookedTrip(value: BookedTrip) {}+ }++ private lateinit var repo: FakeRepo++ @BeforeTest+ fun open() {+ repo = FakeRepo(ApplicationProvider.getApplicationContext())+ com.vayunmathur.travel.network.travelTransport = null+ }++ private fun vm(): TravelViewModel {+ val ctx = ApplicationProvider.getApplicationContext<android.content.Context>()+ return TravelViewModel(ctx as android.app.Application, repo)+ }++ private fun stack() = NavBackStack<Route>(arrayOf(Route.Home))++ private fun rates() = StayRatesDto(+ name = "C5 Grand Hotel",+ rating = 4,+ reviewScore = 8.7,+ address = "1 C5 Plaza, Springfield",+ amenities = listOf("Pool", "Spa", "WiFi", "Gym", "Bar", "Parking", "Sauna", "Desk", "Extra"),+ description = "A grand C5 hotel by the river.",+ checkInTime = "15:00",+ checkOutTime = "11:00",+ rooms = listOf(+ StayRoomDto(+ name = "Deluxe King",+ rates = listOf(+ StayRateDto(id = "rate-1", boardType = "breakfast", totalAmount = "180.00", cancellation = "Free cancellation"),+ StayRateDto(id = "rate-2", boardType = "", totalAmount = "150.00", cancellation = "Non-refundable"),+ ),+ ),+ StayRoomDto(+ name = "",+ rates = listOf(+ StayRateDto(id = "rate-3", boardType = "half board", totalAmount = "210.00", cancellation = "Free cancellation"),+ ),+ ),+ ),+ )++ @Test+ fun stayDetail_fullHotel_showsRoomsAndSelectsRate() {+ val v = vm()+ val s = stack()+ // The page loads rates on entry; serve them (and the quote that a+ // rate tap requests) from the scripted transport.+ val ratesJson = com.vayunmathur.travel.network.travelJson.encodeToString(+ StayRatesDto.serializer(), rates(),+ )+ com.vayunmathur.travel.network.travelTransport = { _, url, _ ->+ when {+ url.contains("/rates") -> com.vayunmathur.travel.network.TravelRaw(200, ratesJson)+ url.contains("/quote") -> com.vayunmathur.travel.network.TravelRaw(+ 200, """{"id":"q-c5","totalAmount":"150.00","totalCurrency":"USD"}""",+ )+ else -> com.vayunmathur.travel.network.TravelRaw(404, """{"message":"not found"}""")+ }+ }+ rule.setContent { StayDetailPage(s, v, Route.StayDetail("sr-c5", "C5 Grand Hotel")) }+ rule.waitUntil(5_000) {+ rule.onAllNodesWithText("Deluxe King").fetchSemanticsNodes().isNotEmpty()+ }+ rule.onNodeWithText("1 C5 Plaza, Springfield").performScrollTo().assertExists()+ rule.onNodeWithText("A grand C5 hotel by the river.", substring = true).performScrollTo().assertExists()+ rule.onNodeWithText("Pool", substring = true).performScrollTo().assertExists()+ rule.onAllNodesWithText("Free cancellation")[0].performScrollTo().assertExists()+ // Blank board type falls back to the room-only label (merged into+ // the rate card's semantics, so it is matched as a substring).+ rule.onAllNodesWithText("Room only", substring = true)[0].assertExists()+ // Bring the rate cards fully on screen, then tap the $150 one.+ rule.onNodeWithText("Deluxe King").performTouchInput { swipeUp() }+ rule.waitForIdle()+ rule.onAllNodesWithText("$150")[0].performClick()+ rule.waitForIdle()+ assertEquals("rate-2", v.selectedStayRate()?.id)+ assertEquals(Route.StayGuests, s.last())+ }++ @Test+ fun stayDetail_loadingAndError_states() {+ val v = vm()+ val s = stack()+ rule.setContent { StayDetailPage(s, v, Route.StayDetail("sr-c5e", "")) }+ rule.waitUntil(5_000) {+ v.stayRatesMutable.value = StayRatesState(error = "C5 stay load failed")+ rule.onAllNodesWithText("C5 stay load failed").fetchSemanticsNodes().isNotEmpty()+ }+ rule.onNodeWithText("C5 stay load failed").assertIsDisplayed()+ }++ private fun offer(expiresAt: String = "") = OfferDto(+ offerId = "off-c5", totalAmount = "250.00", currency = "USD",+ owner = "C5 Air", ownerIata = "C5",+ passengerIds = listOf("pax_1"),+ passengers = listOf(OfferPassengerDto(id = "pax_1", type = "adult")),+ expiresAt = expiresAt,+ slices = listOf(+ SliceDto(+ origin = "SFO", destination = "JFK", durationMinutes = 315, stops = 0,+ departureAt = "2027-06-24T07:15:00", arrivalAt = "2027-06-24T15:50:00",+ segments = listOf(+ SegmentDto(+ id = "seg-c5", carrier = "C5 Air", carrierIata = "C5", flightNumber = "42",+ origin = "SFO", destination = "JFK",+ departureAt = "2027-06-24T07:15:00", arrivalAt = "2027-06-24T15:50:00",+ ),+ ),+ ),+ ),+ )++ @Test+ fun offerReview_heldPrice_andContinue_navigatesToPassengers() {+ val v = vm()+ val s = stack()+ // The page re-verifies the offer on entry; answer with the same offer+ // so verification succeeds and Continue stays enabled.+ val json = com.vayunmathur.travel.network.travelJson.encodeToString(+ OfferDto.serializer(), offer(expiresAt = "2999-01-01T00:00:00Z"),+ )+ com.vayunmathur.travel.network.travelTransport = { _, url, _ ->+ if (url.contains("/offer")) com.vayunmathur.travel.network.TravelRaw(200, json)+ else com.vayunmathur.travel.network.TravelRaw(404, """{"message":"not found"}""")+ }+ v.reviewMutable.value = OfferReviewState(offer = offer(expiresAt = "2999-01-01T00:00:00Z"))+ rule.setContent { OfferReviewPage(s, v, Route.OfferReview("off-c5")) }+ rule.waitUntil(5_000) {+ rule.onAllNodesWithText("Price held", substring = true).fetchSemanticsNodes().isNotEmpty()+ }+ rule.onNodeWithText("Continue").performScrollTo().performClick()+ rule.waitForIdle()+ assertTrue(s.last() is Route.Passengers, "continue goes to passengers, was ${s.last()}")+ }++ @Test+ fun offerReview_error_blocksContinue() {+ val v = vm()+ val s = stack()+ rule.setContent { OfferReviewPage(s, v, Route.OfferReview("off-c5")) }+ rule.waitUntil(5_000) {+ v.reviewMutable.value = OfferReviewState(+ offer = offer(), error = "C5 price check failed",+ )+ rule.onAllNodesWithText("C5 price check failed").fetchSemanticsNodes().isNotEmpty()+ }+ rule.onNodeWithText("C5 price check failed").performScrollTo().assertExists()+ rule.onNodeWithText("Continue").performScrollTo().performClick()+ rule.waitForIdle()+ // Disabled button: no navigation happened.+ assertEquals(Route.Home, s.last())+ }+}
travel/src/test/java/com/vayunmathur/travel/util/TravelBookingC5Test.kt
diff --git a/travel/src/test/java/com/vayunmathur/travel/util/TravelBookingC5Test.kt b/travel/src/test/java/com/vayunmathur/travel/util/TravelBookingC5Test.ktnew file mode 100644index 0000000000..3a203023db--- /dev/null+++ b/travel/src/test/java/com/vayunmathur/travel/util/TravelBookingC5Test.kt@@ -0,0 +1,312 @@+package com.vayunmathur.travel.util++import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.travel.data.BookedTrip+import com.vayunmathur.travel.data.Customer+import com.vayunmathur.travel.data.FrequentFlyer+import com.vayunmathur.travel.data.RecentSearch+import com.vayunmathur.travel.data.TravelRepository+import com.vayunmathur.travel.network.OfferDto+import com.vayunmathur.travel.network.OfferPassengerDto+import com.vayunmathur.travel.network.PassengerInputDto+import com.vayunmathur.travel.network.SeatElementDto+import com.vayunmathur.travel.network.SegmentDto+import com.vayunmathur.travel.network.SliceDto+import com.vayunmathur.travel.network.TravelRaw+import com.vayunmathur.travel.network.TripDto+import com.vayunmathur.travel.network.travelTransport+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertTrue+import kotlinx.coroutines.flow.Flow+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.test.runTest+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import org.robolectric.shadows.ShadowLooper++/**+ * Booking branches beyond the happy path: missing-details checkout, seat-map+ * retry, stored-trip refresh, pending-trip ids, ancillary save failure, and+ * frequent-flyer prefill on passenger init.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class TravelBookingC5Test {++ private class FakeRepo(ctx: android.content.Context) : TravelRepository(ctx) {+ val trips = MutableStateFlow<List<BookedTrip>>(emptyList())+ var flyers: List<FrequentFlyer> = emptyList()+ override fun observeRecent(limit: Int): Flow<List<RecentSearch>> = MutableStateFlow(emptyList())+ override fun observeBookedTrips(): Flow<List<BookedTrip>> = trips+ override fun observeFrequentFlyers(): Flow<List<FrequentFlyer>> = MutableStateFlow(emptyList())+ override fun observeCustomers(): Flow<List<Customer>> = MutableStateFlow(emptyList())+ override suspend fun getAllFrequentFlyers(): List<FrequentFlyer> = flyers+ override suspend fun getAllBookedTrips(): List<BookedTrip> = trips.value+ override suspend fun getBookedTrip(orderId: String): BookedTrip? = trips.value.find { it.orderId == orderId }+ override suspend fun insertRecent(value: RecentSearch) {}+ override suspend fun clearRecent() {}+ override suspend fun trimRecent(keep: Int) {}+ override suspend fun upsertBookedTrip(value: BookedTrip) {+ trips.value = trips.value.filter { it.orderId != value.orderId } + value+ }+ }++ private lateinit var repo: FakeRepo+ private var handler: (String) -> TravelRaw = { TravelRaw(404, """{"message":"not found"}""") }++ @BeforeTest+ fun open() {+ repo = FakeRepo(ApplicationProvider.getApplicationContext())+ handler = { TravelRaw(404, """{"message":"not found"}""") }+ travelTransport = { _, url, _ -> handler(url) }+ }++ @AfterTest fun clear() { travelTransport = null }++ private fun vm(): TravelViewModel {+ val ctx = ApplicationProvider.getApplicationContext<android.content.Context>()+ return TravelViewModel(ctx as android.app.Application, repo)+ }++ private fun idle() { repeat(5) { ShadowLooper.idleMainLooper() } }++ private fun offer() = OfferDto(+ offerId = "off_1", totalAmount = "250.00", currency = "USD", ownerIata = "AS",+ passengerIds = listOf("pax_1"),+ passengers = listOf(OfferPassengerDto(id = "pax_1", type = "adult")),+ slices = listOf(+ SliceDto(+ origin = "SFO", destination = "JFK",+ departureAt = "2027-06-24T07:15:00", arrivalAt = "2027-06-24T15:50:00",+ segments = listOf(+ SegmentDto(+ id = "seg_1", carrierIata = "AS", flightNumber = "100",+ origin = "SFO", destination = "JFK",+ departureAt = "2027-06-24T07:15:00", arrivalAt = "2027-06-24T15:50:00",+ )+ ),+ )+ ),+ )++ @Test+ fun initPassengers_prefillsFrequentFlyerLoyalty() {+ repo.flyers = listOf(FrequentFlyer(airlineIata = "AS", accountNumber = "FF123", airlineName = "Alaska"))+ val v = vm()+ v.initPassengers(offer()); idle()+ assertEquals(1, v.passengers.value.size)+ assertEquals("FF123", v.passengers.value[0].loyaltyProgrammeAccounts.single().accountNumber)+ // Re-init with the same ids keeps the entered values.+ v.updatePassenger(0, v.passengers.value[0].copy(givenName = "Jane"))+ v.initPassengers(offer()); idle()+ assertEquals("Jane", v.passengers.value[0].givenName)+ }++ @Test+ fun prefillFromProfile_fillsBlanksOnly() {+ val v = vm()+ v.initPassengers(offer()); idle()+ v.updatePassenger(0, v.passengers.value[0].copy(givenName = "Typed"))+ v.prefillFromProfile("[email protected]", "Jane", "Doe", "555-1")+ val lead = v.passengers.value[0]+ assertEquals("Typed", lead.givenName)+ assertEquals("Doe", lead.familyName)+ assertEquals("[email protected]", lead.email)+ assertEquals("555-1", lead.phoneNumber)+ }++ @Test+ fun createTrip_missingDetails_routesBackWithFields() {+ handler = { url ->+ if (url.contains("/trips")) TravelRaw(422, """{"message":"Missing passport","missingFields":["passport"]}""")+ else TravelRaw(404, """{"message":"not found"}""")+ }+ val v = vm()+ v.selectOffer(offer()); v.initPassengers(offer()); idle()+ v.createTrip(); idle()+ val missing = v.booking.value as BookingState.MissingDetails+ assertEquals(listOf("passport"), missing.missingFields)+ v.resetBooking()+ assertTrue(v.booking.value is BookingState.Idle)+ }++ @Test+ fun createTrip_emptySelection_isNoOp() {+ val v = vm()+ v.createTrip(); idle()+ assertTrue(v.booking.value is BookingState.Idle)+ }++ @Test+ fun startCheckout_missingDetails_setsBookingState() {+ handler = { url ->+ if (url.contains("/checkout")) TravelRaw(422, """{"message":"Missing DOB","missingFields":["bornOn"]}""")+ else TravelRaw(404, """{"message":"not found"}""")+ }+ val v = vm()+ v.currentTrip = TripDto(tripId = "trip_1", status = "created")+ v.startCheckout(); idle()+ assertTrue(v.booking.value is BookingState.MissingDetails, "booking=${v.booking.value}")+ v.resetCheckout()+ assertTrue(v.checkout.value is CheckoutState.Idle)+ }++ @Test+ fun acceptNewPrice_onlyAppliesToReadyCheckout() {+ val v = vm()+ v.acceptNewPrice() // Idle: no-op, must not throw or change state.+ assertTrue(v.checkout.value is CheckoutState.Idle)+ v.checkoutMutable.value = CheckoutState.Ready(+ com.vayunmathur.travel.network.CheckoutDto(totalAmount = "300.00", priceChanged = true)+ )+ v.acceptNewPrice()+ assertTrue((v.checkout.value as CheckoutState.Ready).acceptedNewPrice)+ }++ @Test+ fun loadAncillaries_error_surfacesMessage() {+ val v = vm()+ v.loadAncillaries("trip_1"); idle()+ assertNotNull(v.ancillaries.value.error)+ }++ @Test+ fun retrySeatMaps_success_updatesAncillariesAndCabins() {+ handler = { url ->+ if (url.contains("/ancillaries")) {+ TravelRaw(+ 200,+ """{"status":"ok","services":[],"seatMaps":[{"cabin":"economy","rows":[]}],"seatMapsPending":false}""",+ )+ } else TravelRaw(404, """{"message":"not found"}""")+ }+ val v = vm()+ v.currentTrip = TripDto(tripId = "trip_1", status = "created")+ v.retrySeatMaps(); idle()+ assertEquals(1, v.seatMap.value.cabins.size)+ assertEquals(false, v.ancillaries.value.seatMapsLoading)+ v.loadSeatMaps()+ assertEquals(1, v.seatMap.value.cabins.size)+ }++ @Test+ fun retrySeatMaps_failure_setsErrorAndNoTripIsNoOp() {+ val v = vm()+ v.retrySeatMaps(); idle() // No current trip: no-op.+ assertEquals(false, v.ancillaries.value.seatMapsLoading)+ v.currentTrip = TripDto(tripId = "trip_1", status = "created")+ v.retrySeatMaps(); idle()+ assertNotNull(v.ancillaries.value.error)+ assertEquals(false, v.ancillaries.value.seatMapsLoading)+ }++ @Test+ fun saveAncillaries_noChanges_proceedsWithoutNetwork() {+ val v = vm()+ v.currentTrip = TripDto(tripId = "trip_1", status = "created")+ var proceeded = false+ v.saveAncillaries { proceeded = true }+ assertTrue(proceeded)+ assertTrue(v.checkout.value is CheckoutState.Idle)+ }++ @Test+ fun saveAncillaries_failure_keepsError() {+ val v = vm()+ v.currentTrip = TripDto(tripId = "trip_1", status = "created")+ v.setBaggageQuantity("bag_1", 1)+ var proceeded = false+ v.saveAncillaries { proceeded = true }; idle()+ assertEquals(false, proceeded)+ assertNotNull(v.ancillaries.value.error)+ v.setBaggageQuantity("bag_1", 0)+ assertTrue(v.selectedBaggage.value.isEmpty())+ v.setExtraQuantity("ext_1", 2)+ assertEquals(2L, v.selectedExtras.value["ext_1"])+ v.setExtraQuantity("ext_1", 0)+ assertTrue(v.selectedExtras.value.isEmpty())+ }++ @Test+ fun toggleSeat_andSelectedServices_carryPassenger() {+ val v = vm()+ v.ancillariesMutable.value = AncillariesState(+ ancillaries = com.vayunmathur.travel.network.TripAncillariesDto(+ services = listOf(+ com.vayunmathur.travel.network.ServiceDto(+ id = "bag_1", type = "baggage", title = "Bag",+ passengerIds = listOf("pax_1"),+ )+ ),+ )+ )+ v.setBaggageQuantity("bag_1", 1)+ v.toggleSeat("seg_1", "pax_1", SeatElementDto(type = "seat", designator = "14A", available = true, serviceId = "seat_svc_1"))+ val services = v.selectedServices()+ assertTrue(services.any { it.id == "bag_1" && it.passengerId == "pax_1" }, "services=$services")+ assertTrue(services.any { it.id == "seat_svc_1" && it.passengerId == "pax_1" }, "services=$services")+ }++ @Test+ fun pollTrip_terminalStatus_finishesAndUpdatesStored() {+ repo.trips.value = listOf(+ BookedTrip(+ orderId = "trip_1", bookingReference = "", route = "SFO → JFK",+ departDate = "2027-06-24", amount = "250.00", currency = "USD", tripId = "trip_1",+ )+ )+ handler = { url ->+ if (url.contains("/trips/")) {+ TravelRaw(200, """{"tripId":"trip_1","status":"confirmed","bookingReference":"ABC123","totalAmount":"250.00","currency":"USD"}""")+ } else TravelRaw(404, """{"message":"not found"}""")+ }+ val v = vm()+ v.pollTrip("trip_1"); idle()+ assertTrue(v.tripPoll.value is TripPollState.Done, "poll=${v.tripPoll.value}")+ assertEquals("ABC123", repo.trips.value.single().bookingReference)+ v.stopTripPoll()+ }++ @Test+ fun confirmPaidTrip_failure_setsPollError() {+ val v = vm()+ v.confirmPaidTrip("trip_1"); idle()+ assertTrue(v.tripPoll.value is TripPollState.Error, "poll=${v.tripPoll.value}")+ }++ @Test+ fun refreshStoredTrip_updatesAmountAndMissingIsNoOp() {+ repo.trips.value = listOf(+ BookedTrip(+ orderId = "trip_1", bookingReference = "ABC123", route = "SFO → JFK",+ departDate = "2027-06-24", amount = "250.00", currency = "USD", tripId = "trip_1",+ )+ )+ handler = { url ->+ if (url.contains("/trips/")) {+ TravelRaw(200, """{"tripId":"trip_1","status":"confirmed","bookingReference":"ABC123","totalAmount":"275.00","currency":"USD"}""")+ } else TravelRaw(404, """{"message":"not found"}""")+ }+ val v = vm()+ v.refreshStoredTrip("missing"); idle()+ v.refreshStoredTrip("trip_1"); idle()+ assertEquals("275.00", repo.trips.value.single().amount)+ }++ @Test+ fun pendingTripIds_filtersByStatusAndFallsBackToOrderId() = runTest {+ repo.trips.value = listOf(+ BookedTrip(orderId = "ord_a", bookingReference = "A", route = "X → Y", departDate = "2027-01-01", amount = "1", currency = "USD", status = "pending_payment", tripId = "trip_a"),+ BookedTrip(orderId = "ord_b", bookingReference = "B", route = "X → Y", departDate = "2027-01-01", amount = "1", currency = "USD", status = "processing", tripId = ""),+ BookedTrip(orderId = "ord_c", bookingReference = "C", route = "X → Y", departDate = "2027-01-01", amount = "1", currency = "USD", status = "confirmed", tripId = "trip_c"),+ )+ val v = vm()+ assertEquals(listOf("trip_a", "ord_b"), v.pendingTripIds())+ assertEquals("Jane", PassengerInputDto(givenName = "Jane").givenName)+ }+}
travel/src/test/java/com/vayunmathur/travel/util/TravelServicingC5Test.kt
diff --git a/travel/src/test/java/com/vayunmathur/travel/util/TravelServicingC5Test.kt b/travel/src/test/java/com/vayunmathur/travel/util/TravelServicingC5Test.ktnew file mode 100644index 0000000000..bdc29067f6--- /dev/null+++ b/travel/src/test/java/com/vayunmathur/travel/util/TravelServicingC5Test.kt@@ -0,0 +1,290 @@+package com.vayunmathur.travel.util++import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.travel.data.BookedTrip+import com.vayunmathur.travel.data.Customer+import com.vayunmathur.travel.data.FrequentFlyer+import com.vayunmathur.travel.data.RecentSearch+import com.vayunmathur.travel.data.TravelRepository+import com.vayunmathur.travel.network.TravelRaw+import com.vayunmathur.travel.network.travelTransport+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.flow.Flow+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.launch+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import org.robolectric.shadows.ShadowLooper++/**+ * Servicing branches the happy-path suite does not reach: missing/blank-ref+ * trips, direct succeeded/failed confirmations, first-poll terminal states,+ * checkout-url change polling, and expired re-checkout.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class TravelServicingC5Test {++ private class FakeRepo(ctx: android.content.Context) : TravelRepository(ctx) {+ val trips = MutableStateFlow<List<BookedTrip>>(emptyList())+ override fun observeRecent(limit: Int): Flow<List<RecentSearch>> = MutableStateFlow(emptyList())+ override fun observeBookedTrips(): Flow<List<BookedTrip>> = trips+ override fun observeFrequentFlyers(): Flow<List<FrequentFlyer>> = MutableStateFlow(emptyList())+ override fun observeCustomers(): Flow<List<Customer>> = MutableStateFlow(emptyList())+ override suspend fun getAllFrequentFlyers(): List<FrequentFlyer> = emptyList()+ override suspend fun getAllBookedTrips(): List<BookedTrip> = trips.value+ override suspend fun getBookedTrip(orderId: String): BookedTrip? = trips.value.find { it.orderId == orderId }+ override suspend fun insertRecent(value: RecentSearch) {}+ override suspend fun clearRecent() {}+ override suspend fun trimRecent(keep: Int) {}+ override suspend fun upsertBookedTrip(value: BookedTrip) {+ trips.value = trips.value.filter { it.orderId != value.orderId } + value+ }+ }++ private lateinit var repo: FakeRepo++ /** URL fragment -> response; tests swap [handler] to script each scenario. */+ private var handler: (String) -> TravelRaw = { TravelRaw(404, """{"message":"not found"}""") }++ @BeforeTest+ fun open() {+ repo = FakeRepo(ApplicationProvider.getApplicationContext())+ handler = { TravelRaw(404, """{"message":"not found"}""") }+ travelTransport = { _, url, _ -> handler(url) }+ }++ @AfterTest fun clear() { travelTransport = null }++ private fun vm(): TravelViewModel {+ val ctx = ApplicationProvider.getApplicationContext<android.content.Context>()+ return TravelViewModel(ctx as android.app.Application, repo)+ }++ private fun idle() { repeat(5) { ShadowLooper.idleMainLooper() } }++ private fun stored(+ orderId: String = "ord_1",+ ref: String = "ABC123",+ expires: String = "",+ ) = BookedTrip(+ orderId = orderId, bookingReference = ref, route = "SFO → JFK",+ departDate = "2027-06-24", amount = "250.00", currency = "USD",+ status = "pending_payment", tripId = "trip_1", lastName = "Doe",+ checkoutExpiresAt = expires,+ )++ private fun respond(map: Map<String, String>, code: Int = 200): (String) -> TravelRaw = { url ->+ map.entries.firstOrNull { url.contains(it.key) }+ ?.let { TravelRaw(code, it.value) }+ ?: TravelRaw(404, """{"message":"not found"}""")+ }++ @Test+ fun loadBookingDetail_missingTrip_reportsNotFound() {+ val v = vm()+ v.loadBookingDetail("nope"); idle()+ assertEquals("Trip not found.", v.orderDetail.value.error)+ }++ @Test+ fun loadBookingDetail_blankRef_refreshesTripAndReportsPending() {+ repo.trips.value = listOf(stored(orderId = "trip_1", ref = ""))+ handler = respond(mapOf("/trips/" to """{"tripId":"trip_1","status":"processing","totalAmount":"260.00","currency":"USD"}"""))+ val v = vm()+ v.loadBookingDetail("trip_1"); idle()+ assertEquals("Payment is still pending for this trip.", v.orderDetail.value.error)+ assertEquals("260.00", repo.trips.value.single().amount)+ }++ @Test+ fun loadBookingDetail_blankRefFailure_surfacesError() {+ repo.trips.value = listOf(stored(ref = ""))+ val v = vm()+ v.loadBookingDetail("ord_1"); idle()+ assertNotNull(v.orderDetail.value.error)+ assertNull(v.orderDetail.value.order)+ }++ @Test+ fun quoteAndChange_missingTrip_reportCant() {+ val v = vm()+ v.quoteCancellation("nope"); idle()+ assertEquals("This trip can't be cancelled.", v.cancellation.value.error)+ v.requestChange("nope", "sli_1", "SFO", "JFK", "2027-07-01", ""); idle()+ assertTrue(v.change.value.requested)+ assertEquals("This trip can't be changed.", v.change.value.error)+ v.priceChange("nope", "chg_1"); idle()+ assertEquals("This trip can't be changed.", v.change.value.error)+ v.confirmChange("nope", "chg_1"); idle()+ assertEquals("This trip can't be changed.", v.change.value.error)+ }++ @Test+ fun confirmCancellation_directSucceeded_marksTripCancelled() {+ repo.trips.value = listOf(stored())+ handler = { url ->+ when {+ url.contains("/confirm") -> TravelRaw(200, """{"id":"can_1","orderId":"ord_1","refundAmount":"200.00","refundCurrency":"USD","status":"succeeded"}""")+ url.contains("/cancel") -> TravelRaw(200, """{"id":"can_1","orderId":"ord_1","refundAmount":"200.00","refundCurrency":"USD","commitable":true,"status":"quoted"}""")+ else -> TravelRaw(404, """{"message":"not found"}""")+ }+ }+ val v = vm()+ v.quoteCancellation("ord_1"); idle()+ v.confirmCancellation("ord_1"); idle()+ assertTrue(v.cancellation.value.done)+ assertEquals("cancelled", repo.trips.value.single().status)+ v.resetCancellation()+ assertNull(v.cancellation.value.quote)+ }++ @Test+ fun confirmCancellation_directFailed_showsServerMessage() {+ repo.trips.value = listOf(stored())+ handler = { url ->+ when {+ url.contains("/confirm") -> TravelRaw(200, """{"id":"can_1","orderId":"ord_1","refundAmount":"200.00","refundCurrency":"USD","status":"failed","message":"Window closed"}""")+ url.contains("/cancel") -> TravelRaw(200, """{"id":"can_1","orderId":"ord_1","refundAmount":"200.00","refundCurrency":"USD","commitable":true,"status":"quoted"}""")+ else -> TravelRaw(404, """{"message":"not found"}""")+ }+ }+ val v = vm()+ v.quoteCancellation("ord_1"); idle()+ v.confirmCancellation("ord_1"); idle()+ assertEquals("Window closed", v.cancellation.value.error)+ }++ @Test+ fun confirmCancellation_processingThenFirstPollSucceeds() {+ repo.trips.value = listOf(stored())+ var confirmCalls = 0+ handler = { url ->+ when {+ url.contains("/cancel") && !url.contains("/cancellations/") ->+ TravelRaw(200, """{"id":"can_1","orderId":"ord_1","refundAmount":"200.00","refundCurrency":"USD","commitable":true,"status":"quoted"}""")+ url.contains("/confirm") -> {+ confirmCalls+++ TravelRaw(200, """{"id":"can_1","orderId":"ord_1","status":"processing"}""")+ }+ url.contains("/cancellations/") ->+ TravelRaw(200, """{"id":"can_1","orderId":"ord_1","status":"succeeded"}""")+ else -> TravelRaw(404, """{"message":"not found"}""")+ }+ }+ val v = vm()+ v.quoteCancellation("ord_1"); idle()+ v.confirmCancellation("ord_1"); idle()+ assertEquals(1, confirmCalls)+ assertTrue(v.cancellation.value.done, "state=${v.cancellation.value}")+ assertEquals("cancelled", repo.trips.value.single().status)+ }++ @Test+ fun confirmCancellation_processingThenFirstPollFails() {+ repo.trips.value = listOf(stored())+ handler = { url ->+ when {+ url.contains("/cancel") && !url.contains("/cancellations/") ->+ TravelRaw(200, """{"id":"can_1","orderId":"ord_1","refundAmount":"200.00","refundCurrency":"USD","commitable":true,"status":"quoted"}""")+ url.contains("/confirm") -> TravelRaw(200, """{"id":"can_1","orderId":"ord_1","status":"processing"}""")+ url.contains("/cancellations/") ->+ TravelRaw(200, """{"id":"can_1","orderId":"ord_1","status":"failed","message":"Refund rejected"}""")+ else -> TravelRaw(404, """{"message":"not found"}""")+ }+ }+ val v = vm()+ v.quoteCancellation("ord_1"); idle()+ v.confirmCancellation("ord_1"); idle()+ assertEquals("Refund rejected", v.cancellation.value.error)+ }++ @Test+ fun confirmChange_withCheckoutUrl_pollsToConfirmed() {+ repo.trips.value = listOf(stored())+ handler = respond(mapOf(+ "/changes/status" to """{"orderId":"ord_1","status":"confirmed"}""",+ "/confirm" to """{"orderId":"ord_1","status":"processing","checkoutUrl":"https://pay.example/chg"}""",+ ))+ val v = vm()+ v.confirmChange("ord_1", "chg_1"); idle()+ assertTrue(v.change.value.done, "state=${v.change.value}")+ assertEquals("https://pay.example/chg", v.change.value.checkoutUrl)+ v.resetChange()+ assertTrue(v.change.value.offers.isEmpty())+ }++ @Test+ fun confirmChange_withoutUrl_appliesPricedFare() {+ repo.trips.value = listOf(stored())+ handler = respond(mapOf(+ "/price" to """{"outcome":"pay","amount":"50.00","currency":"USD","newFareAmount":"300.00"}""",+ "/confirm" to """{"orderId":"ord_1","status":"confirmed"}""",+ ))+ val v = vm()+ v.priceChange("ord_1", "chg_1"); idle()+ assertEquals("300.00", v.change.value.price?.newFareAmount)+ v.confirmChange("ord_1", "chg_1"); idle()+ assertTrue(v.change.value.done)+ assertEquals("300.00", repo.trips.value.single().amount)+ }++ /** Collects [TravelViewModel.bookedTrips] so its WhileSubscribed stateIn emits. */+ private fun subscribeTrips(v: TravelViewModel): kotlinx.coroutines.Job {+ val job = kotlinx.coroutines.CoroutineScope(kotlinx.coroutines.Dispatchers.Unconfined)+ .launch { v.bookedTrips.collect {} }+ idle()+ return job+ }++ @Test+ fun recheckout_expired_reportsErrorWithoutNetwork() {+ repo.trips.value = listOf(stored(expires = "2000-01-01T00:00:00Z"))+ val v = vm()+ val job = subscribeTrips(v)+ try {+ assertEquals(1, v.bookedTrips.value.size)+ v.recheckoutForStoredTrip("ord_1"); idle()+ val error = v.checkout.value as CheckoutState.Error+ assertTrue(error.message.contains("expired"), "error=$error")+ } finally { job.cancel() }+ }++ @Test+ fun recheckout_unexpired_fetchesFreshIntent() {+ repo.trips.value = listOf(stored(expires = "2999-01-01T00:00:00Z"))+ handler = respond(mapOf(+ "/checkout" to """{"clientSecret":"cs_new","publishableKey":"pk_new","totalAmount":"255.00","currency":"USD","expiresAt":"2999-01-02T00:00:00Z"}""",+ ))+ val v = vm()+ val job = subscribeTrips(v)+ try {+ assertEquals(1, v.bookedTrips.value.size)+ v.recheckoutForStoredTrip("ord_1"); idle()+ val ready = v.checkout.value as CheckoutState.Ready+ assertEquals("255.00", ready.checkout.totalAmount)+ assertEquals("cs_new", ready.checkout.clientSecret)+ assertEquals("255.00", repo.trips.value.single().amount)+ } finally { job.cancel() }+ }++ @Test+ fun refreshBookingDetail_reloadsOrder() {+ repo.trips.value = listOf(stored())+ handler = respond(mapOf(+ "/bookings/" to """{"orderId":"ord_1","bookingReference":"ABC123","totalAmount":"250.00","currency":"USD","status":"confirmed","canCancel":true}""",+ ))+ val v = vm()+ v.loadBookingDetail("ord_1"); idle()+ assertEquals("ABC123", v.orderDetail.value.order?.bookingReference)+ v.refreshBookingDetail("ord_1"); idle()+ assertEquals("ABC123", v.orderDetail.value.order?.bookingReference)+ }+}