Modern Apps git

← Modern-Apps.git

communicate: update tests for the share-picker route shape; de-flake two

Commit
23f0e9d63e156e8ff92bd5c8828e6043307f7afa
Author
Vayun Mathur <[email protected]>
When
2026-11-21 14:04 UTC (14 days ago)
Parents
28e2f4b
Four failing classes, none a production bug. Two encoded
pre-Direct-Share behaviour: plain ACTION_SEND now opens the
SharePicker (PendingShare) instead of being ignored, and
Route.Conversation gained sharedText/sharedAttachmentUris
(appended with defaults, old entries still decode) - tests
updated to the new contract with reasons stated. The Signal
socket test iterated synchronized lists without their monitors
(a flake; production uses concurrent maps) - assertions now
go through synchronized snapshots. The group picker test
couldn't see the second contact because the LazyColumn never
composed it in the small test window - bounded index scrolling
composes the row deterministically.

Verified: full communicate suite 1978 tests, 0 failures.

Diff

communicate/src/test/java/com/vayunmathur/communicate/DeepLinksParseSlice5Test.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/DeepLinksParseSlice5Test.kt b/communicate/src/test/java/com/vayunmathur/communicate/DeepLinksParseSlice5Test.ktindex f0a7d1008a..d6facabd14 100644--- a/communicate/src/test/java/com/vayunmathur/communicate/DeepLinksParseSlice5Test.kt+++ b/communicate/src/test/java/com/vayunmathur/communicate/DeepLinksParseSlice5Test.kt@@ -44,8 +44,21 @@ class DeepLinksParseSlice5Test {     }      @Test-    fun unsupportedActionIsIgnored() {-        assertNull(DeepLinks.parse(intent(Intent.ACTION_SEND, "smsto:+15551234567")))+    fun plainSendOpensTheSharePicker() {+        // Direct Share round (dacc87514): a plain ACTION_SEND with no chosen+        // conversation is no longer dropped — it is held as a picker share+        // (PendingShare) and seeds the first thread the user opens. The data+        // URI is not a destination for SEND, so it must not leak through.+        val result = DeepLinks.parse(intent(Intent.ACTION_SEND, "smsto:+15551234567"))+        assertTrue(result is DeepLink.SharePicker, "was $result")+        assertNull((result as DeepLink.SharePicker).body)+    }++    @Test+    fun plainSendCarriesTheSharedTextToThePicker() {+        val result = DeepLinks.parse(intent(Intent.ACTION_SEND, "smsto:+15551234567", text = "hi"))+            as DeepLink.SharePicker+        assertEquals("hi", result.body)     }      @Test
communicate/src/test/java/com/vayunmathur/communicate/RouteSlice6Test.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/RouteSlice6Test.kt b/communicate/src/test/java/com/vayunmathur/communicate/RouteSlice6Test.ktindex 24c1ff4546..30042a8bc0 100644--- a/communicate/src/test/java/com/vayunmathur/communicate/RouteSlice6Test.kt+++ b/communicate/src/test/java/com/vayunmathur/communicate/RouteSlice6Test.kt@@ -28,6 +28,9 @@ class RouteSlice6Test {         assertFalse(route.isGroup)         assertEquals(emptyList(), route.participants)         assertNull(route.groupTitle)+        // Direct Share seeds stay empty for a plain open (dacc87514).+        assertNull(route.sharedText)+        assertEquals(emptyList(), route.sharedAttachmentUris)     }      @Test@@ -40,6 +43,8 @@ class RouteSlice6Test {         assertNotEquals(base, base.copy(isGroup = true))         assertNotEquals(base, base.copy(participants = listOf("+15550001111")))         assertNotEquals(base, base.copy(groupTitle = "Crew"))+        assertNotEquals(base, base.copy(sharedText = "hi"))+        assertNotEquals(base, base.copy(sharedAttachmentUris = listOf("content://x/1")))     }      @Test@@ -106,11 +111,13 @@ class RouteSlice6Test {     }      @Test-    fun conversationExposesEightStablePropertiesInOrder() {+    fun conversationExposesTenStablePropertiesInOrder() {         // Guards the "older back-stack entries stay valid" contract structurally: adding,         // removing or reordering properties here breaks persisted navigation state.         // Java parameter names are unavailable (no -java-parameters); declared-field         // order carries the stable declaration order instead.+        // Direct Share round (dacc87514) appended sharedText/sharedAttachmentUris+        // at the end with defaults, so older entries (missing both) still decode.         assertEquals(             listOf(                 "threadId",@@ -121,6 +128,8 @@ class RouteSlice6Test {                 "isGroup",                 "participants",                 "groupTitle",+                "sharedText",+                "sharedAttachmentUris",             ),             Route.Conversation::class.java.declaredFields                 .map { it.name }
communicate/src/test/java/com/vayunmathur/communicate/signal/Y2SignalSocketRegTest.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/signal/Y2SignalSocketRegTest.kt b/communicate/src/test/java/com/vayunmathur/communicate/signal/Y2SignalSocketRegTest.ktindex a9a0028460..e0d5bf7424 100644--- a/communicate/src/test/java/com/vayunmathur/communicate/signal/Y2SignalSocketRegTest.kt+++ b/communicate/src/test/java/com/vayunmathur/communicate/signal/Y2SignalSocketRegTest.kt@@ -238,6 +238,13 @@ class Y2SignalSocketRegTest {         error("timeout $label")     } +    /**+     * Snapshot of a synchronized list for safe iteration: iterating a+     * `Collections.synchronizedList` without holding its monitor races the+     * socket/server threads appending to it (ConcurrentModificationException).+     */+    private fun <T> List<T>.snapshot(): List<T> = synchronized(this) { toList() }+     private fun socketFor(port: Int, authenticated: Boolean = true, aciValue: String = aci, password: String = "pw-secret", passwordOverride: String? = null) =         SignalSocket(             context = ctx, authData = auth(aciValue, password, authenticated),@@ -253,11 +260,11 @@ class Y2SignalSocketRegTest {             val scope = CoroutineScope(Dispatchers.Default + SupervisorJob())             val stateJob = scope.async { socket.connectionState.collect { states.add(it) } }             socket.connect()-            await("connected") { states.any { it is SignalSocket.ConnectionState.Connected } }+            await("connected") { states.snapshot().any { it is SignalSocket.ConnectionState.Connected } }              // Handshake carried Basic aci.deviceId auth.-            await("handshake") { server.handshakes.isNotEmpty() }-            val hs = server.handshakes.first()+            await("handshake") { server.handshakes.snapshot().isNotEmpty() }+            val hs = server.handshakes.snapshot().first()             assertTrue(hs.contains("GET /v1/websocket/"), hs)             val authLine = hs.lines().first { it.startsWith("Authorization:") }             val decoded = String(@@ -275,8 +282,8 @@ class Y2SignalSocketRegTest {             assertTrue(socket.send(byteArrayOf(9, 8, 7)))             assertTrue(socket.sendText("plain-text"))             await("raw frames") {-                server.frames.any { it.second.contentEquals(byteArrayOf(9, 8, 7)) } &&-                    server.frames.any { it.second.decodeToString() == "plain-text" }+                server.frames.snapshot().any { it.second.contentEquals(byteArrayOf(9, 8, 7)) } &&+                    server.frames.snapshot().any { it.second.decodeToString() == "plain-text" }             }             socket.disconnect()             stateJob.cancel()@@ -293,7 +300,7 @@ class Y2SignalSocketRegTest {             val stateJob = scope.async { socket.connectionState.collect { states.add(it) } }             val msgJob = scope.async { socket.messages.collect { inbox.add(it) } }             socket.connect()-            await("connected") { states.any { it is SignalSocket.ConnectionState.Connected } }+            await("connected") { states.snapshot().any { it is SignalSocket.ConnectionState.Connected } }              // Request/response correlation: generated id and explicit id.             val req = WebSocketRequestMessage.newBuilder()@@ -325,11 +332,11 @@ class Y2SignalSocketRegTest {                     .setId(999L).setVerb("GET").setPath("/v1/messages").build())                 .build().toByteArray()             server.pushToClient(push)-            await("push") { inbox.any { it.contentEquals(push) } }+            await("push") { inbox.snapshot().any { it.contentEquals(push) } }              socket.disconnect()             await("disconnected state") {-                states.any { it is SignalSocket.ConnectionState.Disconnected && it.reason == "client disconnect" }+                states.snapshot().any { it is SignalSocket.ConnectionState.Disconnected && it.reason == "client disconnect" }             }             assertFalse(socket.send(byteArrayOf(1)))             stateJob.cancel(); msgJob.cancel()@@ -344,7 +351,7 @@ class Y2SignalSocketRegTest {             val scope = CoroutineScope(Dispatchers.Default + SupervisorJob())             val job = scope.async { socket.connectionState.collect { states.add(it) } }             socket.connect()-            await("connected") { states.any { it is SignalSocket.ConnectionState.Connected } }+            await("connected") { states.snapshot().any { it is SignalSocket.ConnectionState.Connected } }             val start = System.currentTimeMillis()             val result = socket.sendRequestAwaitingResponse(                 WebSocketRequestMessage.newBuilder().setVerb("GET").setPath("/noreply").build(),@@ -367,7 +374,7 @@ class Y2SignalSocketRegTest {             val job = scope.async { socket.connectionState.collect { states.add(it) } }             socket.connect()             await("4401 disconnected") {-                states.any { it is SignalSocket.ConnectionState.Disconnected && it.reason.contains("4401") }+                states.snapshot().any { it is SignalSocket.ConnectionState.Disconnected && it.reason.contains("4401") }             }             val accepts = server.acceptCount             Thread.sleep(1_500)@@ -384,9 +391,9 @@ class Y2SignalSocketRegTest {             val scope = CoroutineScope(Dispatchers.Default + SupervisorJob())             val job = scope.async { socket.connectionState.collect { states.add(it) } }             socket.connect()-            await("connected") { states.any { it is SignalSocket.ConnectionState.Connected } }-            await("handshake") { server.handshakes.isNotEmpty() }-            assertFalse(server.handshakes.first().contains("Authorization:"), server.handshakes.first())+            await("connected") { states.snapshot().any { it is SignalSocket.ConnectionState.Connected } }+            await("handshake") { server.handshakes.snapshot().isNotEmpty() }+            assertFalse(server.handshakes.snapshot().first().contains("Authorization:"), server.handshakes.snapshot().first())             socket.disconnect(); job.cancel()         }     }@@ -597,8 +604,8 @@ class Y2SignalSocketRegTest {             val afterReuse = SignalAuthData.load(ctx)!!             assertEquals("keep-me", afterReuse.password)             assertEquals("sess-alias", afterReuse.verificationSessionId)-            assertTrue(server.requests.any { it.path == "/v1/verification/session/sess-alias/code" },-                "${server.requests}")+            assertTrue(server.requests.snapshot().any { it.path == "/v1/verification/session/sess-alias/code" },+                "${server.requests.snapshot()}")              // Stale 32-byte UAK scaffold is regenerated for the same number.             val stale = SignalRegistrationKeys.generate("+15550102030").authScaffold.copy(@@ -641,9 +648,9 @@ class Y2SignalSocketRegTest {             }             val ok = client.verifyCode("12-34 56")             assertTrue(ok.ok, "$ok"); assertEquals("aci-only-1", ok.aci); assertNull(ok.pni)-            val codeReq = server.requests.first { it.method == "PUT" }+            val codeReq = server.requests.snapshot().first { it.method == "PUT" }             assertTrue(codeReq.body.contains("\"code\":\"123456\""), codeReq.body)-            val regReq = server.requests.first { it.path == "/v1/registration" }+            val regReq = server.requests.snapshot().first { it.path == "/v1/registration" }             assertNotNull(regReq.auth); assertTrue(regReq.auth!!.startsWith("Basic "))             val regBody = org.json.JSONObject(regReq.body)             assertEquals("sessV", regBody.getString("sessionId"))@@ -691,7 +698,7 @@ class Y2SignalSocketRegTest {             }             val noPw = client.verifyCode("654321")             assertEquals("missing_password", noPw.reason)-            assertTrue(server.requests.none { it.path == "/v1/registration" })+            assertTrue(server.requests.snapshot().none { it.path == "/v1/registration" })              // Unverified code submission HTTP error propagates as an error result.             SignalAuthData.save(ctx, scaffold)
communicate/src/test/java/com/vayunmathur/communicate/ui/Y3GroupCreatePickerTest.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/ui/Y3GroupCreatePickerTest.kt b/communicate/src/test/java/com/vayunmathur/communicate/ui/Y3GroupCreatePickerTest.ktindex c986f93b52..741f86e3c6 100644--- a/communicate/src/test/java/com/vayunmathur/communicate/ui/Y3GroupCreatePickerTest.kt+++ b/communicate/src/test/java/com/vayunmathur/communicate/ui/Y3GroupCreatePickerTest.kt@@ -11,7 +11,7 @@ import androidx.compose.ui.test.hasScrollAction import androidx.compose.ui.test.hasSetTextAction import androidx.compose.ui.test.hasText import androidx.compose.ui.test.isToggleable-import androidx.compose.ui.test.performScrollToNode+import androidx.compose.ui.test.performScrollToIndex import androidx.compose.ui.test.performTextClearance import androidx.compose.ui.test.junit4.createComposeRule import androidx.compose.ui.test.onAllNodesWithText@@ -373,10 +373,47 @@ class Y3GroupCreatePickerTest {      * unreliable here: the picker rows report zero-size bounds under      * Robolectric, so injected clicks land at (0,0) instead of on the row.      */-    private fun pickToggle(name: String, target: Int) {+    /**+     * Scroll the contact LazyColumn until [name]'s row is composed. The column+     * only composes visible rows, and under Robolectric's small window the+     * second contact sits below the fold (zero-size semantics node), so the+     * row must be scrolled into view before it can be clicked — on a real+     * device this is the user's scroll; here it is done deterministically.+     */+    private fun scrollPickerTo(name: String) {+        // Index-based scroll of the lazy contact list (bounded, deterministic):+        // the generic performScrollToNode loops forever under Robolectric when+        // the item can never appear in the scrolled container.+        val scrollables = rule.onAllNodes(hasScrollAction())+        for (i in 0 until scrollables.fetchSemanticsNodes().size) {+            for (index in 0..3) {+                runCatching { scrollables[i].performScrollToIndex(index) }+                runCatching { rule.waitForIdle() }+                if (rule.onAllNodesWithText(name).fetchSemanticsNodes().isNotEmpty()) return+            }+        }+    }++    /** True once [name]'s selected-contact chip is shown above the list. */+    private fun chipSelected(name: String): Boolean =+        // The chip's merged node carries exactly one text entry (the label);+        // the contact row carries two (name + number), so this tells them apart.+        rule.onAllNodesWithText(name).fetchSemanticsNodes().any { node ->+            runCatching {+                val entries = node.config[androidx.compose.ui.semantics.SemanticsProperties.Text]+                entries.size == 1 && entries[0].text == name+            }.getOrDefault(false)+        }++    private fun pickToggle(name: String) {         val deadline = System.currentTimeMillis() + 15_000         while (System.currentTimeMillis() < deadline) {-            if (checkedToggleCount() >= target) return+            // Probe the chip, not the checkbox count: the lazy list only+            // composes visible rows, so a checked-count over composed+            // toggleables drops as rows scroll out and the retry loop would+            // click an already-selected contact back off.+            if (chipSelected(name)) return+            if (rule.onAllNodesWithText(name).fetchSemanticsNodes().isEmpty()) scrollPickerTo(name)             val nodes = rule.onAllNodesWithText(name).fetchSemanticsNodes()             // The contact row is the node whose merged text also carries the number.             val row = nodes.firstOrNull { node ->@@ -390,14 +427,13 @@ class Y3GroupCreatePickerTest {             Thread.sleep(100)         }         dumpState("pickToggle-$name")-        assertTrue(checkedToggleCount() >= target,+        assertTrue(chipSelected(name),             "contact $name never selected; checked=${checkedToggleCount()}")     }      private fun pickBothContactsAndName() {-        // Group switch is already On, so Alice -> 2 checked, Bob -> 3 checked.-        pickToggle("Alice Y3", target = 2)-        pickToggle("Bob Y3", target = 3)+        pickToggle("Alice Y3")+        pickToggle("Bob Y3")         rule.onAllNodes(hasSetTextAction())[0].performTextInput("Y3 Crew")         rule.waitForIdle()     }