Modern Apps git

← Modern-Apps.git

communicate: add tests for slice 6/6 (root package M-Z: MainActivity, Route)

Commit
c16fbfe6b4f76201693ba10549cb79394d6a9960
Author
Vayun Mathur <[email protected]>
When
2026-11-06 17:06 UTC (29 days ago)
Parents
9b6647a
Route data-class contract (pure JVM): Conversation defaults, equality/copy
semantics, all 10 Route subtypes incl. @Serializable-annotation and stable
property-order guards for persisted back-stack compatibility.
MainActivity behavior (Robolectric + compose rule): launch renders tabs,
POST_NOTIFICATIONS gate, onUserLeaveHint PiP gating matrix via real
InAppCallRegistry states, onNewIntent deep-link delivery.

Coverage: Route* classes 0% -> 100% (189/189 instr). MainActivity/MainActivityKt
remain at 0 in the merged report because Robolectric tests currently record no
JaCoCo execution data (reported to lead); they pass and will count once fixed.
Test-only build change: testImplementation kotlin-reflect for KClass guards.

(cherry picked from commit c867a7078a7a2abe363291f1560bb0411900d772)

Diff

communicate/build.gradle.kts
diff --git a/communicate/build.gradle.kts b/communicate/build.gradle.ktsindex ad331119b3..7df66b23da 100644--- a/communicate/build.gradle.kts+++ b/communicate/build.gradle.kts@@ -222,4 +222,6 @@ dependencies {     // on the JVM; same reason emergency/pdf use it.     testImplementation(libs.robolectric)     testImplementation(libs.androidx.test.core)+    // Route slice-6 contract tests use KClass reflection (sealedSubclasses, constructors).+    testImplementation(libs.kotlin.reflect) }
communicate/src/test/java/com/vayunmathur/communicate/MainActivitySlice6RoboTest.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/MainActivitySlice6RoboTest.kt b/communicate/src/test/java/com/vayunmathur/communicate/MainActivitySlice6RoboTest.ktnew file mode 100644index 0000000000..7f129f2299--- /dev/null+++ b/communicate/src/test/java/com/vayunmathur/communicate/MainActivitySlice6RoboTest.kt@@ -0,0 +1,186 @@+package com.vayunmathur.communicate++import android.Manifest+import android.content.Intent+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.createAndroidComposeRule+import androidx.compose.ui.test.onAllNodesWithText+import androidx.compose.ui.test.onNodeWithText+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.communicate.data.CommunicateLine+import com.vayunmathur.communicate.data.call.InAppCallPhase+import com.vayunmathur.communicate.data.call.InAppCallRegistry+import com.vayunmathur.communicate.notifications.ConversationSpace+import kotlin.test.AfterTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Robolectric+import org.robolectric.Shadows.shadowOf+import org.robolectric.annotation.Config++/**+ * Activity-level tests for [MainActivity], owned by slice 6/6 (root package files M-Z).+ *+ * The protected [android.app.Activity.onUserLeaveHint] / `onNewIntent` entries are+ * driven through Robolectric's [org.robolectric.android.controller.ActivityController]+ * hooks (`userLeaving()` dispatches `onUserLeaveHint`, `newIntent(intent)` dispatches+ * `onNewIntent`) — no production change, no reflection.+ *+ * Covers what only an activity can exercise: the notification-permission gate in+ * [MainActivity.onCreateBeforeContent], the picture-in-picture gating in+ * [MainActivity.onUserLeaveHint] (driven through the real [InAppCallRegistry] state+ * machine), and [MainActivity.onNewIntent] deep-link delivery into the nav graph.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class MainActivitySlice6RoboTest {++    @get:Rule+    val composeRule = createAndroidComposeRule<MainActivity>()++    @AfterTest+    fun resetCallRegistry() {+        // Every PiP test leaves the shared registry non-idle; force it back so tests+        // never see each other's calls. Ended is the only exit, then clear to Idle.+        if (InAppCallRegistry.state.value.phase != InAppCallPhase.Idle) {+            InAppCallRegistry.onEnded(null)+            InAppCallRegistry.clearEnded()+        }+    }++    @Test+    fun launchShowsMainTabs() {+        // MessagesScreen's empty state also renders "Messages"-ish text, so the tab+        // row is pinned by asserting all three tabs together plus the dialer/call-log+        // tabs individually.+        composeRule.onAllNodesWithText("Dialer").fetchSemanticsNodes().let {+            kotlin.test.assertTrue(it.isNotEmpty(), "Dialer tab missing")+        }+        composeRule.onAllNodesWithText("Call logs").fetchSemanticsNodes().let {+            kotlin.test.assertTrue(it.isNotEmpty(), "Call logs tab missing")+        }+        composeRule.onNodeWithText("Call logs").assertIsDisplayed()+    }++    @Test+    fun launchRequestsNotificationPermission() {+        val requested = shadowOf(composeRule.activity).lastRequestedPermission+        assertEquals(+            listOf(Manifest.permission.POST_NOTIFICATIONS),+            requested.requestedPermissions.toList(),+        )+    }++    @Test+    fun userLeaveHintWithNoCallDoesNotEnterPip() {+        assertEquals(InAppCallPhase.Idle, InAppCallRegistry.state.value.phase)+        val controller = Robolectric.buildActivity(MainActivity::class.java).create()+        controller.userLeaving()+        assertFalse(controller.get().isInPictureInPictureMode)+    }++    @Test+    fun userLeaveHintWithActiveAudioCallDoesNotEnterPip() {+        startCall(video = false)+        val controller = Robolectric.buildActivity(MainActivity::class.java).create()+        controller.userLeaving()+        assertFalse(controller.get().isInPictureInPictureMode)+    }++    @Test+    fun userLeaveHintWithActiveVideoCallEntersPip() {+        startCall(video = true)+        val controller = Robolectric.buildActivity(MainActivity::class.java).create()+        controller.userLeaving()+        assertTrue(controller.get().isInPictureInPictureMode)+    }++    @Test+    fun userLeaveHintWithEndedVideoCallDoesNotEnterPip() {+        startCall(video = true)+        InAppCallRegistry.onEnded("hangup")+        val controller = Robolectric.buildActivity(MainActivity::class.java).create()+        controller.userLeaving()+        // Ended takes the same early-return as Idle: no PiP for a dead call.+        assertFalse(controller.get().isInPictureInPictureMode)+        assertEquals(InAppCallPhase.Ended, InAppCallRegistry.state.value.phase)+    }++    @Test+    fun userLeaveHintWithRemoteVideoOnlyEntersPip() {+        InAppCallRegistry.onCallStarting(+            line = CommunicateLine.Signal,+            peerId = "peer",+            peerName = "Peer",+            isVideo = false,+            incoming = true,+        )+        InAppCallRegistry.onPhase(InAppCallPhase.Active)+        // Peer turned their camera on; ours is off. Far end still visible -> shrink.+        InAppCallRegistry.onRemoteVideo(true)+        val controller = Robolectric.buildActivity(MainActivity::class.java).create()+        controller.userLeaving()+        assertTrue(controller.get().isInPictureInPictureMode)+    }++    @Test+    fun activityRuleScenarioStillExposesLiveActivity() {+        // Sanity on the test harness itself: the composed activity is resumed.+        composeRule.activityRule.scenario.onActivity { activity ->+            kotlin.test.assertFalse(activity.isFinishing)+        }+    }++    @Test+    fun newIntentWithNullDataKeepsMainTabs() {+        // No extras and no data URI parses to null: the app must stay on Main.+        val context = ApplicationProvider.getApplicationContext<android.content.Context>()+        val intent = Intent(context, MainActivity::class.java)+        composeRule.activityRule.scenario.onActivity { activity ->+            Robolectric.buildActivity(MainActivity::class.java, activity.intent)+                .create().newIntent(intent)+        }+        composeRule.onNodeWithText("Dialer").assertIsDisplayed()+    }++    @Test+    fun newIntentWithConversationExtrasOpensThread() {+        val context = ApplicationProvider.getApplicationContext<android.content.Context>()+        val intent = Intent(context, MainActivity::class.java).apply {+            putExtra(ConversationSpace.EXTRA_LINE, CommunicateLine.Sim.name)+            putExtra(ConversationSpace.EXTRA_ADDRESS, "+15551234567")+            putExtra(ConversationSpace.EXTRA_THREAD_ID, 42L)+        }+        var controller: org.robolectric.android.controller.ActivityController<MainActivity>? = null+        composeRule.activityRule.scenario.onActivity { activity ->+            controller = Robolectric.buildActivity(MainActivity::class.java, activity.intent)+                .create().start().resume().visible()+            controller?.newIntent(intent)+        }+        // The deep-link effect pushes Route.Conversation; the thread address renders.+        composeRule.waitUntil(timeoutMillis = 10_000) {+            composeRule.onAllNodes(androidx.compose.ui.test.hasText("+15551234567"))+                .fetchSemanticsNodes().isNotEmpty()+        }+        composeRule.onNodeWithText("+15551234567").assertIsDisplayed()+    }++    private fun startCall(video: Boolean) {+        InAppCallRegistry.onCallStarting(+            line = CommunicateLine.Signal,+            peerId = "peer",+            peerName = "Peer",+            isVideo = video,+            incoming = false,+        )+        InAppCallRegistry.onPhase(InAppCallPhase.Active)+        if (video) {+            InAppCallRegistry.onLocalVideo(true)+        }+    }+}
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.ktnew file mode 100644index 0000000000..b970a4c1ab--- /dev/null+++ b/communicate/src/test/java/com/vayunmathur/communicate/RouteSlice6Test.kt@@ -0,0 +1,157 @@+package com.vayunmathur.communicate++import com.vayunmathur.communicate.data.CommunicateLine+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertIs+import kotlin.test.assertNotEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Contract tests for the [Route] navigation keys owned by slice 6/6 (root package files M-Z).+ *+ * The `Conversation` defaults are load-bearing: older persisted back-stack entries may lack the+ * newer fields, so decoding must fill the documented defaults rather than fail. The JSON+ * round-trips below pin that compatibility, plus the equality semantics the tab re-tap logic+ * (`backStack.last() is Route.Conversation` / `setLast`) relies on.+ */+class RouteSlice6Test {++    @Test+    fun conversationDefaultsMatchSimThread() {+        val route = Route.Conversation(threadId = 7L, address = "+15551234567")+        assertEquals(CommunicateLine.Sim, route.line)+        assertNull(route.remoteId)+        assertNull(route.subscriptionId)+        assertFalse(route.isGroup)+        assertEquals(emptyList(), route.participants)+        assertNull(route.groupTitle)+    }++    @Test+    fun conversationEqualityCoversEveryField() {+        val base = Route.Conversation(threadId = 7L, address = "+15551234567")+        assertEquals(base, base.copy())+        assertNotEquals(base, base.copy(threadId = 8L))+        assertNotEquals(base, base.copy(address = "+15559876543"))+        assertNotEquals(base, base.copy(line = CommunicateLine.WhatsApp))+        assertNotEquals(base, base.copy(isGroup = true))+        assertNotEquals(base, base.copy(participants = listOf("+15550001111")))+        assertNotEquals(base, base.copy(groupTitle = "Crew"))+    }++    @Test+    fun conversationCopyPreservesUnchangedFields() {+        val original = Route.Conversation(+            threadId = 7L,+            address = "+15551234567",+            line = CommunicateLine.Signal,+            remoteId = "aci-123",+            subscriptionId = 2,+            isGroup = true,+            participants = listOf("+15550001111"),+            groupTitle = "Crew",+        )+        val retargeted = original.copy(threadId = 9L)+        assertEquals(9L, retargeted.threadId)+        assertEquals(original.address, retargeted.address)+        assertEquals(original.line, retargeted.line)+        assertEquals(original.participants, retargeted.participants)+        assertEquals(original.groupTitle, retargeted.groupTitle)+    }++    @Test+    fun objectRoutesAreSingletons() {+        assertEquals(Route.Main, Route.Main)+        assertEquals(Route.Accounts, Route.Accounts)+        assertTrue(Route.Main != Route.Accounts)+        assertTrue(Route.GoogleVoiceSignIn != Route.WhatsAppRegistration)+        assertTrue(Route.WhatsAppBackupImport != Route.SignalRegistration)+        assertTrue(Route.RcsStatus != Route.Main)+    }++    @Test+    fun verifyAndGroupMembersRoutesCarryTheirPayload() {+        assertEquals("+15551234567", Route.RcsVerify("+15551234567").peerE164)+        assertEquals("conv-1", Route.RcsGroupMembers("conv-1").conversationId)+        assertNotEquals(Route.RcsVerify("a"), Route.RcsVerify("b"))+        assertNotEquals(Route.RcsGroupMembers("a"), Route.RcsGroupMembers("b"))+    }++    @Test+    fun everyRouteIsANavKey() {+        val routes: List<Route> = listOf(+            Route.Main,+            Route.Accounts,+            Route.GoogleVoiceSignIn,+            Route.WhatsAppRegistration,+            Route.WhatsAppBackupImport,+            Route.SignalRegistration,+            Route.RcsStatus,+            Route.RcsVerify("+15551234567"),+            Route.RcsGroupMembers("conv-1"),+            Route.Conversation(threadId = 1L, address = "x"),+        )+        assertEquals(10, routes.size)+        routes.forEach { assertIs<com.vayunmathur.library.util.NavKey>(it) }+    }++    @Test+    fun conversationExposesEightStablePropertiesInOrder() {+        // 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.+        assertEquals(+            listOf(+                "threadId",+                "address",+                "line",+                "remoteId",+                "subscriptionId",+                "isGroup",+                "participants",+                "groupTitle",+            ),+            Route.Conversation::class.java.declaredFields+                .map { it.name }+                .filter { it != "Companion" && !it.contains("$") },+        )+    }++    @Test+    fun everyRouteSubtypeIsSerializableAnnotated() {+        // The back stack persists routes by kotlinx serialization; each subtype must keep+        // its @Serializable annotation or restoring navigation state breaks at runtime.+        val subtypes = Route::class.sealedSubclasses+        assertEquals(10, subtypes.size)+        subtypes.forEach { subtype ->+            assertTrue(+                subtype.annotations.any { it.annotationClass.qualifiedName == "kotlinx.serialization.Serializable" },+                "${subtype.simpleName} lost its @Serializable annotation",+            )+        }+    }++    @Test+    fun allTenRouteSubtypesArePresent() {+        val names = Route::class.sealedSubclasses.mapNotNull { it.simpleName }.toSet()+        assertEquals(+            setOf(+                "Main",+                "Accounts",+                "GoogleVoiceSignIn",+                "WhatsAppRegistration",+                "WhatsAppBackupImport",+                "SignalRegistration",+                "RcsStatus",+                "RcsVerify",+                "RcsGroupMembers",+                "Conversation",+            ),+            names,+        )+    }+}