Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
main ▾

Modern-Apps.git / office / src / test / java / com / vayunmathur / office / platform / OfficeViewModelTracked2Slice3Test.kt

OfficeViewModelTracked2Slice3Test.kt291 lines · 12.7 KiBRaw
1package com.vayunmathur.office.platform
2
3import com.vayunmathur.library.ui.odf.OdfContentBlock
4import com.vayunmathur.library.ui.odf.OdfDocument
5import com.vayunmathur.library.ui.odf.OdfParagraph
6import com.vayunmathur.library.ui.odf.OdfSpan
7import com.vayunmathur.library.ui.odf.OdfTable
8import com.vayunmathur.library.ui.odf.OdfTableCell
9import com.vayunmathur.library.ui.odf.OdfTableRow
10import kotlin.test.Test
11import kotlin.test.assertEquals
12import kotlin.test.assertFalse
13import kotlin.test.assertNull
14import kotlin.test.assertTrue
15import kotlinx.coroutines.test.runTest
16import org.mockito.ArgumentMatchers.anyBoolean
17import org.mockito.ArgumentMatchers.anyString
18import org.mockito.Mockito.`when`
19import org.mockito.Mockito.mock
20
21import com.vayunmathur.office.sync.OfficeSync
22/**
23 * Slice 3/4, round 2: tracked-change branches in tables/TOC, footnote/comment edge
24 * paths, page-setup/header guards, plus the network-free sync helpers
25 * (role gates, signing inputs, DataStore index/requests, live presence decode).
26 */
27@OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)
28class OfficeViewModelTracked2Slice3Test : OfficeViewModelSlice3Harness() {
29
30 private fun textDoc(vararg texts: String) = OdfDocument.TextDocument(
31 title = "Doc",
32 content = texts.map { OdfContentBlock.Paragraph(OdfParagraph(listOf(OdfSpan(it)))) },
33 )
34
35 private fun loaded(vararg texts: String): OfficeViewModel {
36 val vm = newVm()
37 vm.stateMutable.value = OfficeViewModel.ViewState.Loaded(textDoc(*texts))
38 return vm
39 }
40
41 private fun textOf(vm: OfficeViewModel): OdfDocument.TextDocument =
42 (vm.state.value as OfficeViewModel.ViewState.Loaded).document as OdfDocument.TextDocument
43
44 private fun paraTexts(doc: OdfDocument.TextDocument): List<String> =
45 doc.content.map {
46 ((it as? OdfContentBlock.Paragraph)?.paragraph?.spans?.joinToString("") { s -> s.text })
47 ?: "<${it.javaClass.simpleName}>"
48 }
49
50 @Test
51 fun `transformChangeSpans covers tables and toc`() = runTest {
52 val cell = OdfTableCell(listOf(OdfParagraph(listOf(
53 OdfSpan("keep "),
54 OdfSpan("gone", changeId = "d1", changeKind = "deletion"),
55 ))))
56 val doc = textDoc("p").copy(
57 changes = listOf(com.vayunmathur.library.ui.odf.OdfChange(id = "d1", type = "deletion")),
58 content = listOf(
59 OdfContentBlock.Table(OdfTable("T", rows = listOf(OdfTableRow(listOf(cell))))),
60 OdfContentBlock.TableOfContents("TOC", listOf(
61 OdfParagraph(listOf(
62 OdfSpan("entry "),
63 OdfSpan("old", changeId = "d1", changeKind = "deletion"),
64 )))),
65 OdfContentBlock.PageBreak,
66 ),
67 )
68 val vm = newVm()
69 vm.stateMutable.value = OfficeViewModel.ViewState.Loaded(doc)
70 // Accept deletion: marked spans removed from table cell and TOC entry.
71 vm.acceptChange("d1")
72 val after = textOf(vm)
73 val cellText = after.let {
74 (((it.content[0] as OdfContentBlock.Table).table.rows[0].cells[0]
75 .paragraphs[0].spans.joinToString("") { s -> s.text }))
76 }
77 assertEquals("keep ", cellText)
78 val tocText = ((after.content[1] as OdfContentBlock.TableOfContents)
79 .entries[0].spans.joinToString("") { it.text })
80 assertEquals("entry ", tocText)
81 assertTrue(after.changes.isEmpty())
82 }
83
84 @Test
85 fun `reject insertion clears markers but keeps other spans`() = runTest {
86 val doc = textDoc("p").copy(
87 changes = listOf(com.vayunmathur.library.ui.odf.OdfChange(id = "i1", type = "insertion")),
88 content = listOf(
89 OdfContentBlock.Paragraph(OdfParagraph(listOf(
90 OdfSpan("a", changeId = "i1", changeKind = "insertion"),
91 OdfSpan("b"),
92 ))),
93 ),
94 )
95 val vm = newVm()
96 vm.stateMutable.value = OfficeViewModel.ViewState.Loaded(doc)
97 vm.rejectChange("i1")
98 assertEquals(listOf("b"), paraTexts(textOf(vm)))
99 }
100
101 @Test
102 fun `footnote without paragraph run still records footnote`() = runTest {
103 val vm = newVm()
104 vm.stateMutable.value = OfficeViewModel.ViewState.Loaded(
105 OdfDocument.TextDocument(title = "D", content = listOf(OdfContentBlock.PageBreak)))
106 // No paragraph run (block 0 is a PageBreak) -> marker insert skipped, footnote kept.
107 vm.insertFootnote(0, 0, 0, "lonely")
108 assertEquals(1, textOf(vm).footnotes.size)
109 assertEquals("1", textOf(vm).footnotes[0].citation)
110 }
111
112 @Test
113 fun `endnote flag and citation increments`() = runTest {
114 val vm = loaded("t")
115 vm.insertFootnote(0, 0, 1, "first")
116 vm.insertFootnote(0, 0, 1, "second", isEndnote = true)
117 assertEquals(listOf("1", "2"), textOf(vm).footnotes.map { it.citation })
118 assertTrue(textOf(vm).footnotes[1].isEndnote)
119 }
120
121 @Test
122 fun `comment guards non-paragraph and plain spans`() = runTest {
123 val vm = newVm()
124 vm.stateMutable.value = OfficeViewModel.ViewState.Loaded(
125 OdfDocument.TextDocument(title = "D", content = listOf(OdfContentBlock.PageBreak)))
126 // Non-paragraph block -> no-op.
127 vm.insertComment(0, "Ann", "x")
128 assertTrue(textOf(vm).content.all { it is OdfContentBlock.PageBreak })
129 val vm2 = loaded("plain")
130 // Span without annotation -> resolve is a no-op (text kept).
131 vm2.resolveComment(0, 0)
132 assertEquals(listOf("plain"), paraTexts(textOf(vm2)))
133 // Out-of-range indices -> no-op.
134 vm2.resolveComment(0, 9)
135 vm2.resolveComment(9, 0)
136 assertEquals(listOf("plain"), paraTexts(textOf(vm2)))
137 }
138
139 @Test
140 fun `page setup header footer ignore non-text docs`() = runTest {
141 val vm = newVm()
142 vm.stateMutable.value = OfficeViewModel.ViewState.Loaded(
143 OdfDocument.Spreadsheet(title = "B", sheets = emptyList()))
144 vm.setPageSetup(com.vayunmathur.library.ui.odf.OdfPageSetup())
145 vm.setHeaderText("h")
146 vm.setFooterText("f")
147 // Still a spreadsheet, untouched.
148 assertTrue((vm.state.value as OfficeViewModel.ViewState.Loaded)
149 .document is OdfDocument.Spreadsheet)
150 assertFalse(vm.canUndo.value)
151 }
152
153 @Test
154 fun `memberKey serves cache without network`() = runTest {
155 val vm = idleVm()
156 vm.memberKeyCache["peer1"] = byteArrayOf(1, 2, 3)
157 assertEquals(listOf<Byte>(1, 2, 3), vm.memberKey("peer1")!!.toList())
158 // NOTE: uncached ids hit OfficeSync.getKey (network) — not exercised here.
159 }
160
161 @Test
162 fun `fetch null-owner paths return empty without network`() = runTest {
163 val vm = idleVm()
164 val key = byteArrayOf(9, 9)
165 assertEquals(0 to key, vm.fetchCurrentKey("d", key, null).let { it.first to it.second })
166 assertTrue(vm.fetchMembers("d", key, null).isEmpty())
167 assertNull(vm.fetchTitle("d", key, null))
168 // Owner-key fetch with blank base returns null before any network.
169 assertNull(vm.fetchOwnerKey("d", ""))
170 assertNull(vm.fetchOwnerKey("d", "!!!not-base64!!!"))
171 }
172
173 @Test
174 fun `pollTitle mismatch and setLoadedTitle guards`() = runTest {
175 val vm = loaded("x")
176 // Different doc id -> early return, no network.
177 vm.pollTitle("other", byteArrayOf(1))
178 assertEquals("x", paraTexts(textOf(vm))[0])
179 // No loaded doc -> setLoadedTitle is a no-op.
180 val empty = idleVm()
181 empty.setLoadedTitle("N")
182 assertTrue(empty.state.value is OfficeViewModel.ViewState.Empty)
183 // Same title -> no state churn.
184 val before = vm.state.value
185 vm.setLoadedTitle("Doc")
186 assertEquals(before, vm.state.value)
187 }
188
189 @Test
190 fun `currentOnlineTitle withTitle all variants`() = runTest {
191 val vm = idleVm()
192 assertNull(vm.currentOnlineTitle())
193 vm.currentDocId = "d1"
194 assertNull(vm.currentOnlineTitle())
195 vm.onlineDocsMutable.value = listOf(
196 OfficeDocMeta(docId = "d1", title = "T", keyB64 = "", owner = false))
197 assertEquals("T", vm.currentOnlineTitle())
198 val sheet = OdfDocument.Spreadsheet(title = "S", sheets = emptyList())
199 assertEquals("N", (vm.withTitle(sheet, "N") as OdfDocument.Spreadsheet).title)
200 val pres = OdfDocument.Presentation(title = "P", slides = emptyList())
201 assertEquals("N", (vm.withTitle(pres, "N") as OdfDocument.Presentation).title)
202 val draw = OdfDocument.Drawing(title = "G", pages = emptyList())
203 assertEquals("N", (vm.withTitle(draw, "N") as OdfDocument.Drawing).title)
204 }
205
206 @Test
207 fun `index and requests round-trip through datastore`() = runTest {
208 // Map-backed DataStoreUtils mock: getInstance() is a process-wide singleton
209 // bound to whichever test's (deleted) tmpDir came first, so drive the
210 // suspend index/request helpers directly against a fake instead.
211 val backing = mutableMapOf<String, String?>()
212 val ds = mock(com.vayunmathur.library.util.DataStoreUtils::class.java)
213 `when`(ds.getString(anyString()))
214 .thenAnswer { backing[it.arguments[0] as String] }
215 `when`(ds.setString(anyString(), anyString(), anyBoolean()))
216 .thenAnswer {
217 backing[it.arguments[0] as String] = it.arguments[1] as String?
218 null
219 }
220 val vm = idleVm()
221 val metas = listOf(
222 OfficeDocMeta(docId = "d1", title = "One", keyB64 = "a2V5", owner = true))
223 vm.saveIndex(ds, metas)
224 assertEquals(metas, vm.loadIndex(ds))
225 assertEquals(metas, vm.onlineDocsMutable.value)
226 val reqs = listOf(OfficeSync.JoinRequest(docId = "d1", requesterId = "r1"))
227 vm.saveRequests(ds, reqs)
228 assertEquals(reqs, vm.loadRequests(ds))
229 assertEquals(reqs, vm.pendingRequestsMutable.value)
230 // Corrupt blobs fall back to empty.
231 backing["officeDocsIndex"] = "not-json{{"
232 assertTrue(vm.loadIndex(ds).isEmpty())
233 backing["officePendingRequests"] = "not-json{{"
234 assertTrue(vm.loadRequests(ds).isEmpty())
235 }
236
237 @Test
238 fun `owner guards refuse without owner role`() = runTest {
239 val vm = idleVm()
240 vm.currentRole = OfficeRoles.VIEWER
241 vm.currentDocKey = byteArrayOf(1)
242 // recordMembers + rotateKey early-return for non-owners (no network, no crash).
243 vm.recordMembers("d", byteArrayOf(1), listOf(OfficeMember("x")))
244 vm.rotateKey("d")
245 assertEquals(0, vm.currentEpoch)
246 }
247
248 @Test
249 fun `applyLivePresence decodes and tracks peers`() = runTest {
250 val selfId = OfficeSync.deviceId
251 val vm = idleVm()
252 val key = ByteArray(32) { it.toByte() }
253 fun blob(p: OfficePresence): String {
254 val raw = com.vayunmathur.e2ee.E2ee.aesEncrypt(
255 key, vm.syncJson.encodeToString(OfficePresence.serializer(), p).encodeToByteArray())
256 return kotlin.io.encoding.Base64.encode(raw)
257 }
258 // Self presence is ignored.
259 vm.applyLivePresence(OfficeSync.LiveMsg(t = "presence", data = blob(
260 OfficePresence(selfId, "Me", typing = false, ts = 1))), key)
261 assertTrue(vm.remotePresenceMutable.value.isEmpty())
262 // Peer presence is recorded.
263 vm.applyLivePresence(OfficeSync.LiveMsg(t = "presence", data = blob(
264 OfficePresence("peer1", "Ann", typing = true, ts = 1, caret = 3))), key)
265 val peers = vm.remotePresenceMutable.value
266 assertEquals(1, peers.size)
267 assertEquals("peer1", peers[0].id)
268 assertTrue(peers[0].typing)
269 assertTrue(peers[0].typingTs > 0)
270 // Garbage blob is ignored.
271 vm.applyLivePresence(OfficeSync.LiveMsg(t = "presence", data = "!!!"), key)
272 assertEquals(1, vm.remotePresenceMutable.value.size)
273 // Typing=false keeps the previous typing timestamp.
274 val tsBefore = vm.remotePresenceMutable.value[0].typingTs
275 vm.applyLivePresence(OfficeSync.LiveMsg(t = "presence", data = blob(
276 OfficePresence("peer1", "Ann", typing = false, ts = 1))), key)
277 assertEquals(tsBefore, vm.remotePresenceMutable.value[0].typingTs)
278 }
279
280 @Test
281 fun `myName derives suffix and enableOnlineSharing short-circuits`() = runTest {
282 val vm = idleVm()
283 // "User " + last 4 of the device id (whatever it is in this environment).
284 assertEquals("User " + OfficeSync.deviceId.takeLast(4), vm.myName())
285 assertEquals(vm.myName(), vm.myDisplayName())
286 vm.onlineEnabledMutable.value = true
287 // Already enabled -> returns before initSync/network.
288 vm.enableOnlineSharing()
289 assertTrue(vm.onlineEnabled.value)
290 }
291}