Modern Apps git

← Modern-Apps.git

office: fake OfficeSync transport in tests, never touch real relay

Commit
1f480289f1689988f20fdbcc6d667298085b919e
Author
Vayun Mathur <[email protected]>
When
2026-11-07 10:41 UTC (29 days ago)
Parents
c57bff6
The pass-2 sync test called OfficeSync entry points with no transport,
so on a machine WITH internet (CI) it would have POSTed to the real
api.maproj.org relay. Add a behavior-preserving seam:
OfficeSync.httpTransport (internal HttpTransport fun interface, null
by default = the real NetworkClient call, unchanged) and rewrite
Slice4Pass2SyncNetworkTest to script all responses through it:
transport failure, HTTP 500, and scripted 200s (getkey bytes, append
seq, pull with one decryptable and one garbage action, undecryptable
inbox batch). The real-websocket start/stop test is dropped (it
dialed wss:// for real); no-session liveAppend/sendPresence stay.

Verified: gslot ./gradlew :office:testDevUnitTest --tests
com.vayunmathur.office.util.Slice4Pass2SyncNetworkTest (passes, no
network touched).

(cherry picked from commit 0e0047b472da7fad2ae54cc4f9f8eef7f858f7b8)

Diff

office/src/main/java/com/vayunmathur/office/util/OfficeSync.kt
diff --git a/office/src/main/java/com/vayunmathur/office/util/OfficeSync.kt b/office/src/main/java/com/vayunmathur/office/util/OfficeSync.ktindex 5c6e25eb2d..c603008d23 100644--- a/office/src/main/java/com/vayunmathur/office/util/OfficeSync.kt+++ b/office/src/main/java/com/vayunmathur/office/util/OfficeSync.kt@@ -10,6 +10,7 @@ import com.vayunmathur.e2ee.E2eeKeyStore import com.vayunmathur.e2ee.Pqc import com.vayunmathur.e2ee.PqcIdentity import com.vayunmathur.library.network.NetworkClient+import com.vayunmathur.library.network.SimpleResponse import com.vayunmathur.library.network.WebSocketClient import com.vayunmathur.library.network.WsSession import com.vayunmathur.library.network.webSocket@@ -244,14 +245,27 @@ object OfficeSync {         return r.status in HTTP_SUCCESS     } +    /** HTTP seam: null (the default) uses the real [NetworkClient]; unit tests install a fake. */+    internal fun interface HttpTransport {+        suspend fun post(url: String, bodyJson: String): SimpleResponse?+    }++    internal var httpTransport: HttpTransport? = null+     private suspend inline fun <reified T> raw(path: String, body: T) =         try {-            NetworkClient.performRequest(-                url = "$URL$path",-                method = "POST",-                headers = mapOf("Content-Type" to "application/json"),-                body = json.encodeToString(body),-            )+            val bodyJson = json.encodeToString(body)+            val seam = httpTransport+            if (seam != null) {+                seam.post("$URL$path", bodyJson)+            } else {+                NetworkClient.performRequest(+                    url = "$URL$path",+                    method = "POST",+                    headers = mapOf("Content-Type" to "application/json"),+                    body = bodyJson,+                )+            }         } catch (e: CancellationException) {             throw e         } catch (expected: Exception) {
office/src/test/java/com/vayunmathur/office/util/Slice4Pass2SyncNetworkTest.kt
diff --git a/office/src/test/java/com/vayunmathur/office/util/Slice4Pass2SyncNetworkTest.kt b/office/src/test/java/com/vayunmathur/office/util/Slice4Pass2SyncNetworkTest.ktindex 451d6a473d..2bc6eda3f2 100644--- a/office/src/test/java/com/vayunmathur/office/util/Slice4Pass2SyncNetworkTest.kt+++ b/office/src/test/java/com/vayunmathur/office/util/Slice4Pass2SyncNetworkTest.kt@@ -1,11 +1,12 @@ package com.vayunmathur.office.util -import kotlinx.coroutines.CoroutineScope-import kotlinx.coroutines.Dispatchers-import kotlinx.coroutines.cancel+import com.vayunmathur.e2ee.E2ee+import com.vayunmathur.library.network.SimpleResponse import kotlinx.coroutines.runBlocking import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner+import kotlin.io.encoding.Base64+import kotlin.test.AfterTest import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFalse@@ -14,14 +15,28 @@ import kotlin.test.assertNull import kotlin.test.assertTrue  /**- * Slice 4 pass 2: OfficeSync offline behaviour. No relay is reachable from- * unit tests, and OfficeSync.raw() maps every transport failure to null —- * these tests pin the graceful-degradation contract of each public entry- * point plus the pure inbox/live-message sorting.+ * Slice 4 pass 2: OfficeSync relay behaviour through the fake [OfficeSync.HttpTransport]+ * seam — tests must never reach the real relay (CI has internet), so every response+ * below is scripted: success bodies, HTTP errors, and transport failure (null).  */ @RunWith(RobolectricTestRunner::class) class Slice4Pass2SyncNetworkTest { +    @AfterTest fun tearDown() {+        OfficeSync.httpTransport = null+    }++    private fun response(status: Int, body: String, url: String = "") =+        SimpleResponse(status, "", body, emptyMap(), url)++    private fun installFake(handler: (String, String) -> SimpleResponse?) {+        val urls = mutableListOf<String>()+        OfficeSync.httpTransport = OfficeSync.HttpTransport { url, body ->+            urls += url+            handler(url, body)+        }+    }+     @Test fun documentKeysAndIdsAreFresh() {         val k1 = OfficeSync.newDocumentKey()         val k2 = OfficeSync.newDocumentKey()@@ -31,14 +46,11 @@ class Slice4Pass2SyncNetworkTest {         assertTrue(OfficeSync.newDocumentId().isNotBlank())     } -    @Test fun networkFailurePathsDegradeGracefully() = runBlocking {+    @Test fun transportFailureDegradesGracefully() = runBlocking {+        installFake { _, _ -> null }         val key = OfficeSync.newDocumentKey()-        // Relay unreachable / NetworkClient uninitialised in tests: raw() -> null.         assertNull(OfficeSync.getKey("device-x"))-        assertEquals(-            OfficeSync.DocActionsResult(emptyList(), 7).items,-            OfficeSync.pullDocActions("doc1", key, 7).items,-        )+        assertEquals(emptyList(), OfficeSync.pullDocActions("doc1", key, 7).items)         assertEquals(7, OfficeSync.pullDocActions("doc1", key, 7).seq)         assertNull(OfficeSync.appendDocActions("doc1", key, listOf("op")))         assertNull(OfficeSync.append("chan", listOf("blob")))@@ -46,15 +58,56 @@ class Slice4Pass2SyncNetworkTest {         val inbox = OfficeSync.pullInbox(5)         assertTrue(inbox.invites.isEmpty() && inbox.requests.isEmpty())         assertEquals(5, inbox.seq)-        val invites = OfficeSync.pullInvites(2)-        assertTrue(invites.invites.isEmpty())-        assertEquals(2, invites.seq)-        assertFalse(-            OfficeSync.sendInvite("recip", "doc1", key, "Title", false, "editor", "", "")-        )+        assertTrue(OfficeSync.pullInvites(2).invites.isEmpty())+        assertFalse(OfficeSync.sendInvite("recip", "doc1", key, "Title", false, "editor", "", ""))         assertFalse(OfficeSync.sendJoinRequest("owner", "doc1", "req", "Name"))     } +    @Test fun scriptedRelaySuccessPaths() = runBlocking {+        val key = OfficeSync.newDocumentKey()+        val encrypted = Base64.encode(E2ee.aesEncrypt(key, "hello op".encodeToByteArray()))+        val seenPaths = mutableListOf<String>()+        OfficeSync.httpTransport = OfficeSync.HttpTransport { url, _ ->+            seenPaths += url+            when {+                url.endsWith("/getkey") -> response(200, Base64.encode(byteArrayOf(9, 8, 7)))+                url.endsWith("/append") -> response(200, """{"seq":42}""")+                url.endsWith("/pull") -> response(+                    200,+                    """{"actions":["$encrypted","!!not-base64!!"],"seq":9}""",+                )+                else -> response(404, "")+            }+        }++        assertEquals(byteArrayOf(9, 8, 7).toList(), OfficeSync.getKey("device-y")!!.toList())+        assertEquals(42, OfficeSync.appendDocActions("doc1", key, listOf("op")))+        assertEquals(42, OfficeSync.append("chan", listOf("blob")))++        // Garbage action in the batch is skipped, the valid one decrypts.+        val pulled = OfficeSync.pullDocActions("doc1", key, 0)+        assertEquals(listOf("hello op"), pulled.items)+        assertEquals(9, pulled.seq)++        // Inbox blobs cannot be decrypted without an identity: batch is emptied, seq kept.+        val inbox = OfficeSync.pullInbox(0)+        assertTrue(inbox.invites.isEmpty() && inbox.requests.isEmpty())+        assertEquals(9, inbox.seq)++        assertTrue(seenPaths.all { it.startsWith("https://api.maproj.org/office/") }, seenPaths.toString())+    }++    @Test fun httpErrorStatusIsFailure() = runBlocking {+        installFake { _, _ -> response(500, "boom") }+        val key = OfficeSync.newDocumentKey()+        assertNull(OfficeSync.getKey("device-x"))+        assertNull(OfficeSync.append("chan", listOf("blob")))+        assertNull(OfficeSync.pull("chan", 0))+        // getKey fails first, so invite/join never reach PQC sealing.+        assertFalse(OfficeSync.sendInvite("recip", "doc1", key, "T", false, "editor", "", ""))+        assertFalse(OfficeSync.sendJoinRequest("owner", "doc1", "req", "N"))+    }+     @Test fun liveAppendAndPresenceWithoutSession() = runBlocking {         val key = OfficeSync.newDocumentKey()         // No WebSocket session: append refuses, presence is a silent no-op.@@ -63,21 +116,6 @@ class Slice4Pass2SyncNetworkTest {         OfficeSync.stopLive()     } -    @Test fun startAndStopLiveDoesNotThrow() {-        val scope = CoroutineScope(Dispatchers.IO)-        try {-            var connected = false-            OfficeSync.startLive(scope, "chan-test", onConnected = { connected = true }, onMessage = {})-            // Same channel while active: second call is a no-op guard.-            OfficeSync.startLive(scope, "chan-test", onConnected = { connected = true }, onMessage = {})-            OfficeSync.stopLive()-            assertFalse(connected, "no relay in tests, so no connection callback")-        } finally {-            scope.cancel()-            OfficeSync.stopLive()-        }-    }-     @Test fun sortInboxTextSortsKindsAndSkipsGarbage() {         val inviteJson = """{"docId":"d1","key":"a2V5","title":"Report","charMode":true,"role":"viewer","ownerKey":"b3du","charKind":"text"}"""         val reqJson = """{"kind":"req","docId":"d2","requesterId":"dev1","name":"Carol"}"""