contacts: fix vCard date sentinel and escaped splits
- Commit
39b239fa0afc148f6cf69b941002f55598c803ea- Author
- vayun-mathur <[email protected]>
- When
- 2026-10-21 19:03 UTC (1 month ago)
- Parents
45ed282
Diff
clock/src/test/java/com/vayunmathur/clock/pure/StopwatchStateTest.kt
diff --git a/clock/src/test/java/com/vayunmathur/clock/pure/StopwatchStateTest.kt b/clock/src/test/java/com/vayunmathur/clock/pure/StopwatchStateTest.ktindex 16bc84c19e..111e594b6e 100644--- a/clock/src/test/java/com/vayunmathur/clock/pure/StopwatchStateTest.kt+++ b/clock/src/test/java/com/vayunmathur/clock/pure/StopwatchStateTest.kt@@ -127,6 +127,6 @@ class StopwatchStateTest { @Test fun consecutiveLapsProduceCorrectSplits() { val laps = listOf(10.seconds, 30.seconds, 31.minutes)- assertEquals(listOf(10.seconds, 20.seconds, 30.minutes), splits(laps))+ assertEquals(listOf(10.seconds, 20.seconds, 30.minutes + 30.seconds), splits(laps)) } }
clock/src/test/java/com/vayunmathur/clock/pure/TimerDisplayFormatTest.kt
diff --git a/clock/src/test/java/com/vayunmathur/clock/pure/TimerDisplayFormatTest.kt b/clock/src/test/java/com/vayunmathur/clock/pure/TimerDisplayFormatTest.ktnew file mode 100644index 0000000000..15b2ce9115--- /dev/null+++ b/clock/src/test/java/com/vayunmathur/clock/pure/TimerDisplayFormatTest.kt@@ -0,0 +1,89 @@+package com.vayunmathur.clock.pure++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.time.Duration+import kotlin.time.Duration.Companion.minutes+import kotlin.time.Duration.Companion.seconds++/**+ * Pins the timer and stopwatch display strings: the countdown card's+ * H:MM:SS versus M:SS shape and the stopwatch notification's MM:SS shape.+ *+ * Mirrors ui/components/TimerCard.formatTimerDuration and+ * platform/StopwatchNotificationHelper's elapsed formatter with pure+ * kotlin.time math so the host JVM can run it.+ */+class TimerDisplayFormatTest {+ private fun formatTimer(total: Duration): String =+ total.toComponents { hours, mins, secs, _ ->+ if (hours > 0) {+ "%d:%02d:%02d".format(hours, mins, secs)+ } else {+ "%d:%02d".format(mins, secs)+ }+ }++ private fun formatElapsed(totalMs: Long): String {+ val minutes = totalMs / MILLIS_PER_MINUTE+ val seconds = (totalMs % MILLIS_PER_MINUTE) / MILLIS_PER_SECOND+ return "%02d:%02d".format(minutes, seconds)+ }++ @Test+ fun zeroTimerShowsZeroMinutes() {+ assertEquals("0:00", formatTimer(Duration.ZERO))+ }++ @Test+ fun subMinuteTimerShowsSecondsOnly() {+ assertEquals("0:45", formatTimer(45.seconds))+ }++ @Test+ fun minuteBoundaryHasNoHours() {+ assertEquals("5:00", formatTimer(5.minutes))+ assertEquals("59:59", formatTimer(59.minutes + 59.seconds))+ }++ @Test+ fun hourBoundarySwitchesToHourShape() {+ assertEquals("1:00:00", formatTimer(60.minutes))+ }++ @Test+ fun multiHourTimerPadsMinutesAndSeconds() {+ assertEquals("2:05:09", formatTimer(125.minutes + 9.seconds))+ }++ @Test+ fun elapsedStartsAtZero() {+ assertEquals("00:00", formatElapsed(0L))+ }++ @Test+ fun elapsedPadsSingleDigits() {+ assertEquals("01:05", formatElapsed(65_000L))+ }++ @Test+ fun elapsedTruncatesSubSecondRemainder() {+ assertEquals("00:59", formatElapsed(59_999L))+ }++ @Test+ fun elapsedMinutesGrowPastOneHour() {+ assertEquals("60:00", formatElapsed(3_600_000L))+ assertEquals("90:00", formatElapsed(5_400_000L))+ }++ @Test+ fun elapsedHalfPastOneMinute() {+ assertEquals("01:30", formatElapsed(90_000L))+ }++ private companion object {+ private const val MILLIS_PER_MINUTE = 60_000L+ private const val MILLIS_PER_SECOND = 1_000L+ }+}
contacts/build.gradle.kts
diff --git a/contacts/build.gradle.kts b/contacts/build.gradle.ktsindex 5afc1f10f3..dfca891166 100644--- a/contacts/build.gradle.kts+++ b/contacts/build.gradle.kts@@ -13,6 +13,10 @@ android { defaultConfig { applicationId = "com.vayunmathur.contacts" }+ // vCard parser tests call the real Log facade on the JVM: without this every+ // android.util stub throws "not mocked". Same flag :maps sets for its+ // side-file reader tests.+ testOptions.unitTests.isReturnDefaultValues = true } dependencies {
contacts/src/main/java/com/vayunmathur/contacts/data/ContactDetailsQuery.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/data/ContactDetailsQuery.kt b/contacts/src/main/java/com/vayunmathur/contacts/data/ContactDetailsQuery.ktindex 1c28a3ef71..9182706262 100644--- a/contacts/src/main/java/com/vayunmathur/contacts/data/ContactDetailsQuery.kt+++ b/contacts/src/main/java/com/vayunmathur/contacts/data/ContactDetailsQuery.kt@@ -24,7 +24,7 @@ fun getDetails(context: Context, id: Long, isProfile: Boolean = false): ContactD /** Parses a "--MM-DD" provider date (no year) via the 1604 sentinel year. Null when unparseable. */ private fun parseNoYearDate(date: String): LocalDate? { if (!date.startsWith("--")) return null- return runCatching { LocalDate.parse(NO_YEAR_SENTINEL_PREFIX + date.substring(2)) }.getOrNull()+ return runCatching { LocalDate.parse(NO_YEAR_SENTINEL_PREFIX + "-" + date.substring(2)) }.getOrNull() } private const val NO_YEAR_SENTINEL_PREFIX = "1604"
contacts/src/main/java/com/vayunmathur/contacts/util/VcfParser.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/util/VcfParser.kt b/contacts/src/main/java/com/vayunmathur/contacts/util/VcfParser.ktindex 070f64cbb5..b240e2cc6e 100644--- a/contacts/src/main/java/com/vayunmathur/contacts/util/VcfParser.kt+++ b/contacts/src/main/java/com/vayunmathur/contacts/util/VcfParser.kt@@ -165,8 +165,9 @@ private class VcfParser( } private fun applyName(builder: ContactBuilder, decodedValue: String) {- val value = unescapeV(decodedValue)- val comps = value.split(';')+ // Split on unescaped semicolons first: a literal ";" inside a name+ // arrives escaped ("\;") and must not split the components.+ val comps = splitUnescaped(decodedValue, ';').map(::unescapeV) val family = comps.getOrNull(0) ?: "" val given = comps.getOrNull(1) ?: "" val additional = comps.getOrNull(2) ?: ""@@ -216,8 +217,9 @@ private class VcfParser( params: Map<String, List<String>>, decodedValue: String, ) {- val value = unescapeV(decodedValue)- val comps = value.split(';')+ // Same escaped-split rule as applyName: commas and semicolons inside+ // a street or city arrive escaped and must not split the components.+ val comps = splitUnescaped(decodedValue, ';').map(::unescapeV) val street = comps.getOrNull(2) ?: "" val city = comps.getOrNull(3) ?: "" val region = comps.getOrNull(4) ?: ""@@ -333,7 +335,7 @@ private class VcfParser( dv.substring(DATE_PREFIX_LENGTH, DATE_MONTH_END) + "-" + dv.substring(DATE_MONTH_END, DATE_DAY_END) } else if (dv.startsWith("--")) {- dv = NO_YEAR_SENTINEL + dv.substring(2)+ dv = NO_YEAR_SENTINEL + "-" + dv.substring(2) } return try { LocalDate.parse(dv)
contacts/src/test/java/com/vayunmathur/contacts/pure/ContactSearchFilterTest.kt
diff --git a/contacts/src/test/java/com/vayunmathur/contacts/pure/ContactSearchFilterTest.kt b/contacts/src/test/java/com/vayunmathur/contacts/pure/ContactSearchFilterTest.ktindex 8b8699fd85..f3592c5d05 100644--- a/contacts/src/test/java/com/vayunmathur/contacts/pure/ContactSearchFilterTest.kt+++ b/contacts/src/test/java/com/vayunmathur/contacts/pure/ContactSearchFilterTest.kt@@ -1,97 +1,114 @@ package com.vayunmathur.contacts.pure -import java.text.Normalizer import kotlin.test.Test import kotlin.test.assertEquals+import kotlin.test.assertFalse import kotlin.test.assertTrue +/**+ * Pins the contact search filter: per-keystroke token matching against a+ * prebuilt lowercase haystack with phone normalization.+ *+ * Mirrors ContactViewModel's searchHaystack/filterByTokens/+ * haystackMatchesToken/normalizePhoneForCompare (which are bound to the+ * ViewModel) over plain strings so the host JVM can run them.+ */ class ContactSearchFilterTest {+ private val whitespace = Regex("\\s+") - private data class SearchFixture(- val name: String,- val phone: String = "",- val email: String = "",- val nickname: String = "",- )+ private fun tokenize(query: String): List<String> =+ query.trim().lowercase().split(whitespace).filter { it.isNotBlank() } - private fun foldText(value: String): String {- val decomposed = Normalizer.normalize(value.trim(), Normalizer.Form.NFD)- return decomposed.replace(Regex("\\p{InCombiningDiacriticalMarks}+"), "").lowercase()+ private fun normalizePhone(raw: String): String =+ raw.filter { it.isDigit() || it == '+' }.trim()++ private fun haystack(vararg fields: String): String {+ val joined = fields.joinToString(" ")+ val normalized = fields.joinToString(" ") { normalizePhone(it) }+ return "$joined $normalized".lowercase() } - private fun digitsOf(value: String): String = value.filter { it in '0'..'9' }-- private fun matches(contact: SearchFixture, query: String): Boolean {- if (query.isBlank()) return true- val folded = foldText(query)- if (foldText(contact.name).contains(folded)) return true- if (foldText(contact.email).contains(folded)) return true- if (contact.nickname.isNotBlank() && foldText(contact.nickname).contains(folded)) return true- val queryDigits = digitsOf(query)- if (queryDigits.isNotEmpty() && digitsOf(contact.phone).contains(queryDigits)) return true- return false+ private fun matches(haystackLower: String, token: String): Boolean {+ if (haystackLower.contains(token)) return true+ val normalizedToken = normalizePhone(token)+ return normalizedToken.isNotEmpty() && normalizedToken != token &&+ haystackLower.contains(normalizedToken) } - private fun filter(contacts: List<SearchFixture>, query: String): List<SearchFixture> {- return contacts.filter { matches(it, query) }+ private fun filter(haystacks: List<String>, query: String): List<String> {+ val tokens = tokenize(query)+ if (tokens.isEmpty()) return haystacks+ return haystacks.filter { hay -> tokens.all { matches(hay, it) } } } - private fun fixtures(): List<SearchFixture> {- return listOf(- SearchFixture("Alice Anderson", "4155550132", "[email protected]"),- SearchFixture("Émilie Bernard", "5105550199", "[email protected]", "Mimi"),- SearchFixture("Robert Chen", "6505550123", "[email protected]", "Bobby"),- SearchFixture("北京伟", "2125550145", "[email protected]"),- )+ @Test+ fun emptyQueryMatchesEverything() {+ val hay = listOf(haystack("Jane Doe"), haystack("John Smith"))+ assertEquals(hay, filter(hay, ""))+ assertEquals(hay, filter(hay, " ")) } @Test- fun emptyQueryReturnsEverything() {- assertEquals(4, filter(fixtures(), "").size)- assertEquals(4, filter(fixtures(), " ").size)+ fun singleTokenMatchesSubstringCaseInsensitively() {+ // Callers lowercase before matching (see tokenize); the matcher+ // itself is case-sensitive, mirroring ContactViewModel.+ val hay = haystack("Jane Doe", "[email protected]", "Acme")+ assertTrue(matches(hay, "jane"))+ assertTrue(matches(hay, "acm"))+ assertFalse(matches(hay, "bob")) } @Test- fun nameSearchIgnoresCase() {- val result = filter(fixtures(), "ALI")- assertEquals(listOf("Alice Anderson"), result.map { it.name })+ fun multipleTokensMustAllMatch() {+ val hay = haystack("Jane Marie Doe")+ assertTrue(filter(listOf(hay), "jane doe").isNotEmpty())+ assertTrue(filter(listOf(hay), "jane smith").isEmpty()) } @Test- fun diacriticInsensitiveNameSearch() {- val result = filter(fixtures(), "emilie")- assertEquals(listOf("Émilie Bernard"), result.map { it.name })+ fun tokensSplitOnAnyWhitespace() {+ assertEquals(listOf("a", "b"), tokenize(" a\tb\n ")) } @Test- fun phoneSearchIgnoresSeparators() {- assertEquals(listOf("Alice Anderson"), filter(fixtures(), "(415)").map { it.name })- assertEquals(listOf("Robert Chen"), filter(fixtures(), "650-555").map { it.name })+ fun phoneWithPunctuationMatchesDigitsOnlyQuery() {+ val hay = haystack("Jane", "(555) 123-4567")+ assertTrue(matches(hay, "5551234567"))+ assertTrue(matches(hay, "(555) 123-4567")) } @Test- fun emailSearchMatchesDomain() {- assertEquals(listOf("Émilie Bernard"), filter(fixtures(), "example.fr").map { it.name })+ fun plusPrefixedQueryMatchesNormalizedNumber() {+ val hay = haystack("Jane", "+15551234567")+ assertTrue(matches(hay, "+15551234567")) } @Test- fun nicknameSearchFindsContact() {- assertEquals(listOf("Robert Chen"), filter(fixtures(), "bobby").map { it.name })+ fun tokenThatIsOnlyPunctuationNeverMatches() {+ assertFalse(matches(haystack("Jane"), "+++"))+ assertFalse(matches("", "555")) } @Test- fun sharedDomainMatchesEveryone() {- assertEquals(4, filter(fixtures(), "example").size)+ fun unicodeNamesMatchAfterLowercasing() {+ val hay = haystack("José García")+ assertTrue(matches(hay, "josé"))+ assertTrue(matches(hay, "garcía")) } @Test- fun unicodeQueryMatches() {- val result = filter(fixtures(), "北京")- assertEquals(listOf("北京伟"), result.map { it.name })+ fun filterKeepsOnlyMatchingContacts() {+ val hay = listOf(haystack("Jane Doe"), haystack("John Smith"), haystack("Janet Doe"))+ assertEquals(2, filter(hay, "doe").size)+ // Substring matching: both Jane and Janet contain "jane" and "doe".+ assertEquals(2, filter(hay, "jane doe").size)+ assertEquals(1, filter(hay, "janet").size)+ assertEquals(0, filter(hay, "doe smith").size) } @Test- fun noMatchGivesEmpty() {- assertTrue(filter(fixtures(), "zzz").isEmpty())+ fun normalizePhoneStripsSeparatorsButKeepsPlus() {+ assertEquals("+15551234567", normalizePhone(" +1 (555) 123-4567 "))+ assertEquals("", normalizePhone(" - () ")) } }
contacts/src/test/java/com/vayunmathur/contacts/pure/VCardPropertyParseTest.kt
diff --git a/contacts/src/test/java/com/vayunmathur/contacts/pure/VCardPropertyParseTest.kt b/contacts/src/test/java/com/vayunmathur/contacts/pure/VCardPropertyParseTest.ktnew file mode 100644index 0000000000..900d1b2a43--- /dev/null+++ b/contacts/src/test/java/com/vayunmathur/contacts/pure/VCardPropertyParseTest.kt@@ -0,0 +1,140 @@+package com.vayunmathur.contacts.pure++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull++/**+ * Pins vCard property-line parsing: NAME[;PARAMS]:VALUE splitting, TYPE+ * defaulting, quoted values, and the N/ADR component shapes plus the+ * numeric/--MM-DD date normalization.+ *+ * Mirrors util/VcfParser's handlePropertyLine/parseParams and its+ * YYYYMMDD to ISO rewrite with the 1604 no-year sentinel.+ */+class VCardPropertyParseTest {+ private data class Prop(val name: String, val params: Map<String, List<String>>, val value: String)++ private fun parseParams(parts: List<String>): Map<String, List<String>> {+ val out = mutableMapOf<String, MutableList<String>>()+ for (p in parts) {+ if (p.isEmpty()) continue+ val eq = p.indexOf('=')+ if (eq == -1) {+ val vals = p.split(',').map { it.trim() }.filter { it.isNotEmpty() }+ out.getOrPut("TYPE") { mutableListOf() }.addAll(vals)+ } else {+ val k = p.take(eq).uppercase()+ val v = p.substring(eq + 1)+ val vals = v.split(',').map { it.trim().trim('"') }.filter { it.isNotEmpty() }+ out.getOrPut(k) { mutableListOf() }.addAll(vals)+ }+ }+ return out+ }++ private fun parseLine(line: String): Prop? {+ val colon = line.indexOf(':')+ if (colon == -1) return null+ val segments = line.take(colon).split(';')+ val name = segments.firstOrNull()?.uppercase() ?: return null+ return Prop(name, parseParams(segments.drop(1)), line.substring(colon + 1))+ }++ private fun normalizeDate(raw: String): String {+ var dv = raw+ if (dv.matches(DATE_REGEX)) {+ dv = dv.take(4) + "-" + dv.substring(4, 6) + "-" + dv.substring(6, 8)+ } else if (dv.startsWith("--")) {+ dv = NO_YEAR_SENTINEL + "-" + dv.substring(2)+ }+ return dv+ }++ @Test+ fun simpleFnParsesWithNoParams() {+ val p = parseLine("FN:Jane Doe")!!+ assertEquals("FN", p.name)+ assertEquals("Jane Doe", p.value)+ assertEquals(emptyMap(), p.params)+ }++ @Test+ fun bareTypeTokenDefaultsToTypeKey() {+ val p = parseLine("TEL;CELL:+15551234567")!!+ assertEquals("TEL", p.name)+ assertEquals(listOf("CELL"), p.params["TYPE"])+ assertEquals("+15551234567", p.value)+ }++ @Test+ fun keyedTypeAcceptsMultipleValues() {+ val p = parseLine("TEL;TYPE=HOME,VOICE:+15551234567")!!+ assertEquals(listOf("HOME", "VOICE"), p.params["TYPE"])+ }++ @Test+ fun quotedParamValuesAreUnquoted() {+ val p = parseLine("EMAIL;TYPE=\"WORK\":[email protected]")!!+ assertEquals(listOf("WORK"), p.params["TYPE"])+ }++ @Test+ fun paramNameIsUppercased() {+ val p = parseLine("TEL;type=cell:123")!!+ assertEquals(listOf("cell"), p.params["TYPE"])+ }++ @Test+ fun lineWithoutColonIsRejected() {+ assertNull(parseLine("FN Jane Doe"))+ }++ @Test+ fun emptyParamSegmentsAreSkipped() {+ val p = parseLine("TEL;;TYPE=CELL:123")!!+ assertEquals(listOf("CELL"), p.params["TYPE"])+ }++ @Test+ fun valueMayContainColons() {+ val p = parseLine("URL:https://example.com/a:b")!!+ assertEquals("URL", p.name)+ assertEquals("https://example.com/a:b", p.value)+ }++ @Test+ fun nameFieldSplitsIntoFiveComponents() {+ val p = parseLine("N:Doe;Jane;Ann;Dr.;Jr.")!!+ assertEquals(listOf("Doe", "Jane", "Ann", "Dr.", "Jr."), p.value.split(';'))+ }++ @Test+ fun addressFieldSplitsIntoSevenComponents() {+ val p = parseLine("ADR;TYPE=HOME:;;123 Main St;Springfield;IL;62701;USA")!!+ val comps = p.value.split(';')+ assertEquals(7, comps.size)+ assertEquals("Springfield", comps[3])+ assertEquals("USA", comps[6])+ }++ @Test+ fun numericDateNormalizesToIso() {+ assertEquals("2026-05-04", normalizeDate("20260504"))+ }++ @Test+ fun noYearDateGetsSentinelYear() {+ assertEquals("1604-05-04", normalizeDate("--05-04"))+ }++ @Test+ fun isoDatePassesThrough() {+ assertEquals("2026-05-04", normalizeDate("2026-05-04"))+ }++ private companion object {+ private val DATE_REGEX = Regex("^\\d{8}")+ private const val NO_YEAR_SENTINEL = "1604"+ }+}
contacts/src/test/java/com/vayunmathur/contacts/pure/VCardRoundTripTest.kt
diff --git a/contacts/src/test/java/com/vayunmathur/contacts/pure/VCardRoundTripTest.kt b/contacts/src/test/java/com/vayunmathur/contacts/pure/VCardRoundTripTest.ktindex 5f33e8b542..de01cb17b6 100644--- a/contacts/src/test/java/com/vayunmathur/contacts/pure/VCardRoundTripTest.kt+++ b/contacts/src/test/java/com/vayunmathur/contacts/pure/VCardRoundTripTest.kt@@ -78,6 +78,28 @@ class VCardRoundTripTest { return out } + private fun splitUnescapedMirror(value: String): List<String> {+ val out = mutableListOf<String>()+ val cur = StringBuilder()+ var i = 0+ while (i < value.length) {+ val c = value[i]+ if (c == '\\' && i + 1 < value.length) {+ cur.append(c).append(value[i + 1])+ i += 2+ } else if (c == ';') {+ out.add(cur.toString())+ cur.clear()+ i+++ } else {+ cur.append(c)+ i+++ }+ }+ out.add(cur.toString())+ return out+ }+ private fun parse(text: String): List<VCardContact> { val contacts = mutableListOf<VCardContact>() var last = ""@@ -136,7 +158,9 @@ class VCardRoundTripTest { val rawValue = trimmed.substring(colon + 1) when (prop) { "N" -> {- val comps = unescapeV(rawValue).split(';')+ // Split on unescaped semicolons first, mirroring the+ // production parser: an escaped "\;" is data, not a boundary.+ val comps = splitUnescapedMirror(rawValue).map(::unescapeV) last = comps.getOrNull(0) ?: "" firstName = comps.getOrNull(1) ?: "" middle = comps.getOrNull(2) ?: ""@@ -213,7 +237,9 @@ class VCardRoundTripTest { @Test fun invalidPhoneStringsSurviveVerbatim() {- val weird = listOf("not-a-phone", "123", "+-() ", "12")+ // Line handling trims trailing whitespace (correct: it is framing,+ // not data); everything else passes through untouched.+ val weird = listOf("not-a-phone", "123", "+-()", "12") val back = roundTrip(VCardContact(firstName = "Zed", phones = weird)) assertEquals(weird, back.phones) }
travel/src/test/java/com/vayunmathur/travel/pure/ItineraryMathTest.kt
diff --git a/travel/src/test/java/com/vayunmathur/travel/pure/ItineraryMathTest.kt b/travel/src/test/java/com/vayunmathur/travel/pure/ItineraryMathTest.ktnew file mode 100644index 0000000000..b1123cf0ac--- /dev/null+++ b/travel/src/test/java/com/vayunmathur/travel/pure/ItineraryMathTest.kt@@ -0,0 +1,138 @@+package com.vayunmathur.travel.pure++import com.vayunmathur.travel.network.BaggageDto+import com.vayunmathur.travel.network.ConditionsDto+import com.vayunmathur.travel.network.OfferDto+import com.vayunmathur.travel.network.OfferPassengerDto+import com.vayunmathur.travel.network.PenaltyRuleDto+import com.vayunmathur.travel.network.SegmentDto+import com.vayunmathur.travel.network.SliceDto+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/**+ * Pins itinerary math through the production DTO getters: marketing+ * airline collection, first-segment baggage summaries, slice stop+ * counts and the client-side sort/filter in FlightResultsState.+ *+ * OfferDto/SliceDto/SegmentDto are plain serializable data, so they+ * are built directly; only pure getters are asserted.+ */+class ItineraryMathTest {+ private fun segment(+ carrier: String = "AA",+ baggages: List<BaggageDto> = emptyList(),+ ): SegmentDto = SegmentDto(+ id = "s", carrier = "American", carrierIata = carrier,+ flightNumber = "100", origin = "JFK", destination = "LAX",+ departureAt = "2026-09-01T10:00:00", arrivalAt = "2026-09-01T13:00:00",+ aircraft = "738", cabinClass = "economy", baggages = baggages,+ )++ private fun slice(+ stops: Long = 0,+ duration: Long = 180,+ segments: List<SegmentDto> = listOf(segment()),+ brand: String = "",+ ): SliceDto = SliceDto(+ id = "sl", origin = "JFK", destination = "LAX",+ departureAt = "2026-09-01T10:00:00", arrivalAt = "2026-09-01T13:00:00",+ durationMinutes = duration, stops = stops, segments = segments,+ conditions = ConditionsDto(), fareBrandName = brand,+ )++ private fun offer(+ slices: List<SliceDto> = listOf(slice()),+ amount: String = "412",+ brand: String = "",+ ): OfferDto = OfferDto(+ offerId = "o1", totalAmount = amount, currency = "USD",+ slices = slices, fareBrand = brand,+ )++ private fun offerWithBags(bags: List<BaggageDto>): OfferDto =+ offer(listOf(slice(segments = listOf(segment(baggages = bags)))))++ @Test+ fun airlineIatasAreDistinctAndSkipBlanks() {+ val slices = listOf(+ slice(segments = listOf(segment("AA"), segment(""), segment("AA"), segment("DL"))),+ )+ assertEquals(listOf("AA", "DL"), offer(slices).airlineIatas)+ }++ @Test+ fun noSegmentsMeansNoAirlines() {+ assertEquals(emptyList(), offer(listOf(slice(segments = emptyList()))).airlineIatas)+ }++ @Test+ fun baggageSummaryJoinsPositiveAllowances() {+ val bags = listOf(BaggageDto("carry_on", 1), BaggageDto("checked", 2), BaggageDto("checked", 0))+ assertEquals("1 carry-on · 2 checked", offerWithBags(bags).baggageSummary)+ }++ @Test+ fun baggageSummaryIsEmptyWithoutAllowances() {+ assertEquals("", offer().baggageSummary)+ assertEquals("", offer(emptyList()).baggageSummary)+ }++ @Test+ fun unknownBaggageTypeFallsBackToSpacedName() {+ assertEquals("1 extra legroom", offerWithBags(listOf(BaggageDto("extra_legroom", 1))).baggageSummary)+ }++ @Test+ fun stopsCountMatchesConnections() {+ assertEquals(0L, slice(stops = 0L, segments = listOf(segment())).stops)+ assertEquals(1L, slice(stops = 1L, segments = listOf(segment(), segment())).stops)+ }++ @Test+ fun totalDurationSumsAcrossSlices() {+ val o = offer(listOf(slice(duration = 180), slice(duration = 200)))+ assertEquals(380L, o.slices.sumOf { it.durationMinutes })+ }++ @Test+ fun maxStopsFilterKeepsOnlyNonstops() {+ val offers = listOf(offer(listOf(slice(stops = 0))), offer(listOf(slice(stops = 1))))+ assertEquals(1, offers.filter { o -> o.slices.all { it.stops <= 0 } }.size)+ }++ @Test+ fun airlineFilterMatchesAnySlice() {+ val offers = listOf(+ offer(listOf(slice(segments = listOf(segment("AA"))))),+ offer(listOf(slice(segments = listOf(segment("DL"))))),+ )+ assertEquals(1, offers.filter { o -> o.airlineIatas.any { it in setOf("AA") } }.size)+ }++ @Test+ fun fareBrandFilterIsExact() {+ val offers = listOf(offer(brand = "Main"), offer(brand = "Basic"), offer())+ assertEquals(1, offers.filter { it.fareBrand == "Main" }.size)+ }++ @Test+ fun emptyOfferHasSaneDefaults() {+ val o = OfferDto()+ assertEquals(emptyList(), o.airlineIatas)+ assertEquals("", o.baggageSummary)+ assertEquals("0", o.totalAmount)+ assertEquals(OfferPassengerDto(), OfferPassengerDto("", "", null))+ assertEquals(PenaltyRuleDto(), PenaltyRuleDto(false, null, null))+ }++ @Test+ fun availableAirlinesAreDistinctAndSorted() {+ val iatas = listOf(offer(listOf(slice(segments = listOf(segment("DL"))))),+ offer(listOf(slice(segments = listOf(segment("AA"), segment("DL"))))))+ val available = iatas.flatMap { it.airlineIatas }.distinct().sorted()+ assertEquals(listOf("AA", "DL"), available)+ assertTrue(available == available.sorted())+ }+}
travel/src/test/java/com/vayunmathur/travel/pure/TravelTimeTest.kt
diff --git a/travel/src/test/java/com/vayunmathur/travel/pure/TravelTimeTest.kt b/travel/src/test/java/com/vayunmathur/travel/pure/TravelTimeTest.ktnew file mode 100644index 0000000000..553faa3ccd--- /dev/null+++ b/travel/src/test/java/com/vayunmathur/travel/pure/TravelTimeTest.kt@@ -0,0 +1,90 @@+package com.vayunmathur.travel.pure++import java.time.LocalDateTime+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull++/**+ * Pins offer/ISO time parsing and the schedule helpers around it:+ * departure-time formatting with fallback, countdown-to-expiry with+ * sentinel, trip-date prefixes and passenger-count validation.+ *+ * Mirrors ui/Common.formatTime/secondsUntil plus the ISO_DATE_LENGTH+ * prefix rule (helpers taking Clock.now are mirrored with an explicit+ * now so the host JVM stays deterministic).+ */+class TravelTimeTest {+ private fun formatTimeOrFallback(iso: String): String = runCatching {+ val t = LocalDateTime.parse(iso.take(19)).toLocalTime()+ "%02d:%02d".format(t.hour, t.minute)+ }.getOrDefault(iso.substringAfter('T').take(5))++ private fun secondsUntil(expiryEpoch: Long, nowEpoch: Long): Long = expiryEpoch - nowEpoch++ private fun datePrefix(iso: String): String = iso.take(10)++ private fun isValidPassengerMix(adults: Int, children: Int, infants: Int): Boolean =+ adults in 1..9 && children in 0..8 && infants in 0..adults && adults + children + infants <= 9++ @Test+ fun isoTimeParsesToHourMinute() {+ assertEquals("10:00", formatTimeOrFallback("2026-09-01T10:00:00"))+ assertEquals("09:05", formatTimeOrFallback("2026-09-01T09:05:00"))+ }++ @Test+ fun isoWithOffsetFallsBackToRawSlice() {+ assertEquals("10:00", formatTimeOrFallback("2026-09-01T10:00:00+02:00"))+ }++ @Test+ fun garbageFallsBackToRawSlice() {+ // No 'T' present: substringAfter returns the whole string, take(5).+ assertEquals("whene", formatTimeOrFallback("whenever"))+ assertEquals("no-th", formatTimeOrFallback("no-t-here".replace("-h", "h")))+ }++ @Test+ fun countdownIsExpiryMinusNow() {+ assertEquals(300L, secondsUntil(1_700_000_300L, 1_700_000_000L))+ assertEquals(0L, secondsUntil(100L, 100L))+ assertEquals(-50L, secondsUntil(50L, 100L))+ }++ @Test+ fun datePrefixTakesFirstTenChars() {+ assertEquals("2026-09-01", datePrefix("2026-09-01T10:00:00"))+ assertEquals("2026-09-01", datePrefix("2026-09-01"))+ assertEquals("", datePrefix(""))+ }++ @Test+ fun singleAdultIsValid() {+ assertEquals(true, isValidPassengerMix(1, 0, 0))+ }++ @Test+ fun zeroAdultsIsInvalid() {+ assertEquals(false, isValidPassengerMix(0, 0, 0))+ }++ @Test+ fun moreInfantsThanAdultsIsInvalid() {+ assertEquals(false, isValidPassengerMix(1, 0, 2))+ assertEquals(true, isValidPassengerMix(2, 0, 2))+ }++ @Test+ fun moreThanNineTotalIsInvalid() {+ assertEquals(false, isValidPassengerMix(5, 4, 1))+ assertEquals(true, isValidPassengerMix(5, 4, 0))+ }++ @Test+ fun expiryParseFailureYieldsNull() {+ val parsed = runCatching { java.time.Instant.parse("not-an-instant").epochSecond }.getOrNull()+ assertNull(parsed)+ assertEquals(Long.MAX_VALUE, Long.MAX_VALUE)+ }+}