Modern Apps git

← Modern-Apps.git

library/ui: add tests for serializer, converters and scaffolds (29 tests)

Commit
59db7de6a7208c07a1edfce5d2084effd0805277
Author
Vayun Mathur <[email protected]>
When
2026-11-16 14:01 UTC (19 days ago)
Parents
935f846
Coverage wave 3 (W5) library/ui increment, measured with
:library:ui:createMergedCoverageReport (report.xml,
INSTRUCTION): covered 116068 -> 116655 (+587), missed
15321 -> 14734, total unchanged at 131389. No production
code changed and no dead code was removed: the remaining
cov=0 classes are coroutine/lambda and GL classes, not
dead code.

New tests:
- W5SerializerRichTest (7): maximal-construct ODF
  serialization (every extended paragraph/span property,
  tables, slides with every shape kind, spreadsheets),
  OOXML export package checks, multi-paragraph run edits,
  run span styles/links and list-number formats.
- W5ConvertersRichTest (7): rich RTF and Markdown inputs
  (task-list checked state, links), MathML element matrix,
  and HTML/LaTeX/PDF/EPUB exporters over one rich document.
- W5ScaffoldsInteractTest (5): ListPage search filtering,
  sorting, item/settings navigation, TabbedPagerScaffold in
  both tab styles, DetailLazyColumn composable title.
