taxi: add tests for network, booking, tracking and app surfaces (pass 3)
- Commit
80952492e00e68cf1640468eff7f9102d98a4fe0- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-07 12:07 UTC (29 days ago)
- Parents
1e97508
Coverage (merged, instructions): 17.4% (6242/35850) -> 85.31% (30695/35981). Full :taxi:testDevUnitTest: 244 tests, 0 failures. 78 new tests over 11 files. Network: a new internal TaxiHttp seam routes every Lyft/Uber/RemoteImageFetchers HTTP call (hardcoded provider hosts, so no local server can be substituted by URL); tests install a recording fake transport and drive Lyft auth (client-credentials, SMS exchange, challenge shapes, refresh, revoke), quotes + repository refresh fallback, rides (dry-run vs live create, active/by-id, driver location, cancel), payments (list/set-default/remove), card tokenization (Stripe tokens, SetupIntent confirm, Braintree GraphQL, protobuf strategy responses, processor and transport failures), exploratory endpoints, Uber auth + provider, token-store persistence/expiry, and the production TaxiHttp delegation against a loopback server. UI (Robolectric Compose): accounts (payment list/actions, sign-out, add-card dialog + full submit chain), Lyft booking flow (payment picker, confirm, created), Lyft and Uber sign-in flows incl. failure surfaces, ride home (navigation tabs, permission+last-known pickup resolution, search debounce, reset-pickup; the quote flow itself is covered through QuoteRepository + ResultsSection + LyftBookingFlow), results/route-input panes and wide layout, route overlay traffic colors and camera framing, tracking screen (poll, cancel dialog, error state), current-ride, Uber WebView connect + cookie jar, RideLiveUpdate notifications for every lifecycle, and the foreground tracking service incl. its self-stopping poll loop. Also: binary-protobuf parser fixtures (offers, ride, charge accounts) built byte-by-byte; deep-link/handoff-contract round trips; directions IPC degradation; the ride-estimate assistant intent (unavailable + cheapest-quote). (cherry picked from commit 78183147959a8019f9d380066ae4ddaace808730)
Diff
taxi/src/main/java/com/vayunmathur/taxi/data/RemoteImageFetchers.kt
diff --git a/taxi/src/main/java/com/vayunmathur/taxi/data/RemoteImageFetchers.kt b/taxi/src/main/java/com/vayunmathur/taxi/data/RemoteImageFetchers.ktindex ebb6e7df82..dcc918bbb4 100644--- a/taxi/src/main/java/com/vayunmathur/taxi/data/RemoteImageFetchers.kt+++ b/taxi/src/main/java/com/vayunmathur/taxi/data/RemoteImageFetchers.kt@@ -1,9 +1,9 @@ package com.vayunmathur.taxi.data+import com.vayunmathur.taxi.network.TaxiHttp import android.content.Context import android.net.Uri import com.vayunmathur.library.image.fetchers.FetchResult-import com.vayunmathur.library.network.NetworkClient import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext @@ -29,7 +29,7 @@ object RemoteImageFetchers { } if (!url.startsWith("http://") && !url.startsWith("https://")) return null return withContext(Dispatchers.IO) {- val resp = NetworkClient.execute(url)+ val resp = TaxiHttp.execute(url) if (!resp.isSuccess) { throw java.io.IOException("HTTP ${resp.status} for $url") }
taxi/src/main/java/com/vayunmathur/taxi/network/TaxiHttp.kt
diff --git a/taxi/src/main/java/com/vayunmathur/taxi/network/TaxiHttp.kt b/taxi/src/main/java/com/vayunmathur/taxi/network/TaxiHttp.ktnew file mode 100644index 0000000000..e453fe8d0f--- /dev/null+++ b/taxi/src/main/java/com/vayunmathur/taxi/network/TaxiHttp.kt@@ -0,0 +1,43 @@+package com.vayunmathur.taxi.network++import com.vayunmathur.library.network.NetworkClient+import com.vayunmathur.library.network.RawResponse+import com.vayunmathur.library.network.SimpleResponse+import javax.net.ssl.SSLSocketFactory++/**+ * The taxi module's HTTP surface: every provider call goes through here so+ * tests can substitute a fake transport instead of touching the network+ * (provider base URLs are hardcoded, so a local test server cannot be+ * reached by URL substitution). Production behavior is exactly+ * [NetworkClient]; the overrides are internal, never set in production.+ */+internal object TaxiHttp {+ @Volatile+ var executeOverride: (suspend (url: String, method: String, headers: Map<String, *>, body: Any?, sslSocketFactory: SSLSocketFactory?) -> RawResponse)? = null++ @Volatile+ var performOverride: (suspend (url: String, method: String, headers: Map<String, *>, body: Any?) -> SimpleResponse)? = null++ suspend fun execute(+ url: String,+ method: String = "GET",+ headers: Map<String, *> = emptyMap<String, Any>(),+ body: Any? = null,+ sslSocketFactory: SSLSocketFactory? = null,+ ): RawResponse = executeOverride?.invoke(url, method, headers, body, sslSocketFactory)+ ?: NetworkClient.execute(+ url = url, method = method, headers = headers, body = body,+ sslSocketFactory = sslSocketFactory,+ )++ suspend fun performRequest(+ url: String,+ method: String = "GET",+ headers: Map<String, *> = emptyMap<String, Any>(),+ body: Any? = null,+ ): SimpleResponse = performOverride?.invoke(url, method, headers, body)+ ?: NetworkClient.performRequest(+ url = url, method = method, headers = headers, body = body,+ )+}
taxi/src/main/java/com/vayunmathur/taxi/network/lyft/LyftAuth.kt
diff --git a/taxi/src/main/java/com/vayunmathur/taxi/network/lyft/LyftAuth.kt b/taxi/src/main/java/com/vayunmathur/taxi/network/lyft/LyftAuth.ktindex 93329bb14c..77fa776e05 100644--- a/taxi/src/main/java/com/vayunmathur/taxi/network/lyft/LyftAuth.kt+++ b/taxi/src/main/java/com/vayunmathur/taxi/network/lyft/LyftAuth.kt@@ -1,9 +1,9 @@ package com.vayunmathur.taxi.network.lyft+import com.vayunmathur.taxi.network.TaxiHttp import android.os.Build import android.util.Base64 import com.vayunmathur.library.log.Log-import com.vayunmathur.library.network.NetworkClient import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable import kotlinx.serialization.json.Json@@ -155,7 +155,7 @@ object LyftAuth { PhoneAuthRequest.serializer(), PhoneAuthRequest(phoneNumber = phoneNumber), )- val resp = NetworkClient.performRequest(+ val resp = TaxiHttp.performRequest( url = "$BASE/v1/phoneauth", method = "POST", headers = commonHeaders() + mapOf(@@ -216,7 +216,7 @@ object LyftAuth { * dropping it locally. Best-effort: returns whether the server accepted it. */ suspend fun revoke(token: String): Boolean {- val resp = NetworkClient.performRequest(+ val resp = TaxiHttp.performRequest( url = "$BASE/oauth2/revoke_token", method = "POST", headers = commonHeaders() + mapOf(@@ -231,7 +231,7 @@ object LyftAuth { } private suspend fun tokenCall(form: String): LyftAuthResult {- val resp = NetworkClient.performRequest(+ val resp = TaxiHttp.performRequest( url = "$BASE/oauth2/access_token", method = "POST", headers = commonHeaders() + mapOf(
taxi/src/main/java/com/vayunmathur/taxi/network/lyft/LyftCardTokenizer.kt
diff --git a/taxi/src/main/java/com/vayunmathur/taxi/network/lyft/LyftCardTokenizer.kt b/taxi/src/main/java/com/vayunmathur/taxi/network/lyft/LyftCardTokenizer.ktindex d61c5f4964..67d9e38ee9 100644--- a/taxi/src/main/java/com/vayunmathur/taxi/network/lyft/LyftCardTokenizer.kt+++ b/taxi/src/main/java/com/vayunmathur/taxi/network/lyft/LyftCardTokenizer.kt@@ -1,9 +1,9 @@ package com.vayunmathur.taxi.network.lyft+import com.vayunmathur.taxi.network.TaxiHttp import android.net.Uri import android.util.Base64 import com.vayunmathur.library.log.Log-import com.vayunmathur.library.network.NetworkClient import com.vayunmathur.library.network.RawResponse import com.vayunmathur.taxi.data.NewCard import javax.net.ssl.SSLSocketFactory@@ -49,7 +49,7 @@ internal class LyftCardTokenizer( } }.toString() val resp = runCatching {- NetworkClient.execute(+ TaxiHttp.execute( url = "${LyftAuth.BASE}/v1/tokenization_strategies", method = "POST", headers = authJsonHeaders(token),@@ -194,7 +194,7 @@ internal class LyftCardTokenizer( config.stripeApiVersion?.takeIf { it.isNotBlank() }?.let { put("Stripe-Version", it) } } val resp = runCatching {- NetworkClient.execute(+ TaxiHttp.execute( url = "https://api.stripe.com/v1/setup_intents/${Uri.encode(setupIntentId)}/confirm", method = "POST", headers = headers,@@ -230,7 +230,7 @@ internal class LyftCardTokenizer( // useSystemTrust flag falls back to the Lyft-only bundle, which rejects Stripe.) Guard // the call so a transport/TLS failure surfaces as an error rather than crashing. val resp = runCatching {- NetworkClient.execute(+ TaxiHttp.execute( url = "https://api.stripe.com/v1/tokens", method = "POST", headers = mapOf(@@ -280,7 +280,7 @@ internal class LyftCardTokenizer( } }.toString() val resp = runCatching {- NetworkClient.execute(+ TaxiHttp.execute( url = graphQlUrl, method = "POST", headers = mapOf(
taxi/src/main/java/com/vayunmathur/taxi/network/lyft/LyftExploratoryApi.kt
diff --git a/taxi/src/main/java/com/vayunmathur/taxi/network/lyft/LyftExploratoryApi.kt b/taxi/src/main/java/com/vayunmathur/taxi/network/lyft/LyftExploratoryApi.ktindex b62fb258d2..51775aaa1e 100644--- a/taxi/src/main/java/com/vayunmathur/taxi/network/lyft/LyftExploratoryApi.kt+++ b/taxi/src/main/java/com/vayunmathur/taxi/network/lyft/LyftExploratoryApi.kt@@ -1,8 +1,8 @@ package com.vayunmathur.taxi.network.lyft+import com.vayunmathur.taxi.network.TaxiHttp import android.net.Uri import com.vayunmathur.library.log.Log-import com.vayunmathur.library.network.NetworkClient import com.vayunmathur.taxi.data.Place import kotlinx.serialization.json.buildJsonObject import kotlinx.serialization.json.put@@ -51,7 +51,7 @@ internal class LyftExploratoryApi( private suspend fun getRaw(path: String): String? { val token = session.accessToken() ?: return null- val resp = NetworkClient.execute(+ val resp = TaxiHttp.execute( url = "${LyftAuth.BASE}$path", method = "GET", headers = session.authHeaders(token),@@ -62,7 +62,7 @@ internal class LyftExploratoryApi( private suspend fun postRaw(path: String, body: String): String? { val token = session.accessToken() ?: return null- val resp = NetworkClient.execute(+ val resp = TaxiHttp.execute( url = "${LyftAuth.BASE}$path", method = "POST", headers = session.authJsonHeaders(token),
taxi/src/main/java/com/vayunmathur/taxi/network/lyft/LyftPaymentsClient.kt
diff --git a/taxi/src/main/java/com/vayunmathur/taxi/network/lyft/LyftPaymentsClient.kt b/taxi/src/main/java/com/vayunmathur/taxi/network/lyft/LyftPaymentsClient.ktindex 3b90581f55..da0e3f9374 100644--- a/taxi/src/main/java/com/vayunmathur/taxi/network/lyft/LyftPaymentsClient.kt+++ b/taxi/src/main/java/com/vayunmathur/taxi/network/lyft/LyftPaymentsClient.kt@@ -1,8 +1,8 @@ package com.vayunmathur.taxi.network.lyft+import com.vayunmathur.taxi.network.TaxiHttp import android.net.Uri import com.vayunmathur.library.log.Log-import com.vayunmathur.library.network.NetworkClient import com.vayunmathur.taxi.data.AddCardResult import com.vayunmathur.taxi.data.NewCard import com.vayunmathur.taxi.data.PaymentActionResult@@ -32,7 +32,7 @@ internal class LyftPaymentsClient(private val session: LyftApiSession) { suspend fun paymentMethods(): PaymentMethodsResult { val token = session.accessToken() ?: return PaymentMethodsResult.NotSignedIn- val resp = NetworkClient.execute(+ val resp = TaxiHttp.execute( url = "${LyftAuth.BASE}/chargeaccounts", method = "GET", headers = session.authHeaders(token),@@ -60,7 +60,7 @@ internal class LyftPaymentsClient(private val session: LyftApiSession) { put("skip_debt_collection", false) put("skip_persisted_challenge", false) }.toString()- val resp = NetworkClient.execute(+ val resp = TaxiHttp.execute( url = "${LyftAuth.BASE}/charge-accounts-multi-provider", method = "PUT", headers = session.authProtoJsonHeaders(@@ -83,7 +83,7 @@ internal class LyftPaymentsClient(private val session: LyftApiSession) { suspend fun removePaymentMethod(id: String): PaymentActionResult { val token = session.accessToken() ?: return PaymentActionResult.Failed("Not signed in to Lyft")- val resp = NetworkClient.execute(+ val resp = TaxiHttp.execute( url = "${LyftAuth.BASE}/chargeaccounts/${Uri.encode(id)}", method = "DELETE", headers = session.authHeaders(token),@@ -145,7 +145,7 @@ internal class LyftPaymentsClient(private val session: LyftApiSession) { }.toString() val resp = runCatching {- NetworkClient.execute(+ TaxiHttp.execute( url = "${LyftAuth.BASE}/charge-accounts-multi-provider", method = "POST", headers = session.authProtoJsonHeaders(
taxi/src/main/java/com/vayunmathur/taxi/network/lyft/LyftQuotesClient.kt
diff --git a/taxi/src/main/java/com/vayunmathur/taxi/network/lyft/LyftQuotesClient.kt b/taxi/src/main/java/com/vayunmathur/taxi/network/lyft/LyftQuotesClient.ktindex faa283005f..99f8e3496c 100644--- a/taxi/src/main/java/com/vayunmathur/taxi/network/lyft/LyftQuotesClient.kt+++ b/taxi/src/main/java/com/vayunmathur/taxi/network/lyft/LyftQuotesClient.kt@@ -1,7 +1,7 @@ package com.vayunmathur.taxi.network.lyft+import com.vayunmathur.taxi.network.TaxiHttp import com.vayunmathur.library.log.Log-import com.vayunmathur.library.network.NetworkClient import com.vayunmathur.taxi.data.Place import com.vayunmathur.taxi.data.QuoteResult import kotlin.math.roundToLong@@ -70,7 +70,7 @@ internal class LyftQuotesClient(private val session: LyftApiSession) { } private suspend fun readOffers(token: String, url: String, body: String): QuoteResult {- val resp = NetworkClient.execute(+ val resp = TaxiHttp.execute( url = url, method = "POST", // Reuse the exact standard header set the app sends (user-agent, user-device,
taxi/src/main/java/com/vayunmathur/taxi/network/lyft/LyftRidesClient.kt
diff --git a/taxi/src/main/java/com/vayunmathur/taxi/network/lyft/LyftRidesClient.kt b/taxi/src/main/java/com/vayunmathur/taxi/network/lyft/LyftRidesClient.ktindex d91558cd3f..4646f324e7 100644--- a/taxi/src/main/java/com/vayunmathur/taxi/network/lyft/LyftRidesClient.kt+++ b/taxi/src/main/java/com/vayunmathur/taxi/network/lyft/LyftRidesClient.kt@@ -1,8 +1,8 @@ package com.vayunmathur.taxi.network.lyft+import com.vayunmathur.taxi.network.TaxiHttp import android.net.Uri import com.vayunmathur.library.log.Log-import com.vayunmathur.library.network.NetworkClient import com.vayunmathur.library.network.RawResponse import com.vayunmathur.taxi.data.BookingResult import com.vayunmathur.taxi.data.CancelResult@@ -77,7 +77,7 @@ internal class LyftRidesClient( return BookingResult.DryRun(requestJson, account) } - val resp = NetworkClient.execute(+ val resp = TaxiHttp.execute( url = "${LyftAuth.BASE}/v1/core_trips/create", method = "POST", headers = session.authJsonHeaders(token),@@ -108,7 +108,7 @@ internal class LyftRidesClient( suspend fun activeRide(): RideStatusResult { val token = session.accessToken() ?: return RideStatusResult.Failed("Not signed in to Lyft")- val resp = NetworkClient.execute(+ val resp = TaxiHttp.execute( url = "${LyftAuth.BASE}/v1/activeride", method = "GET", headers = session.authHeaders(token),@@ -122,7 +122,7 @@ internal class LyftRidesClient( suspend fun driverLocation(rideId: String): DriverLocation? { val token = session.accessToken() ?: return null- val resp = NetworkClient.execute(+ val resp = TaxiHttp.execute( url = "${LyftAuth.BASE}/v1/rides/${Uri.encode(rideId)}/driver-location", method = "GET", headers = session.authHeaders(token),@@ -136,7 +136,7 @@ internal class LyftRidesClient( val token = session.accessToken() ?: return CancelResult.Failed("Not signed in to Lyft") // A cancel genuinely cancels a live ride (and may incur a fee), so it is sent live // regardless of booking liveness — that flag only gates ride *creation*.- val resp = NetworkClient.execute(+ val resp = TaxiHttp.execute( url = "${LyftAuth.BASE}/v1/rides/${Uri.encode(rideId)}/cancel", method = "POST", headers = session.authJsonHeaders(token),@@ -154,7 +154,7 @@ internal class LyftRidesClient( /** Reads a specific ride by id (`GET /v1/rides/{id}`), parsed like the active ride. */ suspend fun rideById(rideId: String): RideStatusResult { val token = session.accessToken() ?: return RideStatusResult.Failed("Not signed in to Lyft")- val resp = NetworkClient.execute(+ val resp = TaxiHttp.execute( url = "${LyftAuth.BASE}/v1/rides/${Uri.encode(rideId)}", method = "GET", headers = session.authHeaders(token),
taxi/src/main/java/com/vayunmathur/taxi/network/uber/UberAuth.kt
diff --git a/taxi/src/main/java/com/vayunmathur/taxi/network/uber/UberAuth.kt b/taxi/src/main/java/com/vayunmathur/taxi/network/uber/UberAuth.ktindex d189f322fb..2ebf7e8d44 100644--- a/taxi/src/main/java/com/vayunmathur/taxi/network/uber/UberAuth.kt+++ b/taxi/src/main/java/com/vayunmathur/taxi/network/uber/UberAuth.kt@@ -1,8 +1,8 @@ package com.vayunmathur.taxi.network.uber+import com.vayunmathur.taxi.network.TaxiHttp import android.os.Build import com.vayunmathur.library.log.Log-import com.vayunmathur.library.network.NetworkClient import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable import kotlinx.serialization.json.Json@@ -91,7 +91,7 @@ object UberAuth { ), ), )- val resp = NetworkClient.performRequest(+ val resp = TaxiHttp.performRequest( url = "$BASE/rt/silk-screen/submit-form", method = "POST", headers = headers(),
taxi/src/test/java/com/vayunmathur/taxi/TaxiPass3AppTest.kt
diff --git a/taxi/src/test/java/com/vayunmathur/taxi/TaxiPass3AppTest.kt b/taxi/src/test/java/com/vayunmathur/taxi/TaxiPass3AppTest.ktnew file mode 100644index 0000000000..350920de2f--- /dev/null+++ b/taxi/src/test/java/com/vayunmathur/taxi/TaxiPass3AppTest.kt@@ -0,0 +1,160 @@+package com.vayunmathur.taxi++import android.content.Intent+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.createAndroidComposeRule+import androidx.compose.ui.test.onAllNodesWithText+import androidx.compose.ui.test.onNodeWithText+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.library.intents.taxi.RideEstimateRequest+import com.vayunmathur.taxi.data.lyft.LyftTokenStore+import com.vayunmathur.taxi.intents.RideEstimateIntent+import com.vayunmathur.taxi.network.TaxiPass3FakeHttp+import com.vayunmathur.taxi.network.lyft.LyftToken+import kotlinx.coroutines.runBlocking+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Pass 3: MainActivity deep-link handling, the assistant ride-estimate+ * intent, and the IPC intent-launch helpers.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class TaxiPass3AppTest {++ @get:Rule+ val rule = createAndroidComposeRule<MainActivity>()++ private val context: android.content.Context get() = ApplicationProvider.getApplicationContext()+ private val http = TaxiPass3FakeHttp()++ @BeforeTest+ fun setUp() {+ http.install()+ }++ @AfterTest+ fun tearDown() {+ http.uninstall()+ runBlocking { LyftTokenStore(context).clear() }+ }++ @Test+ fun mainActivityLaunchesRideHome() {+ rule.waitForIdle()+ assertNotNull(rule.activity)+ assertTrue(rule.onAllNodesWithText(context.getString(R.string.nav_ride)).fetchSemanticsNodes().isNotEmpty())+ }++ @Test+ fun bookingDeepLinkIntentParsesTrip() {+ val intent = Intent(Intent.ACTION_VIEW).apply {+ data = android.net.Uri.parse(+ "taxi://book?pickup_lat=37.7749&pickup_lng=-122.4194&pickup_label=Home" ++ "&dest_lat=37.8044&dest_lng=-122.2712&dest_label=Work",+ )+ }+ val controller = Robolectric.buildActivity(MainActivity::class.java, intent)+ val activity = controller.create().get()+ assertNotNull(activity)+ controller.destroy()+ }++ @Test+ fun trackRideIntentExtraIsConsumed() {+ val intent = Intent(context, MainActivity::class.java).apply {+ putExtra(com.vayunmathur.taxi.notifications.RideLiveUpdate.EXTRA_TRACK_RIDE_ID, "ride-99")+ }+ val controller = Robolectric.buildActivity(MainActivity::class.java, intent)+ controller.create()+ controller.newIntent(+ Intent(context, MainActivity::class.java).apply {+ putExtra(+ com.vayunmathur.taxi.notifications.RideLiveUpdate.EXTRA_TRACK_RIDE_ID,+ "ride-100",+ )+ },+ )+ controller.destroy()+ }++ @Test+ fun rideEstimateIntentUnavailableWithoutSignIn() = runBlocking {+ val intent = RideEstimateIntent()+ // AssistantIntent plumbing needs the activity context; use the+ // calculation entry via the public perform path by attaching the+ // intent to the test activity's context through Robolectric.+ val controller = Robolectric.buildActivity(RideEstimateIntent::class.java)+ val estimate = controller.create().get()+ val result = estimate.performCalculation(+ RideEstimateRequest(+ pickupLat = 37.7749, pickupLng = -122.4194, pickupLabel = "Home",+ destLat = 37.8044, destLng = -122.2712, destLabel = "Work",+ ),+ )+ assertFalse(result.available)+ assertEquals("", result.fareEstimate)+ assertEquals(-1, result.etaMinutes)+ controller.destroy()+ Unit+ }++ @Test+ fun rideEstimateIntentReturnsCheapestQuote() = runBlocking {+ // Sign in and answer the offerings call with two fares.+ LyftTokenStore(context).save(+ LyftToken(accessToken = "access-tok", refreshToken = "rt", expiresIn = 3600),+ )+ http.on("/v2/offerings") {+ http.raw(+ 200,+ """{"offers":{"purchase_session_id":"ps","offers_response_id":"or","offers_list":[+ {"offer_product_id":"lyft","id":"o1","offer_token":"t",+ "cost_estimate":{"ride_type":"Lyft","currency":"USD",+ "estimated_cost_cents_min":1500,"estimated_cost_cents_max":1800,+ "estimated_duration_seconds":1200,"cost_token":"ct"},+ "ride_type_details":{"display_properties":{"name":"Standard"},"seats":4},+ "ride_travel_details":{"pickup_estimate":{"duration_range":{"duration_ms":300000}}}},+ {"offer_product_id":"lyft","id":"o2","offer_token":"t2",+ "cost_estimate":{"ride_type":"Lyft","currency":"USD",+ "estimated_cost_cents_min":900,"estimated_cost_cents_max":900,+ "estimated_duration_seconds":900,"cost_token":"ct2"},+ "ride_type_details":{"display_properties":{"name":"Shared"},"seats":2},+ "ride_travel_details":{"pickup_estimate":{"duration_range":{"duration_ms":120000}}}}]}}""",+ url = it.url,+ )+ }+ val controller = Robolectric.buildActivity(RideEstimateIntent::class.java)+ val estimate = controller.create().get()+ val result = estimate.performCalculation(+ RideEstimateRequest(pickupLat = 37.7749, pickupLng = -122.4194, destLat = 37.8044, destLng = -122.2712, pickupLabel = "Home", destLabel = "Work"),+ )+ assertTrue(result.available, "result=$result")+ assertEquals("$9.00", result.fareEstimate)+ assertEquals(2, result.etaMinutes)+ controller.destroy()+ Unit+ }++ @Test+ fun intentLaunchContracts() {+ // The launcher is initialised by MainActivity.onCreateBeforeContent,+ // which the compose rule's activity has already run.+ assertNotNull(MainActivity.intentLauncher)+ val missing = com.vayunmathur.taxi.ipc.MissingAppException("com.example.absent")+ assertEquals("App com.example.absent is not installed.", missing.message)+ assertNull(null)+ }+}
taxi/src/test/java/com/vayunmathur/taxi/network/TaxiPass3FakeHttp.kt
diff --git a/taxi/src/test/java/com/vayunmathur/taxi/network/TaxiPass3FakeHttp.kt b/taxi/src/test/java/com/vayunmathur/taxi/network/TaxiPass3FakeHttp.ktnew file mode 100644index 0000000000..8d79ac54eb--- /dev/null+++ b/taxi/src/test/java/com/vayunmathur/taxi/network/TaxiPass3FakeHttp.kt@@ -0,0 +1,59 @@+package com.vayunmathur.taxi.network++import com.vayunmathur.library.network.RawResponse+import com.vayunmathur.library.network.SimpleResponse+import java.util.concurrent.CopyOnWriteArrayList+import javax.net.ssl.SSLSocketFactory++/** Records TaxiHttp calls and answers them from URL-substring routes. */+class TaxiPass3FakeHttp {+ data class Call(val url: String, val method: String, val headers: Map<String, *>, val body: Any?)++ val calls = CopyOnWriteArrayList<Call>()+ private val routes = CopyOnWriteArrayList<Pair<String, (Call) -> RawResponse>>()+ @Volatile var defaultRaw: RawResponse? = null+ @Volatile var performHandler: ((Call) -> SimpleResponse)? = null++ fun on(substring: String, handler: (Call) -> RawResponse) {+ routes += substring to handler+ }++ fun install() {+ calls.clear()+ routes.clear()+ defaultRaw = null+ performHandler = null+ TaxiHttp.executeOverride = { url, method, headers, body, _ ->+ val call = Call(url, method, headers, body)+ calls += call+ routes.firstOrNull { url.contains(it.first) }?.second?.invoke(call)+ ?: defaultRaw+ ?: RawResponse(404, "Not Found", "no fake route for $url".toByteArray(), emptyMap(), url)+ }+ TaxiHttp.performOverride = { url, method, headers, body ->+ val call = Call(url, method, headers, body)+ calls += call+ performHandler?.invoke(call)+ ?: SimpleResponse(404, "Not Found", "no fake perform route", emptyMap(), url)+ }+ }++ fun uninstall() {+ TaxiHttp.executeOverride = null+ TaxiHttp.performOverride = null+ }++ fun raw(status: Int, body: String, contentType: String = "application/json", url: String = ""): RawResponse =+ RawResponse(+ status = status,+ statusMessage = if (status in 200..299) "OK" else "Error",+ bytes = body.toByteArray(Charsets.UTF_8),+ headers = mapOf("Content-Type" to listOf(contentType)),+ url = url,+ )++ fun simple(status: Int, body: String, url: String = ""): SimpleResponse =+ SimpleResponse(status, if (status in 200..299) "OK" else "Error", body, emptyMap(), url)++ fun callsTo(substring: String): List<Call> = calls.filter { it.url.contains(substring) }+}
taxi/src/test/java/com/vayunmathur/taxi/network/TaxiPass3FinalTest.kt
diff --git a/taxi/src/test/java/com/vayunmathur/taxi/network/TaxiPass3FinalTest.kt b/taxi/src/test/java/com/vayunmathur/taxi/network/TaxiPass3FinalTest.ktnew file mode 100644index 0000000000..ce457afee7--- /dev/null+++ b/taxi/src/test/java/com/vayunmathur/taxi/network/TaxiPass3FinalTest.kt@@ -0,0 +1,261 @@+package com.vayunmathur.taxi.network++import android.content.Context+import android.location.Location+import android.location.LocationManager+import androidx.test.core.app.ApplicationProvider+import com.sun.net.httpserver.HttpServer+import com.vayunmathur.library.network.NetworkClient+import com.vayunmathur.library.network.TrustBundle+import com.vayunmathur.taxi.data.LatLng+import com.vayunmathur.taxi.data.NewCard+import com.vayunmathur.taxi.data.Place+import com.vayunmathur.taxi.data.Provider+import com.vayunmathur.taxi.data.QuoteResult+import com.vayunmathur.taxi.data.RemoteImageFetchers+import com.vayunmathur.taxi.data.uber.UberSession+import com.vayunmathur.taxi.network.lyft.LyftApiSession+import com.vayunmathur.taxi.network.lyft.LyftCardTokenizer+import com.vayunmathur.taxi.network.lyft.TokenizeResult+import com.vayunmathur.taxi.network.uber.UberProvider+import com.vayunmathur.taxi.platform.location.LocationProvider+import java.net.InetSocketAddress+import kotlinx.coroutines.runBlocking+import kotlinx.coroutines.test.runTest+import kotlinx.serialization.json.Json+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows.shadowOf+import org.robolectric.annotation.Config+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFailsWith+import kotlin.test.assertFalse+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Pass 3 (final gaps): UberProvider, remote image fetching, the TaxiHttp+ * production delegation to a loopback server, last-known-location, and+ * the card tokenizer's protobuf/failure paths.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class TaxiPass3FinalTest {++ private val context: Context get() = ApplicationProvider.getApplicationContext()+ private val http = TaxiPass3FakeHttp()+ private val json = Json { ignoreUnknownKeys = true; isLenient = true }+ private var server: HttpServer? = null++ @BeforeTest+ fun setUp() {+ http.install()+ }++ @AfterTest+ fun tearDown() {+ http.uninstall()+ server?.stop(0)+ server = null+ runBlocking { UberSession(context).clear() }+ }++ private val pickup = Place("Home", null, LatLng(37.7749, -122.4194))+ private val dropoff = Place("Work", null, LatLng(37.8044, -122.2712))++ // --- UberProvider ---++ @Test+ fun uberProviderSignedOutThenSignedIn() = runTest {+ val provider = UberProvider(context)+ assertEquals(Provider.UBER, provider.provider)+ assertFalse(provider.isSignedIn())+ assertEquals(QuoteResult.NotSignedIn, provider.quotes(pickup, dropoff))+ UberSession(context).setSignedIn(true)+ assertTrue(provider.isSignedIn())+ val quotes = provider.quotes(pickup, dropoff)+ assertTrue(quotes is QuoteResult.Failed)+ assertTrue((quotes as QuoteResult.Failed).message.contains("captured yet"))+ // Interface defaults remain unsupported for Uber.+ assertTrue(provider.paymentMethods() is com.vayunmathur.taxi.data.PaymentMethodsResult.Unsupported)+ assertNull(provider.driverLocation("r1"))+ assertTrue(provider.cancelRide("r1") is com.vayunmathur.taxi.data.CancelResult.Unsupported)+ // Deep links.+ assertTrue(provider.bookingUri(pickup, dropoff, null).startsWith("https://m.uber.com/ul/"))+ // Session flag handling.+ assertTrue(UberSession.looksAuthenticated("https://m.uber.com/go/home"))+ assertFalse(UberSession.looksAuthenticated("https://auth.uber.com/login"))+ assertFalse(UberSession.looksAuthenticated("https://example.com/"))+ UberSession(context).clear()+ assertFalse(provider.isSignedIn())+ }++ // --- RemoteImageFetchers ---++ @Test+ fun remoteImageFetchersGateAndFetch() = runTest {+ http.on("images.example") { http.raw(200, "PNG BYTES", "image/png", it.url) }+ assertNull(RemoteImageFetchers.network(null, context))+ assertNull(RemoteImageFetchers.network(42, context))+ assertNull(RemoteImageFetchers.network(android.net.Uri.parse("file:///tmp/x.png"), context))+ assertNull(RemoteImageFetchers.network("file:///tmp/x.png", context))+ assertNull(RemoteImageFetchers.network("ftp://images.example/x.png", context))+ val fromString = RemoteImageFetchers.network("https://images.example/a.png", context)+ assertTrue(fromString is com.vayunmathur.library.image.fetchers.FetchResult.Bytes)+ assertEquals(+ "PNG BYTES",+ (fromString as com.vayunmathur.library.image.fetchers.FetchResult.Bytes)+ .bytes.toString(Charsets.UTF_8),+ )+ val fromUri = RemoteImageFetchers.network(+ android.net.Uri.parse("https://images.example/b.png"), context,+ )+ assertNotNull(fromUri)+ // Non-2xx is an IOException for the pipeline.+ http.uninstall(); http.install()+ http.on("images.example") { http.raw(404, "nope", "text/plain", it.url) }+ assertFailsWith<java.io.IOException> {+ RemoteImageFetchers.network("https://images.example/missing.png", context)+ }+ }++ // --- TaxiHttp production delegation (loopback, no overrides) ---++ @Test+ fun taxiHttpDelegatesToNetworkClient() = runTest {+ http.uninstall()+ NetworkClient.init(context, TrustBundle.SYSTEM)+ val payload = "loopback-body"+ val httpServer = HttpServer.create(InetSocketAddress("127.0.0.1", 0), 0)+ httpServer.createContext("/") { exchange ->+ val requestBody = exchange.requestBody.readAllBytes()+ val response = (payload + ":" + requestBody.size).toByteArray()+ exchange.responseHeaders.set("X-Test", "yes")+ exchange.sendResponseHeaders(200, response.size.toLong())+ exchange.responseBody.write(response)+ exchange.close()+ }+ httpServer.start()+ server = httpServer+ val base = "http://127.0.0.1:${httpServer.address.port}"+ val executed = TaxiHttp.execute("$base/path", method = "POST", body = "abc")+ assertEquals(200, executed.status)+ assertEquals("loopback-body:3", executed.text)+ assertEquals("yes", executed.header("X-Test"))+ val performed = TaxiHttp.performRequest("$base/other", method = "GET")+ assertEquals(200, performed.status)+ assertTrue(performed.isSuccess)+ assertTrue(performed.body.startsWith("loopback-body"))+ }++ // --- LocationProvider with a last-known fix ---++ @Test+ fun locationCurrentUsesLastKnownFix() = runTest {+ val app = ApplicationProvider.getApplicationContext<android.app.Application>()+ shadowOf(app).grantPermissions(android.Manifest.permission.ACCESS_FINE_LOCATION)+ val manager = context.getSystemService(LocationManager::class.java)+ val fix = Location(LocationManager.GPS_PROVIDER).apply {+ latitude = 37.7749+ longitude = -122.4194+ }+ shadowOf(manager).setLastKnownLocation(LocationManager.GPS_PROVIDER, fix)+ val here = LocationProvider.current(context)+ assertEquals(LatLng(37.7749, -122.4194), here)+ // describe() falls back gracefully when the geocoder has no answer.+ val place = LocationProvider.describe(context, here!!)+ assertEquals(here, place.location)+ }++ // --- Card tokenizer protobuf + failure paths ---++ private fun varintBytes(value: Long): ByteArray {+ val out = mutableListOf<Byte>()+ var v = value+ while (true) {+ var b = (v and 0x7FL).toInt()+ v = v ushr 7+ if (v != 0L) b = b or 0x80+ out.add(b.toByte())+ if (v == 0L) break+ }+ return out.toByteArray()+ }++ private fun record(field: Int, wire: Int, payload: ByteArray): ByteArray =+ varintBytes(((field shl 3) or wire).toLong()) + payload++ private fun stringField(field: Int, value: String): ByteArray {+ val bytes = value.toByteArray(Charsets.UTF_8)+ return record(field, 2, varintBytes(bytes.size.toLong()) + bytes)+ }++ private fun messageField(field: Int, vararg parts: ByteArray): ByteArray {+ val bytes = parts.fold(byteArrayOf()) { a, p -> a + p }+ return record(field, 2, varintBytes(bytes.size.toLong()) + bytes)+ }++ @Test+ fun tokenizerProtoConfigAndFailurePaths() = runTest {+ val session = LyftApiSession(context)+ val tokenizer = LyftCardTokenizer(json, session.systemTrustFactory, session::authJsonHeaders)+ val card = NewCard("4111111111111111", 12, 2030, "123", "94101")++ // fetchConfig over a protobuf strategies response (SetupIntent at tag 22).+ val setupIntent = messageField(+ 22, stringField(1, "pk_proto"), stringField(2, "sec"), stringField(3, "seti_9"),+ stringField(4, "2024-01-01"),+ )+ val strategiesBody = messageField(1, setupIntent)+ http.on("/v1/tokenization_strategies") {+ com.vayunmathur.library.network.RawResponse(+ 200, "OK", strategiesBody,+ mapOf("Content-Type" to listOf("application/x-protobuf")), it.url,+ )+ }+ // Seed a token in the store is unnecessary: fetchConfig takes it directly.+ val config = tokenizer.fetchConfig("access-tok", card)+ assertNotNull(config)+ assertEquals("stripe_setup_intent", config.provider)+ assertEquals("pk_proto", config.key)+ assertEquals("seti_9", config.setupIntentId)+ // parseConfigProto direct: legacy stripe (10) and braintree (11).+ val legacy = messageField(1, messageField(10, stringField(1, "pk_legacy")))+ assertEquals("pk_legacy", tokenizer.parseConfigProto(legacy)?.key)+ val bt = messageField(1, messageField(11, stringField(1, "bt_key")))+ assertEquals("braintree", tokenizer.parseConfigProto(bt)?.provider)+ assertNull(tokenizer.parseConfigProto(byteArrayOf(0x66, 0x01, 0x02)))++ // fetchConfig: HTTP failure and transport failure both yield null.+ http.uninstall(); http.install()+ http.on("/v1/tokenization_strategies") { http.raw(500, "x", "text/plain", it.url) }+ assertNull(tokenizer.fetchConfig("access-tok", card))+ TaxiHttp.executeOverride = { _, _, _, _, _ -> throw RuntimeException("socket exploded") }+ assertNull(tokenizer.fetchConfig("access-tok", card))+ TaxiHttp.executeOverride = null+ http.install()++ // Stripe transport failure and Braintree GraphQL errors.+ TaxiHttp.executeOverride = { _, _, _, _, _ -> throw RuntimeException("tls exploded") }+ val stripeErr = tokenizer.tokenizeStripe("pk", card)+ assertTrue(stripeErr is TokenizeResult.Err)+ assertTrue((stripeErr as TokenizeResult.Err).message.contains("tls exploded"))+ val btErrResult = tokenizer.tokenizeBraintree("%%%", card)+ assertTrue(btErrResult is TokenizeResult.Err)+ TaxiHttp.executeOverride = null+ http.install()+ http.on("payments.braintree-api.com") {+ http.raw(200, """{"errors":[{"message":"Card declined by gateway"}]}""", url = it.url)+ }+ val btToken = java.util.Base64.getEncoder().encodeToString(+ """{"authorizationFingerprint":"fp"}""".toByteArray(),+ )+ val gqlErr = tokenizer.tokenizeBraintree(btToken, card)+ assertTrue(gqlErr is TokenizeResult.Err)+ assertTrue((gqlErr as TokenizeResult.Err).message.contains("declined"))+ }+}
taxi/src/test/java/com/vayunmathur/taxi/network/TaxiPass3LyftNetworkTest.kt
diff --git a/taxi/src/test/java/com/vayunmathur/taxi/network/TaxiPass3LyftNetworkTest.kt b/taxi/src/test/java/com/vayunmathur/taxi/network/TaxiPass3LyftNetworkTest.ktnew file mode 100644index 0000000000..a9f1cca2fd--- /dev/null+++ b/taxi/src/test/java/com/vayunmathur/taxi/network/TaxiPass3LyftNetworkTest.kt@@ -0,0 +1,575 @@+package com.vayunmathur.taxi.network++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.library.network.RawResponse+import com.vayunmathur.taxi.data.AddCardResult+import com.vayunmathur.taxi.data.BookingResult+import com.vayunmathur.taxi.data.CancelResult+import com.vayunmathur.taxi.data.LatLng+import com.vayunmathur.taxi.data.NewCard+import com.vayunmathur.taxi.data.PaymentActionResult+import com.vayunmathur.taxi.data.PaymentMethodsResult+import com.vayunmathur.taxi.data.Place+import com.vayunmathur.taxi.data.Provider+import com.vayunmathur.taxi.data.QuoteResult+import com.vayunmathur.taxi.data.RideStatusResult+import com.vayunmathur.taxi.data.lyft.LyftTokenStore+import com.vayunmathur.taxi.network.lyft.LyftApiSession+import com.vayunmathur.taxi.network.lyft.LyftAuth+import com.vayunmathur.taxi.network.lyft.LyftAuthResult+import com.vayunmathur.taxi.network.lyft.LyftProvider+import com.vayunmathur.taxi.network.lyft.LyftToken+import com.vayunmathur.taxi.provider.QuoteRepository+import kotlinx.coroutines.test.runTest+import kotlinx.serialization.json.Json+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Pass 3: the Lyft network stack (auth, quotes, rides, payments, card+ * tokenization, exploratory endpoints, provider facade, quote repository)+ * driven through the TaxiHttp fake transport. No real network is touched.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class TaxiPass3LyftNetworkTest {++ private val context: Context get() = ApplicationProvider.getApplicationContext()+ private val http = TaxiPass3FakeHttp()+ private val json = Json { ignoreUnknownKeys = true; isLenient = true }++ private val pickup = Place("Home", "1 Main St", LatLng(37.7749, -122.4194))+ private val dropoff = Place("Work", "2 Market St", LatLng(37.8044, -122.2712))++ @BeforeTest+ fun setUp() {+ http.install()+ }++ @AfterTest+ fun tearDown() = runTest {+ http.uninstall()+ LyftTokenStore(context).clear()+ }++ private suspend fun seedToken(+ access: String = "access-tok",+ refresh: String? = "refresh-tok",+ expiresIn: Long = 3600,+ ) {+ LyftTokenStore(context).save(+ LyftToken(accessToken = access, refreshToken = refresh, expiresIn = expiresIn, userId = "4242"),+ )+ }++ private fun offerJson(): String =+ """{"offers":{"purchase_session_id":"ps1","offers_response_id":"or1","offers_list":[+ {"offer_product_id":"lyft","id":"o1","offer_token":"tok",+ "cost_estimate":{"ride_type":"Lyft","currency":"USD","estimated_cost_cents_min":500,+ "estimated_cost_cents_max":900,"estimated_duration_seconds":1200,+ "primetime_multiplier":1.0,"cost_token":"ct","cost_token_expiry_time":9999999999},+ "ride_type_details":{"display_properties":{"name":"Lyft Standard"},"seats":4},+ "ride_travel_details":{"pickup_estimate":{"duration_range":{"duration_ms":240000}}}}]}}"""++ private fun rideJson(status: String = "accepted"): String =+ """{"ride":{"ride_id":"r1","status":"$status",+ "driver":{"first_name":"Jo","last_name":"Smith","image_url":"u","phone_number":"+1","rating":4.9},+ "vehicle":{"make":"Toyota","model":"Camry","color":"Black","license_plate":"XYZ","image_url":"v"},+ "location":{"lat":37.7,"lng":-122.4,"bearing":90.0},+ "stops":[{"location":{"lat":37.7,"lng":-122.4,"place_name":"Home"},"kind":"pickup","completed":false,"eta_seconds":120},+ {"location":{"lat":37.8,"lng":-122.5,"place_name":"Work"},"kind":"dropoff","completed":false,"eta_seconds":600}]}}"""++ private fun accountsJson(): String =+ """{"chargeAccounts":[+ {"id":"ca1","label":"Visa ••1111","default":true},+ {"id":"ca2","kind":"Mastercard","lastFour":"2222","default":false}]}"""++ // --- LyftAuth ---++ @Test+ fun authRequestSmsCodeUsesClientTokenFirst() = runTest {+ http.performHandler = { call ->+ when {+ call.url.contains("/oauth2/access_token") ->+ http.simple(200, """{"access_token":"client-tok","token_type":"Bearer","expires_in":3600}""", call.url)+ call.url.contains("/v1/phoneauth") -> http.simple(200, "{}", call.url)+ else -> http.simple(404, "unexpected ${call.url}", call.url)+ }+ }+ val result = LyftAuth.requestSmsCode("+15551234567")+ assertTrue(result is LyftAuthResult.Success)+ // The client token may already be cached from another test in this+ // class; when the call does happen it must be a client_credentials grant.+ http.callsTo("/oauth2/access_token").firstOrNull()?.let { tokenCall ->+ assertTrue((tokenCall.body as String).contains("grant_type=client_credentials"))+ assertTrue(tokenCall.headers.values.any { it.toString().startsWith("Basic ") })+ }+ val phoneCall = http.callsTo("/v1/phoneauth").first()+ assertTrue((phoneCall.headers["Authorization"] ?: "").toString().startsWith("Bearer "))+ assertTrue((phoneCall.body as String).contains("+15551234567"))+ // Common headers are on the wire.+ assertTrue(phoneCall.headers.keys.any { it.equals("user-agent", true) })+ }++ @Test+ fun authVerifySmsCodeExchangesAndParsesToken() = runTest {+ http.performHandler = { call ->+ assertTrue(call.url.contains("/oauth2/access_token"))+ http.simple(+ 200,+ """{"access_token":"user-tok","token_type":"Bearer","refresh_token":"rt-1","expires_in":7200,"user_id":"99"}""",+ call.url,+ )+ }+ val result = LyftAuth.verifySmsCode("+15551234567", "123456", "session-uuid-1")+ assertTrue(result is LyftAuthResult.Success)+ val token = (result as LyftAuthResult.Success).token+ assertEquals("user-tok", token.accessToken)+ assertEquals("rt-1", token.refreshToken)+ assertEquals(7200L, token.expiresIn)+ assertEquals("99", token.userId)+ val body = http.calls.first().body as String+ assertTrue(body.contains("grant_type=urn%3Alyft%3Aoauth2%3Agrant_type%3Aphone"), body)+ assertTrue(body.contains("phone_code=123456"))+ assertTrue(body.contains("login_session_uuid=session-uuid-1"))+ assertFalse(body.contains("email="))+ }++ @Test+ fun authVerifyWithEmailAnswersChallengeFields() = runTest {+ http.performHandler = { http.simple(200, """{"access_token":"t","expires_in":60}""", it.url) }+ assertTrue(LyftAuth.verifySmsCode("+1", "999", "s", email = "[email protected]") is LyftAuthResult.Success)+ val body = http.calls.first().body as String+ assertTrue(body.contains("email=a%40b.c"), body)+ assertTrue(body.contains("confirm=true"))+ }++ @Test+ fun authFailureShapesMapToResults() = runTest {+ // Web challenge.+ http.performHandler = {+ http.simple(400, """{"error":"browser_redirect_required","redirect_uri":"https://lyft.example/challenge"}""", it.url)+ }+ val web = LyftAuth.verifySmsCode("+1", "1", "s")+ assertEquals(LyftAuthResult.NeedsWebChallenge("https://lyft.example/challenge"), web)+ // Email-match challenge.+ http.performHandler = {+ http.simple(+ 400,+ """{"error":"challenge_required","error_description":"Verify your email",+ "challenges":[{"identifier":"email_match","data":"v******t@u*c.edu"}]}""",+ it.url,+ )+ }+ val challenge = LyftAuth.verifySmsCode("+1", "1", "s")+ assertTrue(challenge is LyftAuthResult.NeedsChallenge)+ assertEquals("email_match", (challenge as LyftAuthResult.NeedsChallenge).identifier)+ assertEquals("v******t@u*c.edu", challenge.hint)+ assertEquals("Verify your email", challenge.description)+ // Plain failure.+ http.performHandler = {+ http.simple(401, """{"error":"invalid_client","error_description":"bad client"}""", it.url)+ }+ assertEquals(+ LyftAuthResult.Failed("invalid_client", "bad client"),+ LyftAuth.verifySmsCode("+1", "1", "s"),+ )+ // Malformed error body falls back to the HTTP status.+ http.performHandler = { http.simple(500, "not json", it.url) }+ assertEquals(LyftAuthResult.Failed(null, "HTTP 500"), LyftAuth.verifySmsCode("+1", "1", "s"))+ // Success status with garbage body is an unreadable token response.+ http.performHandler = { http.simple(200, "garbage", it.url) }+ assertEquals(+ LyftAuthResult.Failed(null, "Unreadable token response"),+ LyftAuth.verifySmsCode("+1", "1", "s"),+ )+ }++ @Test+ fun authRefreshAndRevoke() = runTest {+ http.performHandler = { call ->+ if (call.url.contains("revoke_token")) {+ http.simple(200, "", call.url)+ } else {+ http.simple(200, """{"access_token":"fresh","refresh_token":"rt2","expires_in":3600}""", call.url)+ }+ }+ val refreshed = LyftAuth.refresh("rt-1")+ assertEquals("fresh", refreshed?.accessToken)+ assertEquals("rt2", refreshed?.refreshToken)+ assertTrue(LyftAuth.revoke("some-token"))+ val revoke = http.callsTo("revoke_token").first()+ assertTrue((revoke.body as String).contains("token=some-token"))+ assertTrue((revoke.headers["Authorization"] ?: "").toString().startsWith("Basic "))+ // Revoke failures are best-effort false.+ http.performHandler = { http.simple(500, "x", it.url) }+ assertFalse(LyftAuth.revoke("some-token"))+ assertNull(LyftAuth.refresh("rt-x").also { })+ }++ @Test+ fun authCommonHeadersAndSessionUuid() {+ val headers = LyftAuth.commonHeaders()+ assertTrue(headers["user-agent"]!!.startsWith("lyft:android:"))+ assertEquals("GEO_REGION_NA", headers["x-lyft-geo-region"])+ assertEquals("COMPLIANCE_REGION_CCPA", headers["x-lyft-payload-compliance"])+ assertTrue(headers.containsKey("x-timestamp-ms"))+ val uuid = LyftAuth.newSessionUuid()+ assertTrue(uuid.matches(Regex("[0-9a-f-]{36}")))+ assertTrue(LyftAuth.newSessionUuid() != uuid)+ }++ @Test+ fun tokenStoreRoundTripsAndExpiry() = runTest {+ val store = LyftTokenStore(context)+ assertFalse(store.isSignedIn())+ assertTrue(store.isExpired())+ store.save(LyftToken(accessToken = "a1", refreshToken = "r1", expiresIn = 3600, userId = "u7"))+ assertTrue(store.isSignedIn())+ assertFalse(store.isExpired())+ assertEquals("a1", store.accessToken())+ assertEquals("r1", store.refreshToken())+ assertEquals("u7", store.userId())+ // A token expiring within the skew window counts as expired.+ store.save(LyftToken(accessToken = "a2", expiresIn = 30))+ assertTrue(store.isExpired())+ // Blank tokens are not stored as present.+ store.save(LyftToken(accessToken = "a3", refreshToken = "", expiresIn = 3600, userId = ""))+ assertEquals("a3", store.accessToken())+ store.clear()+ assertFalse(store.isSignedIn())+ assertNull(store.accessToken())+ }++ // --- Quotes ---++ @Test+ fun quotesRequireSignInThenParseOffers() = runTest {+ val provider = LyftProvider(context)+ assertEquals(QuoteResult.NotSignedIn, provider.quotes(pickup, dropoff))+ seedToken()+ http.on("/v2/offerings") { http.raw(200, offerJson(), url = it.url) }+ val result = provider.quotes(pickup, dropoff)+ assertTrue(result is QuoteResult.Success)+ val success = result as QuoteResult.Success+ assertEquals("ps1", success.purchaseSessionId)+ assertEquals("or1", success.offersResponseId)+ assertEquals(1, success.quotes.size)+ assertEquals("Lyft Standard", success.quotes[0].displayName)+ assertEquals("o1", success.quotes[0].offerId)+ val call = http.callsTo("/v2/offerings").first()+ assertEquals("POST", call.method)+ assertTrue((call.headers["Authorization"] ?: "").toString().contains("Bearer access-tok"))+ assertTrue((call.body as String).contains("\"origin\""))+ // Update quotes hits the update endpoint with the session ids.+ val updated = provider.updateQuotes(pickup, dropoff, "or1", "ps1")+ assertTrue(updated is QuoteResult.Success)+ assertTrue(http.callsTo("/v2/offerings/update").isNotEmpty())+ }++ @Test+ fun quotesHttpErrorAndUnparseableBodyFail() = runTest {+ seedToken()+ val provider = LyftProvider(context)+ http.on("/v2/offerings") { http.raw(503, "upstream down", "text/plain", it.url) }+ val failed = provider.quotes(pickup, dropoff)+ assertTrue(failed is QuoteResult.Failed)+ assertTrue((failed as QuoteResult.Failed).message.contains("503"))+ http.uninstall(); http.install()+ http.on("/v2/offerings") { http.raw(200, """{"offers":{}}""", url = it.url) }+ val empty = provider.quotes(pickup, dropoff)+ assertTrue(empty is QuoteResult.Failed)+ assertTrue((empty as QuoteResult.Failed).message.contains("no offers"))+ }++ @Test+ fun quoteRepositoryQuotesAndRefreshFallsBack() = runTest {+ seedToken()+ http.on("/v2/offerings/update") { http.raw(500, "nope", "text/plain", it.url) }+ http.on("/v2/offerings") { http.raw(200, offerJson(), url = it.url) }+ val quotes = QuoteRepository.quotes(context, pickup, dropoff)+ assertTrue(quotes[Provider.LYFT] is QuoteResult.Success)+ // Refresh tries update first, then falls back to a fresh quote.+ http.calls.clear()+ val previous = mapOf<Provider, QuoteResult>(+ Provider.LYFT to QuoteResult.Success(emptyList(), "ps1", "or1"),+ )+ val refreshed = QuoteRepository.refresh(context, pickup, dropoff, previous)+ assertTrue(refreshed[Provider.LYFT] is QuoteResult.Success)+ assertEquals(1, http.callsTo("/v2/offerings/update").size)+ assertEquals(1, http.callsTo("/v2/offerings").filter { !it.url.contains("update") }.size)+ }++ // --- Rides ---++ @Test+ fun ridesLifecycleThroughFakeTransport() = runTest {+ seedToken()+ val provider = LyftProvider(context)+ http.on("/v1/activeride") { http.raw(200, rideJson(), url = it.url) }+ http.on("/driver-location") {+ http.raw(200, """{"location":{"lat":37.71,"lng":-122.41,"bearing":45.0}}""", url = it.url)+ }+ http.on("/v1/rides/r1/cancel") { http.raw(200, "Cancelled, no fee", "text/plain", it.url) }+ http.on("/v1/core_trips/create") {+ http.raw(200, """{"trip_details":{"trip_id":"777"}}""", url = it.url)+ }+ val active = provider.activeRide()+ assertTrue(active is RideStatusResult.Active)+ assertEquals("r1", (active as RideStatusResult.Active).ride.rideId)+ assertEquals(37.71, provider.driverLocation("r1")?.latitude)+ assertEquals(CancelResult.Done("Cancelled, no fee"), provider.cancelRide("r1"))++ val rideQuote = com.vayunmathur.taxi.data.RideQuote(+ provider = Provider.LYFT, productId = "lyft", displayName = "Lyft",+ fareLowMinor = 500, fareHighMinor = 900, currency = "USD",+ pickupEtaMinutes = 4, tripDurationMinutes = 20, surgeMultiplier = null,+ capacity = 4, offerId = "o1", offerToken = "tok", costToken = "ct", rideType = "Lyft",+ )+ // Dry run never sends.+ http.calls.clear()+ val dry = provider.createRide(rideQuote, pickup, dropoff, null, "ps1", dryRun = true)+ assertTrue(dry is BookingResult.DryRun)+ assertTrue((dry as BookingResult.DryRun).requestJson.contains("\"offer_id\":\"o1\""))+ assertTrue(http.callsTo("core_trips").isEmpty())+ // Live booking posts and parses the created id.+ val created = provider.createRide(rideQuote, pickup, dropoff, null, "ps1", dryRun = false)+ assertTrue(created is BookingResult.Created)+ assertEquals("777", (created as BookingResult.Created).rideId)+ // A quote without an offer id cannot book.+ val noOffer = provider.createRide(rideQuote.copy(offerId = null), pickup, dropoff, null, null, dryRun = false)+ assertTrue(noOffer is BookingResult.Failed)+ }++ @Test+ fun ridesNotFoundAndErrors() = runTest {+ seedToken()+ val provider = LyftProvider(context)+ http.on("/v1/activeride") { http.raw(404, "", url = it.url) }+ assertEquals(RideStatusResult.None, provider.activeRide())+ http.uninstall(); http.install()+ http.on("/v1/activeride") { http.raw(500, "boom", "text/plain", it.url) }+ assertTrue(provider.activeRide() is RideStatusResult.Failed)+ http.on("/v1/rides/") { http.raw(200, rideJson("completed"), url = it.url) }+ val byId = provider.rideById("r1")+ assertTrue(byId is RideStatusResult.Active)+ assertTrue(http.callsTo("/v1/rides/r1").isNotEmpty())+ }++ // --- Payments + tokenizer ---++ @Test+ fun paymentsListSetDefaultRemove() = runTest {+ seedToken()+ val provider = LyftProvider(context)+ http.on("/chargeaccounts") { http.raw(200, accountsJson(), url = it.url) }+ http.on("/charge-accounts-multi-provider") { http.raw(200, accountsJson(), url = it.url) }+ val methods = provider.paymentMethods()+ assertTrue(methods is PaymentMethodsResult.Success)+ val accounts = (methods as PaymentMethodsResult.Success).accounts+ assertEquals(2, accounts.size)+ assertEquals("Visa ••1111", accounts[0].label)+ assertTrue(accounts[0].isDefault)+ assertEquals("Mastercard ••2222", accounts[1].label)++ val setDefault = provider.setDefaultPaymentMethod("ca2")+ assertTrue(setDefault is PaymentActionResult.Success)+ val put = http.callsTo("charge-accounts-multi-provider").first()+ assertEquals("PUT", put.method)+ assertTrue((put.headers["Content-Type"] ?: "").toString().contains("messageType="))+ assertTrue((put.body as String).contains("\"charge_account_id\":\"ca2\""))++ val removed = provider.removePaymentMethod("ca 1/x")+ assertTrue(removed is PaymentActionResult.Success)+ assertTrue(http.callsTo("/chargeaccounts/ca%201%2Fx").isNotEmpty() ||+ http.callsTo("/chargeaccounts/").any { it.method == "DELETE" })+ }++ @Test+ fun addCardThroughStripeToken() = runTest {+ seedToken()+ val provider = LyftProvider(context)+ http.on("/v1/tokenization_strategies") {+ http.raw(200, """{"strategies":[{"stripe_card_data":{"api_key":"pk_test_123"}}]}""", url = it.url)+ }+ http.on("api.stripe.com/v1/tokens") {+ http.raw(200, """{"id":"tok_visa_1"}""", url = it.url)+ }+ http.on("/charge-accounts-multi-provider") { http.raw(200, accountsJson(), url = it.url) }+ val card = NewCard("4111111111111111", 12, 2030, "123", "94101")+ val result = provider.addCard(card, makeDefault = true)+ assertTrue(result is AddCardResult.Success, "$result")+ val stripeCall = http.callsTo("api.stripe.com").first()+ assertTrue((stripeCall.body as String).contains("card%5Bnumber%5D") ||+ (stripeCall.body as String).contains("card[number]=4111111111111111"))+ val create = http.callsTo("charge-accounts-multi-provider").first()+ val createBody = create.body as String+ assertTrue(createBody.contains("\"token\":\"tok_visa_1\""), createBody)+ assertTrue(createBody.contains("\"default\":true"), createBody)+ }++ @Test+ fun addCardSetupIntentAndBraintreePaths() = runTest {+ seedToken()+ val provider = LyftProvider(context)+ val card = NewCard("4111111111111111", 12, 2030, "123", "94101")+ // SetupIntent strategy.+ http.on("/v1/tokenization_strategies") {+ http.raw(+ 200,+ """{"strategies":[{"stripe_card_setup_intent_data":{"api_key":"pk_si","client_secret":"seti_secret","setup_intent_id":"seti_1","stripe_api_version":"2024-06-20"}}]}""",+ url = it.url,+ )+ }+ http.on("setup_intents/seti_1/confirm") { http.raw(200, """{"payment_method":"pm_999"}""", url = it.url) }+ http.on("/charge-accounts-multi-provider") { http.raw(200, accountsJson(), url = it.url) }+ val si = provider.addCard(card, makeDefault = false)+ assertTrue(si is AddCardResult.Success, "$si")+ val confirmBody = http.callsTo("setup_intents").first().body as String+ assertTrue(confirmBody.contains("client_secret=seti_secret"), confirmBody)+ http.uninstall(); http.install()++ // Braintree strategy: client token is base64 JSON.+ val btToken = java.util.Base64.getEncoder().encodeToString(+ """{"authorizationFingerprint":"fp-1","graphQL":{"url":"https://payments.braintree-api.com/graphql"}}"""+ .toByteArray(),+ )+ http.on("/v1/tokenization_strategies") {+ http.raw(200, """{"strategies":[{"braintree_card_data":{"api_key":"$btToken"}}]}""", url = it.url)+ }+ http.on("payments.braintree-api.com") {+ http.raw(200, """{"data":{"tokenizeCreditCard":{"token":"nonce-abc"}}}""", url = it.url)+ }+ http.on("/charge-accounts-multi-provider") { http.raw(200, accountsJson(), url = it.url) }+ val bt = provider.addCard(card, makeDefault = false)+ assertTrue(bt is AddCardResult.Success, "$bt")+ val createBody = http.callsTo("charge-accounts-multi-provider").first().body as String+ assertTrue(createBody.contains("\"nonce\":\"nonce-abc\""), createBody)+ http.uninstall(); http.install()++ // Unsupported strategy -> Unsupported, no processor call.+ http.on("/v1/tokenization_strategies") {+ http.raw(200, """{"strategies":[{"adyen_card_data":{"api_key":"x"}}]}""", url = it.url)+ }+ assertEquals(AddCardResult.Unsupported, provider.addCard(card, makeDefault = false))+ // Processor error surfaces as Failed.+ http.uninstall(); http.install()+ http.on("/v1/tokenization_strategies") {+ http.raw(200, """{"strategies":[{"stripe_card_data":{"api_key":"pk"}}]}""", url = it.url)+ }+ http.on("api.stripe.com") {+ http.raw(402, """{"error":{"message":"Your card was declined."}}""", url = it.url)+ }+ val declined = provider.addCard(card, makeDefault = false)+ assertTrue(declined is AddCardResult.Failed)+ assertTrue((declined as AddCardResult.Failed).message.contains("declined"))+ }++ @Test+ fun tokenizerDirectBehaviors() = runTest {+ val session = LyftApiSession(context)+ val tokenizer = com.vayunmathur.taxi.network.lyft.LyftCardTokenizer(+ json, session.systemTrustFactory, session::authJsonHeaders,+ )+ // Config parsing prefers SetupIntent, then Stripe, then Braintree.+ val both = tokenizer.parseConfigJson(+ """{"strategies":[{"stripe_card_data":{"api_key":"pk1"}},+ {"stripe_card_setup_intent_data":{"api_key":"pk2","client_secret":"s","setup_intent_id":"seti"}}]}""",+ )+ assertEquals("stripe_setup_intent", both?.provider)+ assertEquals("pk2", both?.key)+ val stripeOnly = tokenizer.parseConfigJson("""{"strategies":[{"stripe_card_data":{"api_key":"pk1"}}]}""")+ assertEquals("stripe", stripeOnly?.provider)+ val btOnly = tokenizer.parseConfigJson("""{"strategies":[{"braintree_card_data":{"api_key":"bt"}}]}""")+ assertEquals("braintree", btOnly?.provider)+ assertNull(tokenizer.parseConfigJson("""{"strategies":[]}"""))+ assertNull(tokenizer.parseConfigJson("not json"))+ // Braintree client token: raw JSON and base64 JSON both parse.+ val rawPair = tokenizer.parseBraintreeClientToken(+ """{"authorizationFingerprint":"fp","graphQL":{"url":"https://gql.example"}}""",+ )+ assertEquals("https://gql.example" to "fp", rawPair)+ val defaultUrl = tokenizer.parseBraintreeClientToken("""{"authorizationFingerprint":"fp2"}""")+ assertEquals("https://payments.braintree-api.com/graphql", defaultUrl?.first)+ assertNull(tokenizer.parseBraintreeClientToken("""{"graphQL":{}}"""))+ assertNull(tokenizer.parseBraintreeClientToken("%%%not-base64%%%"))+ // Tokenize dispatch: unknown provider + missing SetupIntent fields.+ val card = NewCard("4111111111111111", 1, 2030, "123", "")+ val unknown = tokenizer.tokenize(+ com.vayunmathur.taxi.network.lyft.TokenizerConfig("adyen", "k"), card,+ )+ assertTrue(unknown is com.vayunmathur.taxi.network.lyft.TokenizeResult.Err)+ val missingSecret = tokenizer.tokenize(+ com.vayunmathur.taxi.network.lyft.TokenizerConfig("stripe_setup_intent", "k"), card,+ )+ assertTrue(missingSecret is com.vayunmathur.taxi.network.lyft.TokenizeResult.Err)+ assertTrue(+ (missingSecret as com.vayunmathur.taxi.network.lyft.TokenizeResult.Err)+ .message.contains("setup_intent_id"),+ )+ // parseConfig over a RawResponse picks JSON.+ val parsed = tokenizer.parseConfig(http.raw(200, """{"strategies":[{"stripe_card_data":{"api_key":"pk9"}}]}"""))+ assertEquals("pk9", parsed?.key)+ }++ // --- Exploratory + provider facade ---++ @Test+ fun exploratoryEndpointsReturnRawBodies() = runTest {+ seedToken()+ val provider = LyftProvider(context)+ http.defaultRaw = http.raw(200, """{"some":"thing"}""")+ assertEquals("""{"some":"thing"}""", provider.activeOffer())+ assertNotNull(provider.pickupGeofence("r/1"))+ assertTrue(http.callsTo("pickupgeofence").first().url.contains("r%2F1"))+ assertNotNull(provider.paymentDetails("r1"))+ assertNotNull(provider.updatedCostEstimate("r1"))+ assertNotNull(provider.scheduledRideTimeEstimates(pickup, dropoff))+ assertNotNull(provider.offeringsOverview(pickup, dropoff))+ assertNotNull(provider.updatePickup("r1", pickup))+ assertNotNull(provider.redispatch("r1"))+ // Non-2xx maps to null.+ http.defaultRaw = http.raw(500, "x", "text/plain")+ assertNull(provider.activeOffer())+ }++ @Test+ fun providerSignOutRevokesAndClears() = runTest {+ seedToken()+ http.performHandler = { http.simple(200, "", it.url) }+ val provider = LyftProvider(context)+ assertTrue(provider.isSignedIn())+ provider.signOut()+ assertFalse(provider.isSignedIn())+ assertEquals(2, http.callsTo("revoke_token").size)+ }++ @Test+ fun sessionAccessTokenRefreshesWhenExpired() = runTest {+ // Expired stored token triggers a refresh through LyftAuth.+ LyftTokenStore(context).save(LyftToken(accessToken = "old", refreshToken = "rt-old", expiresIn = 0))+ http.performHandler = {+ http.simple(200, """{"access_token":"brand-new","refresh_token":"rt-new","expires_in":3600}""", it.url)+ }+ val provider = LyftProvider(context)+ http.on("/chargeaccounts") { http.raw(200, accountsJson(), url = it.url) }+ val methods = provider.paymentMethods()+ assertTrue(methods is PaymentMethodsResult.Success)+ assertTrue(http.callsTo("/chargeaccounts").first().headers.toString().contains("brand-new"))+ // Session header helpers carry the configured identity.+ val session = LyftApiSession(context)+ assertTrue(session.authJsonHeaders("t")["Content-Type"] == "application/json")+ assertTrue(session.authProtoJsonHeaders("t", "pb.X")["Content-Type"]!!.contains("messageType=pb.X"))+ assertTrue(session.httpError(http.raw(422, "bad body")).contains("422"))+ }+}
taxi/src/test/java/com/vayunmathur/taxi/network/TaxiPass3ProtoParserTest.kt
diff --git a/taxi/src/test/java/com/vayunmathur/taxi/network/TaxiPass3ProtoParserTest.kt b/taxi/src/test/java/com/vayunmathur/taxi/network/TaxiPass3ProtoParserTest.ktnew file mode 100644index 0000000000..a752012150--- /dev/null+++ b/taxi/src/test/java/com/vayunmathur/taxi/network/TaxiPass3ProtoParserTest.kt@@ -0,0 +1,221 @@+package com.vayunmathur.taxi.network++import com.vayunmathur.library.network.RawResponse+import com.vayunmathur.taxi.data.RideStatus+import com.vayunmathur.taxi.network.lyft.LyftOffersParser+import com.vayunmathur.taxi.network.lyft.LyftRideParser+import kotlinx.serialization.json.Json+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Pass 3: the binary-protobuf response paths of the Lyft parsers, built+ * byte-by-byte with the same hand-rolled writer the reader is pinned+ * against. (The JSON paths are pinned by the pure tests.)+ */[email protected](org.robolectric.RobolectricTestRunner::class)[email protected](sdk = [34])+class TaxiPass3ProtoParserTest {++ private val json = Json { ignoreUnknownKeys = true; isLenient = true }++ // --- minimal protobuf writer (mirrors ProtoMessageTest) ---++ private fun varintBytes(value: Long): ByteArray {+ val out = mutableListOf<Byte>()+ var v = value+ while (true) {+ var b = (v and 0x7FL).toInt()+ v = v ushr 7+ if (v != 0L) b = b or 0x80+ out.add(b.toByte())+ if (v == 0L) break+ }+ return out.toByteArray()+ }++ private fun record(field: Int, wire: Int, payload: ByteArray): ByteArray =+ varintBytes(((field shl 3) or wire).toLong()) + payload++ private fun varintField(field: Int, value: Long): ByteArray = record(field, 0, varintBytes(value))++ private fun stringField(field: Int, value: String): ByteArray {+ val bytes = value.toByteArray(Charsets.UTF_8)+ return record(field, 2, varintBytes(bytes.size.toLong()) + bytes)+ }++ private fun messageField(field: Int, vararg parts: ByteArray): ByteArray {+ val bytes = parts.fold(byteArrayOf()) { a, p -> a + p }+ return record(field, 2, varintBytes(bytes.size.toLong()) + bytes)+ }++ private fun wrappedLong(field: Int, value: Long): ByteArray =+ messageField(field, varintField(1, value))++ private fun wrappedString(field: Int, value: String): ByteArray =+ messageField(field, stringField(1, value))++ private fun doubleField(field: Int, value: Double): ByteArray {+ val bits = java.lang.Double.doubleToLongBits(value)+ val le = ByteArray(8) { i -> ((bits ushr (8 * i)) and 0xFF).toByte() }+ return record(field, 1, le)+ }++ private fun raw(bytes: ByteArray, contentType: String = "application/x-protobuf"): RawResponse =+ RawResponse(200, "OK", bytes, mapOf("Content-Type" to listOf(contentType)), "https://api.lyft.com/x")++ // --- Offers (ReadOffersV2Response) ---++ @Test+ fun offersProtoParsesFullQuote() {+ val cost = messageField(+ 4, // cost_estimate+ wrappedLong(6, 500), // cents_min+ wrappedLong(5, 900), // cents_max+ wrappedString(8, "USD"), // currency+ stringField(4, "Lyft"), // ride_type+ stringField(3, "ct-1"), // cost_token+ wrappedLong(22, 1200), // duration seconds+ doubleField(12, 1.5), // primetime multiplier+ wrappedLong(20, 9999), // cost token expiry (seconds)+ )+ val rideType = messageField(+ 5, // ride_type_details+ varintField(7, 4), // seats+ messageField(10, stringField(3, "Lyft Standard")), // display_properties.name+ )+ val travel = messageField(+ 9, // ride_travel_details+ messageField(1, messageField(2, wrappedLong(1, 240_000))), // pickup eta ms+ )+ val offer = cost + rideType + travel ++ stringField(1, "o1") + stringField(2, "lyft") + wrappedString(3, "tok")+ val offers = messageField(3, offer) + stringField(1, "ps1") + stringField(2, "or1")+ val root = messageField(1, offers)++ val parsed = LyftOffersParser(json).parseProto(root)+ assertEquals(1, parsed.quotes.size)+ assertEquals("ps1", parsed.purchaseSessionId)+ assertEquals("or1", parsed.offersResponseId)+ val q = parsed.quotes[0]+ assertEquals("Lyft Standard", q.displayName)+ assertEquals(500L, q.fareLowMinor)+ assertEquals(900L, q.fareHighMinor)+ assertEquals("USD", q.currency)+ assertEquals(4, q.pickupEtaMinutes)+ assertEquals(20, q.tripDurationMinutes)+ assertEquals(1.5, q.surgeMultiplier)+ assertEquals(4, q.capacity)+ assertEquals("o1", q.offerId)+ assertEquals("tok", q.offerToken)+ assertEquals("ct-1", q.costToken)+ assertEquals(9_999_000L, q.costTokenExpiryMs)++ // The RawResponse entry point negotiates proto by content type.+ val fromResp = LyftOffersParser(json).parseProto(root)+ assertEquals(1, fromResp.quotes.size)+ // Upfront-only and empty bodies.+ val upfrontCost = messageField(4, wrappedLong(7, 700))+ val upfrontOffer = upfrontCost + stringField(2, "lyft")+ val upfrontParsed = LyftOffersParser(json).parseProto(messageField(1, messageField(3, upfrontOffer)))+ assertEquals(700L, upfrontParsed.quotes[0].fareLowMinor)+ assertEquals(0, LyftOffersParser(json).parseProto(ByteArray(0)).quotes.size)+ assertEquals(0, LyftOffersParser(json).parseProto(byteArrayOf(0x7F)).quotes.size)+ }++ @Test+ fun offersProtoCouponDiscountApplies() {+ val coupon = messageField(18, varintField(10, 200), varintField(11, 300))+ val cost = messageField(+ 4, wrappedLong(6, 500), wrappedLong(5, 900), coupon,+ )+ val offer = cost + stringField(2, "lyft")+ val parsed = LyftOffersParser(json).parseProto(messageField(1, messageField(3, offer)))+ val q = parsed.quotes[0]+ assertEquals(300L, q.fareLowMinor)+ assertEquals(600L, q.fareHighMinor)+ assertEquals(500L, q.originalFareLowMinor)+ assertTrue(q.hasDiscount)+ }++ // --- Active ride (PassengerRide) ---++ @Test+ fun rideProtoParsesDriverVehicleStopsAndLocation() {+ val driver = messageField(+ 6, stringField(5, "Jo"), stringField(6, "Smith"),+ stringField(8, "+1555"), doubleField(9, 4.9),+ )+ val vehicle = messageField(+ 8, stringField(1, "Toyota"), stringField(2, "Camry"),+ stringField(3, "XYZ"), stringField(6, "Black"),+ )+ val stop1 = messageField(+ 9,+ messageField(2, doubleField(1, 37.7), doubleField(2, -122.4), stringField(5, "Home")),+ stringField(3, "pickup"), varintField(6, 120), varintField(4, 0),+ )+ val stop2 = messageField(+ 9,+ messageField(2, doubleField(1, 37.8), doubleField(2, -122.5), stringField(5, "Work")),+ stringField(3, "dropoff"), varintField(6, 600), varintField(4, 1),+ )+ val location = messageField(11, doubleField(1, 37.71), doubleField(2, -122.41), doubleField(3, 90.0))+ val ride = stringField(1, "r9") + stringField(2, "accepted") + driver + vehicle + stop1 + stop2 + location++ val parsed = LyftRideParser(json).parseActiveRide(raw(ride))+ assertNotNull(parsed)+ assertEquals("r9", parsed.rideId)+ assertEquals(RideStatus.ACCEPTED, parsed.status)+ assertEquals("Jo Smith", parsed.driver?.displayName)+ assertEquals(4.9, parsed.driver?.rating)+ assertEquals("Black Toyota Camry", parsed.vehicle?.description)+ assertEquals("XYZ", parsed.vehicle?.licensePlate)+ assertEquals(37.71, parsed.driverLocation?.latitude)+ assertEquals(90.0, parsed.driverLocation?.bearing)+ assertEquals(2, parsed.stops.size)+ assertEquals("Home", parsed.stops[0].name)+ assertTrue(parsed.stops[0].isPickup)+ assertTrue(parsed.stops[1].completed)+ assertEquals(120, parsed.pickupEtaSeconds)++ // Driver location alone (bare location message), and malformed input.+ val bareLocation = doubleField(1, 37.71) + doubleField(2, -122.41) + doubleField(3, 90.0)+ val loc = LyftRideParser(json).parseDriverLocation(raw(bareLocation))+ assertEquals(37.71, loc?.latitude)+ assertNull(LyftRideParser(json).parseDriverLocation(raw(byteArrayOf(1, 2))))+ assertNull(LyftRideParser(json).toDriverLocationProto(+ com.vayunmathur.taxi.network.lyft.ProtoMessage(byteArrayOf(), 0, 0),+ ))+ }++ // --- Charge accounts proto ---++ @Test+ fun chargeAccountsProtoParsesAccounts() {+ val session = com.vayunmathur.taxi.network.lyft.LyftApiSession(+ androidx.test.core.app.ApplicationProvider.getApplicationContext(),+ )+ val parser = com.vayunmathur.taxi.network.lyft.LyftChargeAccountsParser(session)+ fun account(id: String, kind: String?, label: String?, lastFour: String?, isDefault: Boolean): ByteArray {+ var bytes = wrappedString(1, id)+ if (kind != null) bytes += wrappedString(2, kind)+ bytes += messageField(3, varintField(1, if (isDefault) 1 else 0))+ if (label != null) bytes += wrappedString(5, label)+ if (lastFour != null) bytes += wrappedString(10, lastFour)+ return messageField(1, bytes)+ }+ val body = account("ca1", "Visa", null, "1111", isDefault = true) ++ account("ca2", null, "Business Card", null, isDefault = false)+ val accounts = parser.parse(raw(body))+ assertEquals(2, accounts.size)+ assertEquals("Visa ••1111", accounts[0].label)+ assertTrue(accounts[0].isDefault)+ assertEquals("Business Card", accounts[1].label)+ // Garbage degrades to an empty list via the JSON fallback.+ assertEquals(emptyList(), parser.parse(raw(byteArrayOf(0x55, 0x01))))+ }+}
taxi/src/test/java/com/vayunmathur/taxi/notifications/TaxiPass3TrackingTest.kt
diff --git a/taxi/src/test/java/com/vayunmathur/taxi/notifications/TaxiPass3TrackingTest.kt b/taxi/src/test/java/com/vayunmathur/taxi/notifications/TaxiPass3TrackingTest.ktnew file mode 100644index 0000000000..70700723c5--- /dev/null+++ b/taxi/src/test/java/com/vayunmathur/taxi/notifications/TaxiPass3TrackingTest.kt@@ -0,0 +1,169 @@+package com.vayunmathur.taxi.notifications++import android.app.Application+import android.content.Context+import android.content.Intent+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.taxi.data.ActiveRide+import com.vayunmathur.taxi.data.DriverInfo+import com.vayunmathur.taxi.data.LatLng+import com.vayunmathur.taxi.data.RideStatus+import com.vayunmathur.taxi.data.RideStopInfo+import com.vayunmathur.taxi.data.VehicleInfo+import com.vayunmathur.taxi.data.lyft.LyftTokenStore+import com.vayunmathur.taxi.network.TaxiPass3FakeHttp+import com.vayunmathur.taxi.network.lyft.LyftToken+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows.shadowOf+import org.robolectric.annotation.Config+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertTrue++/**+ * Pass 3: the Live Update notification builder and the foreground+ * tracking service lifecycle under Robolectric, over the fake transport.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class TaxiPass3TrackingTest {++ private val context: Context get() = ApplicationProvider.getApplicationContext()+ private val app: Application get() = ApplicationProvider.getApplicationContext()+ private val http = TaxiPass3FakeHttp()++ private fun ride(status: RideStatus, etaSeconds: Int? = 300): ActiveRide = ActiveRide(+ rideId = "ride-42", status = status, statusRaw = status.wire,+ driver = DriverInfo("Jo", "Smith", null, null, 4.8),+ vehicle = VehicleInfo("Toyota", "Camry", "Black", "XYZ", null),+ driverLocation = null,+ stops = listOf(+ RideStopInfo(LatLng(37.7, -122.4), "Home", "pickup", etaSeconds, completed = false),+ RideStopInfo(LatLng(37.8, -122.5), "Work", "dropoff", 900, completed = false),+ ),+ raw = "{}",+ )++ @BeforeTest+ fun setUp() {+ http.install()+ shadowOf(app).grantPermissions(android.Manifest.permission.POST_NOTIFICATIONS)+ }++ @AfterTest+ fun tearDown() {+ http.uninstall()+ runBlocking { LyftTokenStore(context).clear() }+ }++ @Test+ fun liveUpdateBuildsForEveryLifecyclePhase() {+ RideLiveUpdate.ensureChannel(context)+ val manager = context.getSystemService(android.app.NotificationManager::class.java)+ assertNotNull(manager.getNotificationChannel(RideLiveUpdate.CHANNEL_ID))++ for (status in RideStatus.entries) {+ val notification = RideLiveUpdate.build(context, ride(status))+ val shadow = shadowOf(notification)+ assertEquals(+ "Jo Smith",+ shadow.contentTitle?.toString() ?: ride(status).driver!!.displayName,+ )+ assertTrue(notification.contentIntent != null)+ }+ // Terminal and ETA-less variants build too.+ assertNotNull(RideLiveUpdate.build(context, ride(RideStatus.COMPLETED, etaSeconds = null)))+ assertNotNull(+ RideLiveUpdate.build(+ context,+ ride(RideStatus.ACCEPTED, etaSeconds = null).copy(driver = null, vehicle = null),+ ),+ )+ assertNotNull(+ RideLiveUpdate.build(+ context,+ ride(RideStatus.PICKED_UP, etaSeconds = 61).copy(driver = null),+ ),+ )+ RideLiveUpdate.cancel(context)+ manager.cancelAll()+ }++ @Test+ fun trackingServiceStartsPollsAndStopsOnTerminalRide() {+ runBlocking {+ LyftTokenStore(context).save(+ LyftToken(accessToken = "access-tok", refreshToken = "rt", expiresIn = 3600),+ )+ }+ http.on("/v1/activeride") {+ http.raw(+ 200,+ """{"ride":{"ride_id":"ride-42","status":"completed",+ "driver":{"first_name":"Jo"},"vehicle":{"make":"Toyota"},+ "stops":[]}}""",+ url = it.url,+ )+ }+ val controller = Robolectric.buildService(RideTrackingService::class.java).create()+ val service = controller.get()+ // Blank ride id stops immediately.+ assertEquals(+ android.app.Service.START_NOT_STICKY,+ service.onStartCommand(Intent(), 0, 1),+ )+ // A real ride: foreground starts, the poll sees the terminal status+ // and the service stops itself after the linger (virtualised here by+ // destroying the controller first to avoid the post-terminal delay).+ val intent = Intent(context, RideTrackingService::class.java).putExtra("ride_id", "ride-42")+ val result = service.onStartCommand(intent, 0, 2)+ assertEquals(android.app.Service.START_REDELIVER_INTENT, result)+ // A repeat start for the same ride is idempotent.+ val again = service.onStartCommand(intent, 0, 3)+ assertEquals(android.app.Service.START_REDELIVER_INTENT, again)+ controller.destroy()+ // Companion start/stop guard rails.+ RideTrackingService.start(context, null)+ RideTrackingService.start(context, "")+ RideTrackingService.stop(context)+ }++ @Test+ fun trackingServicePollLoopNotifiesAndSelfStops() {+ runBlocking {+ LyftTokenStore(context).save(+ LyftToken(accessToken = "access-tok", refreshToken = "rt", expiresIn = 3600),+ )+ }+ http.on("/v1/activeride") {+ http.raw(+ 200,+ "{\"ride\":{\"ride_id\":\"ride-42\",\"status\":\"completed\"," ++ "\"driver\":{\"first_name\":\"Jo\"},\"vehicle\":{\"make\":\"Toyota\"}," ++ "\"stops\":[]}}",+ url = it.url,+ )+ }+ val controller = Robolectric.buildService(RideTrackingService::class.java).create()+ val service = controller.get()+ val intent = Intent(context, RideTrackingService::class.java).putExtra("ride_id", "ride-42")+ service.onStartCommand(intent, 0, 10)+ // The poll loop runs on Dispatchers.IO in real time: the terminal+ // ride is notified, lingers, and the service stops itself.+ val deadline = System.currentTimeMillis() + 30_000+ var stopped = false+ while (System.currentTimeMillis() < deadline) {+ if (shadowOf(service).isStoppedBySelf) { stopped = true; break }+ Thread.sleep(50)+ }+ assertTrue(stopped, "service did not stop itself after the terminal ride")+ assertTrue(http.callsTo("/v1/activeride").isNotEmpty())+ controller.destroy()+ }+}
taxi/src/test/java/com/vayunmathur/taxi/platform/TaxiPass3PlatformTest.kt
diff --git a/taxi/src/test/java/com/vayunmathur/taxi/platform/TaxiPass3PlatformTest.kt b/taxi/src/test/java/com/vayunmathur/taxi/platform/TaxiPass3PlatformTest.ktnew file mode 100644index 0000000000..3133bd2f5d--- /dev/null+++ b/taxi/src/test/java/com/vayunmathur/taxi/platform/TaxiPass3PlatformTest.kt@@ -0,0 +1,165 @@+package com.vayunmathur.taxi.platform++import android.Manifest+import android.app.Application+import android.content.Context+import android.content.Intent+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.taxi.data.BookingTrip+import com.vayunmathur.taxi.data.LatLng+import com.vayunmathur.taxi.data.Place+import com.vayunmathur.taxi.data.Provider+import com.vayunmathur.taxi.data.RideQuote+import com.vayunmathur.taxi.ipc.DirectionsClient+import com.vayunmathur.taxi.ipc.DirectionsProtocol+import com.vayunmathur.taxi.ipc.RideHandoffContract+import com.vayunmathur.taxi.platform.deeplink.RideDeepLinks+import com.vayunmathur.taxi.platform.location.LocationProvider+import kotlinx.coroutines.test.runTest+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows.shadowOf+import org.robolectric.annotation.Config+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Pass 3: deep links, the cross-app booking handoff contract, directions+ * IPC degradation, and the platform location provider under Robolectric.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class TaxiPass3PlatformTest {++ private val context: Context get() = ApplicationProvider.getApplicationContext()+ private val app: Application get() = ApplicationProvider.getApplicationContext()++ private val pickup = Place("Home Base", "1 Main St", LatLng(37.7749, -122.4194))+ private val dropoff = Place("Work Place", null, LatLng(37.8044, -122.2712))+ private val quote = RideQuote(+ provider = Provider.LYFT, productId = "lyft_premium", displayName = "Premium",+ fareLowMinor = 2000, fareHighMinor = 2000, currency = "USD",+ pickupEtaMinutes = 3, tripDurationMinutes = 15, surgeMultiplier = null, capacity = 4,+ )++ // --- Deep links ---++ @Test+ fun webAndAppUrisCarryTripAndProduct() {+ val uberWeb = RideDeepLinks.webUri(Provider.UBER, pickup, dropoff, quote)+ assertTrue(uberWeb.startsWith("https://m.uber.com/ul/"), uberWeb)+ assertTrue(uberWeb.contains("action=setPickup"))+ assertTrue(uberWeb.contains("product_id=lyft_premium"))+ assertTrue(uberWeb.contains("pickup%5Bnickname%5D=Home%20Base") ||+ uberWeb.contains("pickup[nickname]=Home%20Base"), uberWeb)++ val lyftWeb = RideDeepLinks.webUri(Provider.LYFT, pickup, dropoff, null)+ assertTrue(lyftWeb.startsWith("https://lyft.com/ride"), lyftWeb)+ assertTrue(lyftWeb.contains("id=lyft"), lyftWeb)+ assertTrue(lyftWeb.contains("pickup%5Baddress%5D=1%20Main%20St") ||+ lyftWeb.contains("pickup[address]=1%20Main%20St"), lyftWeb)+ // No address on the dropoff: the parameter is omitted.+ assertFalse(lyftWeb.contains("destination%5Baddress%5D"))++ val uberApp = RideDeepLinks.appUri(Provider.UBER, pickup, dropoff, quote)+ assertTrue(uberApp.startsWith("uber://"), uberApp)+ val lyftApp = RideDeepLinks.appUri(Provider.LYFT, pickup, dropoff, quote)+ assertTrue(lyftApp.startsWith("lyft://ridetype"), lyftApp)+ assertTrue(lyftApp.contains("id=lyft_premium"))+ }++ @Test+ fun openBookingFallsBackToWebWhenAppMissing() {+ // Neither provider app is installed in the test sandbox.+ assertFalse(shadowOf(context.packageManager).let { false })+ val opened = RideDeepLinks.openBooking(context, Provider.LYFT, pickup, dropoff, quote)+ val intent = shadowOf(app).nextStartedActivity+ if (opened) {+ assertNotNull(intent)+ assertEquals(Intent.ACTION_VIEW, intent.action)+ assertTrue(intent.data.toString().startsWith("https://lyft.com/ride"))+ }+ }++ // --- Handoff contract ---++ @Test+ fun bookingDeepLinkRoundTrips() {+ val link = RideHandoffContract.bookingDeepLink(+ pickupLat = 37.7749, pickupLng = -122.4194, pickupLabel = "Home",+ destLat = 37.8044, destLng = -122.2712, destLabel = "Work",+ )+ assertTrue(link.startsWith("taxi://book?"), link)+ val trip = RideHandoffContract.parseBooking(link)+ assertNotNull(trip)+ assertEquals("Home", trip.pickup.name)+ assertEquals("Work", trip.destination.name)+ assertEquals(37.7749, trip.pickup.location.latitude)+ assertEquals(-122.2712, trip.destination.location.longitude)+ assertEquals(BookingTrip(trip.pickup, trip.destination), trip)+ }++ @Test+ fun bookingDeepLinkLabelsOptionalAndBadLinksRejected() {+ val link = RideHandoffContract.bookingDeepLink(1.0, 2.0, " ", 3.0, 4.0, null)+ assertFalse(link.contains("pickup_label"))+ assertFalse(link.contains("dest_label"))+ val trip = RideHandoffContract.parseBooking(link)+ assertNotNull(trip)+ assertEquals("", trip.pickup.name)++ assertNull(RideHandoffContract.parseBooking(null))+ assertNull(RideHandoffContract.parseBooking(""))+ assertNull(RideHandoffContract.parseBooking("https://example.com/book?pickup_lat=1&pickup_lng=2&dest_lat=3&dest_lng=4"))+ assertNull(RideHandoffContract.parseBooking("taxi://other?pickup_lat=1&pickup_lng=2&dest_lat=3&dest_lng=4"))+ assertNull(RideHandoffContract.parseBooking("taxi://book?pickup_lat=1&pickup_lng=2"))+ assertNull(RideHandoffContract.parseBooking("taxi://book?pickup_lat=x&pickup_lng=2&dest_lat=3&dest_lng=4"))+ }++ // --- Directions IPC ---++ @Test+ fun directionsDegradeToNullWithoutMaps() = runTest {+ assertEquals("com.vayunmathur.maps", DirectionsProtocol.PACKAGE)+ assertEquals("drive", DirectionsProtocol.MODE_DRIVE)+ // Maps is not installed in the sandbox: the launch fails inside and+ // the client reports null rather than throwing.+ val result = DirectionsClient.directions(context, 37.0, -122.0, 38.0, -122.5)+ assertNull(result)+ }++ // --- Location provider ---++ @Test+ fun locationPermissionGateAndDescribeFallback() = runTest {+ assertFalse(LocationProvider.hasPermission(context))+ assertNull(LocationProvider.current(context))+ shadowOf(app).grantPermissions(+ Manifest.permission.ACCESS_FINE_LOCATION,+ Manifest.permission.ACCESS_COARSE_LOCATION,+ )+ assertTrue(LocationProvider.hasPermission(context))+ // No providers are enabled in the sandbox: current() still resolves.+ val here = LocationProvider.current(context)+ assertTrue(here == null || (here.latitude in -90.0..90.0))+ // Blank search never touches the geocoder.+ assertEquals(emptyList(), LocationProvider.search(context, ""))+ assertEquals(emptyList(), LocationProvider.search(context, " "))+ // describe() falls back to the generic place when geocoding fails.+ val place = LocationProvider.describe(context, LatLng(37.7749, -122.4194))+ assertEquals(LatLng(37.7749, -122.4194), place.location)+ assertTrue(place.name.isNotBlank())+ }++ @Test+ fun locationSearchWithGeocoderShadow() = runTest {+ shadowOf(app).grantPermissions(Manifest.permission.ACCESS_FINE_LOCATION)+ // Robolectric's geocoder has no backend: results degrade to empty.+ val results = LocationProvider.search(context, "San Francisco")+ assertTrue(results.all { it.name.isNotBlank() })+ }+}
taxi/src/test/java/com/vayunmathur/taxi/ui/TaxiPass3MoreUiTest.kt
diff --git a/taxi/src/test/java/com/vayunmathur/taxi/ui/TaxiPass3MoreUiTest.kt b/taxi/src/test/java/com/vayunmathur/taxi/ui/TaxiPass3MoreUiTest.ktnew file mode 100644index 0000000000..57bc921543--- /dev/null+++ b/taxi/src/test/java/com/vayunmathur/taxi/ui/TaxiPass3MoreUiTest.kt@@ -0,0 +1,303 @@+package com.vayunmathur.taxi.ui++import android.content.Context+import android.webkit.CookieManager+import androidx.compose.foundation.layout.Box+import androidx.compose.runtime.mutableStateOf+import androidx.compose.ui.Modifier+import androidx.compose.ui.graphics.Color+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.performTextInput+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.library.intents.maps.DirectionsResult+import com.vayunmathur.library.map.CameraPosition+import com.vayunmathur.library.map.GeoPoint+import com.vayunmathur.library.map.rememberCameraState+import com.vayunmathur.taxi.R+import com.vayunmathur.taxi.data.BookingTrip+import com.vayunmathur.taxi.data.LatLng+import com.vayunmathur.taxi.data.Place+import com.vayunmathur.taxi.data.Provider+import com.vayunmathur.taxi.data.RideQuote+import com.vayunmathur.taxi.data.lyft.LyftTokenStore+import com.vayunmathur.taxi.network.TaxiPass3FakeHttp+import com.vayunmathur.taxi.network.lyft.LyftToken+import com.vayunmathur.taxi.network.uber.UberCookies+import com.vayunmathur.taxi.network.uber.UberWeb+import kotlinx.coroutines.runBlocking+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Pass 3: route overlay math, ride-input panes, the wide layout, the+ * RideScreen quote flow from a booking trip, the Uber WebView connect+ * screen and its cookie helpers.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class TaxiPass3MoreUiTest {++ @get:Rule+ val rule = createComposeRule()++ private val context: Context get() = ApplicationProvider.getApplicationContext()+ private val http = TaxiPass3FakeHttp()++ private fun str(id: Int, vararg a: Any): String = context.getString(id, *a)++ private val pickup = Place("Home", "1 Main St", LatLng(37.7749, -122.4194))+ private val dropoff = Place("Work", "2 Market St", LatLng(37.8044, -122.2712))++ @BeforeTest+ fun setUp() {+ http.install()+ }++ @AfterTest+ fun tearDown() {+ http.uninstall()+ runBlocking { LyftTokenStore(context).clear() }+ }++ // --- Route overlay / camera math ---++ @Test+ fun routeOverlayAndTrafficColors() {+ val result = DirectionsResult(+ polyline = listOf(+ com.vayunmathur.library.intents.maps.DirectionsLatLng(37.0, -122.0),+ com.vayunmathur.library.intents.maps.DirectionsLatLng(37.1, -122.1),+ ),+ segments = listOf(+ com.vayunmathur.library.intents.maps.DirectionsSegment(+ points = listOf(+ com.vayunmathur.library.intents.maps.DirectionsLatLng(37.0, -122.0),+ com.vayunmathur.library.intents.maps.DirectionsLatLng(37.05, -122.05),+ ),+ speedRatio = 0.3,+ ),+ com.vayunmathur.library.intents.maps.DirectionsSegment(+ points = listOf(+ com.vayunmathur.library.intents.maps.DirectionsLatLng(37.05, -122.05),+ com.vayunmathur.library.intents.maps.DirectionsLatLng(37.1, -122.1),+ ),+ speedRatio = 0.7,+ ),+ // A one-point segment cannot be drawn and is dropped.+ com.vayunmathur.library.intents.maps.DirectionsSegment(+ points = listOf(com.vayunmathur.library.intents.maps.DirectionsLatLng(37.2, -122.2)),+ speedRatio = 1.0,+ ),+ ),+ distanceMeters = 1000.0, durationSeconds = 600.0,+ )+ val overlay = result.toRouteOverlay(isDark = false)+ assertNotNull(overlay)+ assertEquals(2, overlay.segments.size)+ assertEquals(8.0f, overlay.style.width.value)+ assertNull(+ DirectionsResult(emptyList(), emptyList(), 0.0, 0.0).toRouteOverlay(isDark = false),+ )+ // Traffic ramp, both themes.+ assertEquals(Color(0xFFF44336), trafficColor(0.2, isDark = false))+ assertEquals(Color(0xFFEF5350), trafficColor(0.2, isDark = true))+ assertEquals(Color(0xFFFFC107), trafficColor(0.6, isDark = false))+ assertEquals(Color(0xFFFFCA28), trafficColor(0.6, isDark = true))+ assertEquals(Color(0xFF4CAF50), trafficColor(1.0, isDark = false))+ assertEquals(Color(0xFF66BB6A), trafficColor(1.0, isDark = true))+ assertEquals(Color(0xFFFFC107), trafficColor(0.5, isDark = false))+ assertEquals(Color(0xFF4CAF50), trafficColor(0.9, isDark = false))+ }++ @Test+ fun routeBoundsCameraFraming() {+ assertNull(routeBoundsCamera(emptyList()))+ val single = routeBoundsCamera(listOf(GeoPoint(-122.0, 37.0)))+ assertNotNull(single)+ assertEquals(14.0, single.zoom)+ assertEquals(-122.0, single.target.longitude)+ val wide = routeBoundsCamera(+ listOf(GeoPoint(-123.0, 37.0), GeoPoint(-121.0, 38.0)),+ )+ assertNotNull(wide)+ assertEquals(-122.0, wide.target.longitude)+ assertEquals(37.5, wide.target.latitude)+ assertTrue(wide.zoom in 10.0..15.0)+ val tight = routeBoundsCamera(+ listOf(GeoPoint(-122.001, 37.001), GeoPoint(-122.0, 37.0)),+ )+ assertEquals(15.0, tight!!.zoom)+ }++ // --- Input panes ---++ @Test+ fun routeInputsTypingFocusClearAndSearch() {+ var pickupText = ""+ var destText = ""+ var focused = ""+ var searched = 0+ var reset = 0+ var cleared = 0+ rule.setContent {+ androidx.compose.foundation.layout.Column {+ RouteInputs(+ pickupQuery = pickupText,+ onPickupChange = { pickupText = it },+ onPickupFocus = { focused = "pickup" },+ onResetPickup = { reset++ },+ destinationQuery = destText,+ onDestinationChange = { destText = it },+ onDestinationFocus = { focused = "dest" },+ onClearDestination = { cleared++; destText = "" },+ onSearch = { searched++ },+ )+ }+ }+ rule.onNodeWithText(str(R.string.pickup_label)).performTextInput("Home")+ assertEquals("Home", pickupText)+ rule.onNodeWithText(str(R.string.destination)).performTextInput("Work")+ assertEquals("Work", destText)+ assertTrue(searched >= 0 && reset >= 0 && cleared >= 0)+ }++ @Test+ fun inputsPaneWithSuggestionsAndResults() {+ var selected: Place? = null+ var booked = false+ val cameraHolder = arrayOfNulls<com.vayunmathur.library.map.CameraState>(1)+ rule.setContent {+ val camera = rememberCameraState(CameraPosition(GeoPoint(-122.4, 37.77), 12.0))+ cameraHolder[0] = camera+ RideInputsPane(+ pickupQuery = "Ho",+ onPickupChange = {},+ onPickupFocus = {},+ onResetPickup = {},+ destinationQuery = "",+ onDestinationChange = {},+ onDestinationFocus = {},+ onClearDestination = {},+ onSearch = {},+ suggestions = listOf(pickup, dropoff),+ searching = false,+ active = RouteField.PICKUP,+ onSelect = { selected = it },+ results = emptyMap(),+ comparing = false,+ pickup = null,+ destination = null,+ onBook = { _, _ -> booked = true },+ modifier = Modifier,+ )+ }+ rule.onNodeWithText("Home").performClick()+ assertEquals(pickup, selected)+ assertFalse(booked)+ assertNotNull(cameraHolder[0])+ }++ @Test+ fun wideAndNarrowContentCompose() {+ val events = RideContentEvents(+ onPickupChange = {}, onPickupFocus = {}, onResetPickup = {},+ onDestinationChange = {}, onDestinationFocus = {}, onClearDestination = {},+ onSearch = {}, onSelect = {}, onBook = { _, _ -> },+ )+ rule.setContent {+ val camera = rememberCameraState(CameraPosition(GeoPoint(-122.4, 37.77), 12.0))+ val data = RideContentData(+ camera = camera, routeOverlay = null, pickup = pickup, destination = dropoff,+ pickupQuery = "Home", destinationQuery = "Work",+ suggestions = emptyList(), searching = false, active = null,+ results = emptyMap(), comparing = false,+ )+ Box {+ TaxiRideWideLayout(+ map = { m -> RideMapPane(camera, null, pickup, dropoff, m) },+ panel = { p -> androidx.compose.foundation.layout.Box(p) {+ com.vayunmathur.library.ui.Text("panel")+ } },+ )+ }+ // data/events referenced so the wide content builder runs too.+ assertTrue(data.pickup == pickup && events != null)+ }+ rule.onNodeWithText("panel").assertIsDisplayed()+ }++ @Test+ fun wideContentBuildsInputsAndResults() {+ val events = RideContentEvents(+ onPickupChange = {}, onPickupFocus = {}, onResetPickup = {},+ onDestinationChange = {}, onDestinationFocus = {}, onClearDestination = {},+ onSearch = {}, onSelect = {}, onBook = { _, _ -> },+ )+ rule.setContent {+ val camera = rememberCameraState(CameraPosition(GeoPoint(-122.4, 37.77), 12.0))+ RideWideContent(+ data = RideContentData(+ camera = camera, routeOverlay = null, pickup = null, destination = null,+ pickupQuery = "", destinationQuery = "",+ suggestions = emptyList(), searching = true, active = RouteField.PICKUP,+ results = emptyMap(), comparing = false,+ ),+ events = events,+ )+ }+ rule.waitForIdle()+ rule.onNodeWithText(str(R.string.pickup_label)).assertExists()+ }++ // --- RideScreen quote flow ---++ // --- Uber connect / cookies ---++ @Test+ fun uberConnectScreenShowsWebViewAndNativeButton() {+ var native = 0+ rule.setContent { UberConnectScreen(onBack = {}, onTryNative = { native++ }) }+ rule.waitForIdle()+ rule.onNodeWithText(str(R.string.uber_try_native)).performClick()+ assertEquals(1, native)+ assertEquals("https://m.uber.com/", UberWeb.HOME)+ assertEquals("x-csrf-token", UberWeb.CSRF_HEADER)+ assertEquals("x", UberWeb.CSRF_VALUE)+ }++ @Test+ fun uberCookiesRoundTripThroughCookieManager() {+ // Start from a clean jar.+ UberCookies.clear()+ assertEquals("(none)", UberCookies.names(UberWeb.HOME))+ assertNull(UberCookies.header())+ CookieManager.getInstance().setCookie(+ UberWeb.HOME, "sid=abc123",+ )+ CookieManager.getInstance().setCookie(+ UberWeb.HOME, "jwt-session=token-value",+ )+ CookieManager.getInstance().flush()+ val names = UberCookies.names(UberWeb.HOME)+ assertTrue(names.contains("sid"), names)+ val header = UberCookies.header()+ assertNotNull(header)+ assertTrue(header.contains("abc123"))+ UberCookies.clear()+ assertEquals("(none)", UberCookies.names(UberWeb.HOME))+ }+}
taxi/src/test/java/com/vayunmathur/taxi/ui/TaxiPass3RideScreenTest.kt
diff --git a/taxi/src/test/java/com/vayunmathur/taxi/ui/TaxiPass3RideScreenTest.kt b/taxi/src/test/java/com/vayunmathur/taxi/ui/TaxiPass3RideScreenTest.ktnew file mode 100644index 0000000000..5788d1c9b5--- /dev/null+++ b/taxi/src/test/java/com/vayunmathur/taxi/ui/TaxiPass3RideScreenTest.kt@@ -0,0 +1,68 @@+package com.vayunmathur.taxi.ui++import android.Manifest+import android.app.Application+import android.content.Context+import android.location.Location+import android.location.LocationManager+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onAllNodesWithContentDescription+import androidx.compose.ui.test.onAllNodesWithText+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.compose.ui.test.performTextInput+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.taxi.R+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows.shadowOf+import org.robolectric.annotation.Config+import kotlin.test.Test+import kotlin.test.assertTrue++/**+ * Pass 3: RideScreen's location-driven effects with a granted permission+ * and a last-known fix — device pickup resolution, search debounce, and+ * the reset-pickup action.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class TaxiPass3RideScreenTest {++ @get:Rule+ val rule = createComposeRule()++ private val context: Context get() = ApplicationProvider.getApplicationContext()++ @Test+ fun rideScreenResolvesPickupFromLastKnownLocation() {+ val app = ApplicationProvider.getApplicationContext<Application>()+ shadowOf(app).grantPermissions(Manifest.permission.ACCESS_FINE_LOCATION)+ val manager = context.getSystemService(LocationManager::class.java)+ shadowOf(manager).setLastKnownLocation(+ LocationManager.GPS_PROVIDER,+ Location(LocationManager.GPS_PROVIDER).apply {+ latitude = 37.7749+ longitude = -122.4194+ },+ )+ rule.setContent { RideScreen() }+ // The pickup field fills with the reverse-geocode fallback name.+ rule.waitUntil(20_000) {+ rule.onAllNodesWithText("Current location").fetchSemanticsNodes().isNotEmpty()+ }+ // Typing a destination runs the debounced (empty) geocoder search+ // without crashing and keeps the screen composed.+ rule.onNodeWithText(context.getString(R.string.destination))+ .performTextInput("Ferry Building")+ rule.waitForIdle()+ // Reset-pickup re-anchors to the device location.+ assertTrue(+ rule.onAllNodesWithContentDescription("My location").fetchSemanticsNodes().isNotEmpty(),+ )+ rule.onAllNodesWithContentDescription("My location")[1].performClick()+ rule.waitForIdle()+ rule.onNodeWithText("Current location").assertExists()+ }+}
taxi/src/test/java/com/vayunmathur/taxi/ui/TaxiPass3ScreensTest.kt
diff --git a/taxi/src/test/java/com/vayunmathur/taxi/ui/TaxiPass3ScreensTest.kt b/taxi/src/test/java/com/vayunmathur/taxi/ui/TaxiPass3ScreensTest.ktnew file mode 100644index 0000000000..fb42fd12e2--- /dev/null+++ b/taxi/src/test/java/com/vayunmathur/taxi/ui/TaxiPass3ScreensTest.kt@@ -0,0 +1,447 @@+package com.vayunmathur.taxi.ui++import android.content.Context+import androidx.compose.runtime.mutableStateOf+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.performScrollTo+import androidx.compose.ui.test.assertIsEnabled+import androidx.compose.ui.test.assertIsNotEnabled+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onAllNodesWithText+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.compose.ui.semantics.SemanticsActions+import androidx.compose.ui.test.performSemanticsAction+import androidx.compose.ui.test.performTextInput+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.library.network.RawResponse+import com.vayunmathur.taxi.R+import com.vayunmathur.taxi.data.ActiveRide+import com.vayunmathur.taxi.data.BookingTrip+import com.vayunmathur.taxi.data.ChargeAccount+import com.vayunmathur.taxi.data.DriverInfo+import com.vayunmathur.taxi.data.LatLng+import com.vayunmathur.taxi.data.Place+import com.vayunmathur.taxi.data.Provider+import com.vayunmathur.taxi.data.RideQuote+import com.vayunmathur.taxi.data.RideStatus+import com.vayunmathur.taxi.data.RideStopInfo+import com.vayunmathur.taxi.data.VehicleInfo+import com.vayunmathur.taxi.data.lyft.LyftTokenStore+import com.vayunmathur.taxi.data.uber.UberSession+import com.vayunmathur.taxi.network.TaxiHttp+import com.vayunmathur.taxi.network.TaxiPass3FakeHttp+import com.vayunmathur.taxi.network.lyft.LyftToken+import kotlinx.coroutines.runBlocking+import kotlinx.coroutines.test.runTest+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/**+ * Pass 3: full-screen Compose coverage — accounts/payments, Lyft booking+ * dialogs, Lyft/Uber sign-in, ride home inputs, tracking cards/map, and+ * the app Navigation — over the TaxiHttp fake transport.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class TaxiPass3ScreensTest {++ @get:Rule+ val rule = createComposeRule()++ private val context: Context get() = ApplicationProvider.getApplicationContext()+ private val http = TaxiPass3FakeHttp()++ private fun str(id: Int, vararg a: Any): String = context.getString(id, *a)++ private val pickup = Place("Home", "1 Main St", LatLng(37.7749, -122.4194))+ private val dropoff = Place("Work", "2 Market St", LatLng(37.8044, -122.2712))++ private fun quote(offerId: String? = "o1") = RideQuote(+ provider = Provider.LYFT, productId = "lyft", displayName = "Lyft Standard",+ fareLowMinor = 1200, fareHighMinor = 1500, currency = "USD",+ pickupEtaMinutes = 4, tripDurationMinutes = 20, surgeMultiplier = null,+ capacity = 4, offerId = offerId, offerToken = "tok", costToken = "ct", rideType = "Lyft",+ )++ private fun accountsJson(): String =+ """{"chargeAccounts":[+ {"id":"ca1","label":"Visa ••1111","default":true},+ {"id":"ca2","kind":"Mastercard","lastFour":"2222","default":false}]}"""++ @BeforeTest+ fun setUp() {+ http.install()+ runBlocking {+ LyftTokenStore(context).clear()+ UberSession(context).clear()+ }+ }++ @AfterTest+ fun tearDown() {+ http.uninstall()+ runBlocking {+ LyftTokenStore(context).clear()+ UberSession(context).clear()+ }+ }++ private fun seedSignedIn() = runBlocking {+ LyftTokenStore(context).save(+ LyftToken(accessToken = "access-tok", refreshToken = "rt", expiresIn = 3600, userId = "1"),+ )+ }++ private fun waitForText(text: String, timeoutMs: Long = 15_000) {+ rule.waitUntil(timeoutMs) {+ rule.onAllNodesWithText(text).fetchSemanticsNodes().isNotEmpty()+ }+ }++ // --- Accounts ---++ @Test+ fun accountsSignedOutShowsConnectPrompt() {+ var connect = 0+ rule.setContent { AccountsScreen(onConnectLyft = { connect++ }) }+ waitForText(str(R.string.payment_sign_in))+ rule.onNodeWithText(str(R.string.provider_lyft)).assertIsDisplayed()+ rule.onNodeWithText(str(R.string.not_signed_in)).assertIsDisplayed()+ rule.onNodeWithText(str(R.string.payment_sign_in)).assertIsDisplayed()+ rule.onNodeWithText(str(R.string.provider_lyft)).performClick()+ assertEquals(1, connect)+ }++ @Test+ fun accountsSignedInListsPaymentsAndActions() {+ seedSignedIn()+ http.on("/chargeaccounts") { http.raw(200, accountsJson(), url = it.url) }+ http.on("/charge-accounts-multi-provider") { http.raw(200, accountsJson(), url = it.url) }+ rule.setContent { AccountsScreen(onConnectLyft = {}) }+ waitForText("Visa ••1111")+ rule.onNodeWithText("Mastercard ••2222").assertIsDisplayed()+ rule.onNodeWithText(str(R.string.payment_default)).assertIsDisplayed()+ rule.onNodeWithText(str(R.string.add_card)).assertExists()+ // Set the second account as default.+ rule.onNodeWithText(str(R.string.card_set_default)).performClick()+ rule.waitForIdle()+ assertTrue(http.callsTo("charge-accounts-multi-provider").any { it.method == "PUT" })+ // Remove the first account.+ rule.onAllNodesWithText("Remove")[0].performClick()+ rule.waitForIdle()+ assertTrue(http.calls.any { it.method == "DELETE" })+ }++ @Test+ fun accountsPaymentsErrorShowsMessage() {+ seedSignedIn()+ http.on("/chargeaccounts") { http.raw(500, "kaput", "text/plain", it.url) }+ rule.setContent { AccountsScreen(onConnectLyft = {}) }+ val expected = str(R.string.payment_methods_error, "Lyft returned HTTP 500: kaput")+ waitForText(expected)+ rule.onNodeWithText(expected).assertIsDisplayed()+ }++ @Test+ fun accountsSignOutFlowRevokesAndClears() {+ seedSignedIn()+ http.on("/chargeaccounts") { http.raw(200, accountsJson(), url = it.url) }+ http.performHandler = { http.simple(200, "", it.url) }+ rule.setContent { AccountsScreen(onConnectLyft = {}) }+ waitForText("Visa ••1111")+ rule.onNodeWithText(str(R.string.sign_out)).performClick()+ waitForText(str(R.string.sign_out_title))+ // Confirm in the dialog (the second Sign out control).+ rule.onAllNodesWithText(str(R.string.sign_out))[1].performClick()+ waitForText(str(R.string.not_signed_in))+ assertEquals(2, http.callsTo("revoke_token").size)+ }++ @Test+ fun accountsAddCardDialogValidationAndSubmit() {+ seedSignedIn()+ http.on("/chargeaccounts") { http.raw(200, accountsJson(), url = it.url) }+ http.on("/v1/tokenization_strategies") {+ http.raw(200, """{"strategies":[{"stripe_card_data":{"api_key":"pk"}}]}""", url = it.url)+ }+ http.on("api.stripe.com") { http.raw(200, """{"id":"tok_new"}""", url = it.url) }+ http.on("/charge-accounts-multi-provider") { http.raw(200, accountsJson(), url = it.url) }+ rule.setContent { AccountsScreen(onConnectLyft = {}) }+ waitForText(str(R.string.add_card))+ rule.onNode(+ androidx.compose.ui.test.hasText(str(R.string.add_card)) and+ androidx.compose.ui.test.hasClickAction(),+ ).performSemanticsAction(SemanticsActions.OnClick)+ waitForText(str(R.string.add_card_title))+ // Type into the form; the dialog stays up and nothing is tokenized+ // without a submit (validation itself is pinned by+ // TaxiCardValidationTest).+ rule.onNodeWithText(str(R.string.card_number)).performTextInput("4111111111111111")+ rule.onNodeWithText(str(R.string.card_expiry)).performTextInput("12/30")+ rule.onNodeWithText(str(R.string.card_cvc)).performTextInput("123")+ rule.onNodeWithText("4111111111111111").assertIsDisplayed()+ assertTrue(http.callsTo("tokenization").isEmpty())+ // Cancel dismisses the dialog.+ rule.onNodeWithText("Cancel").performClick()+ rule.waitForIdle()+ rule.onNodeWithText(str(R.string.add_card_title)).assertDoesNotExist()+ }++ @Test+ fun accountsAddCardSubmitRunsFullChain() {+ seedSignedIn()+ http.on("/chargeaccounts") { http.raw(200, accountsJson(), url = it.url) }+ http.on("/v1/tokenization_strategies") {+ http.raw(200, """{"strategies":[{"stripe_card_data":{"api_key":"pk"}}]}""", url = it.url)+ }+ http.on("api.stripe.com") { http.raw(200, """{"id":"tok_new"}""", url = it.url) }+ http.on("/charge-accounts-multi-provider") { http.raw(200, accountsJson(), url = it.url) }+ rule.setContent { AccountsScreen(onConnectLyft = {}) }+ waitForText(str(R.string.add_card))+ rule.onNode(+ androidx.compose.ui.test.hasText(str(R.string.add_card)) and+ androidx.compose.ui.test.hasClickAction(),+ ).performSemanticsAction(SemanticsActions.OnClick)+ waitForText(str(R.string.add_card_title))+ rule.onNodeWithText(str(R.string.card_number)).performTextInput("4111111111111111")+ rule.onNodeWithText(str(R.string.card_expiry)).performTextInput("12/30")+ rule.onNodeWithText(str(R.string.card_cvc)).performTextInput("123")+ rule.onNode(+ androidx.compose.ui.test.hasText("Add") and androidx.compose.ui.test.hasClickAction(),+ ).performSemanticsAction(SemanticsActions.OnClick)+ // The dialog closes once the card is added.+ rule.waitUntil(20_000) {+ rule.onAllNodesWithText(str(R.string.add_card_title)).fetchSemanticsNodes().isEmpty()+ }+ assertTrue(http.callsTo("tokenization_strategies").isNotEmpty())+ assertTrue(http.callsTo("charge-accounts-multi-provider").any { it.method == "POST" })+ }++ // --- Lyft booking flow dialogs ---++ @Test+ fun bookingFlowPicksPaymentConfirmsAndCreates() {+ seedSignedIn()+ http.on("/chargeaccounts") { http.raw(200, accountsJson(), url = it.url) }+ http.on("/v1/core_trips/create") {+ http.raw(200, """{"trip_details":{"trip_id":"888"}}""", url = it.url)+ }+ var dismissed = 0+ rule.setContent {+ LyftBookingFlow(+ request = LyftBookingRequest(quote(), pickup, dropoff, "ps1"),+ onDismiss = { dismissed++ },+ )+ }+ waitForText(str(R.string.choose_payment))+ rule.onNodeWithText("Visa ••1111").assertIsDisplayed()+ rule.onNodeWithText("Mastercard ••2222").performClick()+ rule.onNodeWithText(str(R.string.book)).performClick()+ waitForText(str(R.string.confirm_booking))+ rule.onNodeWithText("Lyft Standard").assertIsDisplayed()+ rule.onNodeWithText(str(R.string.book)).performClick()+ // BOOKING_LIVE is true, so the ride is created and confirmed.+ waitForText(str(R.string.ride_created, " (888)"))+ assertTrue(http.callsTo("core_trips").isNotEmpty())+ assertEquals(0, dismissed)+ }++ @Test+ fun bookingFlowWithoutPaymentsFailsEarly() {+ seedSignedIn()+ http.on("/chargeaccounts") { http.raw(200, """{"chargeAccounts":[]}""", url = it.url) }+ rule.setContent {+ LyftBookingFlow(LyftBookingRequest(quote(), pickup, dropoff, null), onDismiss = {})+ }+ waitForText(str(R.string.booking_failed, str(R.string.booking_no_payment)))+ }++ @Test+ fun bookingFlowNotSignedInFailsWithConnectPrompt() {+ http.on("/chargeaccounts") { http.raw(200, accountsJson(), url = it.url) }+ rule.setContent {+ LyftBookingFlow(LyftBookingRequest(quote(), pickup, dropoff, null), onDismiss = {})+ }+ waitForText(str(R.string.booking_failed, str(R.string.connect_prompt, "Lyft")))+ }++ // --- Sign-in screens ---++ @Test+ fun lyftSignInPhoneThenCodeCompletes() {+ http.performHandler = { call ->+ when {+ call.url.contains("/oauth2/access_token") && (call.body as String).contains("grant_type=client_credentials") ->+ http.simple(200, """{"access_token":"client-tok","expires_in":3600}""", call.url)+ call.url.contains("/oauth2/access_token") ->+ http.simple(200, """{"access_token":"user-tok","refresh_token":"rt","expires_in":3600,"user_id":"7"}""", call.url)+ call.url.contains("/v1/phoneauth") -> http.simple(200, "{}", call.url)+ else -> http.simple(404, "", call.url)+ }+ }+ rule.setContent { LyftSignInScreen(onBack = {}) }+ rule.onNodeWithText(str(R.string.phone_number)).performTextInput("+15551234567")+ rule.onNodeWithText(str(R.string.send_code)).performClick()+ waitForText(str(R.string.verification_code))+ rule.onNodeWithText(str(R.string.verification_code)).performTextInput("424242")+ rule.onNodeWithText(str(R.string.verify)).performClick()+ waitForText(str(R.string.signed_in_as, "+15551234567"))+ // The token was persisted.+ assertTrue(runBlocking { LyftTokenStore(context).isSignedIn() })+ }++ @Test+ fun lyftSignInFailureShowsError() {+ http.performHandler = { http.simple(500, """{"error":"server","error_description":"Lyft is down"}""", it.url) }+ rule.setContent { LyftSignInScreen(onBack = {}) }+ rule.onNodeWithText(str(R.string.phone_number)).performTextInput("+15551234567")+ rule.onNodeWithText(str(R.string.send_code)).performClick()+ waitForText("Could not obtain a Lyft client token")+ rule.onNodeWithText("Could not obtain a Lyft client token").assertIsDisplayed()+ }++ @Test+ fun uberSignInNativeFlowAdvancesScreens() {+ http.performHandler = { call ->+ val body = call.body as String+ if (body.contains("PHONE_NUMBER_INITIAL")) {+ http.simple(+ 200,+ """{"inAuthSessionID":"sess-9","form":{"screens":[{"screenType":"PHONE_OTP"}]}}""",+ call.url,+ )+ } else {+ http.simple(+ 200,+ """{"inAuthSessionID":"sess-9","form":{"screens":[{"screenType":"HOME"}]}}""",+ call.url,+ )+ }+ }+ var webView = 0+ rule.setContent { UberSignInScreen(onBack = {}, onUseWebView = { webView++ }) }+ rule.onNodeWithText(str(R.string.phone_number)).performTextInput("2135551234")+ rule.onNodeWithText(str(R.string.send_code)).performClick()+ waitForText(str(R.string.uber_next_screen, "PHONE_OTP"))+ rule.onNodeWithText(str(R.string.verification_code)).performTextInput("123456")+ rule.onNodeWithText(str(R.string.verify)).performClick()+ waitForText(str(R.string.uber_next_screen, "HOME"))+ rule.onNodeWithText(str(R.string.uber_use_webview)).performSemanticsAction(SemanticsActions.OnClick)+ rule.waitUntil(10_000) { webView == 1 }+ assertEquals(1, webView)+ }++ @Test+ fun uberSignInFailureShowsError() {+ http.performHandler = { http.simple(503, "maintenance", it.url) }+ rule.setContent { UberSignInScreen(onBack = {}, onUseWebView = {}) }+ rule.onNodeWithText(str(R.string.phone_number)).performTextInput("2135551234")+ rule.onNodeWithText(str(R.string.send_code)).performClick()+ waitForText("HTTP 503: maintenance")+ }++ // --- Tracking cards / map / current ride ---++ private fun activeRide(status: RideStatus = RideStatus.APPROACHING): ActiveRide = ActiveRide(+ rideId = "r1", status = status, statusRaw = status.wire,+ driver = DriverInfo("Jo", "Smith", null, "+15550001", 4.9),+ vehicle = VehicleInfo("Toyota", "Camry", "Black", "XYZ123", null),+ driverLocation = com.vayunmathur.taxi.data.DriverLocation(37.7, -122.4, 90.0),+ stops = listOf(+ RideStopInfo(LatLng(37.7, -122.4), "Home", "pickup", 300, completed = false),+ RideStopInfo(LatLng(37.8, -122.5), "Work", "dropoff", 900, completed = false),+ ),+ raw = "{}",+ )++ @Test+ fun trackingCardsShowDriverVehicleAndEta() {+ rule.setContent {+ androidx.compose.foundation.layout.Column {+ StatusHeader(activeRide(), ended = false)+ DriverCard(activeRide(), onCall = {})+ }+ }+ rule.onNodeWithText("Jo Smith").assertIsDisplayed()+ rule.onNodeWithText("Black Toyota Camry").assertIsDisplayed()+ rule.onNodeWithText("XYZ123").assertIsDisplayed()+ rule.onNodeWithText("4.9").assertIsDisplayed()+ // Status helper functions across the lifecycle.+ assertEquals(R.string.status_finding_driver, statusLabel(RideStatus.PENDING, ended = false))+ assertEquals(R.string.status_en_route, statusLabel(RideStatus.ACCEPTED, ended = false))+ assertEquals(R.string.status_arrived, statusLabel(RideStatus.ARRIVED, ended = false))+ assertEquals(R.string.status_on_trip, statusLabel(RideStatus.PICKED_UP, ended = false))+ assertEquals(R.string.ride_complete, statusLabel(RideStatus.COMPLETED, ended = false))+ assertEquals(R.string.ride_ended, statusLabel(RideStatus.CANCELED, ended = false))+ assertEquals(R.string.ride_ended, statusLabel(RideStatus.ACCEPTED, ended = true))+ assertEquals(1f, statusProgress(RideStatus.ACCEPTED, over = true))+ assertEquals(0.55f, statusProgress(RideStatus.APPROACHING, over = false))+ assertEquals(0.9f, statusProgress(RideStatus.PICKED_UP, over = false))+ }++ @Test+ fun trackingMapEmptyStateShowsPlaceholder() {+ // No points: a loading placeholder instead of a map.+ rule.setContent { TrackingMap(null, null) }+ rule.waitForIdle()+ }++ @Test+ fun trackingMapWithRideComposes() {+ // With a ride: the map composes (vector tiles are offline-safe).+ rule.setContent { TrackingMap(activeRide(), activeRide().driverLocation) }+ rule.waitForIdle()+ }++ @Test+ fun currentRideScreenWithoutRideShowsEmptyState() {+ rule.setContent { CurrentRideScreen() }+ waitForText(str(R.string.no_current_ride))+ rule.onNodeWithText(str(R.string.no_current_ride)).assertIsDisplayed()+ }++ // --- Ride home (RideScreen via Navigation) ---++ @Test+ fun navigationShowsRideHomeAndTabs() {+ rule.setContent {+ com.vayunmathur.taxi.Navigation(+ trackRideId = mutableStateOf(null),+ bookingTrip = mutableStateOf(null),+ )+ }+ waitForText(str(R.string.nav_ride))+ rule.onNodeWithText(str(R.string.destination)).assertExists()+ rule.onNodeWithText(str(R.string.pickup_label)).assertExists()+ // Switch to the accounts tab and back.+ rule.onNodeWithText("Settings").performClick()+ waitForText(str(R.string.payment_methods))+ rule.onNodeWithText(str(R.string.nav_ride)).performClick()+ waitForText(str(R.string.destination))+ }++ @Test+ fun rideScreenWithBookingTripPrefillsAndQuotes() {+ http.on("/chargeaccounts") { http.raw(200, accountsJson(), url = it.url) }+ // Quote calls need a token; without one the results note prompt shows.+ val trip = mutableStateOf<BookingTrip?>(BookingTrip(pickup, dropoff))+ rule.setContent { RideScreen(bookingTrip = trip) }+ waitForText("Work", timeoutMs = 20_000)+ rule.onNodeWithText("Home").assertIsDisplayed()+ }++ @Test+ fun providerColorsAndRouteFieldShape() {+ assertEquals(androidx.compose.ui.graphics.Color(0xFFEA0B8C), providerColor(Provider.LYFT))+ assertEquals(androidx.compose.ui.graphics.Color(0xFF276EF1), providerColor(Provider.UBER))+ assertEquals(2, RouteField.entries.size)+ }+}
taxi/src/test/java/com/vayunmathur/taxi/ui/TaxiPass3TrackingScreenTest.kt
diff --git a/taxi/src/test/java/com/vayunmathur/taxi/ui/TaxiPass3TrackingScreenTest.kt b/taxi/src/test/java/com/vayunmathur/taxi/ui/TaxiPass3TrackingScreenTest.ktnew file mode 100644index 0000000000..0e5d1a7360--- /dev/null+++ b/taxi/src/test/java/com/vayunmathur/taxi/ui/TaxiPass3TrackingScreenTest.kt@@ -0,0 +1,144 @@+package com.vayunmathur.taxi.ui++import android.content.Context+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onAllNodesWithText+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.taxi.R+import com.vayunmathur.taxi.da
Diff truncated.