taxi: add tests for Lyft networking and ride UI (46 tests)
- Commit
6a57c7ff1460d7eee124fc16975bcc0b4178159b- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-15 19:00 UTC (20 days ago)
- Parents
93d19de
Add unit tests covering Lyft proto offers/ride parsing, LyftCardTokenizer config priority and tokenize paths over a fake HTTP layer, Lyft quotes/exploratory/rides/payments clients and provider facade, ride live-update notifications, and Robolectric Compose ride input/results/route UI. Assertions check parsed fares, encoded request bodies, and rendered state. Skipped: RideTrackingService poll loop (live foreground service), RideScreen/LocationProvider/UberConnect needing live location, geocoder, WebView or cross-app IPC. Coverage (JaCoCo INSTRUCTION): covered 22,909 -> 27,404 (+4,495), missed 13,053 -> 8,558 (63.7% -> 76.2%). Verified: :taxi:testDevUnitTest (239 tests, 0 failures) :taxi:detekt :taxi:lint green.
Diff
taxi/src/test/java/com/vayunmathur/taxi/network/LyftClientsDeepTest.kt
diff --git a/taxi/src/test/java/com/vayunmathur/taxi/network/LyftClientsDeepTest.kt b/taxi/src/test/java/com/vayunmathur/taxi/network/LyftClientsDeepTest.ktnew file mode 100644index 0000000000..60e68d4f89--- /dev/null+++ b/taxi/src/test/java/com/vayunmathur/taxi/network/LyftClientsDeepTest.kt@@ -0,0 +1,307 @@+package com.vayunmathur.taxi.network++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.taxi.data.BookingResult+import com.vayunmathur.taxi.data.CancelResult+import com.vayunmathur.taxi.data.ChargeAccount+import com.vayunmathur.taxi.data.LatLng+import com.vayunmathur.taxi.data.NewCard+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.RideQuote+import com.vayunmathur.taxi.data.RideStatusResult+import com.vayunmathur.taxi.data.lyft.LyftTokenStore+import com.vayunmathur.taxi.network.ProtoWire as W+import com.vayunmathur.taxi.network.lyft.LyftApiSession+import com.vayunmathur.taxi.network.lyft.LyftChargeAccountsParser+import com.vayunmathur.taxi.network.lyft.LyftExploratoryApi+import com.vayunmathur.taxi.network.lyft.LyftPaymentsClient+import com.vayunmathur.taxi.network.lyft.LyftProvider+import com.vayunmathur.taxi.network.lyft.LyftQuotesClient+import com.vayunmathur.taxi.network.lyft.LyftRidesClient+import com.vayunmathur.taxi.network.lyft.LyftToken+import kotlinx.coroutines.runBlocking+import kotlinx.coroutines.test.runTest+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.assertNull+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class LyftClientsDeepTest {+ private val context: Context get() = ApplicationProvider.getApplicationContext()+ private val http = TaxiPass3FakeHttp()+ private val pickup = Place("Home", "1 Main St", LatLng(37.7749, -122.4194))+ private val dropoff = Place("Work", null, LatLng(37.8044, -122.2712))+ private val session get() = LyftApiSession(context)++ private fun seed() = runBlocking {+ LyftTokenStore(context).save(LyftToken(accessToken = "access-tok", refreshToken = "rt", expiresIn = 3600, userId = "42"))+ }++ @BeforeTest fun setUp() { http.install(); runBlocking { LyftTokenStore(context).clear() } }+ @AfterTest fun tearDown() { http.uninstall(); runBlocking { LyftTokenStore(context).clear() } }++ private val offersJson = """{"offers":{"purchase_session_id":"ps1","offers_response_id":"or1","offers_list":[+ {"offer_product_id":"lyft","id":"o1","cost_estimate":{"ride_type":"Lyft","currency":"USD","estimated_cost_cents_min":500,"estimated_cost_cents_max":900},+ "ride_type_details":{"display_properties":{"name":"Lyft Standard"},"seats":4}}]}}"""++ // ---- Quotes ----+ @Test fun offersBodyEncodesE6AndOptionalIds() {+ val client = LyftQuotesClient(session)+ val body = client.offersBody(pickup, dropoff, null, null)+ assertTrue(body.contains("\"latitude_e6\":37774900"), body)+ assertTrue(body.contains("\"longitude_e6\":-122419400"), body)+ assertTrue(body.contains("OFFER_SELECTOR")); assertFalse(body.contains("last_offers_id"))+ val body2 = client.offersBody(pickup, dropoff, "last1", "sess1")+ assertTrue(body2.contains("\"last_offers_id\":\"last1\"")); assertTrue(body2.contains("\"purchase_session_id\":\"sess1\""))+ // negative / zero coords+ val zero = client.offersBody(Place("Z", null, LatLng(0.0, 0.0)), dropoff, null, null)+ assertTrue(zero.contains("\"latitude_e6\":0"))+ }++ @Test fun quotesNotSignedInSuccessFailedAndEmpty() = runTest {+ val client = LyftQuotesClient(session)+ assertEquals(QuoteResult.NotSignedIn, client.quotes(pickup, dropoff))+ assertTrue(http.calls.isEmpty())+ seed()+ http.on("/v2/offerings") { http.raw(200, offersJson, url = it.url) }+ val ok = client.quotes(pickup, dropoff) as QuoteResult.Success+ assertEquals(1, ok.quotes.size); assertEquals("ps1", ok.purchaseSessionId)+ assertTrue(http.callsTo("/v2/offerings").single().headers.toString().contains("access-tok"))+ http.uninstall(); http.install()+ http.on("/v2/offerings") { http.raw(503, "unavailable", "text/plain", it.url) }+ assertTrue((client.quotes(pickup, dropoff) as QuoteResult.Failed).message.contains("503"))+ http.uninstall(); http.install()+ http.on("/v2/offerings") { http.raw(200, """{"offers":{"offers_list":[]}}""", url = it.url) }+ assertTrue((client.quotes(pickup, dropoff) as QuoteResult.Failed).message.contains("no offers"))+ }++ @Test fun updateQuotesUsesUpdateEndpoint() = runTest {+ seed()+ http.on("/v2/offerings/update") { http.raw(200, offersJson, url = it.url) }+ val client = LyftQuotesClient(session)+ val ok = client.updateQuotes(pickup, dropoff, "or1", "ps1") as QuoteResult.Success+ assertEquals(1, ok.quotes.size)+ assertTrue(http.callsTo("/v2/offerings/update").single().body.toString().contains("last_offers_id"))+ }++ @Test fun quotesProtoResponseParses() = runTest {+ seed()+ // build minimal offers proto+ val cost = W.concat(W.wrappedLong(6, 700), W.wrappedLong(5, 700), W.stringField(4, "Lyft"))+ val offer = W.concat(W.stringField(2, "lyft"), W.msg(4, cost), W.msg(5, W.msg(10, W.stringField(3, "ProtoQ"))))+ val offersMsg = W.concat(W.stringField(1, "psp"), W.bytesField(3, offer))+ val bytes = W.msg(1, offersMsg)+ http.on("/v2/offerings") {+ com.vayunmathur.library.network.RawResponse(200, "OK", bytes, mapOf("Content-Type" to listOf("application/x-protobuf")), it.url)+ }+ val ok = LyftQuotesClient(session).quotes(pickup, dropoff) as QuoteResult.Success+ assertEquals("ProtoQ", ok.quotes.single().displayName); assertEquals(700L, ok.quotes.single().fareLowMinor)+ }++ // ---- Exploratory ----+ @Test fun exploratorySignedOutReturnsNullWithoutCalls() = runTest {+ val api = LyftExploratoryApi(session, { _, _ -> "{}" }, { "{}" })+ assertNull(api.activeOffer()); assertNull(api.pickupGeofence("r 1")); assertNull(api.paymentDetails("r1"))+ assertNull(api.updatedCostEstimate("r1")); assertNull(api.scheduledRideTimeEstimates(pickup, dropoff))+ assertNull(api.offeringsOverview(pickup, dropoff)); assertNull(api.updatePickup("r1", pickup)); assertNull(api.redispatch("r1"))+ assertTrue(http.calls.isEmpty())+ }++ @Test fun exploratorySignedInGetPostAndErrors() = runTest {+ seed()+ http.on("/v1/active-offer") { http.raw(200, "{\"offer\":1}", url = it.url) }+ http.on("pickupgeofence") { http.raw(200, "geo", "text/plain", it.url) }+ http.on("paymentdetails") { http.raw(500, "e", "text/plain", it.url) }+ http.on("updated-cost-estimate") { http.raw(200, "cost!", "text/plain", it.url) }+ http.on("scheduledridetimeestimates") { http.raw(200, "sched", "text/plain", it.url) }+ http.on("offerings/overview") { http.raw(200, "overview", "text/plain", it.url) }+ http.on("/v1/rides/r9/pickup") { http.raw(200, "moved", "text/plain", it.url) }+ http.on("redispatch") { http.raw(200, "redispatched", "text/plain", it.url) }+ val api = LyftExploratoryApi(session, { _, _ -> "OFFERS_BODY" }, { "LOC_BODY" })+ assertEquals("{\"offer\":1}", api.activeOffer())+ assertEquals("geo", api.pickupGeofence("r 1")) // encoded id still routes+ assertTrue(http.calls.any { it.url.contains("r%201") || it.url.contains("r+1") || it.url.contains("%20") })+ assertNull(api.paymentDetails("r1"))+ assertEquals("cost!", api.updatedCostEstimate("r1"))+ assertEquals("sched", api.scheduledRideTimeEstimates(pickup, dropoff))+ assertEquals("overview", api.offeringsOverview(pickup, dropoff))+ assertEquals("moved", api.updatePickup("r9", pickup))+ assertEquals("redispatched", api.redispatch("r1"))+ assertTrue(http.callsTo("redispatch").single().body.toString().contains("r1"))+ // long body truncated to 4000+ http.uninstall(); http.install()+ http.on("/v1/active-offer") { http.raw(200, "x".repeat(5000), "text/plain", it.url) }+ assertEquals(4000, api.activeOffer()!!.length)+ }++ // ---- Rides ----+ private fun quote(offerId: String? = "o1") = RideQuote(+ Provider.LYFT, "lyft", "Lyft Standard", 1200, 1500, "USD", 4, 20, null, 4,+ offerId = offerId, offerToken = "tok", costToken = "ct", rideType = "Lyft",+ )++ @Test fun ridesCreateDryRunMissingOfferAndSignedOut() = runTest {+ val client = LyftRidesClient(session) { false }+ // signed out first (token check precedes offer check? accessToken null -> Failed not signed in)+ assertTrue((client.createRide(quote(), pickup, dropoff, null, false) as BookingResult.Failed).message.contains("Not signed in"))+ seed()+ assertTrue((client.createRide(quote(null), pickup, dropoff, null, false) as BookingResult.Failed).message.contains("no offer id"))+ val dry = client.createRide(quote(), pickup, dropoff, ChargeAccount("ca1", null, "Visa", true), false) as BookingResult.DryRun+ assertTrue(dry.requestJson.contains("\"offer_id\":\"o1\""))+ assertTrue(dry.requestJson.contains("\"charge_token\":\"ca1\"")) // falls back to id+ assertTrue(dry.requestJson.contains("lat_microdegrees"))+ assertTrue(http.callsTo("core_trips").isEmpty())+ // dryRun flag even when live+ val liveClient = LyftRidesClient(session) { true }+ assertTrue(liveClient.createRide(quote(), pickup, dropoff, null, true) is BookingResult.DryRun)+ }++ @Test fun ridesCreateLiveJsonAndProtoIds() = runTest {+ seed()+ http.on("core_trips/create") { http.raw(200, """{"trip_details":{"trip_id":"888"}}""", url = it.url) }+ val client = LyftRidesClient(session) { true }+ val created = client.createRide(quote(), pickup, dropoff, null, false) as BookingResult.Created+ assertEquals("888", created.rideId)+ http.uninstall(); http.install()+ // proto trip_details(1) -> varint trip_id(1) -> string form+ val protoBody = W.msg(1, W.varintField(1, 777))+ http.on("core_trips/create") {+ com.vayunmathur.library.network.RawResponse(200, "OK", protoBody, mapOf("Content-Type" to listOf("application/x-protobuf")), it.url)+ }+ assertEquals("777", (client.createRide(quote(), pickup, dropoff, null, false) as BookingResult.Created).rideId)+ http.uninstall(); http.install()+ http.on("core_trips/create") { http.raw(500, "boom", "text/plain", it.url) }+ assertTrue((client.createRide(quote(), pickup, dropoff, null, false) as BookingResult.Failed).message.contains("500"))+ }++ @Test fun ridesActiveDriverCancelById() = runTest {+ val client = LyftRidesClient(session) { true }+ assertTrue((client.activeRide() as RideStatusResult.Failed).message.contains("Not signed in"))+ assertNull(client.driverLocation("r1"))+ assertTrue((client.cancelRide("r1") as CancelResult.Failed).message.contains("Not signed in"))+ seed()+ http.on("/v1/activeride") { http.raw(404, "none", "text/plain", it.url) }+ assertEquals(RideStatusResult.None, client.activeRide())+ http.uninstall(); http.install()+ http.on("/v1/activeride") { http.raw(200, """{"ride_id":"r5","status":"accepted","driver":{"first_name":"Jo"}}""", url = it.url) }+ assertEquals("r5", (client.activeRide() as RideStatusResult.Active).ride.rideId)+ http.uninstall(); http.install()+ http.on("/v1/activeride") { http.raw(200, """{}""", url = it.url) }+ assertEquals(RideStatusResult.None, client.activeRide()) // no content+ http.on("driver-location") { http.raw(200, """{"lat":3.0,"lng":4.0}""", url = it.url) }+ assertEquals(3.0, client.driverLocation("r 5")?.latitude)+ http.on("/cancel") { http.raw(200, "cancelled ok", "text/plain", it.url) }+ assertEquals(CancelResult.Done("cancelled ok"), client.cancelRide("r5"))+ http.uninstall(); http.install()+ http.on("/cancel") { http.raw(500, "fee error", "text/plain", it.url) }+ assertTrue((client.cancelRide("r5") as CancelResult.Failed).message.contains("500"))+ http.on("/v1/rides/r7") { http.raw(200, """{"ride_id":"r7","status":"arrived"}""", url = it.url) }+ assertEquals("r7", (client.rideById("r7") as RideStatusResult.Active).ride.rideId)+ http.uninstall(); http.install()+ http.on("/v1/rides/r7") { http.raw(404, "", "text/plain", it.url) }+ assertEquals(RideStatusResult.None, client.rideById("r7"))+ // locationV2 body+ val locBody = client.locationV2Body(pickup)+ assertTrue(locBody.contains("37774900") && locBody.contains("Home") && locBody.contains("1 Main St"))+ assertFalse(client.locationV2Body(dropoff).contains("display_address"))+ }++ // ---- Payments + charge accounts parser ----+ @Test fun paymentsListSetDefaultRemove() = runTest {+ val client = LyftPaymentsClient(session)+ assertEquals(PaymentMethodsResult.NotSignedIn, client.paymentMethods())+ seed()+ val accountsJson = """{"chargeAccounts":[{"id":"ca1","label":"Visa ••1111","default":true},{"id":"ca2","kind":"Mastercard","lastFour":"2222"}]}"""+ http.on("/chargeaccounts") { http.raw(200, accountsJson, url = it.url) }+ http.on("charge-accounts-multi-provider") { http.raw(200, accountsJson, url = it.url) }+ val list = (client.paymentMethods() as PaymentMethodsResult.Success).accounts+ assertEquals(2, list.size); assertEquals("Visa ••1111", list[0].label); assertTrue(list[0].isDefault)+ assertEquals("Mastercard ••2222", list[1].label)+ val def = client.setDefaultPaymentMethod("ca2")+ assertTrue(def is com.vayunmathur.taxi.data.PaymentActionResult.Success)+ assertTrue(http.callsTo("charge-accounts-multi-provider").single().body.toString().contains("\"charge_account_id\":\"ca2\""))+ assertTrue(client.removePaymentMethod("ca 1") is com.vayunmathur.taxi.data.PaymentActionResult.Success)+ assertTrue(http.calls.any { it.method == "DELETE" })+ http.uninstall(); http.install()+ http.on("/chargeaccounts") { http.raw(500, "bad", "text/plain", it.url) }+ assertTrue((client.paymentMethods() as PaymentMethodsResult.Failed).message.contains("500"))+ http.on("charge-accounts-multi-provider") { http.raw(422, "invalid", "text/plain", it.url) }+ assertTrue(client.setDefaultPaymentMethod("x") is com.vayunmathur.taxi.data.PaymentActionResult.Failed)+ }++ @Test fun chargeAccountsParserJsonLabelsAndProto() {+ val parser = LyftChargeAccountsParser(session)+ fun resp(text: String) = http.raw(200, text, url = "")+ // label fallbacks via JSON array variants+ val parsed = parser.parse(resp("""{"charge_accounts":[+ {"id":"a","kind":"Visa","last_four":"4242"},+ {"id":"b","lastFour":"9999"},+ {"id":"c","kind":"Amex"},+ {"id":"d"},+ {"kind":"NoId"}]}"""))+ assertEquals(listOf("Visa ••4242", "•• 9999", "Amex", "Card"), parsed.map { it.label })+ assertEquals(0, parser.parse(resp("not json")).size)+ // proto: root field1 repeated account; account id1 wrapped, kind2, default3 wrapped, label5, lastFour10+ fun acct(id: String, label: String?): ByteArray {+ val parts = mutableListOf(W.wrappedString(1, id), W.wrappedBool(3, true), W.wrappedString(10, "1111"))+ label?.let { parts += W.wrappedString(5, it) }+ return W.concat(*parts.toTypedArray())+ }+ val protoBytes = W.concat(W.bytesField(1, acct("p1", "Proto Visa")), W.bytesField(1, acct("p2", null)))+ val protoResp = com.vayunmathur.library.network.RawResponse(200, "OK", protoBytes, mapOf("Content-Type" to listOf("application/x-protobuf")), "")+ val protoParsed = parser.parse(protoResp)+ assertEquals(2, protoParsed.size); assertEquals("Proto Visa", protoParsed[0].label); assertTrue(protoParsed[0].isDefault)+ assertEquals("•• 1111", protoParsed[1].label)+ }++ @Test fun paymentsAddCardUnsupportedAndSuccess() = runTest {+ seed()+ val client = LyftPaymentsClient(session)+ val card = NewCard("4111111111111111", 12, 2030, "123", "94101")+ // no strategy -> Unsupported+ http.on("tokenization_strategies") { http.raw(200, """{"strategies":[]}""", url = it.url) }+ assertEquals(com.vayunmathur.taxi.data.AddCardResult.Unsupported, client.addCard(card, false))+ http.uninstall(); http.install()+ http.on("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, """{"chargeAccounts":[{"id":"ca9","label":"Visa ••1111","default":true}]}""", url = it.url) }+ val ok = client.addCard(card, true) as com.vayunmathur.taxi.data.AddCardResult.Success+ assertEquals("ca9", ok.accounts!!.single().id)+ val createCall = http.callsTo("charge-accounts-multi-provider").single { it.method == "POST" }+ assertTrue(createCall.body.toString().contains("tok_new"))+ assertTrue(createCall.body.toString().contains("\"default\":true"))+ // tokenize failure -> Failed+ http.uninstall(); http.install()+ http.on("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":"declined"}}""", url = it.url) }+ assertEquals("declined", (client.addCard(card, false) as com.vayunmathur.taxi.data.AddCardResult.Failed).message)+ }++ // ---- LyftProvider facade ----+ @Test fun providerFacadeDelegatesAndBookingUri() = runTest {+ val provider = LyftProvider(context)+ assertEquals(Provider.LYFT, provider.provider)+ assertFalse(provider.isSignedIn())+ assertEquals(QuoteResult.NotSignedIn, provider.quotes(pickup, dropoff))+ assertNull(provider.activeOffer()); assertNull(provider.driverLocation("r1"))+ val uri = provider.bookingUri(pickup, dropoff, quote())+ assertTrue(uri.contains("lyft.com/ride"), uri); assertTrue(uri.contains("id=lyft"))+ seed()+ http.on("/v2/offerings") { http.raw(200, offersJson, url = it.url) }+ assertTrue(provider.quotes(pickup, dropoff) is QuoteResult.Success)+ assertTrue(provider.updateQuotes(pickup, dropoff, null, null) is QuoteResult.Failed || provider.updateQuotes(pickup, dropoff, null, null) is QuoteResult.Success)+ assertTrue(LyftProvider.BOOKING_LIVE)+ }+}
taxi/src/test/java/com/vayunmathur/taxi/network/LyftParsersProtoDeepTest.kt
diff --git a/taxi/src/test/java/com/vayunmathur/taxi/network/LyftParsersProtoDeepTest.kt b/taxi/src/test/java/com/vayunmathur/taxi/network/LyftParsersProtoDeepTest.ktnew file mode 100644index 0000000000..0c7f9226ee--- /dev/null+++ b/taxi/src/test/java/com/vayunmathur/taxi/network/LyftParsersProtoDeepTest.kt@@ -0,0 +1,217 @@+package com.vayunmathur.taxi.network++import com.vayunmathur.library.network.RawResponse+import com.vayunmathur.taxi.data.Provider+import com.vayunmathur.taxi.data.RideStatus+import com.vayunmathur.taxi.network.ProtoWire as W+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.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue++class LyftParsersProtoDeepTest {+ private val json = Json { ignoreUnknownKeys = true; isLenient = true }+ private val offers = LyftOffersParser(json)+ private val rides = LyftRideParser(json)++ private fun raw(bytes: ByteArray, ct: String): RawResponse =+ RawResponse(200, "OK", bytes, mapOf("Content-Type" to listOf(ct)), "https://x")+ private fun rawText(text: String, ct: String = "application/json"): RawResponse =+ raw(text.toByteArray(), ct)++ // ---- Offers proto ----+ private fun costProto(min: Long? = 500, max: Long? = 900, upfront: Long? = null): ByteArray {+ val parts = mutableListOf<ByteArray>()+ parts += W.stringField(3, "ctok")+ parts += W.stringField(4, "Lyft")+ max?.let { parts += W.wrappedLong(5, it) }+ min?.let { parts += W.wrappedLong(6, it) }+ upfront?.let { parts += W.wrappedLong(7, it) }+ parts += W.wrappedString(8, "EUR")+ parts += W.doubleField(12, 1.25)+ parts += W.msg(18, W.varintField(10, 100), W.varintField(11, 200))+ parts += W.wrappedLong(20, 1700)+ parts += W.wrappedLong(22, 1260)+ return W.concat(*parts.toTypedArray())+ }++ private fun offerProto(name: String? = "Proto Lyft", withCost: Boolean = true): ByteArray {+ val parts = mutableListOf<ByteArray>()+ parts += W.stringField(1, "offer-1")+ parts += W.stringField(2, "lyft")+ parts += W.wrappedString(3, "otok")+ if (withCost) parts += W.msg(4, costProto())+ val rideType = mutableListOf<ByteArray>()+ rideType += W.varintField(7, 4)+ if (name != null) rideType += W.msg(10, W.stringField(3, name))+ parts += W.msg(5, *rideType.toTypedArray())+ // travel 9 -> pickup 1 -> duration_range 2 -> wrapped 240000+ parts += W.msg(9, W.msg(1, W.msg(2, W.msg(1, W.varintField(1, 240000)))))+ return W.concat(*parts.toTypedArray())+ }++ private fun offersProto(vararg offerBytes: ByteArray): ByteArray {+ val offersParts = mutableListOf<ByteArray>()+ offersParts += W.stringField(1, "ps-proto")+ offersParts += W.stringField(2, "or-proto")+ offerBytes.forEach { offersParts += W.bytesField(3, it) }+ return W.msg(1, *offersParts.toTypedArray())+ }++ @Test fun offersProtoMapsEveryFieldWithCoupon() {+ val parsed = offers.parseProto(offersProto(offerProto()))+ assertEquals("ps-proto", parsed.purchaseSessionId)+ assertEquals("or-proto", parsed.offersResponseId)+ assertEquals(1, parsed.quotes.size)+ val q = parsed.quotes[0]+ assertEquals(Provider.LYFT, q.provider)+ assertEquals("Proto Lyft", q.displayName)+ assertEquals(400L, q.fareLowMinor) // 500-100+ assertEquals(700L, q.fareHighMinor) // 900-200+ assertEquals(500L, q.originalFareLowMinor)+ assertEquals(900L, q.originalFareHighMinor)+ assertEquals("EUR", q.currency)+ assertEquals(4, q.pickupEtaMinutes)+ assertEquals(21, q.tripDurationMinutes)+ assertEquals(1.25, q.surgeMultiplier)+ assertEquals(4, q.capacity)+ assertEquals("offer-1", q.offerId)+ assertEquals("otok", q.offerToken)+ assertEquals("ctok", q.costToken)+ assertEquals(1_700_000L, q.costTokenExpiryMs)+ assertTrue(q.hasDiscount)+ }++ @Test fun offersProtoEmptyAndMissingWrapper() {+ assertEquals(0, offers.parseProto(byteArrayOf()).quotes.size)+ assertEquals(0, offers.parseProto(W.stringField(9, "junk")).quotes.size)+ // offers wrapper present but no list+ val parsed = offers.parseProto(W.msg(1, W.stringField(1, "only-ps")))+ assertEquals("only-ps", parsed.purchaseSessionId)+ assertEquals(0, parsed.quotes.size)+ }++ @Test fun offersProtoUpfrontOnlyAndFallbackNames() {+ val cost = W.concat(W.wrappedLong(7, 2500), W.stringField(4, "LuxType"))+ val offer = W.concat(+ W.stringField(2, "prod-x"),+ W.msg(4, cost),+ // no display name: falls back to cost ride_type+ W.msg(5, W.varintField(7, 2)),+ )+ val q = offers.parseProto(offersProto(offer)).quotes.single()+ assertEquals("LuxType", q.displayName)+ assertEquals(2500L, q.fareLowMinor); assertEquals(2500L, q.fareHighMinor)+ assertFalse(q.hasDiscount)+ // No cost at all dropped, no name dropped+ assertEquals(0, offers.parseProto(offersProto(offerProto(withCost = false))).quotes.size)+ val noName = W.concat(W.stringField(2, "p"), W.msg(4, W.wrappedLong(7, 100)))+ // has product id as fallback name+ assertEquals("p", offers.parseProto(offersProto(noName)).quotes.single().displayName)+ }++ @Test fun farePriceBranches() {+ assertNull(offers.farePrice(null, null, null, null, null))+ assertEquals(100L, offers.farePrice(100, null, null, null, null)!!.low)+ assertEquals(200L, offers.farePrice(null, 200, null, null, null)!!.high)+ // negative discounts clamped, discount exceeding price clamps to 0+ val f = offers.farePrice(100, 100, null, -50, 999)!!+ assertEquals(100L, f.low); assertEquals(0L, f.high)+ val noDisc = offers.farePrice(100, 200, null, 0, 0)!!+ assertNull(noDisc.originalLow)+ }++ @Test fun offersJsonStringNumbersAndDefaults() {+ val raw = """{"offers":{"offers_list":[{"offer_product_id":"lyft","cost_estimate":{"estimated_cost_cents_min":"300","estimated_cost_cents_max":"400"}}]}}"""+ val q = offers.parseJson(raw).quotes.single()+ assertEquals(300L, q.fareLowMinor); assertEquals("USD", q.currency)+ assertEquals(0, offers.parseJson("[]").quotes.size)+ assertEquals(0, offers.parseJson("""{"offers":{}}""").quotes.size)+ }++ // ---- Ride proto ----+ private fun rideProto(): ByteArray {+ val driver = W.concat(+ W.stringField(5, "Jo"), W.stringField(6, "Smith"), W.stringField(7, "img"),+ W.stringField(8, "+1555"), W.doubleField(9, 4.8),+ )+ val vehicle = W.concat(+ W.stringField(1, "Toyota"), W.stringField(2, "Camry"), W.stringField(3, "XYZ"),+ W.stringField(4, "vimg"), W.stringField(6, "Black"),+ )+ val loc = W.concat(W.doubleField(1, 37.7), W.doubleField(2, -122.4), W.doubleField(3, 90.0))+ val place = W.concat(W.doubleField(1, 37.7), W.doubleField(2, -122.4), W.stringField(3, "1 Main"), W.stringField(5, "Home"))+ val stop = W.concat(+ W.msg(2, place), W.stringField(3, "pickup"), W.varintField(4, 0), W.varintField(6, 180),+ )+ val stop2 = W.concat(+ W.msg(7, place), W.stringField(3, "dropoff"), W.varintField(4, 1), W.varintField(6, 900),+ )+ return W.concat(+ W.stringField(1, "ride-proto"), W.stringField(2, "approaching"),+ W.msg(6, driver), W.msg(8, vehicle), W.bytesField(9, stop), W.bytesField(9, stop2), W.msg(11, loc),+ )+ }++ @Test fun rideProtoMapsDriverVehicleStopsLocation() {+ val ride = rides.toActiveRideProto(rideProto())+ assertEquals("ride-proto", ride.rideId)+ assertEquals(RideStatus.APPROACHING, ride.status)+ assertEquals("Jo Smith", ride.driver?.displayName)+ assertEquals(4.8, ride.driver?.rating)+ assertEquals("Black Toyota Camry", ride.vehicle?.description)+ assertEquals("XYZ", ride.vehicle?.licensePlate)+ assertEquals(37.7, ride.driverLocation?.latitude)+ assertEquals(90.0, ride.driverLocation?.bearing)+ assertEquals(2, ride.stops.size)+ assertEquals(180, ride.pickupEtaSeconds)+ assertTrue(ride.stops[0].isPickup); assertTrue(ride.stops[1].isDropoff)+ assertTrue(ride.stops[1].completed)+ assertEquals("Home", ride.stops[0].name)+ assertTrue(ride.hasContent)+ }++ @Test fun rideProtoEmptyHasNoContent() {+ val ride = rides.toActiveRideProto(byteArrayOf())+ assertNull(ride.rideId); assertEquals(RideStatus.UNKNOWN, ride.status)+ assertFalse(ride.hasContent); assertEquals(emptyList(), ride.stops)+ }++ @Test fun parseActiveRideDispatchAndFallback() {+ val protoResp = raw(rideProto(), "application/x-protobuf")+ assertEquals("ride-proto", rides.parseActiveRide(protoResp)?.rideId)+ val jsonResp = rawText("""{"ride_id":"j1","status":"arrived"}""")+ assertEquals("j1", rides.parseActiveRide(jsonResp)?.rideId)+ assertEquals(RideStatus.ARRIVED, rides.parseActiveRide(jsonResp)?.status)+ // proto content-type but JSON body -> fallback to json+ val lying = rawText("""{"ride_id":"j2","status":"pending"}""", "application/x-protobuf")+ assertEquals("j2", rides.parseActiveRide(lying)?.rideId)+ // empty both -> null or empty ride (hasContent false path)+ assertFalse(rides.parseActiveRide(rawText("{}"))?.hasContent ?: false)+ }++ @Test fun driverLocationJsonAndProtoDispatch() {+ val jsonResp = rawText("""{"location":{"lat":1.5,"lng":2.5,"bearing":45.0}}""")+ assertEquals(1.5, rides.parseDriverLocation(jsonResp)?.latitude)+ // bare json root+ assertEquals(2.5, rides.parseDriverLocation(rawText("""{"lat":1.0,"lng":2.5}"""))?.longitude)+ // proto: wrapper field1 = location msg+ val locMsg = W.concat(W.doubleField(1, 10.0), W.doubleField(2, 20.0))+ val wrapped = W.msg(1, locMsg)+ assertEquals(10.0, rides.parseDriverLocation(raw(wrapped, "application/x-protobuf"))?.latitude)+ // bare proto location+ assertEquals(20.0, rides.parseDriverLocation(raw(locMsg, "application/octet-stream"))?.longitude)+ assertNull(rides.toDriverLocationProto(com.vayunmathur.taxi.network.lyft.ProtoMessage(byteArrayOf(), 0, 0)))+ }++ @Test fun stopJsonVariants() {+ val parser = rides+ val noCoords = kotlinx.serialization.json.Json.parseToJsonElement("""{"location":{"place_name":"X"},"kind":"pickup"}""") as kotlinx.serialization.json.JsonObject+ assertNull(parser.toStopJson(noCoords).location)+ assertEquals("X", parser.toStopJson(noCoords).name)+ }+}
taxi/src/test/java/com/vayunmathur/taxi/network/LyftTokenizerDeepTest.kt
diff --git a/taxi/src/test/java/com/vayunmathur/taxi/network/LyftTokenizerDeepTest.kt b/taxi/src/test/java/com/vayunmathur/taxi/network/LyftTokenizerDeepTest.ktnew file mode 100644index 0000000000..c5b5c8542e--- /dev/null+++ b/taxi/src/test/java/com/vayunmathur/taxi/network/LyftTokenizerDeepTest.kt@@ -0,0 +1,172 @@+package com.vayunmathur.taxi.network++import com.vayunmathur.taxi.data.NewCard+import com.vayunmathur.taxi.network.ProtoWire as W+import com.vayunmathur.taxi.network.lyft.LyftCardTokenizer+import com.vayunmathur.taxi.network.lyft.TokenizeResult+import com.vayunmathur.taxi.network.lyft.TokenizerConfig+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 java.security.KeyStore+import javax.net.ssl.SSLContext+import javax.net.ssl.TrustManagerFactory+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class LyftTokenizerDeepTest {+ private val json = Json { ignoreUnknownKeys = true; isLenient = true }+ private val http = TaxiPass3FakeHttp()+ private val factory = run {+ val tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm())+ tmf.init(null as KeyStore?)+ SSLContext.getInstance("TLS").apply { init(null, tmf.trustManagers, null) }.socketFactory+ }+ private val tokenizer = LyftCardTokenizer(json, factory) { tok -> mapOf("Authorization" to "Bearer $tok") }+ private val card = NewCard("4111111111111111", 12, 2030, "123", "94101")+ private val cardNoZip = NewCard("4111111111111111", 12, 2030, "123", "")++ @BeforeTest fun setUp() = http.install()+ @AfterTest fun tearDown() = http.uninstall()++ @Test fun parseConfigJsonSetupIntentWinsOverLegacy() {+ val raw = """{"strategies":[+ {"stripe_card_data":{"api_key":"pk_legacy"}},+ {"stripe_card_setup_intent_data":{"api_key":"pk_setup","client_secret":"cs","setup_intent_id":"seti_1","stripe_api_version":"2024-01"}},+ {"braintree_card_data":{"api_key":"bt_tok"}}]}"""+ val c = tokenizer.parseConfigJson(raw)!!+ assertEquals("stripe_setup_intent", c.provider); assertEquals("pk_setup", c.key)+ assertEquals("cs", c.clientSecret); assertEquals("seti_1", c.setupIntentId); assertEquals("2024-01", c.stripeApiVersion)+ }++ @Test fun parseConfigJsonLegacyStripeThenBraintree() {+ assertEquals("stripe", tokenizer.parseConfigJson("""{"strategies":[{"stripe_card_data":{"api_key":"pk"}}]}""")!!.provider)+ val bt = tokenizer.parseConfigJson("""{"strategies":[{"braintree_card_data":{"api_key":"bt"}}]}""")!!+ assertEquals("braintree", bt.provider); assertEquals("bt", bt.key)+ // unknown provider only -> null+ assertNull(tokenizer.parseConfigJson("""{"strategies":[{"adyen":{"api_key":"x"}}]}"""))+ assertNull(tokenizer.parseConfigJson("""{"strategies":[]}"""))+ assertNull(tokenizer.parseConfigJson("""{}"""))+ assertNull(tokenizer.parseConfigJson("not json"))+ assertNull(tokenizer.parseConfigJson("""{"strategies":[{"stripe_card_data":{}}]}"""))+ }++ @Test fun parseConfigProtoAllProviders() {+ // strategy msg: field22 setup, 10 stripe, 11 braintree; each api_key field1+ fun strategy(field: Int, vararg inner: ByteArray): ByteArray = W.msg(field, *inner)+ val setupBytes = W.msg(1, strategy(22, W.stringField(1, "pk_s"), W.stringField(2, "cs2"), W.stringField(3, "seti_2"), W.stringField(4, "v2")))+ val setup = tokenizer.parseConfigProto(setupBytes)!!+ assertEquals("stripe_setup_intent", setup.provider); assertEquals("seti_2", setup.setupIntentId)+ val stripeBytes = W.msg(1, strategy(10, W.stringField(1, "pk_l")))+ assertEquals("stripe", tokenizer.parseConfigProto(stripeBytes)!!.provider)+ val btBytes = W.msg(1, strategy(11, W.stringField(1, "bt_k")))+ assertEquals("braintree", tokenizer.parseConfigProto(btBytes)!!.provider)+ assertNull(tokenizer.parseConfigProto(byteArrayOf()))+ assertNull(tokenizer.parseConfigProto(W.msg(1, strategy(99, W.stringField(1, "x")))))+ }++ @Test fun parseConfigDispatchByContentType() {+ val jsonResp = http.raw(200, """{"strategies":[{"stripe_card_data":{"api_key":"pkj"}}]}""")+ assertEquals("pkj", tokenizer.parseConfig(jsonResp)?.key)+ val protoBytes = W.msg(1, W.msg(10, W.stringField(1, "pkp")))+ val protoResp = com.vayunmathur.library.network.RawResponse(200, "OK", protoBytes, mapOf("Content-Type" to listOf("application/x-protobuf")), "")+ assertEquals("pkp", tokenizer.parseConfig(protoResp)?.key)+ }++ @Test fun braintreeClientTokenRawBase64AndFailures() {+ val rawJson = """{"authorizationFingerprint":"fp1","graphQL":{"url":"https://gql.example/graphql"}}"""+ assertEquals("https://gql.example/graphql" to "fp1", tokenizer.parseBraintreeClientToken(rawJson))+ val noUrl = """{"authorizationFingerprint":"fp2"}"""+ assertEquals("https://payments.braintree-api.com/graphql" to "fp2", tokenizer.parseBraintreeClientToken(noUrl))+ val b64 = android.util.Base64.encodeToString(noUrl.toByteArray(), android.util.Base64.DEFAULT)+ assertEquals("fp2", tokenizer.parseBraintreeClientToken(b64)?.second)+ assertNull(tokenizer.parseBraintreeClientToken("""{"nope":1}"""))+ assertNull(tokenizer.parseBraintreeClientToken("!!!not-base64-json!!!"))+ assertNull(tokenizer.parseBraintreeClientToken(""))+ }++ @Test fun tokenizeUnsupportedProvider() = runTest {+ val r = tokenizer.tokenize(TokenizerConfig("adyen", "k"), card)+ assertTrue(r is TokenizeResult.Err); assertTrue((r as TokenizeResult.Err).message.contains("Unsupported"))+ }++ @Test fun tokenizeStripeSuccessErrorAndNoToken() = runTest {+ http.on("api.stripe.com/v1/tokens") { http.raw(200, """{"id":"tok_123"}""", url = it.url) }+ val ok = tokenizer.tokenizeStripe("pk", card) as TokenizeResult.Ok+ assertEquals("tok_123", ok.token); assertEquals("STRIPE_TOKEN", ok.version); assertEquals("stripe", ok.provider)+ // request was form encoded with card fields+ assertTrue(http.callsTo("api.stripe.com").single().body.toString().contains("card%5Bnumber%5D") || http.callsTo("api.stripe.com").single().body.toString().contains("card[number]"))+ http.uninstall(); http.install()+ http.on("api.stripe.com") { http.raw(402, """{"error":{"message":"card declined"}}""", url = it.url) }+ assertEquals("card declined", (tokenizer.tokenizeStripe("pk", card) as TokenizeResult.Err).message)+ http.uninstall(); http.install()+ http.on("api.stripe.com") { http.raw(200, """{"foo":1}""", url = it.url) }+ assertTrue((tokenizer.tokenizeStripe("pk", card) as TokenizeResult.Err).message.contains("no token"))+ }++ @Test fun tokenizeSetupIntentBranches() = runTest {+ // missing ids+ assertTrue((tokenizer.tokenizeStripeSetupIntent(TokenizerConfig("stripe_setup_intent", "pk"), card) as TokenizeResult.Err).message.contains("setup_intent_id"))+ assertTrue((tokenizer.tokenizeStripeSetupIntent(TokenizerConfig("stripe_setup_intent", "pk", setupIntentId = "seti"), card) as TokenizeResult.Err).message.contains("client_secret"))+ http.on("setup_intents") { http.raw(200, """{"payment_method":"pm_123"}""", url = it.url) }+ val cfg = TokenizerConfig("stripe_setup_intent", "pk", clientSecret = "cs", setupIntentId = "seti_9", stripeApiVersion = "2024-06")+ val ok = tokenizer.tokenizeStripeSetupIntent(cfg, card) as TokenizeResult.Ok+ assertEquals("pm_123", ok.token); assertEquals("STRIPE_SETUP_INTENT", ok.version)+ assertTrue(http.callsTo("setup_intents/seti_9/confirm").isNotEmpty())+ // without postal code also works (new fake route still matches)+ val ok2 = tokenizer.tokenizeStripeSetupIntent(cfg, cardNoZip) as TokenizeResult.Ok+ assertEquals("pm_123", ok2.token)+ http.uninstall(); http.install()+ http.on("setup_intents") { http.raw(400, """{"error":{"message":"bad secret"}}""", url = it.url) }+ assertEquals("bad secret", (tokenizer.tokenizeStripeSetupIntent(cfg, card) as TokenizeResult.Err).message)+ http.uninstall(); http.install()+ http.on("setup_intents") { http.raw(200, """{}""", url = it.url) }+ assertTrue((tokenizer.tokenizeStripeSetupIntent(cfg, card) as TokenizeResult.Err).message.contains("no payment_method"))+ }++ @Test fun tokenizeBraintreeBranches() = runTest {+ assertTrue((tokenizer.tokenizeBraintree("garbage-token", card) as TokenizeResult.Err).message.contains("parse Braintree"))+ val clientToken = """{"authorizationFingerprint":"fp","graphQL":{"url":"https://gql.example/graphql"}}"""+ http.on("gql.example") { http.raw(200, """{"data":{"tokenizeCreditCard":{"token":"nonce-abc"}}}""", url = it.url) }+ val ok = tokenizer.tokenizeBraintree(clientToken, card) as TokenizeResult.Ok+ assertEquals("nonce-abc", ok.nonce); assertEquals("braintree", ok.provider); assertNull(ok.token)+ http.uninstall(); http.install()+ http.on("gql.example") { http.raw(200, """{"errors":[{"message":"invalid card"}]}""", url = it.url) }+ assertEquals("invalid card", (tokenizer.tokenizeBraintree(clientToken, card) as TokenizeResult.Err).message)+ http.uninstall(); http.install()+ http.on("gql.example") { http.raw(200, """{"data":{}}""", url = it.url) }+ assertTrue((tokenizer.tokenizeBraintree(clientToken, card) as TokenizeResult.Err).message.contains("no nonce"))+ http.uninstall(); http.install()+ http.on("gql.example") { http.raw(500, "oops", "text/plain", it.url) }+ assertTrue((tokenizer.tokenizeBraintree(clientToken, card) as TokenizeResult.Err).message.contains("Braintree HTTP 500"))+ }++ @Test fun fetchConfigSuccessHttpErrorAndEmpty() = runTest {+ http.on("tokenization_strategies") { http.raw(200, """{"strategies":[{"stripe_card_data":{"api_key":"pk_fetch"}}]}""", url = it.url) }+ assertEquals("pk_fetch", tokenizer.fetchConfig("tok", card)?.key)+ val call = http.callsTo("tokenization_strategies").single()+ assertTrue(call.body.toString().contains("411111") || call.body.toString().contains("1111"))+ http.uninstall(); http.install()+ http.on("tokenization_strategies") { http.raw(500, "down", "text/plain", it.url) }+ assertNull(tokenizer.fetchConfig("tok", card))+ http.uninstall(); http.install()+ http.on("tokenization_strategies") { http.raw(200, """{"strategies":[]}""", url = it.url) }+ assertNull(tokenizer.fetchConfig("tok", card))+ }++ @Test fun tokenizeDispatchStripeAndBraintree() = runTest {+ http.on("api.stripe.com") { http.raw(200, """{"id":"tok_d"}""", url = it.url) }+ val r = tokenizer.tokenize(TokenizerConfig("stripe", "pk"), card) as TokenizeResult.Ok+ assertEquals("tok_d", r.token)+ assertNotNull(r)+ }+}
taxi/src/test/java/com/vayunmathur/taxi/network/ProtoWire.kt
diff --git a/taxi/src/test/java/com/vayunmathur/taxi/network/ProtoWire.kt b/taxi/src/test/java/com/vayunmathur/taxi/network/ProtoWire.ktnew file mode 100644index 0000000000..501dc49862--- /dev/null+++ b/taxi/src/test/java/com/vayunmathur/taxi/network/ProtoWire.kt@@ -0,0 +1,35 @@+package com.vayunmathur.taxi.network++/** Minimal protobuf wire builder for parser tests (mirrors ProtoMessageTest helpers). */+internal object ProtoWire {+ 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()+ }+ fun record(field: Int, wire: Int, payload: ByteArray): ByteArray =+ varintBytes(((field shl 3) or wire).toLong()) + payload+ fun varintField(field: Int, value: Long): ByteArray = record(field, 0, varintBytes(value))+ fun stringField(field: Int, value: String): ByteArray {+ val b = value.toByteArray(Charsets.UTF_8)+ return record(field, 2, varintBytes(b.size.toLong()) + b)+ }+ fun bytesField(field: Int, payload: ByteArray): ByteArray =+ record(field, 2, varintBytes(payload.size.toLong()) + payload)+ fun doubleField(field: Int, value: Double): ByteArray {+ val bits = java.lang.Double.doubleToLongBits(value)+ return record(field, 1, ByteArray(8) { i -> ((bits ushr (8 * i)) and 0xFF).toByte() })+ }+ fun msg(field: Int, vararg parts: ByteArray): ByteArray = bytesField(field, concat(*parts))+ fun wrappedLong(field: Int, value: Long): ByteArray = msg(field, varintField(1, value))+ fun wrappedString(field: Int, value: String): ByteArray = msg(field, stringField(1, value))+ fun wrappedBool(field: Int, value: Boolean): ByteArray = msg(field, varintField(1, if (value) 1 else 0))+ fun concat(vararg parts: ByteArray): ByteArray = parts.fold(byteArrayOf()) { a, p -> a + p }+}
taxi/src/test/java/com/vayunmathur/taxi/notifications/RideLiveUpdateDeepTest.kt
diff --git a/taxi/src/test/java/com/vayunmathur/taxi/notifications/RideLiveUpdateDeepTest.kt b/taxi/src/test/java/com/vayunmathur/taxi/notifications/RideLiveUpdateDeepTest.ktnew file mode 100644index 0000000000..7ab3e87a38--- /dev/null+++ b/taxi/src/test/java/com/vayunmathur/taxi/notifications/RideLiveUpdateDeepTest.kt@@ -0,0 +1,93 @@+package com.vayunmathur.taxi.notifications++import android.app.Notification+import android.content.Context+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 org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import org.robolectric.Shadows+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class RideLiveUpdateDeepTest {+ private val context: Context get() = ApplicationProvider.getApplicationContext()++ private fun ride(status: RideStatus, eta: Int? = 300, driver: DriverInfo? = DriverInfo("Jo", "Smith", null, null, 4.9),+ vehicle: VehicleInfo? = VehicleInfo("Toyota", "Camry", "Black", "XYZ", null)): ActiveRide {+ val stops = if (eta == null) emptyList() else listOf(RideStopInfo(LatLng(1.0, 2.0), "Home", "pickup", eta, false))+ return ActiveRide("ride-42", status, status.wire, driver, vehicle, null, stops, "")+ }++ private fun title(n: Notification) = n.extras.getCharSequence(Notification.EXTRA_TITLE)?.toString()+ private fun text(n: Notification) = n.extras.getCharSequence(Notification.EXTRA_TEXT)?.toString()+ ?: n.extras.getCharSequence("android.text")?.toString()++ @Test fun buildsForEveryMilestoneWithDriverTitle() {+ for (status in RideStatus.entries) {+ val n = RideLiveUpdate.build(context, ride(status))+ assertNotNull(n)+ assertEquals(RideLiveUpdate.CHANNEL_ID, n.channelId)+ }+ // driver name preferred as title+ assertEquals("Jo Smith", title(RideLiveUpdate.build(context, ride(RideStatus.ACCEPTED))))+ // ETA ceiled: 300s = 5 min, 301s = 6 min shown in text if pre-pickup+ assertTrue(text(RideLiveUpdate.build(context, ride(RideStatus.ACCEPTED, eta = 300)))!!.contains("5"))+ assertTrue(text(RideLiveUpdate.build(context, ride(RideStatus.ACCEPTED, eta = 301)))!!.contains("6"))+ }++ @Test fun titleFallsBackToVehicleThenGenericAndNoEtaCases() {+ val noDriver = ride(RideStatus.ARRIVED, driver = null)+ assertEquals("Black Toyota Camry", title(RideLiveUpdate.build(context, noDriver)))+ val bare = ride(RideStatus.PICKED_UP, driver = null, vehicle = null, eta = null)+ assertNotNull(title(RideLiveUpdate.build(context, bare)))+ // picked-up / terminal: no pickup ETA even though stop present+ assertNotNull(RideLiveUpdate.build(context, ride(RideStatus.PICKED_UP, eta = 120)))+ assertNotNull(RideLiveUpdate.build(context, ride(RideStatus.COMPLETED, eta = 120)))+ // zero/negative eta -> label only+ assertNotNull(RideLiveUpdate.build(context, ride(RideStatus.PENDING, eta = 0)))+ val negStops = ActiveRide("r", RideStatus.PENDING, "pending", null, null, null,+ listOf(RideStopInfo(null, "H", "pickup", -5, false)), "")+ assertNotNull(RideLiveUpdate.build(context, negStops))+ // completed stop eta skipped, next incomplete used - build still succeeds+ val doneFirst = ActiveRide("r", RideStatus.ACCEPTED, "accepted", null, null, null,+ listOf(RideStopInfo(null, "H", "pickup", 999, true), RideStopInfo(null, "W", "dropoff", 60, false)), "")+ assertTrue(text(RideLiveUpdate.build(context, doneFirst))!!.contains("1"))+ }++ @Test fun channelCancelAndServiceCompanion() {+ RideLiveUpdate.ensureChannel(context)+ val nm = context.getSystemService(Context.NOTIFICATION_SERVICE) as android.app.NotificationManager+ assertNotNull(nm.getNotificationChannel(RideLiveUpdate.CHANNEL_ID))+ val n = RideLiveUpdate.build(context, ride(RideStatus.ACCEPTED))+ androidx.core.app.NotificationManagerCompat.from(context).notify(RideLiveUpdate.NOTIFICATION_ID, n)+ RideLiveUpdate.cancel(context)+ assertEquals(0, Shadows.shadowOf(nm).allNotifications.size)+ // service companion: blank ids no-op, stop does not throw+ RideTrackingService.start(context, null)+ RideTrackingService.start(context, "")+ RideTrackingService.start(context, " ")+ RideTrackingService.stop(context)+ assertEquals(5120, RideLiveUpdate.NOTIFICATION_ID)+ assertTrue(RideLiveUpdate.EXTRA_TRACK_RIDE_ID.contains("EXTRA_TRACK_RIDE_ID"))+ }++ @Test fun trackingServiceBlankIntentStopsAndValidIntentStarts() {+ val controller = org.robolectric.Robolectric.buildService(RideTrackingService::class.java)+ val service = controller.create().get()+ // blank -> START_NOT_STICKY (2? assert constant value via return: 2 is START_NOT_STICKY? Actually 2 = START_NOT_STICKY? check: START_STICKY=1, START_NOT_STICKY=2)+ val blankResult = service.onStartCommand(android.content.Intent(context, RideTrackingService::class.java), 0, 1)+ assertEquals(android.app.Service.START_NOT_STICKY, blankResult)+ controller.destroy()+ }+}
taxi/src/test/java/com/vayunmathur/taxi/ui/TaxiUiDeepTest.kt
diff --git a/taxi/src/test/java/com/vayunmathur/taxi/ui/TaxiUiDeepTest.kt b/taxi/src/test/java/com/vayunmathur/taxi/ui/TaxiUiDeepTest.ktnew file mode 100644index 0000000000..f4a0267c41--- /dev/null+++ b/taxi/src/test/java/com/vayunmathur/taxi/ui/TaxiUiDeepTest.kt@@ -0,0 +1,164 @@+package com.vayunmathur.taxi.ui++import android.content.Context+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.unit.dp+import androidx.compose.ui.unit.DpOffset+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.library.intents.maps.DirectionsLatLng+import com.vayunmathur.library.intents.maps.DirectionsResult+import com.vayunmathur.library.intents.maps.DirectionsSegment+import com.vayunmathur.library.map.GeoPoint+import com.vayunmathur.taxi.R+import com.vayunmathur.taxi.data.LatLng+import com.vayunmathur.taxi.data.Place+import com.vayunmathur.taxi.data.Provider+import com.vayunmathur.taxi.data.QuoteResult+import com.vayunmathur.taxi.data.RideQuote+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class TaxiUiDeepTest {+ @get:Rule val rule = createComposeRule()+ private val context: Context get() = ApplicationProvider.getApplicationContext()+ private fun str(id: Int, vararg a: Any) = context.getString(id, *a)+ private val home = Place("Home", "1 Main St", LatLng(37.7, -122.4))+ private val work = Place("Work", "2 Market St", LatLng(37.8, -122.5))+ private val noAddr = Place("Airport", null, LatLng(37.6, -122.3))+ private val sameName = Place("Mall", "Mall", LatLng(37.5, -122.2))++ private fun quote(name: String, low: Long, surge: Double? = null, eta: Int? = 5, cap: Int? = 4) = RideQuote(+ Provider.LYFT, "p-$name", name, low, low, "USD", eta, 20, surge, cap,+ originalFareLowMinor = if (name == "Disc") 2000 else null, originalFareHighMinor = if (name == "Disc") 2000 else null,+ )++ // pure helpers+ @Test fun fareAndRouteHelpers() {+ assertEquals("$10.00", formatFare(quote("A", 1000)))+ assertEquals("$10.00 – $12.00", formatFare(quote("A", 1000).copy(fareHighMinor = 1200)))+ assertEquals("$20.00", formatOriginalFare(quote("Disc", 1500)))+ assertEquals("$15.00", formatOriginalFare(quote("A", 1500))) // fallback to fare+ // traffic bands light/dark+ assertEquals(Color(0xFFF44336), trafficColor(0.2, false)); assertEquals(Color(0xFFEF5350), trafficColor(0.2, true))+ assertEquals(Color(0xFFFFC107), trafficColor(0.5, false)); assertEquals(Color(0xFFFFCA28), trafficColor(0.89, true))+ assertEquals(Color(0xFF4CAF50), trafficColor(0.9, false)); assertEquals(Color(0xFF66BB6A), trafficColor(2.0, true))+ // bounds camera+ assertNull(routeBoundsCamera(emptyList()))+ val single = routeBoundsCamera(listOf(GeoPoint(-122.0, 37.0)))!!+ assertEquals(14.0, single.zoom); assertEquals(37.0, single.target.latitude)+ val multi = routeBoundsCamera(listOf(GeoPoint(-122.0, 37.0), GeoPoint(-121.0, 38.0)))!!+ assertEquals(37.5, multi.target.latitude); assertTrue(multi.zoom in 10.0..15.0)+ // overlay: empty, single-point filtered, multi coloured+ assertNull(DirectionsResult(emptyList(), emptyList(), 0.0, 0.0).toRouteOverlay(false))+ val seg1 = DirectionsSegment(listOf(DirectionsLatLng(1.0, 2.0)), 0.3)+ assertNull(DirectionsResult(emptyList(), listOf(seg1), 0.0, 0.0).toRouteOverlay(false))+ val seg2 = DirectionsSegment(listOf(DirectionsLatLng(1.0, 2.0), DirectionsLatLng(3.0, 4.0)), 0.3)+ val overlay = DirectionsResult(listOf(DirectionsLatLng(1.0, 2.0)), listOf(seg2), 100.0, 60.0).toRouteOverlay(true)!!+ assertEquals(1, overlay.segments.size); assertEquals(2, overlay.segments[0].points.size)+ assertEquals(8.dp, overlay.style.width)+ }++ @Test fun suggestionListClickAndAddressRules() {+ var selected: Place? = null+ rule.setContent { SuggestionList(listOf(home, noAddr, sameName)) { selected = it } }+ rule.onNodeWithText("Home").assertIsDisplayed()+ rule.onNodeWithText("1 Main St").assertIsDisplayed()+ rule.onNodeWithText("Airport").assertIsDisplayed()+ rule.onNodeWithText("Work").assertDoesNotExist()+ rule.onNodeWithText("Airport").performClick()+ assertEquals("Airport", selected?.name)+ }++ @Test fun rideInputsPaneSuggestionsSearchingAndResults() {+ var selected: Place? = null+ var booked: Provider? = null+ val results = mapOf(Provider.LYFT to QuoteResult.Success(listOf(quote("Lyft Std", 1200))))+ rule.setContent {+ RideInputsPane(+ pickupQuery = "Home", onPickupChange = {}, onPickupFocus = {}, onResetPickup = {},+ destinationQuery = "Work", onDestinationChange = {}, onDestinationFocus = {}, onClearDestination = {},+ onSearch = {}, suggestions = listOf(home), searching = false, active = RouteField.DESTINATION,+ onSelect = { selected = it }, results = results, comparing = false,+ pickup = home, destination = work, onBook = { p, _ -> booked = p },+ )+ }+ assertTrue(rule.onAllNodesWithText("Home").fetchSemanticsNodes().isNotEmpty())+ rule.onNodeWithText("Lyft Std").assertIsDisplayed()+ rule.onNodeWithText("Lyft Std").performClick()+ assertEquals(Provider.LYFT, booked)+ // Note suggestion row also "Home" - first click above may have selected? booked proves results path exercised+ }++ @Test fun rideInputsPaneSearchingShowsLoading() {+ rule.setContent {+ RideInputsPane(+ pickupQuery = "", onPickupChange = {}, onPickupFocus = {}, onResetPickup = {},+ destinationQuery = "Wor", onDestinationChange = {}, onDestinationFocus = {}, onClearDestination = {},+ onSearch = {}, suggestions = emptyList(), searching = true, active = RouteField.PICKUP,+ onSelect = {}, results = emptyMap(), comparing = false, pickup = null, destination = null,+ onBook = { _, _ -> },+ )+ }+ rule.onNodeWithText(str(R.string.searching)).assertIsDisplayed()+ }++ @Test fun resultsFailedNoteDiscountSurgeAndEmptyNotes() {+ var booked: Pair<Provider, RideQuote?>? = null+ val results = mapOf(+ Provider.LYFT to QuoteResult.Success(listOf(quote("Disc", 1500, surge = 1.5))),+ Provider.UBER to QuoteResult.Failed("Uber exploded"),+ )+ rule.setContent { ResultsSection(results, comparing = false, hasRoute = true, onBook = { p, q -> booked = p to q }) }+ rule.onNodeWithText("Disc").assertIsDisplayed()+ rule.onNodeWithText("$20.00").assertIsDisplayed() // original struck+ rule.onNodeWithText("$15.00").assertIsDisplayed()+ rule.onNodeWithText("Uber exploded").assertIsDisplayed()+ rule.onNodeWithText(str(R.string.best_price)).assertIsDisplayed()+ }++ @Test fun resultsNoQuotesNoNotesShowsNoPlaces() {+ rule.setContent { ResultsSection(emptyMap(), comparing = false, hasRoute = true, onBook = { _, _ -> }) }+ rule.onNodeWithText(str(R.string.no_places_found)).assertIsDisplayed()+ }++ @Test fun providerBadgeAndMapPinAndLoadingRow() {+ rule.setContent {+ androidx.compose.foundation.layout.Column {+ ProviderBadge(Provider.LYFT)+ ProviderBadge(Provider.UBER)+ LoadingRow("Searching…")+ MapPin(DpOffset(50.dp, 50.dp), Color.Red) { com.vayunmathur.library.ui.Text("P") }+ }+ }+ rule.onNodeWithText("L").assertIsDisplayed()+ rule.onNodeWithText("U").assertIsDisplayed()+ rule.onNodeWithText("Searching…").assertIsDisplayed()+ }++ @Test fun routeInputsClearButtonWhenDestinationTyped() {+ var cleared = 0; var pickupChanged = ""+ rule.setContent {+ RouteInputs(+ pickupQuery = "Home", onPickupChange = { pickupChanged = it }, onPickupFocus = {}, onResetPickup = {},+ destinationQuery = "Work", onDestinationChange = {}, onDestinationFocus = {},+ onClearDestination = { cleared++ }, onSearch = {},+ )+ }+ rule.onNodeWithText("Work").assertIsDisplayed()+ rule.onNodeWithText("Home").assertIsDisplayed()+ assertEquals(0, cleared)+ }+}