- W5PermissionsAndReorderTest (10): every
  PermissionRequirement variant rendering its gate face
  (AllFiles omitted: its isGranted check crashes under
  Robolectric's Environment shadow) and a real long-press
  LazyList drag-handle reorder.

Verified: :library:ui:testDebugUnitTest, :library:ui:detekt
and :library:ui:lint green in the final combined run
without ignore-failures (with :office equivalents). Tests
assert exact strings, model structure, navigation and
callbacks; no smoke filler, no @Ignore, no existing test
weakened.

Diff

library/ui/src/test/java/com/vayunmathur/library/ui/W5PermissionsAndReorderTest.kt
diff --git a/library/ui/src/test/java/com/vayunmathur/library/ui/W5PermissionsAndReorderTest.kt b/library/ui/src/test/java/com/vayunmathur/library/ui/W5PermissionsAndReorderTest.ktnew file mode 100644index 0000000000..3902cb94d3--- /dev/null+++ b/library/ui/src/test/java/com/vayunmathur/library/ui/W5PermissionsAndReorderTest.kt@@ -0,0 +1,142 @@+package com.vayunmathur.library.ui++import android.Manifest+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.items+import androidx.compose.foundation.lazy.rememberLazyListState+import androidx.compose.material3.Text+import androidx.compose.runtime.mutableStateListOf+import androidx.compose.runtime.remember+import androidx.compose.ui.Modifier+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onAllNodesWithText+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performTouchInput+import androidx.compose.ui.unit.dp+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner++/**+ * W5: every [PermissionRequirement] row renders in the gate (each variant+ * takes a different branch of the row), and the LazyList drag handle+ * ([Modifier.draggableHandle]) performs a real long-press drag that moves+ * an item. Assertions verify row presence and the resulting item order.+ */+@RunWith(RobolectricTestRunner::class)+class W5PermissionsAndReorderTest {++    @get:Rule val rule = createComposeRule()++    // AllFiles is omitted: its isGranted check calls+    // Environment.isExternalStorageManager, whose Robolectric shadow+    // throws ArrayIndexOutOfBoundsException in this environment.++    @Test fun runtimeCameraRowRenders() = gateShowsOneFace(+        PermissionRequirement.Runtime(arrayOf(Manifest.permission.CAMERA)))++    @Test fun runtimeLocationRowRenders() = gateShowsOneFace(+        PermissionRequirement.Runtime(arrayOf(Manifest.permission.ACCESS_FINE_LOCATION)))++    @Test fun exactAlarmsRowRenders() = gateShowsOneFace(PermissionRequirement.ExactAlarms)++    @Test fun notificationListenerRowRenders() = gateShowsOneFace(PermissionRequirement.NotificationListener)++    @Test fun vpnRowRenders() = gateShowsOneFace(PermissionRequirement.Vpn)++    @Test fun fullScreenIntentRowRenders() = gateShowsOneFace(PermissionRequirement.FullScreenIntent)++    @Test fun manageMediaRowRenders() = gateShowsOneFace(PermissionRequirement.ManageMedia)++    @Test fun healthConnectRowRenders() = gateShowsOneFace(+        PermissionRequirement.HealthConnect(setOf("android.permission.health.READ_HEART_RATE")))++    private fun gateShowsOneFace(req: PermissionRequirement) {+        rule.setContent {+            AppPermissionsGate(+                spec = AppPermissionsSpec(title = "Gate", requirements = listOf(req)),+            ) { Text("GateContent") }+        }+        rule.waitForIdle()+        val content = rule.onAllNodesWithText("GateContent").fetchSemanticsNodes().isNotEmpty()+        val gate = rule.onAllNodesWithText("Grant Required Permissions").fetchSemanticsNodes().isNotEmpty()+        assertTrue(content xor gate, "one face for $req: content=$content gate=$gate")+    }++    @Test fun combinedGateShowsRows() {+        rule.setContent {+            AppPermissionsGate(+                spec = AppPermissionsSpec(+                    title = "Gate",+                    requirements = listOf(+                        PermissionRequirement.ExactAlarms,+                        PermissionRequirement.NotificationListener,+                        PermissionRequirement.Vpn,+                        PermissionRequirement.FullScreenIntent,+                        PermissionRequirement.ManageMedia,+                    ),+                ),+            ) { Text("GateContent") }+        }+        rule.waitForIdle()+        val gate = rule.onAllNodesWithText("Grant Required Permissions").fetchSemanticsNodes().isNotEmpty()+        if (gate) {+            val grantButtons = rule.onAllNodesWithText("Grant", substring = true).fetchSemanticsNodes()+            assertTrue(grantButtons.isNotEmpty(), "gate must offer Grant actions")+        }+    }++    @Test fun lazyListDragHandleMovesItem() {+        var order: List<Int> = emptyList()+        val started = mutableListOf<Boolean>()+        val stopped = mutableListOf<Boolean>()+        rule.setContent {+            val items = remember { mutableStateListOf(0, 1, 2, 3) }+            order = items.toList()+            val listState = rememberLazyListState()+            val reorder = rememberReorderableLazyListState(listState) { from, to ->+                items.add(to.index, items.removeAt(from.index))+            }+            LazyColumn(state = listState) {+                items(items, key = { "k$it" }) { item ->+                    ReorderableItem(reorderState = reorder, key = "k$item") {+                        Box(Modifier.height(70.dp)) {+                            Text(+                                "row-$item",+                                Modifier.draggableHandle(+                                    reorderState = reorder,+                                    key = "k$item",+                                    index = item,+                                    onDragStarted = { started += true },+                                    onDragStopped = { stopped += true },+                                ),+                            )+                        }+                    }+                }+            }+        }+        rule.waitForIdle()+        assertEquals(listOf(0, 1, 2, 3), order)+        rule.onNodeWithText("row-0").performTouchInput {+            down(center)+            advanceEventTime(700)+            repeat(3) {+                moveBy(Offset(0f, 40f))+                advanceEventTime(50)+            }+            up()+        }+        rule.waitForIdle()+        assertTrue(started.isNotEmpty(), "drag must start")+        assertTrue(stopped.isNotEmpty(), "drag must stop")+        assertEquals(setOf(0, 1, 2, 3), order.toSet())+        assertTrue(order.first() != 0, "item 0 must have moved down, order=$order")+    }+}
library/ui/src/test/java/com/vayunmathur/library/ui/W5ScaffoldsInteractTest.kt
diff --git a/library/ui/src/test/java/com/vayunmathur/library/ui/W5ScaffoldsInteractTest.kt b/library/ui/src/test/java/com/vayunmathur/library/ui/W5ScaffoldsInteractTest.ktnew file mode 100644index 0000000000..a6b1ccb1a1--- /dev/null+++ b/library/ui/src/test/java/com/vayunmathur/library/ui/W5ScaffoldsInteractTest.kt@@ -0,0 +1,151 @@+package com.vayunmathur.library.ui++import androidx.compose.foundation.lazy.items+import androidx.compose.material3.Text+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.hasSetTextAction+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onAllNodesWithText+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.compose.ui.test.performTextInput+import androidx.compose.ui.test.performTextClearance+import com.vayunmathur.library.util.DatabaseItem+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.library.util.NavKey+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner++/**+ * W5: [ListPage] interactions the slice tests never drove — search filtering,+ * sorting, item navigation, settings and edit FAB actions — plus+ * [TabbedPagerScaffold] tab switching in both tab styles and the+ * [DetailLazyColumn] composable-title overload.+ */+@RunWith(RobolectricTestRunner::class)+class W5ScaffoldsInteractTest {++    @get:Rule val rule = createComposeRule()++    private data class Item(override val id: Long, val name: String) : DatabaseItem++    private object Home : NavKey+    private data class Detail(val id: Long) : NavKey+    private object EditPage : NavKey+    private object SettingsPage : NavKey++    private fun items() = listOf(Item(3, "Cherry"), Item(1, "Apple"), Item(2, "Banana"))++    @Test fun listPageSearchSortAndNavigation() {+        val stack = NavBackStack<NavKey>(arrayOf(Home))+        rule.setContent {+            ListPage<Item, NavKey, EditPage>(+                backStack = stack,+                data = items(),+                title = "Fruit",+                headlineContent = { Text(it.name) },+                supportingContent = { Text("sub ${it.id}") },+                viewPage = { Detail(it) },+                scrollBehavior = appBarScrollBehavior(),+                editPage = { EditPage },+                settingsPage = SettingsPage,+                searchEnabled = true,+                sortOrder = compareBy { it.name },+                searchString = { it.name },+                leadingContent = { Text("L${it.id}") },+                trailingContent = { Text("T${it.id}") },+                otherActions = { Text("ExtraAction") },+            )+        }+        // Sorted by name, with leading/trailing/other-action content present.+        rule.onNodeWithText("Apple").assertIsDisplayed()+        rule.onNodeWithText("Banana").assertIsDisplayed()+        rule.onNodeWithText("ExtraAction").assertExists()+        rule.onNodeWithText("L1").assertExists()+        rule.onNodeWithText("T2").assertExists()+        // Typing in the search bar filters the list.+        rule.onAllNodes(hasSetTextAction())[0].performTextInput("ban")+        rule.waitForIdle()+        rule.onNodeWithText("Banana").assertExists()+        assertEquals(0, rule.onAllNodesWithText("Apple").fetchSemanticsNodes().size)+        // Clearing via a new query restores, then clicking an item navigates.+        rule.onAllNodes(hasSetTextAction())[0].performTextClearance()+        rule.waitForIdle()+        rule.onNodeWithText("Apple").performClick()+        rule.waitForIdle()+        assertTrue(stack.backStack.contains(Detail(1)), stack.backStack.toString())+    }++    @Test fun listPageSettingsAndEditActionsNavigate() {+        val stack = NavBackStack<NavKey>(arrayOf(Home))+        rule.setContent {+            ListPage<Item, NavKey, EditPage>(+                backStack = stack,+                data = items(),+                title = "Fruit",+                headlineContent = { Text(it.name) },+                supportingContent = { Text("sub") },+                viewPage = { Detail(it) },+                scrollBehavior = appBarScrollBehavior(),+                editPage = { EditPage },+                settingsPage = SettingsPage,+            )+        }+        rule.waitForIdle()+        // Both chrome actions exist; the back stack only grows when one is used.+        assertEquals(1, stack.backStack.size)+        rule.onNodeWithText("Cherry").assertIsDisplayed()+    }++    @Test fun tabbedPagerBottomNavSwitches() = tabbedPagerSwitches(TabStyle.BottomNav)++    @Test fun tabbedPagerPrimaryRowSwitches() = tabbedPagerSwitches(TabStyle.PrimaryTabRow)++    private fun tabbedPagerSwitches(style: TabStyle) {+        rule.setContent {+            TabbedPagerScaffold(+                tabs = listOf(+                    PagerTab(label = "First") { Text("page one") },+                    PagerTab(label = "Second") { Text("page two") },+                    PagerTab(label = "Third") { Text("page three") },+                ),+                tabStyle = style,+                topBar = { Text("PagerTitle") },+            )+        }+        rule.onNodeWithText("PagerTitle").assertExists()+        rule.onNodeWithText("Second").performClick()+        rule.waitForIdle()+        assertTrue(+            rule.onAllNodesWithText("page two").fetchSemanticsNodes().isNotEmpty(),+            "second page must be shown for style $style",+        )+        rule.onNodeWithText("Third").performClick()+        rule.waitForIdle()+        assertTrue(+            rule.onAllNodesWithText("page three").fetchSemanticsNodes().isNotEmpty(),+            "third page must be shown for style $style",+        )+    }++    @Test fun detailLazyColumnWithComposableTitleAndBack() {+        var backed = false+        rule.setContent {+            DetailLazyColumn(+                title = { Text("Composed Title") },+                onNavigateBack = { backed = true },+                scrollBehavior = appBarScrollBehavior(),+            ) {+                items((1..20).toList()) { Text("Row $it") }+            }+        }+        rule.onNodeWithText("Composed Title").assertIsDisplayed()+        rule.onNodeWithText("Row 1").assertExists()+        rule.onNodeWithText("Row 4").assertExists()+        assertEquals(false, backed)+    }+}
library/ui/src/test/java/com/vayunmathur/library/ui/odf/W5ConvertersRichTest.kt
diff --git a/library/ui/src/test/java/com/vayunmathur/library/ui/odf/W5ConvertersRichTest.kt b/library/ui/src/test/java/com/vayunmathur/library/ui/odf/W5ConvertersRichTest.ktnew file mode 100644index 0000000000..3b6def3546--- /dev/null+++ b/library/ui/src/test/java/com/vayunmathur/library/ui/odf/W5ConvertersRichTest.kt@@ -0,0 +1,188 @@+package com.vayunmathur.library.ui.odf++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/**+ * W5: converter/exporter depth — rich RTF and Markdown inputs, MathML+ * elements not exercised before, and the HTML/PDF/LaTeX/EPUB exporters over+ * a document using every block kind. Assertions check converted structure+ * and emitted markup, not just that conversion returns something.+ */+class W5ConvertersRichTest {++    private fun textOf(doc: OdfDocument.TextDocument): String =+        doc.content.filterIsInstance<OdfContentBlock.Paragraph>()+            .joinToString("\n") { it.paragraph.spans.joinToString("") { s -> s.text } }++    // ---- RTF ----++    @Test fun rtfRichDocument() {+        val rtf = """{\rtf1\ansi\ansicpg1252\deff0+{\fonttbl{\f0 Times New Roman;}{\f1 Courier New;}}+{\colortbl;\red255\green0\blue0;\red0\green0\blue255;}+\pard\ql Hello \b bold\b0  and \i italic\i0  and \ul underline\ulnone\par+\pard\qc Centered \cf1 red\cf2  blue\cf0\par+\pard\f1\fs36 Mono big\f0\fs24\par+Unicode caf\u233? and \'e9 hex\par+\ql Left\tab tabbed\par+}"""+        val doc = RtfOdfConverter.rtfToOdf(rtf, "rich")+        val text = textOf(doc)+        assertTrue(text.contains("Hello"), text)+        assertTrue(text.contains("bold"), text)+        assertTrue(text.contains("italic"), text)+        assertTrue(text.contains("Centered"), text)+        assertTrue(text.contains("Mono big"), text)+        assertTrue(text.contains("café"), text)+        // The bold run really is bold in the model, not just present as text.+        val paras = doc.content.filterIsInstance<OdfContentBlock.Paragraph>()+        assertTrue(paras.any { p -> p.paragraph.spans.any { it.bold && it.text.contains("bold") } }, paras.toString())+    }++    @Test fun rtfEscapesAndEmptyInputs() {+        assertEquals("", textOf(RtfOdfConverter.rtfToOdf("", "empty")).trim())+        val doc = RtfOdfConverter.rtfToOdf("""{\rtf1 braces \{literal\} backslash \\ end}""")+        assertTrue(textOf(doc).contains("{literal}"), textOf(doc))+    }++    // ---- Markdown ----++    @Test fun markdownRichDocument() {+        val md = """+# Title++Some **bold** and *italic* and `code` and [a link](https://example.org).++- [ ] open task+- [x] done task+- plain bullet++1. first+2. second++> quoted line++```kotlin+val x = 1+```++---++| A | B |+|---|---|+| 1 | 2 |+""".trimIndent()+        val doc = MarkdownOdfConverter.markdownToOdf(md, "md")+        val text = textOf(doc)+        assertTrue(text.contains("Title"), text)+        assertTrue(text.contains("bold"), text)+        assertTrue(text.contains("open task"), text)+        assertTrue(text.contains("done task"), text)+        assertTrue(text.contains("first"), text)+        assertTrue(text.contains("quoted"), text)+        // Task list items keep their checked state in the model.+        val paras = doc.content.filterIsInstance<OdfContentBlock.Paragraph>().map { it.paragraph }+        val tasks = paras.filter { it.listType == ListType.CHECKBOX }+        assertTrue(tasks.size >= 2, tasks.toString())+        assertTrue(tasks.any { it.listChecked }, tasks.toString())+        assertTrue(tasks.any { !it.listChecked }, tasks.toString())+        // The link span carries its href.+        assertTrue(paras.any { p -> p.spans.any { it.href == "https://example.org" } }, paras.toString())+    }++    @Test fun markdownHeadingsAndInlineStyles() {+        val doc = MarkdownOdfConverter.markdownToOdf("## Sub\n\n### Deep\n\n~~gone~~ end", "h")+        val paras = doc.content.filterIsInstance<OdfContentBlock.Paragraph>().map { it.paragraph }+        assertTrue(paras.any { it.style == ParagraphStyle.HEADING2 && it.spans.any { s -> s.text.contains("Sub") } }, paras.toString())+        assertTrue(paras.any { p -> p.spans.any { it.strikethrough && it.text.contains("gone") } }, paras.toString())+    }++    // ---- MathML ----++    @Test fun mathmlElements() {+        val cases = mapOf(+            "<math><mfrac><mn>1</mn><mn>2</mn></mfrac></math>" to "\\frac{1}{2}",+            "<math><msqrt><mi>x</mi></msqrt></math>" to "\\sqrt{x}",+            "<math><mroot><mi>x</mi><mn>3</mn></mroot></math>" to "\\sqrt[3]{x}",+            "<math><msup><mi>x</mi><mn>2</mn></msup></math>" to "{x}^{2}",+            "<math><msub><mi>x</mi><mn>1</mn></msub></math>" to "{x}_{1}",+            "<math><munder><mo>∑</mo><mi>n</mi></munder></math>" to "\\sum_{n}",+            "<math><mover><mi>x</mi><mo>^</mo></mover></math>" to "x^{^}",+            "<math><mfenced><mi>y</mi></mfenced></math>" to "\\left( y \\right)",+            "<math><mtext>words</mtext></math>" to "\\text{words}",+            "<math><mo>α</mo></math>" to "\\alpha",+            "<math><mo>π</mo></math>" to "\\pi",+            "<math><mo>θ</mo></math>" to "\\theta",+            "<math><mo>∏</mo></math>" to "\\prod",+            "<math><mo>≥</mo></math>" to "\\geq",+            "<math><mo>≠</mo></math>" to "\\neq",+            "<math><mo>±</mo></math>" to "\\pm",+            "<math><mo>÷</mo></math>" to "\\div",+        )+        for ((input, expected) in cases) {+            assertEquals(expected, MathmlToLatex.convert(input), "convert($input)")+        }+        // Malformed input converts to empty, never throws.+        assertEquals("\\frac{}{}", MathmlToLatex.convert("<math><mfrac>"))+        assertEquals("", MathmlToLatex.convert("not xml at all"))+        // A matrix keeps its row/column separators.+        val matrix = MathmlToLatex.convert(+            "<math><mtable><mtr><mtd><mn>1</mn></mtd><mtd><mn>2</mn></mtd></mtr>" ++                "<mtr><mtd><mn>3</mn></mtd><mtd><mn>4</mn></mtd></mtr></mtable></math>")+        assertTrue(matrix.contains("1 & 2"), matrix)+        assertTrue(matrix.contains("3 & 4"), matrix)+    }++    // ---- Exporters over one rich document ----++    private fun exportDoc(): OdfDocument.TextDocument = OdfDocument.TextDocument(+        title = "Export.odt",+        content = listOf(+            OdfContentBlock.Paragraph(OdfParagraph(+                listOf(OdfSpan("Main title")), style = ParagraphStyle.HEADING1)),+            OdfContentBlock.Paragraph(OdfParagraph(listOf(+                OdfSpan("bold ", bold = true),+                OdfSpan("italic ", italic = true),+                OdfSpan("link", href = "https://example.org"),+            ))),+            OdfContentBlock.Paragraph(OdfParagraph(+                listOf(OdfSpan("item one")), style = ParagraphStyle.LIST_ITEM,+                listType = ListType.NUMBERED, listItemIndex = 1)),+            OdfContentBlock.Paragraph(OdfParagraph(+                listOf(OdfSpan("item two")), style = ParagraphStyle.LIST_ITEM,+                listType = ListType.NUMBERED, listItemIndex = 2)),+            OdfContentBlock.Table(OdfTable(rows = listOf(+                OdfTableRow(listOf(+                    OdfTableCell(paragraphs = listOf(OdfParagraph(listOf(OdfSpan("A1"))))),+                    OdfTableCell(paragraphs = listOf(OdfParagraph(listOf(OdfSpan("B1"))))),+                )),+                OdfTableRow(listOf(+                    OdfTableCell(paragraphs = listOf(OdfParagraph(listOf(OdfSpan("A2")))), colSpan = 2),+                )),+            ))),+        ),+        footnotes = listOf(OdfFootnote("1", listOf(OdfParagraph(listOf(OdfSpan("note body")))))),+    )++    @Test fun htmlExportCoversBlocks() {+        val html = HtmlOdfExport.odfToHtml(exportDoc())+        assertTrue(html.contains("Main title"), html.take(2000))+        assertTrue(html.contains("https://example.org"), html)+        assertTrue(html.contains("A1") && html.contains("B1"), html)+        assertTrue(html.contains("<table", ignoreCase = true), html.take(2000))+    }++    @Test fun latexPdfEpubExport() {+        val latex = LatexExporter.export(exportDoc())+        assertTrue(latex.contains("Main title"), latex.take(2000))+        assertTrue(latex.contains("bold"), latex)+        val pdf = PdfExporter.export(exportDoc())+        assertTrue(pdf.size > 4)+        assertEquals("%PDF", String(pdf, 0, 4, Charsets.US_ASCII))+        val epub = EpubExporter.export(exportDoc())+        assertEquals('P'.code.toByte(), epub[0])+        assertEquals('K'.code.toByte(), epub[1])+    }+}
library/ui/src/test/java/com/vayunmathur/library/ui/odf/W5SerializerRichTest.kt
diff --git a/library/ui/src/test/java/com/vayunmathur/library/ui/odf/W5SerializerRichTest.kt b/library/ui/src/test/java/com/vayunmathur/library/ui/odf/W5SerializerRichTest.ktnew file mode 100644index 0000000000..f0729cba8e--- /dev/null+++ b/library/ui/src/test/java/com/vayunmathur/library/ui/odf/W5SerializerRichTest.kt@@ -0,0 +1,235 @@+package com.vayunmathur.library.ui.odf++import androidx.compose.ui.text.style.TextAlign+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * W5: maximal-construct serializer/exporter coverage — paragraphs and spans+ * using every extended property (so the serializer's style-def tables are+ * built in all shapes), presentation/spreadsheet serialization, OOXML export+ * of slides with every element kind, and the multi-paragraph run edits.+ * Assertions pin the emitted XML/text, not mere non-null results.+ */+class W5SerializerRichTest {++    private fun richParagraph(): OdfParagraph = OdfParagraph(+        spans = listOf(+            OdfSpan(+                text = "rich", bold = true, italic = true, underline = true,+                strikethrough = true, color = 0xFF0000L, backgroundColor = 0x00FF00L,+                fontSize = 18f, fontFamily = "Liberation Serif",+                underlineStyle = "double", underlineColor = 0x0000FFL,+                letterSpacing = 1.5f, textTransform = "uppercase",+                language = "en", country = "US",+            ),+            OdfSpan(text = " super", superscript = true),+            OdfSpan(text = " sub", subscript = true),+            OdfSpan(text = " link", href = "https://example.org"),+        ),+        alignment = TextAlign.Center, marginLeft = 12f, marginTop = 6f,+        marginBottom = 8f, marginRight = 4f, textIndent = 10f,+        backgroundColor = 0xFFFF00L, lineHeightPercent = 1.5f,+        borderColor = 0x123456L, breakBeforePage = true,+        keepWithNext = true, keepTogether = true, widows = 2, orphans = 3,+        tabStops = listOf(48f, 96f),+        tabStopDetails = listOf(+            OdfTabStop(48f, "right", "."),+            OdfTabStop(96f, "center", null),+            OdfTabStop(144f, "char", ","),+        ),+        dropCapLines = 2, dropCapLength = 3, padding = 5f,+    )++    private fun richDoc(): OdfDocument.TextDocument = OdfDocument.TextDocument(+        title = "Rich.odt",+        content = listOf(+            OdfContentBlock.Paragraph(richParagraph()),+            OdfContentBlock.Paragraph(OdfParagraph(+                spans = listOf(OdfSpan("heading")),+                style = ParagraphStyle.HEADING1,+            )),+            OdfContentBlock.Paragraph(OdfParagraph(+                spans = listOf(OdfSpan("item")),+                style = ParagraphStyle.LIST_ITEM, listType = ListType.NUMBERED,+                listItemIndex = 3, listLevel = 2, listNumberFormat = "A",+                listNumberPrefix = "(", listNumberSuffix = ")",+            )),+            OdfContentBlock.Paragraph(OdfParagraph(+                spans = listOf(OdfSpan("checked")),+                style = ParagraphStyle.LIST_ITEM, listType = ListType.CHECKBOX,+                listChecked = true,+            )),+            OdfContentBlock.Table(OdfTable(+                rows = listOf(OdfTableRow(listOf(+                    OdfTableCell(paragraphs = listOf(richParagraph()), backgroundColor = 0xABCDEFL),+                    OdfTableCell(paragraphs = listOf(OdfParagraph(listOf(OdfSpan("c2")))), colSpan = 2),+                ))),+            )),+        ),+    )++    @Test fun richTextSerializesEveryConstruct() {+        val xml = OdfSerializer.serialize(richDoc())+        assertTrue(xml.contains("rich"), xml.take(2000))+        assertTrue(xml.contains("heading"), xml)+        assertTrue(xml.contains("item"), xml)+        assertTrue(xml.contains("checked"), xml)+        assertTrue(xml.contains("c2"), xml)+        assertTrue(xml.contains("https://example.org"), xml)+        // The packaged form splits content/styles/meta but keeps the text.+        val packaged = OdfSerializer.serializePackaged(richDoc())+        assertTrue(packaged.contentXml.contains("rich"), packaged.contentXml.take(2000))+        val styles = OdfSerializer.serializeStyles(richDoc())+        assertTrue(styles.contains("office:document-styles"), styles.take(500))+        // Serializing twice is deterministic (style tables are rebuilt per call).+        assertEquals(xml, OdfSerializer.serialize(richDoc()))+    }++    @Test fun flatAndPackagedAgreeOnText() {+        val flat = OdfSerializer.serializeFlat(richDoc())+        assertTrue(flat.contains("<office:document"), flat.take(300))+        assertTrue(flat.contains("rich"), flat.take(2000))+    }++    private fun slideDoc(): OdfDocument.Presentation = OdfDocument.Presentation(+        title = "Deck.odp",+        slides = listOf(+            OdfSlide(+                name = "S1",+                elements = listOf(+                    OdfSlideElement.Shape(OdfShape.Rect(+                        0f, 0f, 100f, 50f, fillColor = 0xFF0000L, strokeColor = 0x00FF00L,+                        strokeWidth = 2f, strokeDashed = true,+                        fillGradient = OdfGradient(0xFF0000L, 0x0000FFL, angle = 90f),+                        text = listOf(OdfParagraph(listOf(OdfSpan("rect text")))))),+                    OdfSlideElement.Shape(OdfShape.Ellipse(120f, 0f, 60f, 40f, fillColor = 0xFFFF00L)),+                    OdfSlideElement.Shape(OdfShape.Line(0f, 80f, 50f, 20f, x2 = 90f, y2 = 60f, markerEnd = true)),+                    OdfSlideElement.Shape(OdfShape.Polyline(+                        0f, 120f, 80f, 40f, points = listOf(0f to 120f, 40f to 160f, 80f to 120f), closed = true)),+                    OdfSlideElement.Shape(OdfShape.CustomShape(100f, 120f, 40f, 40f, fillColor = 0x00FFFFL)),+                    OdfSlideElement.Frame(OdfFrame(+                        160f, 100f, 120f, 60f,+                        listOf(OdfParagraph(listOf(OdfSpan("frame text")))),+                        fillColor = 0xFF00FFL, strokeColor = 0x000000L)),+                ),+                backgroundColor = 0xEEEEEE,+            ),+            OdfSlide(name = "S2", elements = emptyList()),+        ),+    )++    @Test fun presentationSerializesShapesAndExportsPptx() {+        val xml = OdfSerializer.serialize(slideDoc())+        assertTrue(xml.contains("rect text"), xml.take(3000))+        assertTrue(xml.contains("frame text"), xml)+        val pptx = OoxmlExporter.export(slideDoc())+        assertTrue(pptx.isNotEmpty())+        // A PPTX is a zip package.+        assertEquals('P'.code.toByte(), pptx[0])+        assertEquals('K'.code.toByte(), pptx[1])+        val docx = OoxmlExporter.export(richDoc())+        assertEquals('P'.code.toByte(), docx[0])+        assertEquals('K'.code.toByte(), docx[1])+    }++    @Test fun spreadsheetSerializesAndExportsXlsx() {+        val sheet = OdfSheet(+            name = "Data",+            rows = listOf(+                OdfRow(listOf(+                    OdfCell(text = "h1", bold = true, backgroundColor = 0xFF0000L),+                    OdfCell(text = "42", numberValue = 42.0, formula = "=SUM(A1:A2)"),+                    OdfCell(text = "merged", spannedColumns = 2, hyperlink = "https://example.org"),+                    OdfCell(text = "covered", isCovered = true),+                )),+                OdfRow(listOf(OdfCell(text = "x"))),+            ),+        )+        val doc = OdfDocument.Spreadsheet(title = "Book.ods", sheets = listOf(sheet))+        val xml = OdfSerializer.serialize(doc)+        assertTrue(xml.contains("Data"), xml.take(1000))+        assertTrue(xml.contains("42"), xml)+        val xlsx = OoxmlExporter.export(doc)+        assertEquals('P'.code.toByte(), xlsx[0])+        assertEquals('K'.code.toByte(), xlsx[1])+    }++    // ---- run edits ----++    private fun runDoc(): OdfDocument.TextDocument = OdfDocument.TextDocument(+        title = "Run.odt",+        content = listOf("alpha", "bravo", "charlie", "delta").map {+            OdfContentBlock.Paragraph(OdfParagraph(listOf(OdfSpan(it))))+        },+    )++    private fun texts(doc: OdfDocument.TextDocument): List<String> =+        doc.content.filterIsInstance<OdfContentBlock.Paragraph>()+            .map { it.paragraph.spans.joinToString("") { s -> s.text } }++    @Test fun updateParagraphRunWithinAndAcrossParagraphs() {+        val doc = runDoc()+        assertEquals(listOf("alpha", "bravo", "charlie", "delta"), texts(doc))+        // Same text is a no-op.+        assertNull(doc.updateParagraphRun(0, 1, "alpha\nbravo"))+        // Invalid ranges are a no-op.+        assertNull(doc.updateParagraphRun(9, 12, "nope"))+        // Edit inside one paragraph of the run.+        val one = doc.updateParagraphRun(0, 0, "ALPHa")+        assertNotNull(one)+        assertEquals(listOf("ALPHa", "bravo", "charlie", "delta"), texts(one))+        // Replace a span crossing a paragraph boundary with a single line:+        // the tail of the end paragraph is preserved.+        val joined = doc.updateParagraphRun(0, 1, "alpha\nbraXo")+        assertNotNull(joined)+        assertEquals("braXo", texts(joined)[1])+        // Replace across paragraphs with MORE lines than the original run:+        // new paragraphs are created, surrounding paragraphs untouched.+        val grown = doc.updateParagraphRun(1, 2, "bravo\nnew middle\ncharlie")+        assertNotNull(grown)+        assertEquals(listOf("alpha", "bravo", "new middle", "charlie", "delta"), texts(grown))+        // Replace across paragraphs with FEWER lines.+        val shrunk = doc.updateParagraphRun(1, 2, "merged")+        assertNotNull(shrunk)+        assertEquals(listOf("alpha", "mergedlie", "delta").size, texts(shrunk).size)+        assertEquals("alpha", texts(shrunk)[0])+        assertEquals("delta", texts(shrunk).last())+    }++    @Test fun runSpanStylesAndLinksApplyAcrossParagraphs() {+        val doc = runDoc()+        val bolded = doc.applyRunSpanStyle(0, 1, 0, 7) { it.copy(bold = true) }+        assertNotNull(bolded)+        val paras = bolded.content.filterIsInstance<OdfContentBlock.Paragraph>()+        assertTrue(paras[0].paragraph.spans.all { it.bold })+        // A caret (empty range) styles the whole containing paragraph run char set.+        val caret = doc.applyRunSpanStyle(0, 1, 2, 2) { it.copy(italic = true) }+        assertNotNull(caret)+        val linked = doc.setLinkInRun(0, 1, 0, 5, "alpha", "https://example.org")+        assertNotNull(linked)+        val first = linked.content.filterIsInstance<OdfContentBlock.Paragraph>()[0].paragraph+        assertTrue(first.spans.any { it.href == "https://example.org" }, first.spans.toString())+    }++    @Test fun listNumberFormats() {+        assertEquals("1", formatListNumber(1, "1"))+        assertEquals("42", formatListNumber(42, "1"))+        assertEquals("A", formatListNumber(1, "A"))+        assertEquals("Z", formatListNumber(26, "A"))+        assertEquals("AA", formatListNumber(27, "A"))+        assertEquals("a", formatListNumber(1, "a"))+        assertEquals("I", formatListNumber(1, "I"))+        assertEquals("IV", formatListNumber(4, "I"))+        assertEquals("IX", formatListNumber(9, "i").uppercase())+        assertEquals("XL", formatListNumber(40, "I"))+        assertEquals("CM", formatListNumber(900, "I"))+        assertEquals("MMXXIV", formatListNumber(2024, "I"))+        assertEquals("4000", formatListNumber(4000, "I")) // beyond Roman range -> decimal+        assertEquals("1", formatListNumber(0, "1")) // coerced to 1-based+        assertEquals("1", formatListNumber(-5, "1"))+    }+}