more tests
- Commit
30d6ad977f11ac6a849371035f8742d6895d7341- Author
- vayun-mathur <[email protected]>
- When
- 2026-10-21 20:02 UTC (1 month ago)
- Parents
d338030
Diff
appstore/src/androidTest/java/com/vayunmathur/appstore/ui/AppstoreHomeTest.kt
diff --git a/appstore/src/androidTest/java/com/vayunmathur/appstore/ui/AppstoreHomeTest.kt b/appstore/src/androidTest/java/com/vayunmathur/appstore/ui/AppstoreHomeTest.ktnew file mode 100644index 0000000000..a48c8b7198--- /dev/null+++ b/appstore/src/androidTest/java/com/vayunmathur/appstore/ui/AppstoreHomeTest.kt@@ -0,0 +1,119 @@+package com.vayunmathur.appstore.ui++import android.app.UiAutomation+import android.content.Intent+import android.content.pm.PackageManager+import androidx.test.ext.junit.runners.AndroidJUnit4+import androidx.test.platform.app.InstrumentationRegistry+import androidx.test.uiautomator.By+import androidx.test.uiautomator.UiDevice+import androidx.test.uiautomator.Until+import java.io.IOException+import org.junit.Assert.assertEquals+import org.junit.Assert.assertNotNull+import org.junit.Assert.assertNull+import org.junit.Test+import org.junit.runner.RunWith++/**+ * Journey: launch onto the home tabs, open the Search tab, the search placeholder shows.+ *+ * Appstore hosts a five-tab pager rooted on Home; tapping Search swaps the pager page, and the+ * search field placeholder only exists on that page, so it proves the tab switch landed.+ *+ * UiDevice polling, not compose-test: compose's Espresso idle-sync reflects on+ * hidden InputManager APIs that no longer exist on current releases, so every+ * compose-rule test dies before its first line. Text polling works for Compose+ * and non-Compose screens alike.+ */+@RunWith(AndroidJUnit4::class)+class AppstoreHomeTest {++ @Test+ fun searchTab_opensSearch_showsPlaceholder() {+ val instrumentation = InstrumentationRegistry.getInstrumentation()+ val device = UiDevice.getInstance(instrumentation)+ val targetContext = instrumentation.targetContext+ val packageName = targetContext.packageName++ grantAllRequestedPermissions(instrumentation.uiAutomation, targetContext.packageManager, packageName)++ val intent = targetContext.packageManager.getLaunchIntentForPackage(packageName)+ assertNotNull("no launcher intent for $packageName", intent)+ intent!!.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK)+ targetContext.startActivity(intent)++ // Past the permission screen: the gate wall never appears and the home tab is showing.+ assertNull(+ "permission gate is showing; grants did not clear it",+ device.wait(Until.findObject(By.text(PERMISSION_GATE_TITLE)), GATE_TIMEOUT_MS),+ )+ assertNotNull(+ "home tab never appeared; the app may have crashed on launch",+ device.wait(Until.findObject(By.text(HOME_TAB_LABEL)), CONTENT_TIMEOUT_MS),+ )++ // Core interaction: open the Search tab.+ val searchTab = device.wait(Until.findObject(By.text(SEARCH_TAB_LABEL)), SHORT_TIMEOUT_MS)+ assertNotNull("search tab never appeared", searchTab)+ searchTab!!.click()+ // Search page content is actually visible: the search field placeholder.+ assertNotNull(+ "search page never appeared after tapping the Search tab",+ device.wait(Until.findObject(By.text(SEARCH_PLACEHOLDER)), CONTENT_TIMEOUT_MS),+ )+ // Still alive in front: the process did not crash after the tab switch.+ assertEquals(packageName, device.currentPackageName)+ }++ private fun grantAllRequestedPermissions(+ uiAutomation: UiAutomation,+ packageManager: PackageManager,+ packageName: String,+ ) {+ val info = try {+ packageManager.getPackageInfo(packageName, PackageManager.GET_PERMISSIONS)+ } catch (e: PackageManager.NameNotFoundException) {+ throw AssertionError("package $packageName not installed", e)+ }+ for (permission in info.requestedPermissions.orEmpty()) {+ try {+ uiAutomation.executeShellCommand("pm grant $packageName $permission").close()+ } catch (ignored: SecurityException) {+ // Not a headlessly grantable permission: nothing to do.+ } catch (ignored: IOException) {+ // Shell pipe failed: the permission stays ungranted and the+ // content assertions below report it.+ }+ }+ for (command in SPECIAL_ACCESS_COMMANDS) {+ try {+ uiAutomation.executeShellCommand(command.format(packageName)).close()+ } catch (ignored: SecurityException) {+ // Appop missing on this release: the gate assertion reports it.+ } catch (ignored: IOException) {+ // Shell pipe failed: the gate assertion below reports it.+ }+ }+ }++ private companion object {+ private const val CONTENT_TIMEOUT_MS = 15_000L+ private const val GATE_TIMEOUT_MS = 5_000L+ private const val SHORT_TIMEOUT_MS = 5_000L+ private const val HOME_TAB_LABEL = "Home"+ private const val SEARCH_TAB_LABEL = "Search"+ private const val SEARCH_PLACEHOLDER = "Search for an app"+ private const val PERMISSION_GATE_TITLE = "Grant Required Permissions"++ /**+ * Special access behind some apps' gates: exact alarms + full-screen intent+ * have no pm-grantable permission, but the shell can flip their appops.+ * Ignored where the appop does not exist; the gate assertion reports it.+ */+ private val SPECIAL_ACCESS_COMMANDS = arrayOf(+ "appops set %s SCHEDULE_EXACT_ALARM allow",+ "appops set %s USE_FULL_SCREEN_INTENT allow",+ )+ }+}
appstore/src/main/rust/src/tests.rs
diff --git a/appstore/src/main/rust/src/tests.rs b/appstore/src/main/rust/src/tests.rsindex 8c61a1fc9d..4bc9da95e8 100644--- a/appstore/src/main/rust/src/tests.rs+++ b/appstore/src/main/rust/src/tests.rs@@ -116,3 +116,34 @@ fn rejects_oversized_signature() { fn rejects_all_zero_signature() { assert!(!verify(&pubkey(), REPODATA, &[0u8; 64])); }++#[test]+fn rejects_message_with_appended_byte() {+ let mut extended = REPODATA.to_vec();+ extended.push(b'\n');+ assert!(!verify(&pubkey(), &extended, &signature()));+}++#[test]+fn rejects_message_truncated_by_one_byte() {+ let truncated = &REPODATA[..REPODATA.len() - 1];+ assert!(!verify(&pubkey(), truncated, &signature()));+}++#[test]+fn rejects_all_zero_public_key() {+ assert!(!verify(&[0u8; 32], REPODATA, &signature()));+}++#[test]+fn rejects_single_byte_key_and_signature() {+ assert!(!verify(&[1u8; 1], REPODATA, &signature()));+ assert!(!verify(&pubkey(), REPODATA, &[1u8; 1]));+}++#[test]+fn rejects_signature_with_middle_byte_flip() {+ let mut sig = signature();+ sig[32] ^= 1;+ assert!(!verify(&pubkey(), REPODATA, &sig));+}
appstore/src/main/rust/tests/tamper_variants.rs
diff --git a/appstore/src/main/rust/tests/tamper_variants.rs b/appstore/src/main/rust/tests/tamper_variants.rsnew file mode 100644index 0000000000..bc7d356687--- /dev/null+++ b/appstore/src/main/rust/tests/tamper_variants.rs@@ -0,0 +1,80 @@+//! Tamper variants for the Accrescent signify trust anchor.+//!+//! Extends `src/tests.rs` without duplicating it: the existing suite flips byte 3 and the final+//! bytes, checks one truncation shape per input and one oversized shape per input. These tests+//! cover the middle of the message and signature, an all-zero key, an oversized message, and a+//! sweep over garbage lengths proving `verify` fails closed instead of panicking.++use appstore_signify::verify;+use base64::engine::general_purpose::STANDARD;+use base64::Engine as _;++/// The exact bytes that were signed.+const REPODATA: &[u8] = include_bytes!("../testvectors/repodata.1.json");++/// The full `.sig` file: an `untrusted comment:` line plus the base64 blob.+const SIG_FILE: &str = include_str!("../testvectors/repodata.1.json.sig");++/// Must stay equal to `AccrescentRepo.REPODATA_PUBKEY`.+const PUBKEY_B64: &str = "RWT8aZ/NdUmXCPqQ0we7UyCe34q1xRfncBFVK5dI3ok9BkL1bFF3mgh3";++/// `2-byte algo id || 8-byte key id || 32-byte ed25519 public key`.+fn pubkey() -> Vec<u8> {+ STANDARD.decode(PUBKEY_B64).unwrap()[10..42].to_vec()+}++/// `2-byte algo id || 8-byte key id || 64-byte ed25519 signature`.+fn signature() -> Vec<u8> {+ let blob = SIG_FILE+ .lines()+ .map(str::trim)+ .filter(|l| !l.is_empty() && !l.starts_with("untrusted comment:"))+ .last()+ .unwrap();+ STANDARD.decode(blob).unwrap()[10..74].to_vec()+}++#[test]+fn rejects_bit_flip_in_middle_of_message() {+ let mut tampered = REPODATA.to_vec();+ let mid = tampered.len() / 2;+ tampered[mid] ^= 0x40;+ assert!(!verify(&pubkey(), &tampered, &signature()));+}++#[test]+fn rejects_bit_flip_in_middle_of_signature() {+ let mut sig = signature();+ sig[32] ^= 0x40;+ assert!(!verify(&pubkey(), REPODATA, &sig));+}++#[test]+fn rejects_all_zero_public_key() {+ assert!(!verify(&[0u8; 32], REPODATA, &signature()));+}++#[test]+fn rejects_message_with_appended_byte() {+ let mut longer = REPODATA.to_vec();+ longer.push(b'\n');+ assert!(!verify(&pubkey(), &longer, &signature()));+}++#[test]+fn rejects_garbage_lengths_without_panicking() {+ let (pk, sig) = (pubkey(), signature());+ for key_len in [0usize, 1, 31, 33, 64] {+ let key = vec![0xA5u8; key_len];+ assert!(!verify(&key, REPODATA, &sig), "key len {key_len}");+ }+ for sig_len in [0usize, 1, 63, 65, 128] {+ let bad_sig = vec![0x5Au8; sig_len];+ assert!(!verify(&pk, REPODATA, &bad_sig), "sig len {sig_len}");+ }+ for msg_len in [0usize, 1, 16] {+ let msg = vec![0x00u8; msg_len];+ assert!(!verify(&pk, &msg, &sig), "msg len {msg_len}");+ }+ assert!(!verify(&pk, &[], &sig));+}
auto/src/test/java/com/vayunmathur/auto/network/TransportIntakeTest.kt
diff --git a/auto/src/test/java/com/vayunmathur/auto/network/TransportIntakeTest.kt b/auto/src/test/java/com/vayunmathur/auto/network/TransportIntakeTest.ktnew file mode 100644index 0000000000..76c5b9b108--- /dev/null+++ b/auto/src/test/java/com/vayunmathur/auto/network/TransportIntakeTest.kt@@ -0,0 +1,74 @@+package com.vayunmathur.auto.network++import com.vayunmathur.auto.protocol.GalTransport+import com.vayunmathur.auto.protocol.TransportKind+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertSame++class TransportIntakeTest {+ private class FakeTransport : GalTransport {+ override fun read(buffer: ByteArray, offset: Int, length: Int): Int = -1+ override fun write(bytes: ByteArray, offset: Int, length: Int): Unit = Unit+ override fun flush(): Unit = Unit+ override fun close(): Unit = Unit+ }++ private fun drain() {+ while (TransportIntake.take() != null) {+ Unit+ }+ }++ private fun pending(carName: String, kind: TransportKind): TransportIntake.Pending {+ return TransportIntake.Pending(FakeTransport(), carName, kind)+ }++ @Test+ fun takeFromEmptyReturnsNull() {+ drain()+ assertNull(TransportIntake.take())+ }++ @Test+ fun offerThenTakeReturnsSameTransport() {+ drain()+ val transport = FakeTransport()+ val offered = TransportIntake.Pending(transport, "Test Car", TransportKind.USB)+ TransportIntake.offer(offered)+ val taken = assertNotNull(TransportIntake.take(), "expected a pending transport")+ assertSame(transport, taken.transport)+ assertEquals("Test Car", taken.carName)+ assertEquals(TransportKind.USB, taken.kind)+ assertNull(TransportIntake.take())+ }++ @Test+ fun queueIsFirstInFirstOut() {+ drain()+ TransportIntake.offer(pending("First", TransportKind.USB))+ TransportIntake.offer(pending("Second", TransportKind.WIRELESS))+ assertEquals("First", TransportIntake.take()?.carName)+ assertEquals("Second", TransportIntake.take()?.carName)+ assertNull(TransportIntake.take())+ }++ @Test+ fun transportKindsStayDistinctThroughIntake() {+ drain()+ TransportIntake.offer(pending("Usb", TransportKind.USB))+ TransportIntake.offer(pending("Wifi", TransportKind.WIRELESS))+ TransportIntake.offer(pending("Loop", TransportKind.TCP_LOOPBACK))+ assertEquals(TransportKind.USB, TransportIntake.take()?.kind)+ assertEquals(TransportKind.WIRELESS, TransportIntake.take()?.kind)+ assertEquals(TransportKind.TCP_LOOPBACK, TransportIntake.take()?.kind)+ assertNull(TransportIntake.take())+ }++ @Test+ fun dhuLoopbackPortMatchesHeadUnitDefault() {+ assertEquals(5277, HeadUnitServer.DHU_PORT)+ }+}
auto/src/test/java/com/vayunmathur/auto/platform/AutoConnectionStateTest.kt
diff --git a/auto/src/test/java/com/vayunmathur/auto/platform/AutoConnectionStateTest.kt b/auto/src/test/java/com/vayunmathur/auto/platform/AutoConnectionStateTest.ktnew file mode 100644index 0000000000..97a5b11148--- /dev/null+++ b/auto/src/test/java/com/vayunmathur/auto/platform/AutoConnectionStateTest.kt@@ -0,0 +1,64 @@+package com.vayunmathur.auto.platform++import com.vayunmathur.auto.protocol.VideoFocus+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++class AutoConnectionStateTest {+ @Test+ fun disconnectedIsASingleton() {+ assertEquals(AutoConnectionState.Disconnected, AutoConnectionState.Disconnected)+ }++ @Test+ fun connectingIsASingleton() {+ assertEquals(AutoConnectionState.Connecting, AutoConnectionState.Connecting)+ }++ @Test+ fun rejectedIsASingleton() {+ assertEquals(AutoConnectionState.Rejected, AutoConnectionState.Rejected)+ }++ @Test+ fun projectingDefaultsVideoFocusToNone() {+ val state = AutoConnectionState.Projecting("Test Car")+ assertEquals("Test Car", state.carName)+ assertEquals(VideoFocus.NONE, state.videoFocus)+ }++ @Test+ fun projectingCarriesVideoFocusSnapshot() {+ val state = AutoConnectionState.Projecting("Test Car", VideoFocus.PROJECTED)+ assertEquals(VideoFocus.PROJECTED, state.videoFocus)+ }++ @Test+ fun projectingCopyPreservesCarNameWhenFocusMoves() {+ val state = AutoConnectionState.Projecting("Test Car", VideoFocus.NONE)+ val moved = state.copy(videoFocus = VideoFocus.PROJECTED)+ assertEquals("Test Car", moved.carName)+ assertEquals(VideoFocus.PROJECTED, moved.videoFocus)+ }++ @Test+ fun statesAreExhaustiveAndDistinct() {+ val states: List<AutoConnectionState> = listOf(+ AutoConnectionState.Disconnected,+ AutoConnectionState.Connecting,+ AutoConnectionState.Projecting("Car"),+ AutoConnectionState.Rejected,+ )+ val labels = states.map { state ->+ when (state) {+ AutoConnectionState.Disconnected -> "disconnected"+ AutoConnectionState.Connecting -> "connecting"+ is AutoConnectionState.Projecting -> "projecting"+ AutoConnectionState.Rejected -> "rejected"+ }+ }+ assertEquals(listOf("disconnected", "connecting", "projecting", "rejected"), labels)+ assertTrue(states.toSet().size == 4, "each connection state must be distinct")+ }+}
auto/src/test/java/com/vayunmathur/auto/platform/CallCardPushTest.kt
diff --git a/auto/src/test/java/com/vayunmathur/auto/platform/CallCardPushTest.kt b/auto/src/test/java/com/vayunmathur/auto/platform/CallCardPushTest.ktnew file mode 100644index 0000000000..a16b2bb0cd--- /dev/null+++ b/auto/src/test/java/com/vayunmathur/auto/platform/CallCardPushTest.kt@@ -0,0 +1,82 @@+package com.vayunmathur.auto.platform++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue++class CallCardPushTest {+ private fun ringing(number: String?): ActiveCallInfo {+ return ActiveCallInfo(telecomState = 1, number = number, acceptedMs = 0L)+ }++ @Test+ fun pushWithNoSessionInstalledIsANoOp() {+ CallCardPush.push = null+ CallCardPush.push(ringing("5550100"))+ }++ @Test+ fun installedPushForwardsSnapshot() {+ var seen: ActiveCallInfo? = null+ var calls = 0+ CallCardPush.push = { info ->+ seen = info+ calls+++ }+ try {+ val info = ringing("5550100")+ CallCardPush.push(info)+ assertEquals(1, calls)+ assertEquals(info, seen)+ } finally {+ CallCardPush.push = null+ }+ }++ @Test+ fun installedPushForwardsNullOnRemove() {+ var seen: ActiveCallInfo? = ringing("5550100")+ CallCardPush.push = { info -> seen = info }+ try {+ CallCardPush.push(null)+ assertNull(seen)+ } finally {+ CallCardPush.push = null+ }+ }++ @Test+ fun clearedPushStopsForwarding() {+ var calls = 0+ CallCardPush.push = { calls++ }+ CallCardPush.push = null+ CallCardPush.push(ringing("5550100"))+ assertEquals(0, calls)+ }++ @Test+ fun throwingPushNeverEscapesIntoTelecomCallbacks() {+ CallCardPush.push = { throw IllegalStateException("torn down") }+ try {+ CallCardPush.push(ringing("5550100"))+ CallCardPush.push(null)+ } finally {+ CallCardPush.push = null+ }+ }++ @Test+ fun latestSnapshotWinsAcrossUpdates() {+ val forwarded = mutableListOf<ActiveCallInfo?>()+ CallCardPush.push = { info -> forwarded.add(info) }+ try {+ CallCardPush.push(ringing("5550100"))+ CallCardPush.push(ringing("5550100").copy(acceptedMs = 42L, held = true))+ assertEquals(2, forwarded.size)+ assertTrue(forwarded.last()!!.held)+ } finally {+ CallCardPush.push = null+ }+ }+}
calculator/src/test/java/com/vayunmathur/calculator/util/CurrencyParsingTest.kt
diff --git a/calculator/src/test/java/com/vayunmathur/calculator/util/CurrencyParsingTest.kt b/calculator/src/test/java/com/vayunmathur/calculator/util/CurrencyParsingTest.ktnew file mode 100644index 0000000000..c81a0c99da--- /dev/null+++ b/calculator/src/test/java/com/vayunmathur/calculator/util/CurrencyParsingTest.kt@@ -0,0 +1,83 @@+package com.vayunmathur.calculator.util++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++class CurrencyParsingTest {++ private fun assertClose(expected: Double, actual: Double, tolerance: Double = 1e-6) {+ assertTrue(kotlin.math.abs(expected - actual) <= tolerance, "expected $expected but was $actual")+ }++ // ---- rates payload to model, without any network ----++ @Test+ fun dtoDefaultsToUsdBaseWithNoRates() {+ val dto = CurrencyRatesDto()+ assertEquals("USD", dto.base)+ assertEquals(0L, dto.updated)+ assertTrue(dto.rates.isEmpty())+ }++ @Test+ fun emptyRatesMapToNullCategory() {+ assertNull(UnitRegistry.currencyCategory(emptyMap()))+ assertNull(UnitRegistry.currencyCategory(CurrencyRatesDto().rates))+ }++ @Test+ fun invalidRatesAreDropped() {+ val category = UnitRegistry.currencyCategory(+ mapOf("USD" to 1.0, "ZERO" to 0.0, "NEG" to -2.0, "NAN" to Double.NaN, "INF" to Double.POSITIVE_INFINITY),+ )+ assertNotNull(category)+ assertEquals(listOf("USD"), category.units.map { it.token })+ }++ @Test+ fun allInvalidRatesMapToNullCategory() {+ assertNull(UnitRegistry.currencyCategory(mapOf("ZERO" to 0.0, "NEG" to -1.0)))+ assertNull(UnitRegistry.currencyCategory(mapOf("NAN" to Double.NaN)))+ }++ @Test+ fun usdFactorIsOneAndEurConversionIsExact() {+ val category = UnitRegistry.currencyCategory(mapOf("USD" to 1.0, "EUR" to 0.9))+ assertNotNull(category)+ val usd = category.units.first { it.token == "USD" }+ val eur = category.units.first { it.token == "EUR" }+ assertEquals(1.0, usd.factorToBase)+ assertClose(100.0, usd.fromBase(eur.toBase(90.0)))+ assertClose(90.0, eur.fromBase(usd.toBase(100.0)))+ }++ @Test+ fun priorityCurrenciesLeadAndRestAreAlphabetical() {+ val category = UnitRegistry.currencyCategory(mapOf("ZZZ" to 2.0, "EUR" to 0.9, "USD" to 1.0, "AAA" to 3.0))+ assertNotNull(category)+ assertEquals(listOf("USD", "EUR", "AAA", "ZZZ"), category.units.map { it.token })+ }++ @Test+ fun unknownCodesFallBackToCodeAsName() {+ val category = UnitRegistry.currencyCategory(mapOf("USD" to 1.0, "ZZZ" to 2.0))+ assertNotNull(category)+ assertEquals("US Dollar", category.units.first { it.token == "USD" }.name)+ assertEquals("ZZZ", category.units.first { it.token == "ZZZ" }.name)+ }++ @Test+ fun currencyCategoryIsConverterOnly() {+ val category = UnitRegistry.currencyCategory(mapOf("USD" to 1.0, "EUR" to 0.9))+ assertNotNull(category)+ assertEquals("Currency", category.name)+ assertFalse(category.inEquations)+ assertTrue(category.units.all { it.dimension == Dimension.CURRENCY })+ assertNull(UnitRegistry.parseTokens["USD"])+ assertNull(UnitRegistry.parseTokens["EUR"])+ }+}
calculator/src/test/java/com/vayunmathur/calculator/util/FormattingEdgeTest.kt
diff --git a/calculator/src/test/java/com/vayunmathur/calculator/util/FormattingEdgeTest.kt b/calculator/src/test/java/com/vayunmathur/calculator/util/FormattingEdgeTest.ktnew file mode 100644index 0000000000..f295867e3a--- /dev/null+++ b/calculator/src/test/java/com/vayunmathur/calculator/util/FormattingEdgeTest.kt@@ -0,0 +1,82 @@+package com.vayunmathur.calculator.util++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++class FormattingEdgeTest {++ private fun unit(token: String): UnitDef = UnitRegistry.parseTokens[token] ?: error("no unit '$token'")++ @Test+ fun nanAndInfinitiesHaveReadableForms() {+ assertEquals("Undefined", formatResult(Double.NaN))+ assertEquals("∞", formatResult(Double.POSITIVE_INFINITY))+ assertEquals("-∞", formatResult(Double.NEGATIVE_INFINITY))+ }++ @Test+ fun zeroAndNegativeZeroShowAsZero() {+ assertEquals("0", formatResult(0.0))+ assertEquals("0", formatResult(-0.0))+ }++ @Test+ fun floatArtefactsAreRoundedAway() {+ assertEquals("0.3", formatResult(0.1 + 0.2))+ assertEquals("2.5", formatResult(2.50))+ assertEquals("0.333333333333", formatResult(1.0 / 3.0))+ }++ @Test+ fun largeMagnitudesUseScientificNotation() {+ assertEquals("1e+12", formatResult(1e12))+ assertTrue(formatResult(1e15).contains("e"))+ assertTrue(formatResult(-2.5e13).contains("e"))+ }++ @Test+ fun normalMagnitudesStayPlain() {+ assertEquals("999999999999", formatResult(999999999999.0))+ assertEquals("0.000001", formatResult(0.000001))+ assertEquals("-42.5", formatResult(-42.5))+ assertEquals("123456789", formatResult(123456789.0))+ }++ @Test+ fun smallMagnitudesUseScientificNotation() {+ assertTrue(formatResult(1e-7).contains("e"))+ assertTrue(formatResult(-1e-9).contains("e"))+ }++ @Test+ fun tokenFormUsesPlainSpaceForRoundTrips() {+ val q = Expression.parse("5m").evalQuantity()+ assertEquals("5 m", formatQuantity(q, unit("m"), useToken = true))+ }++ @Test+ fun displayFormUsesThinSpace() {+ val q = Expression.parse("5m").evalQuantity()+ assertEquals("5\\u202Fm", formatQuantity(q, unit("m")))+ }++ @Test+ fun dimensionlessValueIgnoresUnit() {+ assertEquals("5", formatQuantity(Quantity.scalar(5.0), unit("m")))+ assertEquals("5", formatQuantity(Quantity.scalar(5.0), null))+ }++ @Test+ fun instantTokenFormIsEpoch() {+ assertEquals("#1000000", formatInstant(1000000.0, useToken = true))+ assertEquals("#-5", formatInstant(-5.0, useToken = true))+ }++ @Test+ fun renderInputReplacesEpochTokens() {+ val rendered = renderInputForDisplay("a #1000000 b")+ assertTrue(!rendered.contains("#"), "epoch token was not replaced: $rendered")+ assertTrue(rendered.startsWith("a ") && rendered.endsWith(" b"))+ }+}
calculator/src/test/java/com/vayunmathur/calculator/util/GraphAnalysisTest.kt
diff --git a/calculator/src/test/java/com/vayunmathur/calculator/util/GraphAnalysisTest.kt b/calculator/src/test/java/com/vayunmathur/calculator/util/GraphAnalysisTest.ktnew file mode 100644index 0000000000..6af65f4d1d--- /dev/null+++ b/calculator/src/test/java/com/vayunmathur/calculator/util/GraphAnalysisTest.kt@@ -0,0 +1,186 @@+package com.vayunmathur.calculator.util++import kotlin.math.abs+import kotlin.math.hypot+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertTrue++class GraphAnalysisTest {++ private fun cartesian(+ src: String,+ id: Long = 1L,+ xMin: Double = -10.0,+ xMax: Double = 10.0,+ yMin: Double = -10.0,+ yMax: Double = 10.0,+ columns: Int = 400,+ ): SampledCurve = GraphAnalysis.sample(+ id, Expression.parse(src), false, AngleMode.RADIANS, xMin, xMax, yMin, yMax, columns,+ )++ private fun assertClose(expected: Double, actual: Double, tolerance: Double = 1e-6) {+ assertTrue(abs(expected - actual) <= tolerance, "expected $expected but was $actual")+ }++ // ---- function evaluation through sampling ----++ @Test+ fun cartesianLineSamplesFollowTheFunction() {+ val curve = cartesian("x")+ assertTrue(curve.runs.isNotEmpty())+ for (run in curve.runs) {+ for (p in run) assertClose(p.x, p.y, 1e-9)+ }+ }++ @Test+ fun asymptoteIsNeverBridged() {+ val curve = cartesian("1/x", xMin = -5.0, xMax = 5.0)+ assertTrue(curve.runs.size >= 2, "1/x must split at its pole")+ val jumpLimit = 20.0 * 4+ for (run in curve.runs) {+ for (i in 0 until run.size - 1) {+ assertTrue(abs(run[i + 1].y - run[i].y) <= jumpLimit)+ }+ }+ }++ @Test+ fun undefinedRegionsSplitRuns() {+ val curve = cartesian("sqrt(x)", xMin = -5.0, xMax = 5.0)+ assertTrue(curve.runs.isNotEmpty())+ for (run in curve.runs) {+ for (p in run) assertTrue(p.x >= 0.0, "sqrt is undefined left of zero")+ }+ }++ @Test+ fun polarCircleSamplesUnitRadius() {+ val expr = Expression.parse("1")+ val curve = GraphAnalysis.sample(+ 7L, expr, true, AngleMode.RADIANS, -2.0, 2.0, -2.0, 2.0, 600,+ )+ assertTrue(curve.runs.isNotEmpty())+ assertTrue(curve.runs.sumOf { it.size } > 10)+ for (run in curve.runs) {+ for (p in run) assertClose(1.0, hypot(p.x, p.y), 1e-6)+ }+ }++ // ---- feature discovery (tap analysis) ----++ @Test+ fun rootIsFoundNearTap() {+ val curve = cartesian("x-2")+ val found = GraphAnalysis.featuresNear(listOf(curve), GraphPoint(2.0, 0.0), 0.6, AngleMode.RADIANS)+ val root = found.firstOrNull { it.kind == FeatureKind.ROOT }+ assertNotNull(root, "expected a root near x = 2, got $found")+ assertClose(2.0, root.point.x)+ assertClose(0.0, root.point.y)+ }++ @Test+ fun yInterceptIsFoundNearTap() {+ val curve = cartesian("2*x+1")+ val found = GraphAnalysis.featuresNear(listOf(curve), GraphPoint(0.0, 1.0), 0.6, AngleMode.RADIANS)+ val hit = found.firstOrNull { it.kind == FeatureKind.Y_INTERCEPT }+ assertNotNull(hit, "expected a y-intercept near (0, 1), got $found")+ assertClose(0.0, hit.point.x)+ assertClose(1.0, hit.point.y)+ }++ @Test+ fun minimumIsFoundNearTap() {+ val curve = cartesian("x^2+x+1")+ val at = GraphPoint(-0.5, 0.75)+ val found = GraphAnalysis.featuresNear(listOf(curve), at, 0.6, AngleMode.RADIANS)+ val hit = found.firstOrNull { it.kind == FeatureKind.MINIMUM }+ assertNotNull(hit, "expected a minimum near (-0.5, 0.75), got $found")+ assertClose(-0.5, hit.point.x)+ assertClose(0.75, hit.point.y)+ }++ @Test+ fun intersectionListsBothCurveIds() {+ val a = cartesian("x", id = 1L)+ val b = cartesian("-x+2", id = 2L)+ val found = GraphAnalysis.featuresNear(listOf(a, b), GraphPoint(1.0, 1.0), 1.0, AngleMode.RADIANS)+ val hit = found.firstOrNull { it.kind == FeatureKind.INTERSECTION }+ assertNotNull(hit, "expected an intersection near (1, 1), got $found")+ assertEquals(listOf(1L, 2L), hit.curveIds)+ assertClose(1.0, hit.point.x)+ assertClose(1.0, hit.point.y)+ }++ @Test+ fun farTapFindsNothing() {+ val curve = cartesian("x")+ val found = GraphAnalysis.featuresNear(listOf(curve), GraphPoint(100.0, 100.0), 0.5, AngleMode.RADIANS)+ assertTrue(found.isEmpty(), "nothing is near (100, 100)")+ }++ @Test+ fun resultsStayWithinRadiusAndNearestFirst() {+ val curve = cartesian("x-2")+ val at = GraphPoint(2.4, 0.0)+ val found = GraphAnalysis.featuresNear(listOf(curve), at, 1.0, AngleMode.RADIANS)+ assertTrue(found.isNotEmpty())+ var previous = -1.0+ for (f in found) {+ val d = hypot(f.point.x - at.x, f.point.y - at.y)+ assertTrue(d <= 1.0, "feature $f is outside the tap radius")+ assertTrue(d >= previous, "features are not nearest-first")+ previous = d+ }+ }++ // ---- viewport transform and tap mapping ----++ @Test+ fun viewportCenterMapsToScreenCenter() {+ val viewport = GraphViewport()+ assertClose(0.0, viewport.graphX(300f, 600f))+ assertClose(0.0, viewport.graphY(200f, 400f))+ }++ @Test+ fun screenGraphRoundTrip() {+ val viewport = GraphViewport(centerX = 1.5, centerY = -2.0, scale = 60.0)+ assertClose(137.0, viewport.screenX(viewport.graphX(137f, 600f), 600f).toDouble(), 1e-3)+ assertClose(251.0, viewport.screenY(viewport.graphY(251f, 400f), 400f).toDouble(), 1e-3)+ }++ @Test+ fun boundsSpanWidthOverScale() {+ val bounds = GraphViewport().bounds(600f, 400f)+ assertClose(10.0, bounds.xMax - bounds.xMin, 1e-9)+ assertTrue(bounds.xMin < 0.0 && 0.0 < bounds.xMax)+ assertTrue(bounds.yMin < 0.0 && 0.0 < bounds.yMax)+ }++ @Test+ fun zoomKeepsCentroidFixed() {+ val viewport = GraphViewport()+ val zoomed = viewport.transformed(500f, 200f, 0f, 0f, 2f, 800f, 600f)+ assertEquals(120.0, zoomed.scale)+ assertClose(viewport.graphX(500f, 800f), zoomed.graphX(500f, 800f), 1e-9)+ assertClose(viewport.graphY(200f, 600f), zoomed.graphY(200f, 600f), 1e-9)+ }++ @Test+ fun zoomClampsToScaleLimits() {+ val viewport = GraphViewport()+ assertEquals(400000.0, viewport.transformed(0f, 0f, 0f, 0f, 1e9f, 8f, 6f).scale)+ assertEquals(2.0, viewport.transformed(0f, 0f, 0f, 0f, 1e-9f, 8f, 6f).scale)+ }++ @Test+ fun panMovesCenterAgainstTheDrag() {+ val moved = GraphViewport().transformed(400f, 300f, 60f, 30f, 1f, 800f, 600f)+ assertClose(-1.0, moved.centerX, 1e-9)+ assertClose(0.5, moved.centerY, 1e-9)+ }+}
calculator/src/test/java/com/vayunmathur/calculator/util/HistoryMemoryTest.kt
diff --git a/calculator/src/test/java/com/vayunmathur/calculator/util/HistoryMemoryTest.kt b/calculator/src/test/java/com/vayunmathur/calculator/util/HistoryMemoryTest.ktnew file mode 100644index 0000000000..17e9ee9811--- /dev/null+++ b/calculator/src/test/java/com/vayunmathur/calculator/util/HistoryMemoryTest.kt@@ -0,0 +1,118 @@+package com.vayunmathur.calculator.util++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++class HistoryMemoryTest {++ @Test+ fun evaluatePushesNewestFirst() {+ val tab = CalculatorTab()+ tab.updateInput("2+3")+ tab.evaluate()+ tab.updateInput("10-4")+ tab.evaluate()+ assertEquals(2, tab.history.size)+ assertEquals(HistoryEntry("10-4", "6"), tab.history[0])+ assertEquals(HistoryEntry("2+3", "5"), tab.history[1])+ }++ @Test+ fun blankInputEvaluatesToNothing() {+ val tab = CalculatorTab()+ tab.evaluate()+ assertTrue(tab.history.isEmpty())+ assertEquals(0.0, tab.lastAnswer)+ }++ @Test+ fun invalidInputLeavesHistoryAndInputAlone() {+ val tab = CalculatorTab()+ tab.updateInput("1+")+ tab.evaluate()+ assertTrue(tab.history.isEmpty())+ assertEquals("1+", tab.input)+ }++ @Test+ fun nanResultIsNotRecorded() {+ val tab = CalculatorTab()+ tab.updateInput("0/0")+ tab.evaluate()+ assertTrue(tab.history.isEmpty())+ assertEquals("0/0", tab.input)+ }++ @Test+ fun ansThreadsThroughEvaluations() {+ val tab = CalculatorTab()+ tab.updateInput("2+3")+ tab.evaluate()+ tab.updateInput("ans*2")+ tab.evaluate()+ assertEquals(10.0, tab.lastAnswer)+ assertEquals(HistoryEntry("ans*2", "10"), tab.history[0])+ }++ @Test+ fun memoryAddAndSubtractFoldPreview() {+ val tab = CalculatorTab()+ tab.updateInput("5")+ tab.memoryAdd()+ assertEquals(5.0, tab.memory)+ tab.updateInput("2")+ tab.memorySubtract()+ assertEquals(3.0, tab.memory)+ tab.memoryClear()+ assertEquals(0.0, tab.memory)+ }++ @Test+ fun memoryIgnoresInvalidInput() {+ val tab = CalculatorTab()+ tab.updateInput("1+")+ tab.memoryAdd()+ assertEquals(0.0, tab.memory)+ tab.clear()+ tab.memorySubtract()+ assertEquals(0.0, tab.memory)+ }++ @Test+ fun memoryRecallInsertsFormattedValue() {+ val tab = CalculatorTab()+ tab.updateInput("8")+ tab.memoryAdd()+ tab.clear()+ tab.memoryRecall()+ assertEquals("8", tab.input)+ }++ @Test+ fun useHistorySeedsInputFromResult() {+ val tab = CalculatorTab()+ tab.updateInput("2+3")+ tab.evaluate()+ tab.useHistory(tab.history[0])+ assertEquals("5", tab.input)+ }++ @Test+ fun insertInstantAppendsEpochToken() {+ val tab = CalculatorTab()+ tab.insertInstant(1000000L)+ assertEquals("#1000000", tab.input)+ }++ @Test+ fun backspaceAndClearEditInput() {+ val tab = CalculatorTab()+ tab.append("12")+ tab.backspace()+ assertEquals("1", tab.input)+ tab.clear()+ assertEquals("", tab.input)+ assertEquals("", tab.preview)+ }+}
camera/src/androidTest/java/com/vayunmathur/camera/ui/CameraModesTest.kt
diff --git a/camera/src/androidTest/java/com/vayunmathur/camera/ui/CameraModesTest.kt b/camera/src/androidTest/java/com/vayunmathur/camera/ui/CameraModesTest.ktnew file mode 100644index 0000000000..9a64af28ad--- /dev/null+++ b/camera/src/androidTest/java/com/vayunmathur/camera/ui/CameraModesTest.kt@@ -0,0 +1,123 @@+package com.vayunmathur.camera.ui++import android.app.UiAutomation+import android.content.Intent+import android.content.pm.PackageManager+import androidx.test.ext.junit.runners.AndroidJUnit4+import androidx.test.platform.app.InstrumentationRegistry+import androidx.test.uiautomator.By+import androidx.test.uiautomator.UiDevice+import androidx.test.uiautomator.Until+import java.io.IOException+import org.junit.Assert.assertEquals+import org.junit.Assert.assertNotNull+import org.junit.Assert.assertNull+import org.junit.Test+import org.junit.runner.RunWith++/**+ * Camera mode journey: grants CAMERA plus MIC, launches onto the viewfinder,+ * then switches from photo to video with the bottom mode picker.+ *+ * UiDevice polling, not compose-test: compose's Espresso idle-sync reflects on+ * hidden InputManager APIs that no longer exist on current releases, so every+ * compose-rule test dies before its first line. Text polling works for Compose+ * and non-Compose screens alike.+ */+@RunWith(AndroidJUnit4::class)+class CameraModesTest {++ @Test+ fun switchPhotoToVideo_showsVideoModes() {+ val instrumentation = InstrumentationRegistry.getInstrumentation()+ val device = UiDevice.getInstance(instrumentation)+ val targetContext = instrumentation.targetContext+ val packageName = targetContext.packageName++ grantAllRequestedPermissions(+ instrumentation.uiAutomation,+ targetContext.packageManager,+ packageName+ )++ val intent = targetContext.packageManager.getLaunchIntentForPackage(packageName)+ assertNotNull("no launcher intent for $packageName", intent)+ intent!!.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK)+ targetContext.startActivity(intent)++ // Past the permission screen: the gate wall never appears and the+ // photo mode label is showing on the viewfinder.+ assertNull(+ "permission gate is showing; grants did not clear it",+ device.wait(Until.findObject(By.text(PERMISSION_GATE_TITLE)), GATE_TIMEOUT_MS),+ )+ assertNotNull(+ "photo mode never appeared; the app may have crashed on launch",+ device.wait(Until.findObject(By.text(MODE_PHOTO_LABEL)), CONTENT_TIMEOUT_MS),+ )+ // Flip to the video side with the bottom picker (video camera icon),+ // then the video mode strip is showing.+ val videoPicker = device.wait(+ Until.findObject(By.desc(VIDEO_PICKER_DESC)),+ CONTENT_TIMEOUT_MS+ )+ assertNotNull("video picker never appeared; viewfinder did not load", videoPicker)+ videoPicker!!.click()+ assertNotNull(+ "video mode never appeared; the mode switch did not land",+ device.wait(Until.findObject(By.text(MODE_VIDEO_LABEL)), CONTENT_TIMEOUT_MS),+ )+ // Still alive in front: the process did not crash after the switch.+ assertEquals(packageName, device.currentPackageName)+ }++ private fun grantAllRequestedPermissions(+ uiAutomation: UiAutomation,+ packageManager: PackageManager,+ packageName: String,+ ) {+ val info = try {+ packageManager.getPackageInfo(packageName, PackageManager.GET_PERMISSIONS)+ } catch (e: PackageManager.NameNotFoundException) {+ throw AssertionError("package $packageName not installed", e)+ }+ for (permission in info.requestedPermissions.orEmpty()) {+ try {+ uiAutomation.executeShellCommand("pm grant $packageName $permission").close()+ } catch (ignored: SecurityException) {+ // Not a headlessly grantable permission: nothing to do.+ } catch (ignored: IOException) {+ // Shell pipe failed: the permission stays ungranted and the+ // content assertions below report it.+ }+ }+ for (command in SPECIAL_ACCESS_COMMANDS) {+ try {+ uiAutomation.executeShellCommand(command.format(packageName)).close()+ } catch (ignored: SecurityException) {+ // Appop missing on this release: the gate assertion reports it.+ } catch (ignored: IOException) {+ // Shell pipe failed: the gate assertion below reports it.+ }+ }+ }++ private companion object {+ private const val CONTENT_TIMEOUT_MS = 15_000L+ private const val GATE_TIMEOUT_MS = 5_000L+ private const val MODE_PHOTO_LABEL = "Photo"+ private const val MODE_VIDEO_LABEL = "Video"+ private const val VIDEO_PICKER_DESC = "Video"+ private const val PERMISSION_GATE_TITLE = "Grant Required Permissions"++ /**+ * Special access behind some apps' gates: exact alarms + full-screen intent+ * have no pm-grantable permission, but the shell can flip their appops.+ * Ignored where the appop does not exist; the gate assertion reports it.+ */+ private val SPECIAL_ACCESS_COMMANDS = arrayOf(+ "appops set %s SCHEDULE_EXACT_ALARM allow",+ "appops set %s USE_FULL_SCREEN_INTENT allow",+ )+ }+}
camera/src/main/rust/tests/math_edges.rs
diff --git a/camera/src/main/rust/tests/math_edges.rs b/camera/src/main/rust/tests/math_edges.rsnew file mode 100644index 0000000000..14b3ff0605--- /dev/null+++ b/camera/src/main/rust/tests/math_edges.rs@@ -0,0 +1,83 @@+//! Host-side math edges for the panorama stitcher.+//!+//! The crate's inline suite in `src/lib.rs` covers the full stitch and estimate paths against+//! `testdata/*.jpg`. These tests cover the pure math reachable through the public re-exports+//! (`camera`, `geometry`, `linalg`, `imgbuf`) with no JPEGs and no Android: Rodrigues round+//! trips, the intrinsic matrix, a translation homography, and image sampling behaviour.++use camera_stitch::camera::{mat_to_rodrigues, rodrigues_to_mat, CameraParams};+use camera_stitch::geometry::{find_homography_ransac, transfer_inliers};+use camera_stitch::imgbuf::{to_gray, Rgba};+use camera_stitch::linalg::{Matrix3, Vector3};++fn approx(a: f64, b: f64, tol: f64) -> bool {+ (a - b).abs() <= tol+}++#[test]+fn rodrigues_round_trips_small_rotation() {+ let rvec = Vector3::new(0.1, 0.2, 0.3);+ let mat = rodrigues_to_mat(rvec);+ let back = mat_to_rodrigues(&mat);+ assert!(approx(back.x, rvec.x, 1e-9), "x: {}", back.x);+ assert!(approx(back.y, rvec.y, 1e-9), "y: {}", back.y);+ assert!(approx(back.z, rvec.z, 1e-9), "z: {}", back.z);+}++#[test]+fn rodrigues_identity_stays_identity() {+ let mat = rodrigues_to_mat(Vector3::zeros());+ for r in 0..3 {+ for c in 0..3 {+ let want = if r == c { 1.0 } else { 0.0 };+ assert!(approx(mat[(r, c)], want, 1e-12), "m[{r}{c}]={}", mat[(r, c)]);+ }+ }+ let back = mat_to_rodrigues(&Matrix3::identity());+ assert!(back.norm() < 1e-9, "norm {}", back.norm());+}++#[test]+fn camera_k_matrix_has_expected_shape() {+ let params = CameraParams {+ focal: 800.0,+ aspect: 1.0,+ ppx: 320.0,+ ppy: 240.0,+ r: Matrix3::identity(),+ };+ let k = params.k();+ assert!(approx(k[(0, 0)], 800.0, 1e-9));+ assert!(approx(k[(1, 1)], 800.0, 1e-9));+ assert!(approx(k[(0, 2)], 320.0, 1e-9));+ assert!(approx(k[(1, 2)], 240.0, 1e-9));+ assert!(approx(k[(2, 2)], 1.0, 1e-12));+ assert!(approx(k[(0, 1)], 0.0, 1e-12));+}++#[test]+fn homography_recovers_translation() {+ let a = vec![(0.0f32, 0.0f32), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0), (5.0, 5.0), (15.0, 5.0)];+ let b: Vec<(f32, f32)> = a.iter().map(|(x, y)| (x + 3.0, y + 4.0)).collect();+ let (h, inliers) = find_homography_ransac(&a, &b, 200, 2.0).expect("homography");+ assert!(inliers >= 4, "inliers {inliers}");+ assert!(approx(h[(0, 2)], 3.0, 0.5), "tx {}", h[(0, 2)]);+ assert!(approx(h[(1, 2)], 4.0, 0.5), "ty {}", h[(1, 2)]);+ assert_eq!(transfer_inliers(&h, &a, &b, 2.0).len(), inliers);+}++#[test]+fn rgba_sample_resize_and_gray_behave() {+ let mut img = Rgba::new(4, 4);+ img.set(1, 1, [255, 0, 0, 255]);+ assert_eq!(img.get(1, 1), [255, 0, 0, 255]);+ assert!(img.sample(-1.0, 0.0).is_none());+ assert!(img.sample(99.0, 99.0).is_none());+ let clear = Rgba::new(2, 2);+ assert!(clear.sample(0.5, 0.5).is_none(), "fully transparent has no data");+ let small = img.resized(2, 2);+ assert_eq!((small.w, small.h), (2, 2));+ let gray = to_gray(&img);+ assert_eq!((gray.w, gray.h), (4, 4));+ assert_eq!(gray.px[1 * 4 + 1], ((255u32 * 77) >> 8) as u8);+}
cast/src/androidTest/java/com/vayunmathur/cast/ui/CastHomeTest.kt
diff --git a/cast/src/androidTest/java/com/vayunmathur/cast/ui/CastHomeTest.kt b/cast/src/androidTest/java/com/vayunmathur/cast/ui/CastHomeTest.ktnew file mode 100644index 0000000000..4bed6bc37e--- /dev/null+++ b/cast/src/androidTest/java/com/vayunmathur/cast/ui/CastHomeTest.kt@@ -0,0 +1,129 @@+package com.vayunmathur.cast.ui++import android.app.UiAutomation+import android.content.Intent+import android.content.pm.PackageManager+import androidx.test.ext.junit.runners.AndroidJUnit4+import androidx.test.platform.app.InstrumentationRegistry+import androidx.test.uiautomator.By+import androidx.test.uiautomator.UiDevice+import androidx.test.uiautomator.Until+import java.io.IOException+import org.junit.Assert.assertEquals+import org.junit.Assert.assertNotNull+import org.junit.Assert.assertNull+import org.junit.Test+import org.junit.runner.RunWith++/**+ * Journey: launch onto the television picker, the list body renders, scroll the list.+ *+ * Cast is a single-screen app rooted on the TV picker; the launcher entry is an+ * activity-alias (LauncherAlias -> MainActivity) which getLaunchIntentForPackage+ * resolves, so the standard launch path applies. An empty install shows either the+ * scanning row or the no-devices empty state, then a swipe proves the list holds+ * the screen without crashing.+ *+ * UiDevice polling, not compose-test: compose's Espresso idle-sync reflects on+ * hidden InputManager APIs that no longer exist on current releases, so every+ * compose-rule test dies before its first line. Text polling works for Compose+ * and non-Compose screens alike.+ */+@RunWith(AndroidJUnit4::class)+class CastHomeTest {++ @Test+ fun deviceList_rendersBody_scrollKeepsHeading() {+ val instrumentation = InstrumentationRegistry.getInstrumentation()+ val device = UiDevice.getInstance(instrumentation)+ val targetContext = instrumentation.targetContext+ val packageName = targetContext.packageName++ grantAllRequestedPermissions(instrumentation.uiAutomation, targetContext.packageManager, packageName)++ val intent = targetContext.packageManager.getLaunchIntentForPackage(packageName)+ assertNotNull("no launcher intent for $packageName", intent)+ intent!!.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK)+ targetContext.startActivity(intent)++ // Past the permission screen: the gate wall never appears and the picker heading shows.+ assertNull(+ "permission gate is showing; grants did not clear it",+ device.wait(Until.findObject(By.text(PERMISSION_GATE_TITLE)), GATE_TIMEOUT_MS),+ )+ assertNotNull(+ "device list never appeared; the app may have crashed on launch",+ device.wait(Until.findObject(By.text(DEVICES_HEADING)), CONTENT_TIMEOUT_MS),+ )+ // The list body rendered: either the scanning row or the no-devices empty state.+ val empty = device.wait(Until.findObject(By.text(NO_DEVICES_LABEL)), SHORT_TIMEOUT_MS)+ val scanning = if (empty == null) {+ device.wait(Until.findObject(By.text(SEARCHING_LABEL)), SHORT_TIMEOUT_MS)+ } else {+ null+ }+ assertNotNull("device list body never appeared", empty ?: scanning)++ // Core interaction: scroll the list; the heading survives the gesture.+ val width = device.displayWidth+ val height = device.displayHeight+ device.swipe(width / 2, (height * 0.7).toInt(), width / 2, (height * 0.3).toInt(), 20)+ assertNotNull(+ "picker heading is gone after scrolling the list",+ device.wait(Until.findObject(By.text(DEVICES_HEADING)), CONTENT_TIMEOUT_MS),+ )+ // Still alive in front: the process did not crash after painting content.+ assertEquals(packageName, device.currentPackageName)+ }++ private fun grantAllRequestedPermissions(+ uiAutomation: UiAutomation,+ packageManager: PackageManager,+ packageName: String,+ ) {+ val info = try {+ packageManager.getPackageInfo(packageName, PackageManager.GET_PERMISSIONS)+ } catch (e: PackageManager.NameNotFoundException) {+ throw AssertionError("package $packageName not installed", e)+ }+ for (permission in info.requestedPermissions.orEmpty()) {+ try {+ uiAutomation.executeShellCommand("pm grant $packageName $permission").close()+ } catch (ignored: SecurityException) {+ // Not a headlessly grantable permission: nothing to do.+ } catch (ignored: IOException) {+ // Shell pipe failed: the permission stays ungranted and the+ // content assertions below report it.+ }+ }+ for (command in SPECIAL_ACCESS_COMMANDS) {+ try {+ uiAutomation.executeShellCommand(command.format(packageName)).close()+ } catch (ignored: SecurityException) {+ // Appop missing on this release: the gate assertion reports it.+ } catch (ignored: IOException) {+ // Shell pipe failed: the gate assertion below reports it.+ }+ }+ }++ private companion object {+ private const val CONTENT_TIMEOUT_MS = 15_000L+ private const val GATE_TIMEOUT_MS = 5_000L+ private const val SHORT_TIMEOUT_MS = 5_000L+ private const val DEVICES_HEADING = "Televisions"+ private const val NO_DEVICES_LABEL = "No televisions found"+ private const val SEARCHING_LABEL = "Searching for televisions."+ private const val PERMISSION_GATE_TITLE = "Grant Required Permissions"++ /**+ * Special access behind some apps' gates: exact alarms + full-screen intent+ * have no pm-grantable permission, but the shell can flip their appops.+ * Ignored where the appop does not exist; the gate assertion reports it.+ */+ private val SPECIAL_ACCESS_COMMANDS = arrayOf(+ "appops set %s SCHEDULE_EXACT_ALARM allow",+ "appops set %s USE_FULL_SCREEN_INTENT allow",+ )+ }+}
cast/tv/src/test/java/com/vayunmathur/cast/tv/platform/ReceiverNowPlayingGateTest.kt
diff --git a/cast/tv/src/test/java/com/vayunmathur/cast/tv/platform/ReceiverNowPlayingGateTest.kt b/cast/tv/src/test/java/com/vayunmathur/cast/tv/platform/ReceiverNowPlayingGateTest.ktnew file mode 100644index 0000000000..4de07974bd--- /dev/null+++ b/cast/tv/src/test/java/com/vayunmathur/cast/tv/platform/ReceiverNowPlayingGateTest.kt@@ -0,0 +1,84 @@+package com.vayunmathur.cast.tv.platform++import com.vayunmathur.cast.protocol.NowPlaying+import com.vayunmathur.cast.protocol.PlaybackState+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull++/**+ * The served-session correlation gate and the overlay clock, apart from any TV framework.+ *+ * The channel is ordered but the phone's producers are not, so a metadata snapshot is stored+ * unconditionally and only shown while it names the resource the player is actually playing.+ */+class ReceiverNowPlayingGateTest {++ private fun state(resourceId: String, playingResourceId: String) = ReceiverUiState(+ nowPlaying = NowPlaying(resourceId = resourceId, title = "Blue Monday"),+ playingResourceId = playingResourceId,+ )++ @Test+ fun `a snapshot naming the playing resource is shown`() {+ assertEquals("Blue Monday", state("track-1", "track-1").nowPlayingForCurrentItem?.title)+ }++ @Test+ fun `a snapshot for a skipped-past track is never shown`() {+ assertNull(state("track-1", "track-2").nowPlayingForCurrentItem)+ }++ @Test+ fun `a snapshot arriving before its play is hidden until the play lands`() {+ val early = state("track-2", "")+ assertNull(early.nowPlayingForCurrentItem)+ assertEquals("Blue Monday", early.copy(playingResourceId = "track-2").nowPlayingForCurrentItem?.title)+ }++ @Test+ fun `a mirrored snapshot with no resource id is always shown`() {+ val mirrored = ReceiverUiState(+ nowPlaying = NowPlaying(title = "Official Video"),+ playingResourceId = "",+ )+ assertEquals("Official Video", mirrored.nowPlayingForCurrentItem?.title)+ }++ @Test+ fun `no snapshot means nothing to show`() {+ assertNull(ReceiverUiState().nowPlayingForCurrentItem)+ }++ @Test+ fun `a playing snapshot advances from the moment it landed`() {+ val snapshot = PlaybackSnapshot(+ state = PlaybackState(30_000, 600_000, playing = true, buffering = false),+ receivedAtMs = 1_000,+ )+ assertEquals(30_500, snapshot.positionAt(1_500))+ }++ @Test+ fun `a paused snapshot holds still however late the panel redraws`() {+ val snapshot = PlaybackSnapshot(+ state = PlaybackState(30_000, 600_000, playing = false, buffering = false),+ receivedAtMs = 1_000,+ )+ assertEquals(30_000, snapshot.positionAt(6_000))+ }++ @Test+ fun `a fresh snapshot re-anchors rather than compounding the last one`() {+ val first = PlaybackSnapshot(+ state = PlaybackState(10_000, 600_000, playing = true, buffering = false),+ receivedAtMs = 1_000,+ )+ assertEquals(10_500, first.positionAt(1_500))+ val second = PlaybackSnapshot(+ state = PlaybackState(3_000, 600_000, playing = true, buffering = false),+ receivedAtMs = 2_000,+ )+ assertEquals(3_500, second.positionAt(2_500))+ }+}
cast/tv/src/test/java/com/vayunmathur/cast/tv/platform/ReceiverPairCodeTest.kt
diff --git a/cast/tv/src/test/java/com/vayunmathur/cast/tv/platform/ReceiverPairCodeTest.kt b/cast/tv/src/test/java/com/vayunmathur/cast/tv/platform/ReceiverPairCodeTest.ktnew file mode 100644index 0000000000..0b2f06ae37--- /dev/null+++ b/cast/tv/src/test/java/com/vayunmathur/cast/tv/platform/ReceiverPairCodeTest.kt@@ -0,0 +1,55 @@+package com.vayunmathur.cast.tv.platform++import com.vayunmathur.cast.protocol.PairCode+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++/**+ * The six digits the TV puts on screen, apart from any TV framework.+ *+ * Six digits are enough only because the proof is transcript-bound and the receiver limits+ * attempts, so the shape of the code and the attempt boundary are pinned here.+ */+class ReceiverPairCodeTest {++ @Test+ fun `the code is six digits`() {+ assertEquals(6, PairCode.DIGITS)+ }++ @Test+ fun `three wrong attempts retire the code on screen`() {+ assertEquals(3, PairCode.MAX_ATTEMPTS)+ }++ @Test+ fun `six digits pass, including all zeros`() {+ assertTrue(PairCode.isWellFormed("123456"))+ assertTrue(PairCode.isWellFormed("000000"))+ }++ @Test+ fun `anything but six digits is refused without an HMAC`() {+ assertFalse(PairCode.isWellFormed("12345"))+ assertFalse(PairCode.isWellFormed("1234567"))+ assertFalse(PairCode.isWellFormed(""))+ }++ @Test+ fun `non-digits are refused, even at the right length`() {+ assertFalse(PairCode.isWellFormed("12a456"))+ assertFalse(PairCode.isWellFormed(" 12345"))+ assertFalse(PairCode.isWellFormed("12345 "))+ }++ @Test+ fun `generated codes are six well-formed digits`() {+ repeat(25) {+ val code = PairCode.random()+ assertEquals(PairCode.DIGITS, code.length)+ assertTrue(PairCode.isWellFormed(code), "$code is not well formed")+ }+ }+}
cast/tv/src/test/java/com/vayunmathur/cast/tv/platform/ReceiverPhaseTest.kt
diff --git a/cast/tv/src/test/java/com/vayunmathur/cast/tv/platform/ReceiverPhaseTest.kt b/cast/tv/src/test/java/com/vayunmathur/cast/tv/platform/ReceiverPhaseTest.ktnew file mode 100644index 0000000000..f4c1a6f311--- /dev/null+++ b/cast/tv/src/test/java/com/vayunmathur/cast/tv/platform/ReceiverPhaseTest.kt@@ -0,0 +1,97 @@+package com.vayunmathur.cast.tv.platform++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++/**+ * The receiver's screen states, apart from any TV framework.+ *+ * Phases are plain data; the controller moves between them on sockets,+ * so the naming, defaults and source-name choice are pinned here.+ */+class ReceiverPhaseTest {++ @Test+ fun `pairing shows who is pairing and what to type`() {+ val phase = ReceiverPhase.Pairing(senderName = "Pixel 9", code = "123456", attemptsLeft = 3)+ assertEquals("Pixel 9", phase.senderName)+ assertEquals("123456", phase.code)+ assertEquals(3, phase.attemptsLeft)+ }++ @Test+ fun `pairing starts with the code unchanged`() {+ val phase = ReceiverPhase.Pairing(senderName = "Pixel 9", code = "123456", attemptsLeft = 3)+ assertFalse(phase.codeChanged)+ }++ @Test+ fun `pairing can flag that the code was replaced`() {+ val phase = ReceiverPhase.Pairing(+ senderName = "Pixel 9",+ code = "654321",+ attemptsLeft = 3,+ codeChanged = true,+ )+ assertTrue(phase.codeChanged)+ }++ @Test+ fun `mirroring names the app when one is casting`() {+ val phase = ReceiverPhase.Mirroring(+ senderName = "Pixel 9",+ width = 1920,+ height = 1080,+ appLabel = "YouPipe",+ )+ assertEquals("YouPipe", phase.sourceName)+ }++ @Test+ fun `mirroring falls back to the phone for a screen mirror`() {+ val phase = ReceiverPhase.Mirroring(senderName = "Pixel 9", width = 1080, height = 2400)+ assertEquals("Pixel 9", phase.sourceName)+ }++ @Test+ fun `mirroring treats blank app label as a screen mirror`() {+ val phase = ReceiverPhase.Mirroring(+ senderName = "Pixel 9",+ width = 1080,+ height = 2400,+ appLabel = " ",+ )+ assertEquals("Pixel 9", phase.sourceName)+ }++ @Test+ fun `mirroring defaults to video with unknown rate`() {+ val phase = ReceiverPhase.Mirroring(senderName = "Pixel 9", width = 1920, height = 1080)+ assertTrue(phase.hasVideo)+ assertEquals(0f, phase.frameRate)+ }++ @Test+ fun `audio-only mirroring carries no picture`() {+ val phase = ReceiverPhase.Mirroring(+ senderName = "Pixel 9",+ width = 0,+ height = 0,+ hasVideo = false,+ )+ assertFalse(phase.hasVideo)+ }++ @Test+ fun `each failure names a different answer`() {+ val reasons = ReceiverFailure.values().map { ReceiverPhase.Failed(it).reason }+ assertEquals(ReceiverFailure.values().toList(), reasons)+ }++ @Test+ fun `connected keeps the sender name`() {+ assertEquals("Pixel 9", ReceiverPhase.Connected("Pixel 9").senderName)+ }+}
cast/tv/src/test/java/com/vayunmathur/cast/tv/platform/ReceiverPlayoutQueueTest.kt
diff --git a/cast/tv/src/test/java/com/vayunmathur/cast/tv/platform/ReceiverPlayoutQueueTest.kt b/cast/tv/src/test/java/com/vayunmathur/cast/tv/platform/ReceiverPlayoutQueueTest.ktnew file mode 100644index 0000000000..cb17b0634f--- /dev/null+++ b/cast/tv/src/test/java/com/vayunmathur/cast/tv/platform/ReceiverPlayoutQueueTest.kt@@ -0,0 +1,77 @@+package com.vayunmathur.cast.tv.platform++import com.vayunmathur.cast.protocol.DecodableFrame+import com.vayunmathur.cast.protocol.FrameId+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull++/**+ * The receiver's playout queue, apart from any TV framework.+ *+ * Scheduling is by RTP-timestamp delta from the first frame, so playout follows capture+ * spacing rather than arrival spacing, and a mapping that has drifted a full buffer off+ * the target delay is re-established on the newest frame.+ */+class ReceiverPlayoutQueueTest {++ private fun frame(id: Long, rtpTimestamp: Long) = DecodableFrame(+ frameId = FrameId(id),+ rtpTimestamp = rtpTimestamp,+ isKeyFrame = id == 0L,+ payload = byteArrayOf(id.toByte()),+ )++ @Test+ fun `an empty queue has nothing due`() {+ assertNull(PlayoutQueue(targetDelayMs = 150, timebase = 1_000).due(1_000))+ }++ @Test+ fun `the first frame is due one target delay after it arrives`() {+ val queue = PlayoutQueue(targetDelayMs = 150, timebase = 1_000)+ queue.add(frame(0, 0), 1_000)+ assertNull(queue.due(1_000))+ assertEquals(0L, queue.due(1_150)?.frameId?.value)+ assertNull(queue.due(1_150))+ }++ @Test+ fun `frames come out in order at their capture spacing`() {+ val queue = PlayoutQueue(targetDelayMs = 150, timebase = 1_000)+ queue.add(frame(0, 0), 1_000)+ queue.add(frame(1, 30), 1_000)+ assertEquals(0L, queue.due(1_150)?.frameId?.value)+ assertNull(queue.due(1_150))+ assertEquals(1, queue.depth)+ assertEquals(1L, queue.due(1_180)?.frameId?.value)+ }++ @Test+ fun `a mapping that drifted far ahead is re-established on the newest frame`() {+ val queue = PlayoutQueue(targetDelayMs = 150, timebase = 1_000)+ queue.add(frame(0, 0), 0)+ queue.add(frame(1, 100_000), 10)+ assertEquals(1, queue.rebases)+ }++ @Test+ fun `a mapping that drifted far behind is re-established too`() {+ val queue = PlayoutQueue(targetDelayMs = 150, timebase = 1_000)+ queue.add(frame(0, 0), 0)+ queue.add(frame(1, 0), 1_000)+ assertEquals(1, queue.rebases)+ }++ @Test+ fun `clearing drops everything and re-establishes the mapping on the next frame`() {+ val queue = PlayoutQueue(targetDelayMs = 150, timebase = 1_000)+ queue.add(frame(0, 0), 1_000)+ queue.clear()+ assertEquals(0, queue.depth)+ assertNull(queue.due(10_000))+ queue.add(frame(5, 5_000), 2_000)+ assertNull(queue.due(2_000))+ assertEquals(5L, queue.due(2_150)?.frameId?.value)+ }+}
clock/src/androidTest/java/com/vayunmathur/clock/ui/ClockAlarmCreateTest.kt
diff --git a/clock/src/androidTest/java/com/vayunmathur/clock/ui/ClockAlarmCreateTest.kt b/clock/src/androidTest/java/com/vayunmathur/clock/ui/ClockAlarmCreateTest.ktnew file mode 100644index 0000000000..86533b3c30--- /dev/null+++ b/clock/src/androidTest/java/com/vayunmathur/clock/ui/ClockAlarmCreateTest.kt@@ -0,0 +1,153 @@+package com.vayunmathur.clock.ui++import android.app.UiAutomation+import android.content.Intent+import android.content.pm.PackageManager+import androidx.test.ext.junit.runners.AndroidJUnit4+import androidx.test.platform.app.InstrumentationRegistry+import androidx.test.uiautomator.By+import androidx.test.uiautomator.UiDevice+import androidx.test.uiautomator.Until+import java.io.IOException+import org.junit.Assert.assertEquals+import org.junit.Assert.assertNotNull+import org.junit.Assert.assertNull+import org.junit.Test+import org.junit.runner.RunWith++/**+ * Journey: create an alarm with a unique name and assert it appears in the list.+ *+ * Opens the creator from the empty-state button or the add button, names the+ * alarm so the list assertion keys on this run, saves, then waits for the name+ * in the list.+ *+ * UiDevice polling, not compose-test: compose's Espresso idle-sync reflects on+ * hidden InputManager APIs that no longer exist on current releases, so every+ * compose-rule test dies before its first line. Text polling works for Compose+ * and non-Compose screens alike.+ */+@RunWith(AndroidJUnit4::class)+class ClockAlarmCreateTest {++ @Test+ fun createAlarm_appearsInList() {+ val instrumentation = InstrumentationRegistry.getInstrumentation()+ val device = UiDevice.getInstance(instrumentation)+ val targetContext = instrumentation.targetContext+ val packageName = targetContext.packageName++ grantAllRequestedPermissions(+ instrumentation.uiAutomation,+ targetContext.packageManager,+ packageName,+ )++ val intent = targetContext.packageManager.getLaunchIntentForPackage(packageName)+ assertNotNull("no launcher intent for $packageName", intent)+ intent!!.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK)+ targetContext.startActivity(intent)++ // Past the permission screen: the gate wall never appears and the+ // alarms tab is showing.+ assertNull(+ "permission gate is showing; grants did not clear it",+ device.wait(Until.findObject(By.text(PERMISSION_GATE_TITLE)), GATE_TIMEOUT_MS),+ )+ assertNotNull(+ "alarms screen never appeared; the app may have crashed on launch",+ device.wait(Until.findObject(By.text(ALARM_TAB_LABEL)), CONTENT_TIMEOUT_MS),+ )++ // Open the creator: empty-state button on first run, add button after.+ val emptyCta = device.wait(Until.findObject(By.text(EMPTY_STATE_CTA)), GATE_TIMEOUT_MS)+ if (emptyCta != null) {+ emptyCta.click()+ } else {+ val add = device.wait(Until.findObject(By.desc(ADD_DESC)), GATE_TIMEOUT_MS)+ assertNotNull("no alarm creator control found", add)+ add!!.click()+ }++ // The new-alarm dialog is showing.+ assertNotNull(+ "new-alarm dialog never appeared",+ device.wait(Until.findObject(By.text(SAVE_LABEL)), CONTENT_TIMEOUT_MS),+ )++ // Name it so the list assertion keys on this alarm, not an older one.+ val nameHint = device.wait(Until.findObject(By.text(NAME_HINT)), GATE_TIMEOUT_MS)+ assertNotNull("alarm name field never appeared", nameHint)+ nameHint!!.click()+ nameHint.setText(ALARM_NAME)++ val save = device.wait(Until.findObject(By.text(SAVE_LABEL)), GATE_TIMEOUT_MS)+ assertNotNull("save button never appeared", save)+ save!!.click()++ // Dialog closed and the new alarm row is in the list.+ assertNull(+ "new-alarm dialog did not close after save",+ device.wait(Until.findObject(By.text(SAVE_LABEL)), GATE_TIMEOUT_MS),+ )+ assertNotNull(+ "created alarm never appeared in the list",+ device.wait(Until.findObject(By.text(ALARM_NAME)), CONTENT_TIMEOUT_MS),+ )+ // Still alive in front: the process did not crash after saving.+ assertEquals(packageName, device.currentPackageName)+ }++ private fun grantAllRequestedPermissions(+ uiAutomation: UiAutomation,+ packageManager: PackageManager,+ packageName: String,+ ) {+ val info = try {+ packageManager.getPackageInfo(packageName, PackageManager.GET_PERMISSIONS)+ } catch (e: PackageManager.NameNotFoundException) {+ throw AssertionError("package $packageName not installed", e)+ }+ for (permission in info.requestedPermissions.orEmpty()) {+ try {+ uiAutomation.executeShellCommand("pm grant $packageName $permission").close()+ } catch (ignored: SecurityException) {+ // Not a headlessly grantable permission: nothing to do.+ } catch (ignored: IOException) {+ // Shell pipe failed: the permission stays ungranted and the+ // content assertions below report it.+ }+ }+ for (command in SPECIAL_ACCESS_COMMANDS) {+ try {+ uiAutomation.executeShellCommand(command.format(packageName)).close()+ } catch (ignored: SecurityException) {+ // Appop missing on this release: the gate assertion reports it.+ } catch (ignored: IOException) {+ // Shell pipe failed: the gate assertion below reports it.+ }+ }+ }++ private companion object {+ private const val CONTENT_TIMEOUT_MS = 15_000L+ private const val GATE_TIMEOUT_MS = 5_000L+ private const val ALARM_TAB_LABEL = "Alarm"+ private const val PERMISSION_GATE_TITLE = "Grant Required Permissions"+ private const val EMPTY_STATE_CTA = "Set an alarm"+ private const val ADD_DESC = "Add"+ private const val SAVE_LABEL = "Save"+ private const val NAME_HINT = "Alarm name (optional)"+ private const val ALARM_NAME = "Journey Alarm"++ /**+ * Special access behind clock's gate: exact alarms + full-screen intent have+ * no pm-grantable permission, but the shell can flip their appops. Ignored+ * where the appop does not exist; the gate assertion reports it.+ */+ private val SPECIAL_ACCESS_COMMANDS = arrayOf(+ "appops set %s SCHEDULE_EXACT_ALARM allow",+ "appops set %s USE_FULL_SCREEN_INTENT allow",+ )+ }+}
clock/src/androidTest/java/com/vayunmathur/clock/ui/ClockTimerTest.kt
diff --git a/clock/src/androidTest/java/com/vayunmathur/clock/ui/ClockTimerTest.kt b/clock/src/androidTest/java/com/vayunmathur/clock/ui/ClockTimerTest.ktnew file mode 100644index 0000000000..6d86445080--- /dev/null+++ b/clock/src/androidTest/java/com/vayunmathur/clock/ui/ClockTimerTest.kt@@ -0,0 +1,148 @@+package com.vayunmathur.clock.ui++import android.app.UiAutomation+import android.content.Intent+import android.content.pm.PackageManager+import androidx.test.ext.junit.runners.AndroidJUnit4+import androidx.test.platform.app.InstrumentationRegistry+import androidx.test.uiautomator.By+import androidx.test.uiautomator.UiDevice+import androidx.test.uiautomator.Until+import java.io.IOException+import org.junit.Assert.assertEquals+import org.junit.Assert.assertNotNull+import org.junit.Assert.assertNull+import org.junit.Test+import org.junit.runner.RunWith++/**+ * Journey: open the timer tab, enter ten seconds on the keypad, start it, and+ * assert a running timer card is visible.+ *+ * UiDevice polling, not compose-test: compose's Espresso idle-sync reflects on+ * hidden InputManager APIs that no longer exist on current releases, so every+ * compose-rule test dies before its first line. Text polling works for Compose+ * and non-Compose screens alike.+ */+@RunWith(AndroidJUnit4::class)+class ClockTimerTest {++ @Test+ fun timerStart_showsRunningTimer() {+ val instrumentation = InstrumentationRegistry.getInstrumentation()+ val device = UiDevice.getInstance(instrumentation)+ val targetContext = instrumentation.targetContext+ val packageName = targetContext.packageName++ grantAllRequestedPermissions(+ instrumentation.uiAutomation,+ targetContext.packageManager,+ packageName,+ )++ val intent = targetContext.packageManager.getLaunchIntentForPackage(packageName)+ assertNotNull("no launcher intent for $packageName", intent)+ intent!!.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK)+ targetContext.startActivity(intent)++ // Past the permission screen: the gate wall never appears and the+ // alarms tab is showing.+ assertNull(+ "permission gate is showing; grants did not clear it",+ device.wait(Until.findObject(By.text(PERMISSION_GATE_TITLE)), GATE_TIMEOUT_MS),+ )+ assertNotNull(+ "alarms screen never appeared; the app may have crashed on launch",+ device.wait(Until.findObject(By.text(ALARM_TAB_LABEL)), CONTENT_TIMEOUT_MS),+ )++ // Go to the timer tab.+ val timerTab = device.wait(Until.findObject(By.text(TIMER_TAB_LABEL)), CONTENT_TIMEOUT_MS)+ assertNotNull("timer tab never appeared", timerTab)+ timerTab!!.click()++ // Keypad shows while empty; the add button reveals it when timers exist.+ var nameHint = device.wait(Until.findObject(By.text(KEYPAD_NAME_HINT)), GATE_TIMEOUT_MS)+ if (nameHint == null) {+ val add = device.wait(Until.findObject(By.desc(ADD_DESC)), GATE_TIMEOUT_MS)+ assertNotNull("timer keypad never appeared", add)+ add!!.click()+ nameHint = device.wait(Until.findObject(By.text(KEYPAD_NAME_HINT)), CONTENT_TIMEOUT_MS)+ }+ assertNotNull("timer keypad never appeared", nameHint)++ // Enter ten seconds on the keypad, then start.+ val one = device.wait(Until.findObject(By.text(DIGIT_ONE)), GATE_TIMEOUT_MS)+ assertNotNull("timer keypad digit never appeared", one)+ one!!.click()+ val zero = device.wait(Until.findObject(By.text(DIGIT_ZERO)), GATE_TIMEOUT_MS)+ assertNotNull("timer keypad digit never appeared", zero)+ zero!!.click()++ val play = device.wait(Until.findObject(By.desc(PLAY_DESC)), GATE_TIMEOUT_MS)+ assertNotNull("timer start control never appeared", play)+ play!!.click()++ assertNotNull(+ "started timer never appeared",+ device.wait(Until.findObject(By.text(RUNNING_LABEL)), CONTENT_TIMEOUT_MS),+ )+ // Still alive in front: the process did not crash after starting.+ assertEquals(packageName, device.currentPackageName)+ }++ private fun grantAllRequestedPermissions(+ uiAutomation: UiAutomation,+ packageManager: PackageManager,+ packageName: String,+ ) {+ val info = try {+ packageManager.getPackageInfo(packageName, PackageManager.GET_PERMISSIONS)+ } catch (e: PackageManager.NameNotFoundException) {+ throw AssertionError("package $packageName not installed", e)+ }+ for (permission in info.requestedPermissions.orEmpty()) {+ try {+ uiAutomation.executeShellCommand("pm grant $packageName $permission").close()+ } catch (ignored: SecurityException) {+ // Not a headlessly grantable permission: nothing to do.+ } catch (ignored: IOException) {+ // Shell pipe failed: the permission stays ungranted and the+ // content assertions below report it.+ }+ }+ for (command in SPECIAL_ACCESS_COMMANDS) {+ try {+ uiAutomation.executeShellCommand(command.format(packageName)).close()+ } catch (ignored: SecurityException) {+ // Appop missing on this release: the gate assertion reports it.+ } catch (ignored: IOException) {+ // Shell pipe failed: the gate assertion below reports it.+ }+ }+ }++ private companion object {+ private const val CONTENT_TIMEOUT_MS = 15_000L+ private const val GATE_TIMEOUT_MS = 5_000L+ private const val ALARM_TAB_LABEL = "Alarm"+ private const val TIMER_TAB_LABEL = "Timer"+ private const val PERMISSION_GATE_TITLE = "Grant Required Permissions"+ private const val KEYPAD_NAME_HINT = "Timer name (optional)"+ private const val ADD_DESC = "Add"+ private const val PLAY_DESC = "Play"+ private const val DIGIT_ONE = "1"+ private const val DIGIT_ZERO = "0"+ private const val RUNNING_LABEL = "Running"++ /**+ * Special access behind clock's gate: exact alarms + full-screen intent have+ * no pm-grantable permission, but the shell can flip their appops. Ignored+ * where the appop does not exist; the gate assertion reports it.+ */+ private val SPECIAL_ACCESS_COMMANDS = arrayOf(+ "appops set %s SCHEDULE_EXACT_ALARM allow",+ "appops set %s USE_FULL_SCREEN_INTENT allow",+ )+ }+}
code/src/androidTest/java/com/vayunmathur/code/ui/CodeBrowseTest.kt
diff --git a/code/src/androidTest/java/com/vayunmathur/code/ui/CodeBrowseTest.kt b/code/src/androidTest/java/com/vayunmathur/code/ui/CodeBrowseTest.ktnew file mode 100644index 0000000000..db24cd7ec7--- /dev/null+++ b/code/src/androidTest/java/com/vayunmathur/code/ui/CodeBrowseTest.kt@@ -0,0 +1,117 @@+package com.vayunmathur.code.ui++import android.app.UiAutomation+import android.content.Intent+import android.content.pm.PackageManager+import androidx.test.ext.junit.runners.AndroidJUnit4+import androidx.test.platform.app.InstrumentationRegistry+import androidx.test.uiautomator.By+import androidx.test.uiautomator.UiDevice+import androidx.test.uiautomator.Until+import java.io.IOException+import org.junit.Assert.assertEquals+import org.junit.Assert.assertNotNull+import org.junit.Assert.assertNull+import org.junit.Test+import org.junit.runner.RunWith++/**+ * Code browse journey: grants all-files access, launches past the gate, and+ * asserts the editor empty state is showing.+ *+ * UiDevice polling, not compose-test: compose's Espresso idle-sync reflects on+ * hidden InputManager APIs that no longer exist on current releases, so every+ * compose-rule test dies before its first line. Text polling works for Compose+ * and non-Compose screens alike.+ */+@RunWith(AndroidJUnit4::class)+class CodeBrowseTest {++ @Test+ fun launch_grantsAllFiles_showsEditor() {+ val instrumentation = InstrumentationRegistry.getInstrumentation()+ val device = UiDevice.getInstance(instrumentation)+ val targetContext = instrumentation.targetContext+ val packageName = targetContext.packageName++ grantAllRequestedPermissions(+ instrumentation.uiAutomation,+ targetContext.packageManager,+ packageName+ )++ val intent = targetContext.packageManager.getLaunchIntentForPackage(packageName)+ assertNotNull("no launcher intent for $packageName", intent)+ intent!!.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK)+ targetContext.startActivity(intent)++ // Past the permission screen: the gate wall never appears and the+ // empty editor state is showing.+ assertNull(+ "permission gate is showing; grants did not clear it",+ device.wait(Until.findObject(By.text(PERMISSION_GATE_TITLE)), GATE_TIMEOUT_MS),+ )+ assertNotNull(+ "editor never appeared; the app may have crashed on launch",+ device.wait(Until.findObject(By.text(EMPTY_EDITOR_TEXT)), CONTENT_TIMEOUT_MS),+ )+ assertNotNull(+ "folder entry never appeared; the editor did not load",+ device.wait(Until.findObject(By.text(OPEN_FOLDER_LABEL)), CONTENT_TIMEOUT_MS),+ )+ // Still alive in front: the process did not crash after painting content.+ assertEquals(packageName, device.currentPackageName)+ }++ private fun grantAllRequestedPermissions(+ uiAutomation: UiAutomation,+ packageManager: PackageManager,+ packageName: String,+ ) {+ val info = try {+ packageManager.getPackageInfo(packageName, PackageManager.GET_PERMISSIONS)+ } catch (e: PackageManager.NameNotFoundException) {+ throw AssertionError("package $packageName not installed", e)+ }+ for (permission in info.requestedPermissions.orEmpty()) {+ try {+ uiAutomation.executeShellCommand("pm grant $packageName $permission").close()+ } catch (ignored: SecurityException) {+ // Not a headlessly grantable permission: nothing to do.+ } catch (ignored: IOException) {+ // Shell pipe failed: the permission stays ungranted and the+ // content assertions below report it.+ }+ }+ for (command in SPECIAL_ACCESS_COMMANDS) {+ try {+ uiAutomation.executeShellCommand(command.format(packageName)).close()+ } catch (ignored: SecurityException) {+ // Appop missing on this release: the gate assertion reports it.+ } catch (ignored: IOException) {+ // Shell pipe failed: the gate assertion below reports it.+ }+ }+ }++ private companion object {+ private const val CONTENT_TIMEOUT_MS = 15_000L+ private const val GATE_TIMEOUT_MS = 5_000L+ private const val EMPTY_EDITOR_TEXT = "No file open"+ private const val OPEN_FOLDER_LABEL = "Open folder"+ private const val PERMISSION_GATE_TITLE = "Grant Required Permissions"++ /**+ * Special access behind some apps' gates: exact alarms + full-screen intent+ * have no pm-grantable permission, but the shell can flip their appops.+ * Code has no launcher permission dialog for all-files access (settings+ * page only), so MANAGE_EXTERNAL_STORAGE is flipped the same way.+ * Ignored where the appop does not exist; the gate assertion reports it.+ */+ private val SPECIAL_ACCESS_COMMANDS = arrayOf(+ "appops set %s SCHEDULE_EXACT_ALARM allow",+ "appops set %s USE_FULL_SCREEN_INTENT allow",+ "appops set --uid %s MANAGE_EXTERNAL_STORAGE allow",+ )+ }+}
communicate/src/main/rust-mls/tests/mls_edges.rs
diff --git a/communicate/src/main/rust-mls/tests/mls_edges.rs b/communicate/src/main/rust-mls/tests/mls_edges.rsnew file mode 100644index 0000000000..f0df4a2d00--- /dev/null+++ b/communicate/src/main/rust-mls/tests/mls_edges.rs@@ -0,0 +1,102 @@+//! Boundary and malformed-input tests for the communicate MLS crate.+//!+//! Extends `src/tests.rs` without duplicating it: that suite covers identity, snapshot, the+//! happy-path closed loop and garbage framing. These tests cover key-package validation,+//! welcome/message envelope boundaries, member removal, and snapshot/identity parser edges.++use communicate_mls::group;+use communicate_mls::keys;+use communicate_mls::message::{payload_kind, PayloadKind};+use communicate_mls::store::SnapshotProvider;++fn alice_id() -> Vec<u8> {+ keys::serialize_identity(&keys::generate_identity("+15550001111").expect("alice"))+}++fn bob_parts() -> (Vec<u8>, Vec<u8>) {+ let bob = keys::generate_identity("+15550002222").expect("bob");+ (SnapshotProvider::fresh().snapshot(), keys::serialize_identity(&bob))+}++#[test]+fn key_package_rejects_bad_snapshot_and_identity() {+ let (_, bob_id) = bob_parts();+ assert!(group::build_key_package(b"not-a-snapshot-at-all!!!!!!!!!!!!!!", &bob_id).is_err());+ assert!(group::build_key_package(&[], b"short").is_err());+ assert!(group::build_key_package(&[], &[]).is_err());+}++#[test]+fn add_members_rejects_empty_key_packages() {+ let store = SnapshotProvider::fresh().snapshot();+ let alice = alice_id();+ let created = group::create_group(&store, &alice).expect("create");+ assert!(group::add_members(&created.storage, &alice, &created.group_id, &[]).is_err());+}++#[test]+fn create_group_rejects_empty_identity_and_bad_storage() {+ assert!(group::create_group(&[], &[]).is_err());+ assert!(group::create_group(&SnapshotProvider::fresh().snapshot(), b"junk").is_err());+}++#[test]+fn welcome_envelope_boundaries_are_rejected() {+ let (store_bob, bob_id) = bob_parts();+ let alice = alice_id();+ let (store_bob_after, bob_kp) = group::build_key_package(&store_bob, &bob_id).expect("bob kp");+ let created = group::create_group(&[], &alice).expect("create");+ let added =+ group::add_members(&created.storage, &alice, &created.group_id, &[bob_kp]).expect("add");+ assert_eq!(payload_kind(&added.welcome), PayloadKind::Welcome);+ let mut truncated = added.welcome.clone();+ truncated.truncate(added.welcome.len() / 2);+ assert!(group::join_group(&store_bob_after, &truncated).is_err());+ let mut bad_magic = added.welcome.clone();+ bad_magic[0] = b'X';+ assert!(group::join_group(&store_bob_after, &bad_magic).is_err());+ let mut trailing = added.welcome.clone();+ trailing.push(0xFF);+ assert!(group::join_group(&store_bob_after, &trailing).is_err());+ assert!(group::join_group(&store_bob_after, &[]).is_err());+}++#[test]+fn message_envelope_boundaries_are_rejected() {+ let (store_bob, bob_id) = bob_parts();+ let alice = alice_id();+ let (store_bob_after, bob_kp) = group::build_key_package(&store_bob, &bob_id).expect("kp");+ let created = group::create_group(&[], &alice).expect("create");+ let added =+ group::add_members(&created.storage, &alice, &created.group_id, &[bob_kp]).expect("add");+ let (_, bob_gid) = group::join_group(&store_bob_after, &added.welcome).expect("join");+ let enc = group::encrypt(&added.storage, &alice, &created.group_id, b"ping").expect("encrypt");+ assert_eq!(payload_kind(&enc.payload), PayloadKind::Message);+ let mut tampered = enc.payload.clone();+ let last = tampered.len() - 1;+ tampered[last] ^= 1;+ assert!(group::decrypt(&store_bob_after, &bob_gid, &tampered).is_err());+ let mut bad_magic = enc.payload.clone();+ bad_magic[0] = b'X';+ assert!(group::decrypt(&store_bob_after, &bob_gid, &bad_magic).is_err());+ assert!(group::decrypt(&store_bob_after, &bob_gid, &[]).is_err());+ assert!(group::decrypt(&store_bob_after, b"unknown-group", &enc.payload).is_err());+}++#[test]+fn removed_member_can_no_longer_decrypt() {+ let (store_bob, bob_id) = bob_parts();+ let alice = alice_id();+ let (store_bob_after, bob_kp) = group::build_key_package(&store_bob, &bob_id).expect("kp");+ let created = group::create_group(&[], &alice).expect("create");+ let added =+ group::add_members(&created.storage, &alice, &created.group_id, &[bob_kp]).expect("add");+ let (store_bob_joined, bob_gid) =+ group::join_group(&store_bob_after, &added.welcome).expect("join");+ let (storage_after_remove, _commit) =+ group::remove_members(&added.storage, &alice, &created.group_id, &[1]).expect("remove");+ assert!(group::remove_members(&added.storage, &alice, &created.group_id, &[]).is_err());+ let enc = group::encrypt(&storage_after_remove, &alice, &created.group_id, b"after removal")+ .expect("encrypt");+ assert!(group::decrypt(&store_bob_joined, &bob_gid, &enc.payload).is_err());+}
communicate/src/main/rust/tests/signal_edges.rs
diff --git a/communicate/src/main/rust/tests/signal_edges.rs b/communicate/src/main/rust/tests/signal_edges.rsnew file mode 100644index 0000000000..2ec34053fe--- /dev/null+++ b/communicate/src/main/rust/tests/signal_edges.rs@@ -0,0 +1,191 @@+//! Framing, state-logic and boundary tests for the communicate Signal crate.+//!+//! `src/tests.rs` is a placeholder with no coverage, so this file seeds it: pure round trips and+//! malformed-input handling for the wire codec, node codec, crypto primitives and sender-key+//! state machine. Host-only, no JNI involved.++use communicate_signal::crypto;+use communicate_signal::group;+use communicate_signal::group::SenderKeyState;+use communicate_signal::signal::{mark_kyber_pre_key_used, sealed_sender_encrypt};+use communicate_signal::signal::{sealed_sender_decrypt, sealed_sender_decrypt_any};+use communicate_signal::wa_binary::{decode_node, encode_node, Node};+use communicate_signal::wire::{+ PbReader, PbValue, PbWriter, PreKeySignalMessage, SenderKeyDistributionMessage, SenderKeyMessage,+ SignalMessage,+};++fn key_pair() -> ([u8; 32], [u8; 32]) {+ crypto::generate_key_pair(&mut communicate_signal::OsRng::default())+}++#[test]+fn signal_message_mac_round_trip_and_tamper() {+ let (_, pub_a) = key_pair();+ let (_, pub_b) = key_pair();+ let (_, ratchet_pub) = key_pair();+ let cipher = [7u8; 24];+ let mac_key = [0x11u8; 32];+ let msg = SignalMessage::new(&mac_key, &pub_a, &pub_b, &ratchet_pub, 3, 1, &cipher);+ assert!(msg.verify_mac(&mac_key, &pub_a, &pub_b));+ let parsed = SignalMessage::parse(&msg.serialized).expect("parse");+ assert!(parsed.verify_mac(&mac_key, &pub_a, &pub_b));+ assert_eq!(parsed.counter, 3);+ assert_eq!(parsed.previous_counter, 1);+ assert_eq!(parsed.ciphertext, cipher);+ let mut bad_mac = msg.serialized.clone();+ let last = bad_mac.len() - 1;+ bad_mac[last] ^= 1;+ let tampered = SignalMessage::parse(&bad_mac).expect("parse tampered");+ assert!(!tampered.verify_mac(&mac_key, &pub_a, &pub_b));+ assert!(SignalMessage::parse(&[]).is_err());+ assert!(SignalMessage::parse(&msg.serialized[..msg.serialized.len() - 1]).is_err());+}++#[test]+fn prekey_message_round_trip_and_truncated_rejected() {+ let (_, base) = key_pair();+ let (_, ident) = key_pair();+ let original = PreKeySignalMessage {+ registration_id: 4242,+ pre_key_id: Some(7),+ signed_pre_key_id: 9,+ base_key: base,+ identity_key: ident,+ message: vec![1, 2, 3, 4],+ };+ let back = PreKeySignalMessage::parse(&original.serialize()).expect("parse");+ assert_eq!(back.registration_id, 4242);+ assert_eq!(back.pre_key_id, Some(7));+ assert_eq!(back.base_key, base);+ assert_eq!(back.message, vec![1, 2, 3, 4]);+ assert!(PreKeySignalMessage::parse(&[]).is_err());+ let mut truncated = original.serialize();+ truncated.truncate(truncated.len() / 2);+ assert!(PreKeySignalMessage::parse(&truncated).is_err());+}++#[test]+fn sender_key_message_signature_verifies_and_breaks_on_tamper() {+ let (sign_priv, sign_pub) = key_pair();+ let random = [0x22u8; 64];+ let msg = SenderKeyMessage::new(5, 12, b"hello group", &sign_priv, &random);+ assert!(msg.verify_signature(&sign_pub));+ let parsed = SenderKeyMessage::parse(&msg.serialized).expect("parse");+ assert!(parsed.verify_signature(&sign_pub));+ let mut bad = msg.serialized.clone();+ bad[10] ^= 1;+ assert!(!SenderKeyMessage::parse(&bad).map(|m| m.verify_signature(&sign_pub)).unwrap_or(false));+ assert!(SenderKeyMessage::parse(&[]).is_err());+}++#[test]+fn protobuf_reader_round_trips_and_rejects_bad_input() {+ let mut writer = PbWriter::new();+ writer.uint32(1, 300);+ writer.bytes(2, b"payload");+ let mut reader = PbReader::new(&writer.buf);+ let mut seen_varint = false;+ let mut seen_bytes = false;+ while let Some((field, value)) = reader.next_field().expect("field") {+ match (field, value) {+ (1, PbValue::Varint(v)) => {+ assert_eq!(v, 300);+ seen_varint = true;+ }+ (2, PbValue::Bytes(b)) => {+ assert_eq!(b, b"payload");+ seen_bytes = true;+ }+ _ => panic!("unexpected field"),+ }+ }+ assert!(seen_varint && seen_bytes);+ assert!(PbReader::new(&writer.buf[..writer.buf.len() - 2]).next_field().is_err());+ assert!(PbReader::new(&[0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01])+ .next_field()+ .is_err());+ assert!(PbReader::new(&[0x1B]).next_field().is_err(), "wire type 3 is unsupported");+}++#[test]+fn node_codec_round_trips_children_payload_and_malformed_input() {+ let mut parent = Node::new("message");+ parent.attrs.insert("to".into(), "[email protected]".into());+ let mut child = Node::new("body");+ child.data = Some(b"hello".to_vec());+ parent.content.push(child);+ let encoded = encode_node(&parent);+ assert_eq!(encoded[0], 0, "frame flag byte leads");+ assert_eq!(decode_node(&encoded[1..]).expect("decode"), parent);+ assert!(decode_node(&[]).is_err());+ assert!(decode_node(&[0xFF, 0xFF]).is_err());+ let mut cut = encode_node(&Node::new("iq").attr("to", "[email protected]"));+ cut.truncate(cut.len() / 2);+ assert!(decode_node(&cut[1..]).is_err());+}++#[test]+fn crypto_primitives_round_trip_and_reject_tampering() {+ let key = [0x42u8; 32];+ let iv = [0x24u8; 16];+ let plain = b"round trip through cbc";+ let cipher = crypto::aes_cbc_encrypt(&key, &iv, plain);+ assert_eq!(crypto::aes_cbc_decrypt(&key, &iv, &cipher).expect("decrypt"), plain);+ assert!(crypto::aes_cbc_decrypt(&key, &iv, &[]).is_err());+ assert!(crypto::aes_cbc_decrypt(&key, &iv, &[1, 2, 3]).is_err());+ let mut bad_pad = cipher.clone();+ let last = bad_pad.len() - 1;+ bad_pad[last] ^= 1;+ assert!(crypto::aes_cbc_decrypt(&key, &iv, &bad_pad).is_err());+ let (priv_a, pub_a) = key_pair();+ let (_, pub_b) = key_pair();+ let (priv_b, _) = key_pair();+ let shared_ab = crypto::agreement(&priv_a, &pub_b);+ let shared_ba = crypto::agreement(&priv_b, &pub_a);+ assert_ne!(shared_ab, shared_ba, "different private keys give different secrets");+ assert_eq!(shared_ab.len(), 32);+ let mac = crypto::hmac_sha256(&key, plain);+ assert!(crypto::ct_eq(&mac, &crypto::hmac_sha256(&key, plain)));+ assert!(!crypto::ct_eq(&mac, &[0u8; 32]));+ assert!(!crypto::ct_eq(&mac, &mac[..16]));+ assert_eq!(crypto::serialize_public(&pub_a).len(), 33);+ assert_eq!(crypto::parse_public(&crypto::serialize_public(&pub_a)).expect("parse"), pub_a);+ assert!(crypto::parse_public(&[0u8; 5]).is_err());+}++#[test]+fn sender_key_state_encrypt_decrypt_and_rejects_wrong_key_id() {+ let mut rng = communicate_signal::OsRng::default();+ let (own_state, skdm) = group::create(&mut rng);+ let mut sender = own_state.clone();+ let cipher = group::encrypt(&mut rng, &mut sender, b"group hello").expect("encrypt");+ let mut peer = group::process(&skdm).expect("process");+ let plain = group::decrypt(&mut peer, &cipher).expect("decrypt");+ assert_eq!(plain, b"group hello");+ let blob = own_state.serialize();+ let restored = SenderKeyState::deserialize(&blob).expect("record");+ assert_eq!(restored.key_id, own_state.key_id);+ assert!(SenderKeyState::deserialize(&[]).is_err());+ assert!(SenderKeyState::deserialize(&blob[..blob.len() / 2]).is_err());+ let mut wrong_id = SenderKeyDistributionMessage {+ key_id: skdm.key_id ^ 1,+ iteration: skdm.iteration,+ chain_key: skdm.chain_key.clone(),+ signing_key: skdm.signing_key,+ };+ let mut wrong_peer = group::process(&wrong_id).expect("process wrong id");+ assert!(group::decrypt(&mut wrong_peer, &cipher).is_err());+}++#[test]+fn sealed_sender_stub_encrypts_and_rejects_garbage() {+ let cipher = sealed_sender_encrypt(b"sealed hello", "alice");+ assert!(!cipher.is_empty());+ assert_eq!(cipher[0], 1, "sealed stub version byte");+ assert!(sealed_sender_decrypt(&[], Some("alice")).is_err());+ assert!(sealed_sender_decrypt(b"junk", Some("alice")).is_err());+ assert!(sealed_sender_decrypt_any(b"junk").is_err());+ assert!(mark_kyber_pre_key_used(11, 22, b"base-key"));+ assert!(!mark_kyber_pre_key_used(11, 22, b"base-key"), "replay of same base key is rejected");+}
contacts/src/androidTest/java/com/vayunmathur/contacts/ui/ContactsOpenTest.kt
diff --git a/contacts/src/androidTest/java/com/vayunmathur/contacts/ui/ContactsOpenTest.kt b/contacts/src/androidTest/java/com/vayunmathur/contacts/ui/ContactsOpenTest.ktnew file mode 100644index 0000000000..70cf252bf2--- /dev/null+++ b/contacts/src/androidTest/java/com/vayunmathur/contacts/ui/ContactsOpenTest.kt@@ -0,0 +1,179 @@+package com.vayunmathur.contacts.ui++import android.app.UiAutomation+import android.content.ContentResolver+import android.content.Intent+import android.content.pm.PackageManager+import android.provider.ContactsContract+import androidx.test.ext.junit.runners.AndroidJUnit4+import androidx.test.platform.app.InstrumentationRegistry+import androidx.test.uiautomator.By+import androidx.test.uiautomator.UiDevice+import androidx.test.uiautomator.Until+import java.io.IOException+import org.junit.Assert.assertEquals+import org.junit.Assert.assertNotNull+import org.junit.Assert.assertNull+import org.junit.Test+import org.junit.runner.RunWith++/**+ * Journey: tap a seeded contact row and assert the detail page shows its+ * number.+ *+ * Name and number come from the contacts provider at runtime, so the test keys+ * on the seeded data itself instead of hardcoded strings. The number assertion+ * uses a contains match on the trailing digits so display formatting cannot+ * break it.+ *+ * UiDevice polling, not compose-test: compose's Espresso idle-sync reflects on+ * hidden InputManager APIs that no longer exist on current releases, so every+ * compose-rule test dies before its first line. Text polling works for Compose+ * and non-Compose screens alike.+ */+@RunWith(AndroidJUnit4::class)+class ContactsOpenTest {++ @Test+ fun openSeededContact_showsNumber() {+ val instrumentation = InstrumentationRegistry.getInstrumentation()+ val device = UiDevice.getInstance(instrumentation)+ val targetContext = instrumentation.targetContext+ val packageName = targetContext.packageName++ grantAllRequestedPermissions(+ instrumentation.uiAutomation,+ targetContext.packageManager,+ packageName,+ )++ val intent = targetContext.packageManager.getLaunchIntentForPackage(packageName)+ assertNotNull("no launcher intent for $packageName", intent)+ intent!!.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK)+ targetContext.startActivity(intent)++ // Past the permission screen: the gate wall never appears and the+ // contacts list search field is showing.+ assertNull(+ "permission gate is showing; grants did not clear it",+ device.wait(Until.findObject(By.text(PERMISSION_GATE_TITLE)), GATE_TIMEOUT_MS),+ )+ assertNotNull(+ "contacts list never appeared; the app may have crashed on launch",+ device.wait(Until.findObject(By.text(SEARCH_PLACEHOLDER)), CONTENT_TIMEOUT_MS),+ )++ val seeded = readSeededContactWithNumber(targetContext.contentResolver)+ assertNotNull("no seeded contact found on the device", seeded)+ val fullName = seeded!!.first+ val numberTail = seeded.second++ val row = device.wait(Until.findObject(By.text(fullName)), CONTENT_TIMEOUT_MS)+ assertNotNull("seeded contact row never appeared", row)+ row!!.click()++ if (numberTail != null) {+ assertNotNull(+ "contact number never appeared on the detail page",+ device.wait(Until.findObject(By.textContains(numberTail)), CONTENT_TIMEOUT_MS),+ )+ } else {+ assertNotNull(+ "phone section never appeared on the detail page",+ device.wait(Until.findObject(By.text(PHONE_SECTION)), CONTENT_TIMEOUT_MS),+ )+ }+ // Still alive in front: the process did not crash after opening.+ assertEquals(packageName, device.currentPackageName)+ }++ /**+ * First seeded contact with a phone number: full name plus the trailing+ * digits of its first number, or null digits when numbers are missing.+ */+ private fun readSeededContactWithNumber(resolver: ContentResolver): Pair<String, String?>? {+ val uri = ContactsContract.Contacts.CONTENT_URI+ val projection = arrayOf(+ ContactsContract.Contacts._ID,+ ContactsContract.Contacts.DISPLAY_NAME,+ )+ val sort = ContactsContract.Contacts.DISPLAY_NAME + " ASC"+ resolver.query(uri, projection, null, null, sort)?.use { cursor ->+ val idIndex = cursor.getColumnIndex(ContactsContract.Contacts._ID)+ val nameIndex = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)+ while (cursor.moveToNext()) {+ val name = if (nameIndex >= 0) cursor.getString(nameIndex).orEmpty().trim() else ""+ if (name.length < 2 || idIndex < 0) continue+ val tail = readNumberTail(resolver, cursor.getLong(idIndex))+ return Pair(name, tail)+ }+ }+ return null+ }++ private fun readNumberTail(resolver: ContentResolver, contactId: Long): String? {+ val uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI+ val projection = arrayOf(ContactsContract.CommonDataKinds.Phone.NUMBER)+ val selection = ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?"+ val args = arrayOf(contactId.toString())+ resolver.query(uri, projection, selection, args, null)?.use { cursor ->+ val index = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)+ while (cursor.moveToNext()) {+ val digits = if (index >= 0) cursor.getString(index).orEmpty() else ""+ val tail = digits.filter { it.isDigit() }.takeLast(NUMBER_TAIL_LENGTH)+ if (tail.length == NUMBER_TAIL_LENGTH) return tail+ }+ }+ return null+ }++ private fun grantAllRequestedPermissions(+ uiAutomation: UiAutomation,+ packageManager: PackageManager,+ packageName: String,+ ) {+ val info = try {+ packageManager.getPackageInfo(packageName, PackageManager.GET_PERMISSIONS)+ } catch (e: PackageManager.NameNotFoundException) {+ throw AssertionError("package $packageName not installed", e)+ }+ for (permission in info.requestedPermissions.orEmpty()) {+ try {+ uiAutomation.executeShellCommand("pm grant $packageName $permission").close()+ } catch (ignored: SecurityException) {+ // Not a headlessly grantable permission: nothing to do.+ } catch (ignored: IOException) {+ // Shell pipe failed: the permission stays ungranted and the+ // content assertions below report it.+ }+ }+ for (command in SPECIAL_ACCESS_COMMANDS) {+ try {+ uiAutomation.executeShellCommand(command.format(packageName)).close()+ } catch (ignored: SecurityException) {+ // Appop missing on this release: the gate assertion reports it.+ } catch (ignored: IOException) {+ // Shell pipe failed: the gate assertion below reports it.+ }+ }+ }++ private companion object {+ private const val CONTENT_TIMEOUT_MS = 15_000L+ private const val GATE_TIMEOUT_MS = 5_000L+ private const val NUMBER_TAIL_LENGTH = 7+ private const val SEARCH_PLACEHOLDER = "Search contacts"+ private const val PHONE_SECTION = "Phone"+ private const val PERMISSION_GATE_TITLE = "Grant Required Permissions"++ /**+ * Special access behind some apps' gates: exact alarms + full-screen intent+ * have no pm-grantable permission, but the shell can flip their appops.+ * Ignored where the appop does not exist; the gate assertion reports it.+ */+ private val SPECIAL_ACCESS_COMMANDS = arrayOf(+ "appops set %s SCHEDULE_EXACT_ALARM allow",+ "appops set %s USE_FULL_SCREEN_INTENT allow",+ )+ }+}
contacts/src/androidTest/java/com/vayunmathur/contacts/ui/ContactsSearchTest.kt
diff --git a/contacts/src/androidTest/java/com/vayunmathur/contacts/ui/ContactsSearchTest.kt b/contacts/src/androidTest/java/com/vayunmathur/contacts/ui/ContactsSearchTest.ktnew file mode 100644index 0000000000..19f7e26940--- /dev/null+++ b/contacts/src/androidTest/java/com/vayunmathur/contacts/ui/ContactsSearchTest.kt@@ -0,0 +1,158 @@+package com.vayunmathur.contacts.ui++import android.app.UiAutomation+import android.content.ContentResolver+import android.content.Intent+import android.content.pm.PackageManager+import android.provider.ContactsContract+import androidx.test.ext.junit.runners.AndroidJUnit4+import androidx.test.platform.app.InstrumentationRegistry+import androidx.test.uiautomator.By+import androidx.test.uiautomator.UiDevice+import androidx.test.uiautomator.Until+import java.io.IOException+import org.junit.Assert.assertEquals+import org.junit.Assert.assertNotNull+import org.junit.Assert.assertNull+import org.junit.Test+import org.junit.runner.RunWith++/**+ * Journey: read a seeded device contact, type its first name into search, and+ * assert the full-name row appears.+ *+ * The name comes from the contacts provider at runtime, so the test keys on+ * the seeded data itself instead of a hardcoded string.+ *+ * UiDevice polling, not compose-test: compose's Espresso idle-sync reflects on+ * hidden InputManager APIs that no longer exist on current releases, so every+ * compose-rule test dies before its first line. Text polling works for Compose+ * and non-Compose screens alike.+ */+@RunWith(AndroidJUnit4::class)+class ContactsSearchTest {++ @Test+ fun search_seededName_showsRow() {+ val instrumentation = InstrumentationRegistry.getInstrumentation()+ val device = UiDevice.getInstance(instrumentation)+ val targetContext = instrumentation.targetContext+ val packageName = targetContext.packageName++ grantAllRequestedPermissions(+ instrumentation.uiAutomation,+ targetContext.packageManager,+ packageName,+ )++ val intent = targetContext.packageManager.getLaunchIntentForPackage(packageName)+ assertNotNull("no launcher intent for $packageName", intent)+ intent!!.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK)+ targetContext.startActivity(intent)++ // Past the permission screen: the gate wall never appears and the+ // contacts tabs are showing (first paint is the tab row, not the+ // search field — verified on device via uiautomator dump).+ assertNull(+ "permission gate is showing; grants did not clear it",+ device.wait(Until.findObject(By.text(PERMISSION_GATE_TITLE)), GATE_TIMEOUT_MS),+ )+ assertNotNull(+ "contacts list never appeared; the app may have crashed on launch",+ device.wait(Until.findObject(By.text(CONTACTS_TAB)), CONTENT_TIMEOUT_MS),+ )++ // Seeded query: full name for the row assertion, first token typed in.+ val seeded = readSeededContact(targetContext.contentResolver)+ assertNotNull("no seeded contact found on the device", seeded)+ val fullName = seeded!!.first+ val token = seeded.second++ // The search field is part of first paint (proven by LaunchNoCrashTest):+ // tap it directly. Do NOT tap the Search action icon — that toggles+ // search UI state and collapses the field we need. Note the field is+ // an EditText with EMPTY text: the "Search contacts" Compose hint+ // never reaches the accessibility tree, so key on the class.+ val searchField = device.wait(Until.findObject(By.clazz(EDIT_TEXT_CLASS)), GATE_TIMEOUT_MS)+ assertNotNull("search field never appeared", searchField)+ searchField!!.click()+ searchField.setText(token)++ // The row carries the full name while the field holds only the token,+ // so this proves the row filtered in rather than the field itself.+ assertNotNull(+ "seeded contact row never appeared for the search query",+ device.wait(Until.findObject(By.text(fullName)), CONTENT_TIMEOUT_MS),+ )+ // Still alive in front: the process did not crash after searching.+ assertEquals(packageName, device.currentPackageName)+ }++ /**+ * First seeded contact by display name: full name plus its first long+ * token, which is what gets typed into search.+ */+ private fun readSeededContact(resolver: ContentResolver): Pair<String, String>? {+ val uri = ContactsContract.Contacts.CONTENT_URI+ val projection = arrayOf(ContactsContract.Contacts.DISPLAY_NAME)+ val sort = ContactsContract.Contacts.DISPLAY_NAME + " ASC"+ resolver.query(uri, projection, null, null, sort)?.use { cursor ->+ val index = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)+ while (cursor.moveToNext()) {+ val name = if (index >= 0) cursor.getString(index).orEmpty().trim() else ""+ val token = name.split(' ').firstOrNull { it.length >= 2 }.orEmpty()+ if (name.length >= 2 && token.isNotEmpty()) return Pair(name, token)+ }+ }+ return null+ }++ private fun grantAllRequestedPermissions(+ uiAutomation: UiAutomation,+ packageManager: PackageManager,+ packageName: String,+ ) {+ val info = try {+ packageManager.getPackageInfo(packageName, PackageManager.GET_PERMISSIONS)+ } catch (e: PackageManager.NameNotFoundException) {+ throw AssertionError("package $packageName not installed", e)+ }+ for (permission in info.requestedPermissions.orEmpty()) {+ try {+ uiAutomation.executeShellCommand("pm grant $packageName $permission").close()+ } catch (ignored: SecurityException) {+ // Not a headlessly grantable permission: nothing to do.+ } catch (ignored: IOException) {+ // Shell pipe failed: the permission stays ungranted and the+ // content assertions below report it.+ }+ }+ for (command in SPECIAL_ACCESS_COMMANDS) {+ try {+ uiAutomation.executeShellCommand(command.format(packageName)).close()+ } catch (ignored: SecurityException) {+ // Appop missing on this release: the gate assertion reports it.+ } catch (ignored: IOException) {+ // Shell pipe failed: the gate assertion below reports it.+ }+ }+ }++ private companion object {+ private const val CONTENT_TIMEOUT_MS = 15_000L+ private const val GATE_TIMEOUT_MS = 5_000L+ private const val CONTACTS_TAB = "Contacts"+ private const val EDIT_TEXT_CLASS = "android.widget.EditText"+ private const val PERMISSION_GATE_TITLE = "Grant Required Permissions"++ /**+ * Special access behind some apps' gates: exact alarms + full-screen intent+ * have no pm-grantable permission, but the shell can flip their appops.+ * Ignored where the appop does not exist; the gate assertion reports it.+ */+ private val SPECIAL_ACCESS_COMMANDS = arrayOf(+ "appops set %s SCHEDULE_EXACT_ALARM allow",+ "appops set %s USE_FULL_SCREEN_INTENT allow",+ )+ }+}
contacts/src/androidTest/java/com/vayunmathur/contacts/ui/LaunchNoCrashTest.kt
diff --git a/contacts/src/androidTest/java/com/vayunmathur/contacts/ui/LaunchNoCrashTest.kt b/contacts/src/androidTest/java/com/vayunmathur/contacts/ui/LaunchNoCrashTest.ktindex f9cee8dcb8..28d3461286 100644--- a/contacts/src/androidTest/java/com/vayunmathur/contacts/ui/LaunchNoCrashTest.kt+++ b/contacts/src/androidTest/java/com/vayunmathur/contacts/ui/LaunchNoCrashTest.kt@@ -47,14 +47,16 @@ class LaunchNoCrashTest { targetContext.startActivity(intent) // Past the permission screen: the gate wall never appears and the- // contacts list search field is showing.+ // contacts tab row is showing ("Contacts" label; verified on device+ // via uiautomator dump — the search hint text never reaches the+ // accessibility tree, so the tab label is the stable marker). assertNull( "permission gate is showing; grants did not clear it", device.wait(Until.findObject(By.text(PERMISSION_GATE_TITLE)), GATE_TIMEOUT_MS), ) assertNotNull( "contacts list never appeared; the app may have crashed on launch",- device.wait(Until.findObject(By.text(SEARCH_PLACEHOLDER)), CONTENT_TIMEOUT_MS),+ device.wait(Until.findObject(By.text(CONTACTS_TAB)), CONTENT_TIMEOUT_MS), ) // Still alive in front: the process did not crash after painting content. assertEquals(packageName, device.currentPackageName)@@ -94,7 +96,7 @@ class LaunchNoCrashTest { private companion object { private const val CONTENT_TIMEOUT_MS = 15_000L private const val GATE_TIMEOUT_MS = 5_000L- private const val SEARCH_PLACEHOLDER = "Search contacts"+ private const val CONTACTS_TAB = "Contacts" private const val PERMISSION_GATE_TITLE = "Grant Required Permissions" /**
contacts/src/test/java/com/vayunmathur/contacts/pure/ContactGroupLogicTest.kt
diff --git a/contacts/src/test/java/com/vayunmathur/contacts/pure/ContactGroupLogicTest.kt b/contacts/src/test/java/com/vayunmathur/contacts/pure/ContactGroupLogicTest.ktnew file mode 100644index 0000000000..c41cd28132--- /dev/null+++ b/contacts/src/test/java/com/vayunmathur/contacts/pure/ContactGroupLogicTest.kt@@ -0,0 +1,135 @@+package com.vayunmathur.contacts.pure++import com.vayunmathur.contacts.data.Contact+import com.vayunmathur.contacts.data.ContactDetails+import com.vayunmathur.contacts.data.ContactGroup+import com.vayunmathur.contacts.data.GroupMembership+import com.vayunmathur.contacts.data.SimContact+import com.vayunmathur.contacts.data.SimContactsDataSource+import com.vayunmathur.contacts.data.isDefaultLocalAccount+import com.vayunmathur.contacts.data.isLocalAccountType+import com.vayunmathur.contacts.data.isSimAccountType+import com.vayunmathur.contacts.ui.contactGroupsOf+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++/**+ * Pins contact group membership and account-type logic: group lookup by+ * id with blank-name filtering, account-key encoding, SIM/local account+ * classification and deterministic SIM synthetic ids.+ *+ * contactGroupsOf and the SimContacts helpers are pure and called+ * directly; the ViewModel's key encoding is mirrored (it is private).+ */+class ContactGroupLogicTest {+ private fun memberOf(vararg groupIds: Long): Contact =+ Contact(+ 1, null, null, false,+ ContactDetails.empty().copy(groups = groupIds.map { GroupMembership(0, it) }),+ )++ private fun accountKey(type: String?, name: String?): String = "${type ?: ""}|${name ?: ""}"++ private fun encodedAccountKey(type: String?, name: String?): String {+ fun enc(raw: String): String =+ raw.replace("%", "%25").replace("|", "%7C").replace(",", "%2C")+ return "${enc(type ?: "")}|${enc(name ?: "")}"+ }++ @Test+ fun groupsOfReturnsOnlyMemberGroups() {+ val all = listOf(ContactGroup(1, "Friends"), ContactGroup(2, "Family"), ContactGroup(3, "Work"))+ assertEquals(listOf(ContactGroup(1, "Friends")), contactGroupsOf(memberOf(1), all))+ }++ @Test+ fun groupsWithBlankNamesAreExcluded() {+ val all = listOf(ContactGroup(1, ""), ContactGroup(2, " "), ContactGroup(3, "Kept"))+ assertEquals(listOf(ContactGroup(3, "Kept")), contactGroupsOf(memberOf(1, 2, 3), all))+ }++ @Test+ fun contactWithNoGroupsGetsNone() {+ val all = listOf(ContactGroup(1, "Friends"))+ assertEquals(emptyList(), contactGroupsOf(memberOf(), all))+ }++ @Test+ fun unknownGroupIdsAreIgnored() {+ val all = listOf(ContactGroup(1, "Friends"))+ assertEquals(emptyList(), contactGroupsOf(memberOf(99), all))+ }++ @Test+ fun accountKeyJoinsTypeAndName() {+ assertEquals("google|x", accountKey("google", "x"))+ assertEquals("|", accountKey(null, null))+ assertEquals("t|", accountKey("t", null))+ }++ @Test+ fun encodedKeyEscapesSeparatorChars() {+ assertEquals("a%7Cb%2Cc%25d|n", encodedAccountKey("a|b,c%d", "n"))+ }++ @Test+ fun encodedKeyMatchesPlainKeyWhenNoSpecials() {+ assertEquals(accountKey("google", "x"), encodedAccountKey("google", "x"))+ }++ @Test+ fun simAccountTypeMatchesOnlySimType() {+ assertTrue(isSimAccountType("com.vayunmathur.contacts.sim"))+ assertFalse(isSimAccountType("com.google"))+ assertFalse(isSimAccountType(null))+ assertFalse(isSimAccountType(""))+ }++ @Test+ fun localAccountTypeCoversNullBlankAndLocal() {+ assertTrue(isLocalAccountType(null))+ assertTrue(isLocalAccountType(""))+ assertTrue(isLocalAccountType("com.vayunmathur.contacts.local"))+ assertFalse(isLocalAccountType("com.google"))+ assertFalse(isLocalAccountType("com.vayunmathur.contacts.sim"))+ }++ @Test+ fun defaultLocalAccountNeedsBothBlank() {+ assertTrue(isDefaultLocalAccount(null, null))+ assertTrue(isDefaultLocalAccount("", ""))+ assertFalse(isDefaultLocalAccount("name", null))+ assertFalse(isDefaultLocalAccount(null, "type"))+ }++ @Test+ fun syntheticIdsAreNegativeStableAndDistinct() {+ val a = SimContact(name = "Ann", number = "111")+ val b = SimContact(name = "Bob", number = "222")+ val idA1 = SimContactsDataSource.syntheticIdFor(a)+ val idA2 = SimContactsDataSource.syntheticIdFor(a.copy(subscriptionId = 5))+ assertTrue(idA1 < 0)+ assertEquals(idA1, SimContactsDataSource.syntheticIdFor(a))+ assertTrue(idA2 != idA1, "subscription must feed the hash")+ assertTrue(SimContactsDataSource.syntheticIdFor(b) != idA1)+ }++ @Test+ fun slotNumbersAreOneBased() {+ val info = SimContactsDataSource.SimSubscriptionInfo(5, 0, null, null)+ assertEquals(1, SimContactsDataSource.slotNumberFor(info))+ assertEquals(2, SimContactsDataSource.slotNumberFor(info.copy(slotIndex = 1)))+ assertEquals(1, SimContactsDataSource.slotNumberFor(info.copy(slotIndex = -1)))+ }++ @Test+ fun simAccountNameKeysOnSubscriptionId() {+ val info = SimContactsDataSource.SimSubscriptionInfo(7, 0, "SIM 1", null)+ assertEquals("7", SimContactsDataSource.accountNameFor(info))+ val sim = SimContact(subscriptionId = 7, name = "A", number = "1")+ assertEquals("7", SimContactsDataSource.accountNameForSimContact(sim))+ assertEquals("", SimContactsDataSource.accountNameForSimContact(SimContact(name = "A", number = "1")))+ }+}
contacts/src/test/java/com/vayunmathur/contacts/pure/ContactSortTest.kt
diff --git a/contacts/src/test/java/com/vayunmathur/contacts/pure/ContactSortTest.kt b/contacts/src/test/java/com/vayunmathur/contacts/pure/ContactSortTest.ktindex 867c275627..5ebd2358bf 100644--- a/contacts/src/test/java/com/vayunmathur/contacts/pure/ContactSortTest.kt+++ b/contacts/src/test/java/com/vayunmathur/contacts/pure/ContactSortTest.kt@@ -1,95 +1,118 @@ package com.vayunmathur.contacts.pure -import java.text.Collator-import java.util.Locale+import com.vayunmathur.contacts.data.Contact+import com.vayunmathur.contacts.data.ContactDetails+import com.vayunmathur.contacts.data.Name+import com.vayunmathur.contacts.util.ContactSorting+import com.vayunmathur.contacts.util.ContactSorting.sectionKey+import com.vayunmathur.contacts.util.ContactSorting.sortDisplayName+import com.vayunmathur.contacts.util.ContactSorting.sortedByMode+import com.vayunmathur.contacts.util.ContactSorting.sortedByNameLocale+import com.vayunmathur.contacts.util.ContactSorting.sortedLocale import kotlin.test.Test import kotlin.test.assertEquals +/**+ * Pins locale-aware contact sorting through the production sorter:+ * section keys, first/last-name modes, accent-insensitive ordering and+ * the name join/split helpers the sort names are built from.+ *+ * Builds Contact graphs directly (their constructors are pure data);+ * no provider, database or device is touched.+ */ class ContactSortTest {+ private fun contact(first: String, last: String, id: Long = 0L): Contact =+ Contact(id, null, null, false, ContactDetails.empty().copy(names = listOf(Name(0, "", first, "", last, "")))) - private enum class Mode { First, Last }+ @Test+ fun sectionKeyUppercasesAscii() {+ assertEquals('J', ContactSorting.groupKey("jane"))+ } - private data class SortFixture(val first: String, val last: String)+ @Test+ fun sectionKeyStripsDiacritics() {+ assertEquals('E', ContactSorting.groupKey("Émile"))+ assertEquals('C', ContactSorting.groupKey("çedille"))+ } - private fun displayOf(contact: SortFixture): String {- return listOf(contact.first, contact.last)- .map { it.trim() }- .filter { it.isNotEmpty() }- .joinToString(" ")+ @Test+ fun sectionKeyRejectsBlanksDigitsAndSymbols() {+ assertEquals('#', ContactSorting.groupKey(""))+ assertEquals('#', ContactSorting.groupKey(" "))+ assertEquals('#', ContactSorting.groupKey("9lives"))+ assertEquals('#', ContactSorting.groupKey("@home")) } - private fun sortName(contact: SortFixture, mode: Mode): String {- if (mode == Mode.First) return displayOf(contact)- val last = contact.last.trim()- val first = contact.first.trim()- return when {- last.isNotEmpty() && first.isNotEmpty() -> "$last $first"- last.isNotEmpty() -> last- displayOf(contact).isNotBlank() -> displayOf(contact)- else -> first- }+ @Test+ fun firstNameModeUsesDisplayValue() {+ val c = contact("John", "Doe")+ assertEquals("John Doe", c.sortDisplayName(ContactSorting.ContactSortMode.FirstName)) } - private fun collator(): Collator {- return Collator.getInstance(Locale.ROOT).apply {- strength = Collator.PRIMARY- decomposition = Collator.CANONICAL_DECOMPOSITION- }+ @Test+ fun lastNameModePutsFamilyNameFirst() {+ val c = contact("John", "Doe")+ assertEquals("Doe John", c.sortDisplayName(ContactSorting.ContactSortMode.LastName)) } - private fun sortedByMode(contacts: List<SortFixture>, mode: Mode): List<SortFixture> {- val col = collator()- return contacts.map { it to col.getCollationKey(sortName(it, mode)) }- .sortedWith(compareBy { it.second })- .map { it.first }+ @Test+ fun singleNameFallsBackToDisplayValue() {+ val c = contact("Madonna", "")+ assertEquals("Madonna", c.sortDisplayName(ContactSorting.ContactSortMode.LastName))+ assertEquals('M', c.sectionKey(ContactSorting.ContactSortMode.LastName)) } @Test- fun sortsByFirstNameIgnoringCase() {- val contacts = listOf(SortFixture("bob", "B"), SortFixture("alice", "A"), SortFixture("Carol", "C"))- val result = sortedByMode(contacts, Mode.First)- assertEquals(listOf("alice", "bob", "Carol"), result.map { it.first })+ fun sortIsAccentInsensitive() {+ val names = listOf(contact("Victor", "Hugo"), contact("Véronique", "Alix"))+ val sorted = names.sortedLocale().map { it.name.firstName }+ assertEquals(listOf("Véronique", "Victor"), sorted) } @Test- fun sortsByLastNameMode() {- val contacts = listOf(SortFixture("Ada", "Zebra"), SortFixture("Bob", "Apple"))- val result = sortedByMode(contacts, Mode.Last)- assertEquals(listOf("Apple", "Zebra"), result.map { it.last })+ fun sortIgnoresCase() {+ val names = listOf(contact("bob", "B"), contact("Alice", "A"), contact("cherry", "C"))+ val sorted = names.sortedLocale().map { it.name.firstName }+ assertEquals(listOf("Alice", "bob", "cherry"), sorted) } @Test- fun accentedSortsWithBaseLetter() {- val contacts = listOf(SortFixture("Victor", "V"), SortFixture("Véronique", "V"))- val result = sortedByMode(contacts, Mode.First)- assertEquals("Véronique", result[0].first)- assertEquals("Victor", result[1].first)+ fun sortByLastNameModeOrdersByFamilyName() {+ val names = listOf(contact("John", "Doe"), contact("Amy", "Adams"))+ val sorted = names.sortedByMode(ContactSorting.ContactSortMode.LastName)+ assertEquals(listOf("Adams", "Doe"), sorted.map { it.name.lastName }) } @Test- fun emptyDisplaySortsBeforeLetters() {- val contacts = listOf(SortFixture("Amy", "A"), SortFixture("", ""))- val result = sortedByMode(contacts, Mode.First)- assertEquals("", result[0].first)- assertEquals("Amy", result[1].first)+ fun emptyListSortsToEmpty() {+ assertEquals(emptyList(), emptyList<Contact>().sortedLocale()) } @Test- fun singleNameFallsBackToFullValue() {- assertEquals("Madonna", sortName(SortFixture("Madonna", ""), Mode.Last))+ fun genericNameSelectorSortsGroups() {+ val groups = listOf("Zebra", "apple", "Mango")+ assertEquals(listOf("apple", "Mango", "Zebra"), groups.sortedByNameLocale { it }) } @Test- fun lastNameModePrefersLastFirst() {- assertEquals("Doe John", sortName(SortFixture("John", "Doe"), Mode.Last))+ fun nameValueSkipsBlankPartsWithoutDoubleSpaces() {+ assertEquals("Dr. Jane Ann Doe Jr.", Name(0, "Dr.", "Jane", "Ann", "Doe", "Jr.").value)+ assertEquals("Jane Doe", Name(0, "", "Jane", "", "Doe", "").value)+ assertEquals("", Name(0, "", "", "", "", "").value) } @Test- fun unicodeSortIsStableAndLossless() {- val contacts = listOf(SortFixture("伟", "北京"), SortFixture("Amy", "A"), SortFixture("Émile", "B"))- val once = sortedByMode(contacts, Mode.First)- val twice = sortedByMode(once, Mode.First)- assertEquals(once.map { it.first }, twice.map { it.first })- assertEquals(setOf("伟", "Amy", "Émile"), once.map { it.first }.toSet())+ fun displaySplitKeepsMultiWordFamilyName() {+ assertEquals("Mary" to "Kay Olsen", splitGivenFamily("Mary Kay Olsen"))+ assertEquals("Madonna" to "", splitGivenFamily("Madonna"))+ assertEquals("" to "", splitGivenFamily(" "))+ }++ private fun splitGivenFamily(display: String): Pair<String, String> {+ val trimmed = display.trim()+ if (trimmed.isEmpty()) return "" to ""+ val first = trimmed.substringBefore(" ")+ val last = if (" " in trimmed) trimmed.substringAfter(" ") else ""+ return first to last } }
contacts/src/test/java/com/vayunmathur/contacts/pure/VCardEscapeTest.kt
diff --git a/contacts/src/test/java/com/vayunmathur/contacts/pure/VCardEscapeTest.kt b/contacts/src/test/java/com/vayunmathur/contacts/pure/VCardEscapeTest.ktnew file mode 100644index 0000000000..63834d1b71--- /dev/null+++ b/contacts/src/test/java/com/vayunmathur/contacts/pure/VCardEscapeTest.kt@@ -0,0 +1,85 @@+package com.vayunmathur.contacts.pure++import kotlin.test.Test+import kotlin.test.assertEquals++/**+ * Pins vCard text escaping: the backslash/comma/semicolon/newline codec+ * shared by the importer and the exporter.+ *+ * Mirrors the escape/unescape helpers used by util/VcfUtils (export) and+ * util/VcfParser (import): encode escapes backslash first, decode unescapes+ * it last, so a round trip is lossless.+ */+class VCardEscapeTest {+ private fun escapeV(value: String): String {+ return value.replace("\\", "\\\\").replace("\n", "\\n").replace(",", "\\,").replace(";", "\\;")+ }++ private fun unescapeV(value: String): String {+ return value+ .replace("\\n", "\n")+ .replace("\\N", "\n")+ .replace("\\,", ",")+ .replace("\\;", ";")+ .replace("\\\\", "\\")+ }++ @Test+ fun plainTextPassesThroughBothWays() {+ assertEquals("John Doe", escapeV("John Doe"))+ assertEquals("John Doe", unescapeV("John Doe"))+ }++ @Test+ fun emptyStringRoundTrips() {+ assertEquals("", escapeV(""))+ assertEquals("", unescapeV(""))+ }++ @Test+ fun commasAndSemicolonsAreEscaped() {+ assertEquals("a\\,b\\;c", escapeV("a,b;c"))+ assertEquals("a,b;c", unescapeV("a\\,b\\;c"))+ }++ @Test+ fun bothNewlineVariantsDecodeToNewline() {+ assertEquals("a\nb", unescapeV("a\\nb"))+ assertEquals("a\nb", unescapeV("a\\Nb"))+ }++ @Test+ fun backslashIsEscapedFirstAndUnescapedLast() {+ assertEquals("a\\\\b", escapeV("a\\b"))+ assertEquals("a\\b", unescapeV("a\\\\b"))+ }++ @Test+ fun literalBackslashNIsNotConfusedWithNewline() {+ assertEquals("a\\\nb", unescapeV("a\\\\\\nb"))+ }++ @Test+ fun fullRoundTripPreservesEverySpecial() {+ val raw = "line1\nline2, with; specials \\ done"+ assertEquals(raw, unescapeV(escapeV(raw)))+ }++ @Test+ fun unicodeTextRoundTripsUntouched() {+ val raw = "José García, 東京; Züri\nch"+ assertEquals(raw, unescapeV(escapeV(raw)))+ }++ @Test+ fun addressStyleValueRoundTrips() {+ val raw = "123 Main St, Apt 4; Springfield"+ assertEquals(raw, unescapeV(escapeV(raw)))+ }++ @Test+ fun unknownEscapeSequenceIsKeptVerbatim() {+ assertEquals("a\\tb", unescapeV("a\\tb"))+ }+}
contacts/src/test/java/com/vayunmathur/contacts/pure/VCardFoldTest.kt
diff --git a/contacts/src/test/java/com/vayunmathur/contacts/pure/VCardFoldTest.kt b/contacts/src/test/java/com/vayunmathur/contacts/pure/VCardFoldTest.ktnew file mode 100644index 0000000000..7253e96404--- /dev/null+++ b/contacts/src/test/java/com/vayunmathur/contacts/pure/VCardFoldTest.kt@@ -0,0 +1,101 @@+package com.vayunmathur.contacts.pure++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/**+ * Pins vCard line folding: 75-octet lines, space-prefixed continuations,+ * and the streaming unfold the importer relies on.+ *+ * Mirrors util/VcfUtils' fold writer and the unfold loop in+ * parseVcfContacts, where a tab also continues a folded line.+ */+class VCardFoldTest {+ private fun fold(line: String): String {+ if (line.length <= FOLD_LENGTH) return line + "\r\n"+ val sb = StringBuilder()+ var idx = 0+ while
Diff truncated.