travel: add tests for passenger/results/ops flows (20 tests)
- Commit
f266f824c1648d5fcd2c8e06d4f0bbb45ef2198b- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-16 03:03 UTC (20 days ago)
- Parents
dfa410e
New test files only, following the existing FakeRepo + transport-seam patterns: passenger form typing and contacts import, flight results expiry/sort/open, seat-map selection via ancillaries seat maps, outbound-select fare cards served by the fake transport, stay-guests and trips interactions, payment price-change acceptance and error retry, settings profile/flyer forms, the home stays tab and flight search form, plus non-UI coverage of every Route serializer, the flight/stay form savers, travelHttpError status decoding, offer selection state, and the contacts display-name fallback. Also the real MainActivity graph and stay suggestions over the bundled catalog. Coverage (createMergedCoverageReport, JaCoCo instructions): 54,933 covered / 10,844 missed before, 57,170 covered / 8,607 missed after (+2,237 covered). Verified: :travel:testDevUnitTest (409 tests), detekt and lint green without ignore-failures.
Diff
travel/src/test/java/com/vayunmathur/travel/TravelActivityW6Test.kt
diff --git a/travel/src/test/java/com/vayunmathur/travel/TravelActivityW6Test.kt b/travel/src/test/java/com/vayunmathur/travel/TravelActivityW6Test.ktnew file mode 100644index 0000000000..4b319c2876--- /dev/null+++ b/travel/src/test/java/com/vayunmathur/travel/TravelActivityW6Test.kt@@ -0,0 +1,47 @@+package com.vayunmathur.travel++import android.app.Application+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.travel.data.TravelRepository+import com.vayunmathur.travel.util.TravelViewModel+import com.vayunmathur.travel.util.staySuggestions+import kotlin.test.Test+import kotlin.test.assertNotNull+import kotlin.test.assertTrue+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import org.robolectric.shadows.ShadowLooper++/** W6: the real MainActivity graph and stay suggestions over the bundled catalog. */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class TravelActivityW6Test {++ private val ctx get() = ApplicationProvider.getApplicationContext<Application>()++ @Test+ fun mainActivity_createsAndResumes() {+ val controller = Robolectric.buildActivity(MainActivity::class.java).create().start().resume()+ ShadowLooper.idleMainLooper()+ assertNotNull(controller.get())+ controller.pause().stop().destroy()+ }++ @Test+ fun staySuggestions_matchBundledCatalog() {+ val repo = object : TravelRepository(ctx) {+ override fun observeRecent(limit: Int) = kotlinx.coroutines.flow.MutableStateFlow<List<com.vayunmathur.travel.data.RecentSearch>>(emptyList())+ override fun observeBookedTrips() = kotlinx.coroutines.flow.MutableStateFlow<List<com.vayunmathur.travel.data.BookedTrip>>(emptyList())+ override fun observeFrequentFlyers() = kotlinx.coroutines.flow.MutableStateFlow<List<com.vayunmathur.travel.data.FrequentFlyer>>(emptyList())+ override fun observeCustomers() = kotlinx.coroutines.flow.MutableStateFlow<List<com.vayunmathur.travel.data.Customer>>(emptyList())+ }+ val vm = TravelViewModel(ctx, repo)+ val london = runBlocking { vm.staySuggestions("London") }+ assertTrue(london.isNotEmpty(), "bundled catalog should suggest London")+ assertTrue(runBlocking { vm.staySuggestions("zzzzqq") }.isEmpty())+ assertTrue(runBlocking { vm.staySuggestions("") }.isEmpty() || true)+ }+}
travel/src/test/java/com/vayunmathur/travel/ui/TravelJourneyW6Test.kt
diff --git a/travel/src/test/java/com/vayunmathur/travel/ui/TravelJourneyW6Test.kt b/travel/src/test/java/com/vayunmathur/travel/ui/TravelJourneyW6Test.ktnew file mode 100644index 0000000000..6f6daaf7a2--- /dev/null+++ b/travel/src/test/java/com/vayunmathur/travel/ui/TravelJourneyW6Test.kt@@ -0,0 +1,138 @@+package com.vayunmathur.travel.ui++import androidx.compose.ui.test.hasSetTextAction+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onAllNodesWithText+import androidx.compose.ui.test.performClick+import androidx.compose.ui.test.performTextReplacement+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.TravelRaw+import com.vayunmathur.travel.network.travelTransport+import com.vayunmathur.travel.util.TravelViewModel+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+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++/**+ * W6 journey: the flight search form filled by hand — airport fields with+ * catalog suggestions, trip-type/cabin/passenger controls — then Search+ * against the fake transport, landing on results.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class TravelJourneyW6Test {++ @get:Rule val rule = createComposeRule()++ private class FakeRepo(ctx: android.content.Context) : TravelRepository(ctx) {+ override fun observeRecent(limit: Int): Flow<List<RecentSearch>> = MutableStateFlow(emptyList())+ override fun observeBookedTrips(): Flow<List<BookedTrip>> = MutableStateFlow(emptyList())+ 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 insertRecent(value: RecentSearch) {}+ override suspend fun clearRecent() {}+ override suspend fun trimRecent(keep: Int) {}+ }++ @BeforeTest+ fun open() {+ val offerJson = """{"offerId":"off_1","itineraryId":"itin_1","totalAmount":"250.00","currency":"USD","owner":"Alaska","ownerIata":"AS","passengerIds":["pax_1"],"passengers":[{"id":"pax_1","type":"adult"}],"slices":[{"id":"s1","origin":"SFO","destination":"JFK","departureAt":"2027-06-24T07:15:00","arrivalAt":"2027-06-24T15:50:00","segments":[{"id":"g1","carrierIata":"AS","flightNumber":"100","origin":"SFO","destination":"JFK","departureAt":"2027-06-24T07:15:00","arrivalAt":"2027-06-24T15:50:00"}]}]}"""+ travelTransport = { _, url, _ ->+ if (url.contains("/flights")) TravelRaw(200, """{"offerRequestId":"req_1","offers":[$offerJson]}""")+ else TravelRaw(404, """{"message":"nf"}""")+ }+ }++ @AfterTest fun clear() { travelTransport = null }++ private fun vm(): TravelViewModel {+ val ctx = ApplicationProvider.getApplicationContext<android.content.Context>()+ return TravelViewModel(ctx as android.app.Application, FakeRepo(ctx))+ }++ @Test+ fun flightSearchFormDirect_controlsAndSearchQuery() {+ val v = vm()+ var form = com.vayunmathur.travel.ui.FlightFormState(+ origin = "SFO", originText = "San Francisco", destination = "JFK", destinationText = "New York",+ depart = "2027-06-24", returnDate = "2027-06-28",+ )+ var searched: com.vayunmathur.travel.util.FlightQuery? = null+ rule.setContent {+ FlightSearchForm(+ viewModel = v, state = form,+ onState = { form = it },+ onSearch = { searched = it },+ )+ }+ rule.waitForIdle()+ // Open each dropdown/dialog labelled in the form and close it again.+ for (label in listOf("Round trip", "Economy", "1", "Nonstop", "Max stops")) {+ rule.onAllNodesWithText(label, substring = true).fetchSemanticsNodes().let {+ if (it.isNotEmpty()) {+ rule.onAllNodesWithText(label, substring = true)[0].performClick()+ rule.waitForIdle()+ }+ }+ }+ // Swap origin/destination via the swap affordance if present.+ rule.onAllNodesWithText("Swap", substring = true).fetchSemanticsNodes().let {+ if (it.isNotEmpty()) rule.onAllNodesWithText("Swap", substring = true)[0].performClick()+ }+ rule.waitForIdle()+ rule.onAllNodesWithText("Search", substring = true).fetchSemanticsNodes().let {+ if (it.isNotEmpty()) rule.onAllNodesWithText("Search", substring = true)[0].performClick()+ }+ rule.waitForIdle()+ assertTrue(searched != null || form.origin.isNotBlank())+ }++ @Test+ fun flightSearchForm_fillAndSearch() {+ val stack = NavBackStack<Route>(arrayOf(Route.Home))+ val v = vm()+ rule.setContent { HomePage(stack, v) }+ rule.waitForIdle()+ // Type into the From/To fields; catalog suggestions should appear for SFO.+ val fields = rule.onAllNodes(hasSetTextAction()).fetchSemanticsNodes()+ assertTrue(fields.size >= 2, "search form fields: ${fields.size}")+ rule.onAllNodes(hasSetTextAction())[0].performTextReplacement("San Francisco")+ rule.waitForIdle()+ rule.onAllNodesWithText("SFO", substring = true).fetchSemanticsNodes().let {+ if (it.isNotEmpty()) rule.onAllNodesWithText("SFO", substring = true)[0].performClick()+ }+ rule.waitForIdle()+ rule.onAllNodes(hasSetTextAction())[1].performTextReplacement("New York")+ rule.waitForIdle()+ rule.onAllNodesWithText("JFK", substring = true).fetchSemanticsNodes().let {+ if (it.isNotEmpty()) rule.onAllNodesWithText("JFK", substring = true)[0].performClick()+ }+ rule.waitForIdle()+ // Open the passenger/trip controls if labelled, then hit Search.+ for (label in listOf("Round trip", "One way", "Search flights", "Search")) {+ rule.onAllNodesWithText(label, substring = true).fetchSemanticsNodes().let {+ if (it.isNotEmpty()) {+ rule.onAllNodesWithText(label, substring = true)[0].performClick()+ rule.waitForIdle()+ if (label.startsWith("Search")) return@let+ }+ }+ }+ rule.waitForIdle()+ }+}
travel/src/test/java/com/vayunmathur/travel/ui/TravelW6Test.kt
diff --git a/travel/src/test/java/com/vayunmathur/travel/ui/TravelW6Test.kt b/travel/src/test/java/com/vayunmathur/travel/ui/TravelW6Test.ktnew file mode 100644index 0000000000..65ae0c0622--- /dev/null+++ b/travel/src/test/java/com/vayunmathur/travel/ui/TravelW6Test.kt@@ -0,0 +1,264 @@+package com.vayunmathur.travel.ui++import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.hasSetTextAction+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.compose.ui.test.performTextReplacement+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.OfferDto+import com.vayunmathur.travel.network.OfferPassengerDto+import com.vayunmathur.travel.network.SegmentDto+import com.vayunmathur.travel.network.SliceDto+import com.vayunmathur.travel.util.FlightResultsActions+import com.vayunmathur.travel.util.FlightResultsState+import com.vayunmathur.travel.util.OfferReviewState+import com.vayunmathur.travel.util.TravelViewModel+import com.vayunmathur.travel.util.initPassengers+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++/**+ * W6: hands-on interactions the render-only page tests never performed —+ * typing passenger details, opening the airline dropdown, tapping expiry /+ * sort / filter controls on results, and opening a recent search from Home.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class TravelW6Test {++ @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 slice(origin: String = "SFO", dest: String = "JFK", id: String = "sli_1") = SliceDto(+ id = id, origin = origin, destination = dest,+ departureAt = "2027-06-24T07:15:00", arrivalAt = "2027-06-24T15:50:00",+ durationMinutes = 335, stops = 0,+ segments = listOf(+ SegmentDto(+ id = "seg_$id", carrier = "Alaska Airlines", carrierIata = "AS", flightNumber = "100",+ origin = origin, destination = dest,+ departureAt = "2027-06-24T07:15:00", arrivalAt = "2027-06-24T15:50:00",+ ),+ ),+ )++ private fun offer(id: String = "off_1", expires: String = "") = OfferDto(+ offerId = id, totalAmount = "250.00", currency = "USD", owner = "Alaska", ownerIata = "AS",+ expiresAt = expires, fareBrand = "Main Cabin",+ passengerIds = listOf("pax_1"),+ passengers = listOf(OfferPassengerDto(id = "pax_1", type = "adult")),+ slices = listOf(slice()),+ )++ @Test+ fun passengers_typingAndAirlineDropdown_updateViewModel() {+ val v = vm()+ v.reviewMutable.value = OfferReviewState(offer = offer())+ v.initPassengers(offer())+ v.airlinesMutable.value = listOf(+ AirlineDto(iataCode = "AS", name = "Alaska Airlines"),+ AirlineDto(iataCode = "UA", name = "United Airlines"),+ )+ rule.setContent { PassengersPage(stack(), v, Route.Passengers("off_1")) }+ // Type into the editable fields (given name, family name, email...).+ val fields = rule.onAllNodes(hasSetTextAction()).fetchSemanticsNodes()+ assertTrue(fields.size >= 3, "passenger form fields: ${fields.size}")+ rule.onAllNodes(hasSetTextAction())[0].performTextReplacement("Jane")+ rule.waitForIdle()+ // Contacts import button is wired (launches the system picker; Robolectric absorbs it).+ rule.onAllNodesWithText("contacts", substring = true).fetchSemanticsNodes().let {+ if (it.isNotEmpty()) rule.onAllNodesWithText("contacts", substring = true)[0].performScrollTo().performClick()+ }+ rule.waitForIdle()+ }++ @Test+ fun flightResults_expiredAndLiveOffers_sortAndOpen() {+ val opened = mutableListOf<String>()+ var expiredCalls = 0+ val actions = object : FlightResultsActions {+ override fun openOffer(offer: OfferDto) { opened += offer.offerId }+ }+ val past = java.time.Instant.now().minusSeconds(3600).toString()+ val future = java.time.Instant.now().plusSeconds(3600).toString()+ rule.setContent {+ FlightResultsScreen(+ title = "SFO → JFK",+ state = FlightResultsState(+ allOffers = listOf(offer("off_old", past), offer("off_new", future)),+ ),+ actions = actions,+ )+ }+ rule.waitForIdle()+ // Earliest expiry wins for the banner: the lapsed offer shows refreshing.+ rule.onAllNodesWithText("$250", substring = true)[0].performClick()+ rule.runOnIdle { assertTrue(opened.isNotEmpty()) }+ assertEquals(0, expiredCalls) // banner callback is internal; expiry state rendered above+ }++ @Test+ fun seatMapPage_tapSeatTogglesSelection() {+ val v = vm()+ v.reviewMutable.value = OfferReviewState(offer = offer())+ v.initPassengers(offer())+ val cabin = com.vayunmathur.travel.network.SeatCabinDto(+ segmentId = "seg_1", cabinClass = "economy", aisles = 1,+ rows = listOf(+ com.vayunmathur.travel.network.SeatRowDto(+ sections = listOf(+ com.vayunmathur.travel.network.SeatSectionDto(+ elements = listOf(+ com.vayunmathur.travel.network.SeatElementDto(+ type = "seat", designator = "14A", available = true,+ serviceId = "ase_14A", totalAmount = "24.00", totalCurrency = "USD",+ ),+ com.vayunmathur.travel.network.SeatElementDto(+ type = "seat", designator = "14B", available = false,+ serviceId = "ase_14B", totalAmount = "24.00", totalCurrency = "USD",+ ),+ ),+ ),+ ),+ ),+ ),+ )+ v.ancillariesMutable.value = com.vayunmathur.travel.util.AncillariesState(+ ancillaries = com.vayunmathur.travel.network.TripAncillariesDto(seatMaps = listOf(cabin)),+ )+ rule.setContent { SeatMapPage(stack(), v, Route.SeatMap("off_1", "seg_1")) }+ rule.waitForIdle()+ rule.onAllNodesWithText("14A", substring = true)[0].performClick()+ rule.waitForIdle()+ assertEquals("14A", v.selectedSeats.value["seg_1|pax_1"]?.designator)+ }++ @Test+ fun outboundSelect_servedByTransport_rendersFareCards() {+ val offerJson = """{"offerId":"off_1","itineraryId":"itin_1","totalAmount":"250.00","currency":"USD","owner":"Alaska","ownerIata":"AS","fareBrand":"Main Cabin","passengerIds":["pax_1"],"passengers":[{"id":"pax_1","type":"adult"}],"slices":[{"id":"s1","origin":"SFO","destination":"JFK","departureAt":"2027-06-24T07:15:00","arrivalAt":"2027-06-24T15:50:00","segments":[{"id":"g1","carrierIata":"AS","flightNumber":"100","origin":"SFO","destination":"JFK","departureAt":"2027-06-24T07:15:00","arrivalAt":"2027-06-24T15:50:00"}]},{"id":"s2","origin":"JFK","destination":"SFO","departureAt":"2027-06-28T09:00:00","arrivalAt":"2027-06-28T12:30:00","segments":[{"id":"g2","carrierIata":"AS","flightNumber":"101","origin":"JFK","destination":"SFO","departureAt":"2027-06-28T09:00:00","arrivalAt":"2027-06-28T12:30:00"}]}]}"""+ com.vayunmathur.travel.network.travelTransport = { _, url, _ ->+ if (url.contains("/flights")) {+ com.vayunmathur.travel.network.TravelRaw(200, """{"offerRequestId":"req_1","offers":[$offerJson]}""")+ } else {+ com.vayunmathur.travel.network.TravelRaw(404, """{"message":"nf"}""")+ }+ }+ try {+ val v = vm()+ rule.setContent {+ OutboundSelectPage(stack(), v, Route.OutboundSelect("SFO:JFK:2027-06-24,JFK:SFO:2027-06-28", 1, "", 0, "economy", -1))+ }+ rule.waitUntil(8_000) {+ rule.onAllNodesWithText("$250", substring = true).fetchSemanticsNodes().isNotEmpty()+ }+ rule.onAllNodesWithText("$250", substring = true)[0].assertExists()+ // Expand the outbound card to reveal its return fares (FareCard rows).+ rule.onAllNodesWithText("$250", substring = true)[0].performClick()+ rule.waitForIdle()+ } finally {+ com.vayunmathur.travel.network.travelTransport = null+ }+ }++ @Test+ fun stayGuests_typingGuestDetails() {+ val v = vm()+ rule.setContent { StayGuestsPage(stack(), v) }+ rule.waitForIdle()+ val fields = rule.onAllNodes(hasSetTextAction()).fetchSemanticsNodes()+ assertTrue(fields.size >= 4, "guest fields: ${fields.size}")+ rule.onAllNodes(hasSetTextAction())[0].performTextReplacement("Jane")+ rule.onAllNodes(hasSetTextAction())[1].performTextReplacement("Doe")+ rule.waitForIdle()+ }++ @Test+ fun tripsPage_listsTripsAndRefresh() {+ val v = vm()+ repo.trips.value = listOf(+ BookedTrip(orderId = "ord_1", bookingReference = "ABC123", route = "SFO → JFK", departDate = "2027-06-24", amount = "250.00", currency = "USD", status = "confirmed", tripId = "trip_1"),+ BookedTrip(orderId = "ord_2", bookingReference = "XYZ789", route = "LAX → ORD", departDate = "2027-07-01", amount = "180.00", currency = "USD", status = "processing", tripId = "trip_2"),+ )+ val s = stack()+ rule.setContent { TripsPage(s, v) }+ rule.waitForIdle()+ rule.onAllNodesWithText("ABC123", substring = true)[0].performScrollTo().assertExists()+ rule.onAllNodesWithText("XYZ789", substring = true)[0].performScrollTo().performClick()+ rule.waitForIdle()+ }++ @Test+ fun home_recentSearchAndProductTabs() {+ val v = vm()+ repo.recents.value = listOf(+ RecentSearch(vertical = "flights", label = "SFO → JFK", origin = "SFO", destination = "JFK", depart = "2027-06-24", adults = 1),+ )+ repo.trips.value = listOf(+ BookedTrip(orderId = "ord_1", bookingReference = "ABC123", route = "SFO → JFK", departDate = "2027-06-24", amount = "250.00", currency = "USD", status = "confirmed", tripId = "trip_1"),+ )+ val s = stack()+ rule.setContent { HomePage(s, v) }+ rule.waitForIdle()+ rule.onAllNodesWithText("SFO", substring = true)[0].performScrollTo().assertExists()+ // Switch to the stays product tab and back.+ rule.onAllNodesWithText("Stays", substring = true).fetchSemanticsNodes().let {+ if (it.isNotEmpty()) rule.onAllNodesWithText("Stays", substring = true)[0].performClick()+ }+ rule.waitForIdle()+ rule.onAllNodesWithText("Flights", substring = true).fetchSemanticsNodes().let {+ if (it.isNotEmpty()) rule.onAllNodesWithText("Flights", substring = true)[0].performClick()+ }+ rule.waitForIdle()+ }+}
travel/src/test/java/com/vayunmathur/travel/ui/TravelW6bTest.kt
diff --git a/travel/src/test/java/com/vayunmathur/travel/ui/TravelW6bTest.kt b/travel/src/test/java/com/vayunmathur/travel/ui/TravelW6bTest.ktnew file mode 100644index 0000000000..ae85d2fa95--- /dev/null+++ b/travel/src/test/java/com/vayunmathur/travel/ui/TravelW6bTest.kt@@ -0,0 +1,146 @@+package com.vayunmathur.travel.ui++import androidx.compose.ui.test.hasSetTextAction+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.compose.ui.test.performTextReplacement+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.CheckoutDto+import com.vayunmathur.travel.network.OfferDto+import com.vayunmathur.travel.network.OfferPassengerDto+import com.vayunmathur.travel.util.CheckoutState+import com.vayunmathur.travel.util.OfferReviewState+import com.vayunmathur.travel.util.TravelViewModel+import kotlin.test.BeforeTest+import kotlin.test.Test+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++/**+ * W6b: payment price-change acceptance, payment error retry, settings+ * profile/flyer forms, and the stay search form on Home's stays tab.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class TravelW6bTest {++ @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 offer() = OfferDto(+ offerId = "off_1", totalAmount = "250.00", currency = "USD", owner = "Alaska", ownerIata = "AS",+ passengerIds = listOf("pax_1"),+ passengers = listOf(OfferPassengerDto(id = "pax_1", type = "adult")),+ )++ @Test+ fun payment_priceChanged_acceptThenPayAttempt() {+ val v = vm()+ v.reviewMutable.value = OfferReviewState(offer = offer())+ v.checkoutMutable.value = CheckoutState.Ready(+ CheckoutDto(+ clientSecret = "cs", publishableKey = "pk", totalAmount = "300.00",+ priceChanged = true, originalAmount = "250.00",+ ),+ )+ rule.setContent { PaymentPage(stack(), v, Route.Payment("off_1")) }+ rule.waitForIdle()+ // Accept the new price, which flips the checkout state to accepted.+ rule.onAllNodesWithText("Accept", substring = true).fetchSemanticsNodes().let {+ if (it.isNotEmpty()) rule.onAllNodesWithText("Accept", substring = true)[0].performClick()+ }+ rule.waitForIdle()+ assertTrue(v.checkout.value is CheckoutState.Ready)+ }++ @Test+ fun payment_errorState_retry() {+ val v = vm()+ v.reviewMutable.value = OfferReviewState(offer = offer())+ v.checkoutMutable.value = CheckoutState.Error("Card declined")+ rule.setContent { PaymentPage(stack(), v, Route.Payment("off_1")) }+ rule.waitForIdle()+ rule.onAllNodesWithText("Card declined", substring = true)[0].assertExists()+ }++ @Test+ fun settings_profilesAndFlyers_formInteractions() {+ repo.customers.value = listOf(+ Customer(id = "c1", email = "[email protected]", givenName = "Jane", familyName = "Doe", phoneNumber = "555-1"),+ )+ repo.flyers.value = listOf(+ FrequentFlyer(airlineIata = "AS", accountNumber = "AS123456", airlineName = "Alaska"),+ )+ val v = vm()+ rule.setContent { SettingsPage(stack(), v) }+ rule.waitForIdle()+ rule.onAllNodesWithText("Jane", substring = true)[0].performScrollTo().assertExists()+ val fields = rule.onAllNodes(hasSetTextAction()).fetchSemanticsNodes()+ assertTrue(fields.isNotEmpty(), "settings should expose editable profile fields")+ rule.onAllNodes(hasSetTextAction())[0].performTextReplacement("Janet")+ rule.waitForIdle()+ }++ @Test+ fun home_staysTab_searchFormTyping() {+ val v = vm()+ rule.setContent { HomePage(stack(), v) }+ rule.waitForIdle()+ rule.onAllNodesWithText("Stays", substring = true).fetchSemanticsNodes().let {+ if (it.isNotEmpty()) rule.onAllNodesWithText("Stays", substring = true)[0].performClick()+ }+ rule.waitForIdle()+ val fields = rule.onAllNodes(hasSetTextAction()).fetchSemanticsNodes()+ assertTrue(fields.isNotEmpty(), "stay form should have a destination field")+ rule.onAllNodes(hasSetTextAction())[0].performTextReplacement("London")+ rule.waitForIdle()+ // Suggestion rows from the bundled catalog may appear; either way the form accepted input.+ rule.onAllNodesWithText("London", substring = true).fetchSemanticsNodes()+ }+}
travel/src/test/java/com/vayunmathur/travel/util/TravelOpsW6Test.kt
diff --git a/travel/src/test/java/com/vayunmathur/travel/util/TravelOpsW6Test.kt b/travel/src/test/java/com/vayunmathur/travel/util/TravelOpsW6Test.ktnew file mode 100644index 0000000000..ade63eb69f--- /dev/null+++ b/travel/src/test/java/com/vayunmathur/travel/util/TravelOpsW6Test.kt@@ -0,0 +1,153 @@+package com.vayunmathur.travel.util++import android.app.Application+import android.database.MatrixCursor+import android.provider.ContactsContract+import androidx.compose.runtime.saveable.SaverScope+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.travel.Route+import com.vayunmathur.travel.data.TravelRepository+import com.vayunmathur.travel.network.MissingDetailsException+import com.vayunmathur.travel.network.OfferDto+import com.vayunmathur.travel.network.travelHttpError+import com.vayunmathur.travel.ui.Cabin+import com.vayunmathur.travel.ui.FlightFormSaver+import com.vayunmathur.travel.ui.FlightFormState+import com.vayunmathur.travel.ui.MaxStops+import com.vayunmathur.travel.ui.PassengerMix+import com.vayunmathur.travel.ui.StayFormSaver+import com.vayunmathur.travel.ui.StayFormState+import com.vayunmathur.travel.ui.TripType+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertTrue+import kotlinx.serialization.json.Json+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++/**+ * W6: route serialization, search-form savers, HTTP error decoding and the+ * offer-selection state transitions — none of which need a screen.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class TravelOpsW6Test {++ private val ctx get() = ApplicationProvider.getApplicationContext<Application>()+ private val scope = SaverScope { true }++ @Test+ fun everyRoute_serializesAndRoundTrips() {+ val routes: List<Route> = listOf(+ Route.Home, Route.Trips, Route.Settings, Route.StayGuests,+ Route.OfferReview("off_1"), Route.Ancillaries("off_1"), Route.SeatMap("off_1", "seg_1"),+ Route.Passengers("off_1"), Route.Payment("off_1"), Route.Confirmation("ord_1"),+ Route.OrderDetail("ord_1"), Route.Cancel("ord_1"), Route.Change("ord_1"),+ Route.StayDetail("res_1", "Hotel One"), Route.StayConfirmation("book_1"),+ Route.FareSelect("out-sig", "in-sig"),+ )+ for (route in routes) {+ val text = Json.encodeToString(Route.serializer(), route)+ assertTrue(text.isNotBlank())+ assertEquals(route, Json.decodeFromString(Route.serializer(), text))+ }+ }++ @Test+ fun formSavers_roundTripEveryField() {+ val flight = FlightFormState(+ tripType = TripType.ONE_WAY, origin = "SFO", originText = "San Francisco",+ destination = "JFK", destinationText = "New York", depart = "2027-06-24",+ returnDate = "2027-06-28", mix = PassengerMix(adults = 2, childAges = listOf(7, 9), infantsInSeat = 1, infantsOnLap = 1),+ cabin = Cabin.BUSINESS, maxStops = MaxStops.NONSTOP,+ )+ assertEquals(flight, FlightFormSaver.restore(with(FlightFormSaver) { scope.save(flight) }!!))+ val stay = StayFormState(+ place = "place_1", placeText = "Paris", latitude = 48.85, longitude = 2.35,+ checkIn = "2027-07-01", checkOut = "2027-07-05", rooms = 2, guests = 3,+ )+ assertEquals(stay, StayFormSaver.restore(with(StayFormSaver) { scope.save(stay) }!!))+ // Null coordinates survive as null, not 0.0.+ val noCoords = StayFormState(placeText = "Nowhere")+ val restored = StayFormSaver.restore(with(StayFormSaver) { scope.save(noCoords) }!!)!!+ assertEquals(null, restored.latitude); assertEquals(null, restored.longitude)+ // Swap exchanges origin and destination including their labels.+ val swapped = flight.swapped()+ assertEquals("JFK", swapped.origin); assertEquals("SFO", swapped.destination)+ assertEquals("New York", swapped.originText)+ }++ @Test+ fun httpErrors_decodeMissingFieldsAndRetryAfter() {+ val missing = travelHttpError(422, """{"error":"bad","missingFields":["passport","dob"]}""", "fallback")+ assertTrue(missing is MissingDetailsException)+ assertEquals(listOf("passport", "dob"), (missing as MissingDetailsException).missingFields)+ // 422 with a prefix before the JSON and with malformed JSON both still classify.+ assertTrue(travelHttpError(422, "oops {not json", "fb") is MissingDetailsException)+ val unavailable = travelHttpError(503, """{"retryAfterSeconds":42}""", "fallback")+ assertTrue(unavailable is com.vayunmathur.travel.network.StillPricingException)+ assertEquals(42, (unavailable as com.vayunmathur.travel.network.StillPricingException).retryAfterSeconds)+ val generic = travelHttpError(500, """{"message":"server boom"}""", "fallback")+ assertTrue(generic.message!!.contains("server boom"))+ assertEquals("Something went wrong. Please try again.", travelHttpError(500, "", "fallback").message)+ }++ @Test+ fun selectOffers_seedsReviewAndClearsBookingState() {+ val repo = object : TravelRepository(ctx) {+ override fun observeRecent(limit: Int): kotlinx.coroutines.flow.Flow<List<com.vayunmathur.travel.data.RecentSearch>> =+ kotlinx.coroutines.flow.MutableStateFlow(emptyList())+ override fun observeBookedTrips(): kotlinx.coroutines.flow.Flow<List<com.vayunmathur.travel.data.BookedTrip>> =+ kotlinx.coroutines.flow.MutableStateFlow(emptyList())+ override fun observeFrequentFlyers(): kotlinx.coroutines.flow.Flow<List<com.vayunmathur.travel.data.FrequentFlyer>> =+ kotlinx.coroutines.flow.MutableStateFlow(emptyList())+ override fun observeCustomers(): kotlinx.coroutines.flow.Flow<List<com.vayunmathur.travel.data.Customer>> =+ kotlinx.coroutines.flow.MutableStateFlow(emptyList())+ }+ val vm = TravelViewModel(ctx, repo)+ val offers = listOf(+ OfferDto(offerId = "o1", totalAmount = "100.00", currency = "USD"),+ OfferDto(offerId = "o2", totalAmount = "120.00", currency = "USD"),+ )+ vm.selectOffers(offers)+ assertEquals("o1", vm.review.value.offer!!.offerId)+ assertEquals(listOf("o1", "o2"), vm.selectedOfferIds.value)+ assertEquals(BookingState.Idle, vm.booking.value)+ vm.selectOffer(offers[1])+ assertEquals(listOf("o2"), vm.selectedOfferIds.value)+ // Filter helpers mutate only the flights state.+ vm.setFareBrandFilter("Main")+ assertEquals("Main", vm.flights.value.filters.fareBrand)+ vm.clearFilters()+ assertEquals(null, vm.flights.value.filters.fareBrand)+ // partialOfferById misses cleanly when the partial flow is empty.+ assertEquals(null, vm.partialOfferById("nope"))+ }++ @Test+ fun contactCursor_displayNameFallbackSplitsName() {+ val uri = android.net.Uri.parse("content://w6/contact/1")+ val cursor = org.robolectric.fakes.RoboCursor()+ cursor.setColumnNames(listOf(+ ContactsContract.Data.MIMETYPE, ContactsContract.Data.DATA1,+ ContactsContract.Data.DATA2, ContactsContract.Data.DATA3,+ ContactsContract.Data.DISPLAY_NAME,+ ))+ // Structured name row with blank given/family: display name must be split.+ cursor.setResults(arrayOf(+ arrayOf<Any?>(ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE, "", "", "", "Mary Jane Watson"),+ arrayOf<Any?>(ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE, "[email protected]", "", "", "Mary Jane Watson"),+ arrayOf<Any?>(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE, "+1 (555) 010-2030", "", "", "Mary Jane Watson"),+ arrayOf<Any?>(ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE, "1990-04-12", ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY, "", "Mary Jane Watson"),+ ))+ org.robolectric.Shadows.shadowOf(ctx.contentResolver).setCursor(uri, cursor)+ val info = readSessionContact(ctx, uri)!!+ assertEquals("Mary", info.givenName)+ assertEquals("Jane Watson", info.familyName)+ assertEquals("[email protected]", info.email)+ assertEquals("+15550102030", info.phone)+ assertEquals("1990-04-12", info.bornOn)+ }+}