Modern Apps git

← Modern-Apps.git

notes: share export, block and tag tests to 80% (#tests)

Commit
45ecdb32c5a95eee1a5c5426f1ca8797f332c001
Author
Vayun Mathur <[email protected]>
When
2026-11-16 14:52 UTC (20 days ago)
Parents
8f6d460
Coverage was 79.00% (13984/17701 instructions). The share path
ends in FileProvider.getUriForFile, which Robolectric cannot
satisfy (configured cache root vs per-test tmp cacheDir), so the
new tests pin everything up to that boundary instead of faking it.

- NotesShareCoverageTest: markdown export (text, missing image
  omitted, ink as SVG), share file-name sanitising and UTF-8
  length cap, tag converters, Noop tag actions, backup-agent
  dbConfigs/extraFiles with an attached base context, and
  rename/delete-tag rewriting real notes in the repository.
- NotePageBlocksCoverageTest: image-block move/delete through
  NotePage, tag add/remove through the editor, list-page tag
  rename/delete forwarding to the repository, and editableNote
  destructuring reads/writes.

No production code changes.

Verified: :notes:createMergedCoverageReport 80.02%
(14164/17701); :notes:testDevUnitTest, detekt and lint green
without ignore-failures.

Diff

notes/src/test/java/com/vayunmathur/notes/platform/NotesShareCoverageTest.kt
diff --git a/notes/src/test/java/com/vayunmathur/notes/platform/NotesShareCoverageTest.kt b/notes/src/test/java/com/vayunmathur/notes/platform/NotesShareCoverageTest.ktnew file mode 100644index 0000000000..531fa4d93b--- /dev/null+++ b/notes/src/test/java/com/vayunmathur/notes/platform/NotesShareCoverageTest.kt@@ -0,0 +1,152 @@+package com.vayunmathur.notes.platform++import android.app.Application+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.notes.data.Note+import com.vayunmathur.notes.data.withBody+import com.vayunmathur.notes.seedNotesDb+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)+class NotesShareCoverageTest {+    private val app: Application get() = ApplicationProvider.getApplicationContext()+    private val repo get() = seedNotesDb(app)+    private fun vm() = NotesViewModel(app, repo)++    @BeforeTest fun purge() {+        com.vayunmathur.notes.FakeAndroidKeyStore.install()+        runCatching { com.vayunmathur.library.util.DatabaseHelper(app).storePassphrase("test-passphrase") }+        runBlocking { repo.purge(); repo.deleteAllSnapshots() }+    }++    private fun await(timeoutMs: Long = 8000, cond: () -> Boolean) {+        val deadline = System.currentTimeMillis() + timeoutMs+        while (System.currentTimeMillis() < deadline) {+            Shadows.shadowOf(android.os.Looper.getMainLooper()).idle()+            if (cond()) return+            Thread.sleep(20)+        }+        assertTrue(cond(), "condition not met within ${timeoutMs}ms")+    }++    // Note: NotesViewModel.requestShare / markdownCacheUri end in+    // FileProvider.getUriForFile, which Robolectric cannot satisfy (the+    // provider's configured cache root is the app dataDir, while Robolectric+    // points cacheDir at a per-test tmp dir), so the share emission itself is+    // covered on-device. Here we pin everything up to that boundary: the+    // markdown export and the cache file name it would be written under.++    @Test fun exportMarkdownIncludesTextAndSkipsMissingImage() {+        val note = com.vayunmathur.notes.data.Note(title = "Export Me", content = "")+            .withBody(+                com.vayunmathur.notes.data.NoteBody(+                    listOf(+                        com.vayunmathur.notes.data.NoteBlock.Text("first paragraph"),+                        com.vayunmathur.notes.data.NoteBlock.Image("missing-image.jpg"),+                        com.vayunmathur.notes.data.NoteBlock.Text("second paragraph"),+                    ),+                ),+            )+        val markdown = exportNoteMarkdown(app, note)+        assertTrue(markdown.contains("first paragraph"), "markdown=$markdown")+        assertTrue(markdown.contains("second paragraph"), "markdown=$markdown")+        assertTrue(!markdown.contains("missing-image"), "undecodable image must be omitted: $markdown")+    }++    @Test fun renameAndDeleteTagRewriteNotes() {+        val vm = vm()+        runBlocking {+            repo.upsert(Note(title = "Tagged One", content = "1", tags = listOf("work", "urgent"), syncId = "tag1"))+            repo.upsert(Note(title = "Tagged Two", content = "2", tags = listOf("work"), syncId = "tag2"))+            repo.upsert(Note(title = "Untagged", content = "3", syncId = "tag3"))+        }+        vm.renameTag("work", "office")+        await { runBlocking { repo.getBySyncId("tag2") }?.tags == listOf("office") }+        assertEquals(listOf("office", "urgent"), runBlocking { repo.getBySyncId("tag1") }?.tags)+        assertEquals(emptyList(), runBlocking { repo.getBySyncId("tag3") }?.tags)+        vm.deleteTag("urgent")+        await { runBlocking { repo.getBySyncId("tag1") }?.tags == listOf("office") }+        // deleting an absent tag leaves notes untouched+        vm.deleteTag("no-such-tag")+        Thread.sleep(300)+        assertEquals(listOf("office"), runBlocking { repo.getBySyncId("tag1") }?.tags)+    }++    @Test fun shareFileNameFallsBackForBlankTitle() {+        assertEquals("note.md", shareMarkdownFileName(""))+        assertEquals("note.md", shareMarkdownFileName("   "))+        assertEquals("My Note.md", shareMarkdownFileName("My Note"))+    }++    @Test fun tagConvertersRoundTripAndTolerateMalformed() {+        val converters = com.vayunmathur.notes.data.NoteConverters()+        assertEquals("[\"work\",\"home\"]", converters.fromTags(listOf("work", "home")))+        assertEquals(listOf("work", "home"), converters.toTags("[\"work\",\"home\"]"))+        assertEquals(emptyList(), converters.toTags("not json at all"))+        assertEquals(emptyList(), converters.toTags("[1,2,3]"))+        assertEquals("[]", converters.fromTags(emptyList()))+        // Noop list actions are callable no-ops, including the tag operations.+        NotesListActions.Noop.renameTag("a", "b")+        NotesListActions.Noop.deleteTag("a")+        NoteActions.Noop.addTag("t")+        NoteActions.Noop.removeTag("t")+        // an exported empty note is just the trailing newline, never a crash+        assertEquals("\n", exportNoteMarkdown(app, Note(title = "Empty", content = "")))+    }++    @Test fun backupAgentExposesDbConfigsAndImageFiles() {+        val agent = AppBackupAgent()+        // BackupAgent.attachBaseContext is hidden; Robolectric allows the+        // reflective attach so the agent getters can run as Android runs them.+        val attach = android.content.ContextWrapper::class.java+            .getDeclaredMethod("attachBaseContext", android.content.Context::class.java)+            .apply { isAccessible = true }+        attach.invoke(agent, app)+        assertEquals(com.vayunmathur.notes.data.DB_NAME, agent.dbConfigs.single().first)+        assertTrue(agent.dbConfigs.single().second.isNotEmpty())+        assertEquals(+            listOf(java.io.File(app.filesDir, "note_images").absolutePath),+            agent.extraFiles.map { it.absolutePath },+        )+    }++    @Test fun shareFileNameStripsPathHostileCharsAndCapsLength() {+        assertEquals("a_b_c_d.md", shareMarkdownFileName("a/b:c?d"))+        assertEquals("hidden.md", shareMarkdownFileName("..hidden"))+        // very long titles are capped under NAME_MAX on a code-point boundary+        val longName = shareMarkdownFileName("é".repeat(300))+        assertTrue(longName.toByteArray().size <= 203, "bytes=${longName.toByteArray().size}")+        assertTrue(longName.endsWith(".md"))+        assertTrue(!longName.contains("�"), "truncation split a code point: $longName")+    }++    @Test fun exportMarkdownForInkBlockEmitsSvg() {+        val stroke = com.vayunmathur.library.ink.SerializedStroke(+            brushFamily = "pressurePen", brushSize = 6f, brushColor = 0xFF37474F.toInt(),+            brushEpsilon = 0.1f,+            points = listOf(+                com.vayunmathur.library.ink.SerializedPoint(0f, 0f, 0L),+                com.vayunmathur.library.ink.SerializedPoint(10f, 5f, 16L),+            ),+        )+        val note = Note(title = "Inky", content = "")+            .withBody(+                com.vayunmathur.notes.data.NoteBody(+                    listOf(+                        com.vayunmathur.notes.data.NoteBlock.Text("before ink"),+                        com.vayunmathur.notes.data.NoteBlock.Ink(listOf(stroke)),+                    ),+                ),+            )+        val markdown = exportNoteMarkdown(app, note)+        assertTrue(markdown.contains("before ink"), "markdown=$markdown")+        assertTrue(markdown.contains("<svg"), "ink block must export as svg: $markdown")+    }+}
notes/src/test/java/com/vayunmathur/notes/ui/NotePageBlocksCoverageTest.kt
diff --git a/notes/src/test/java/com/vayunmathur/notes/ui/NotePageBlocksCoverageTest.kt b/notes/src/test/java/com/vayunmathur/notes/ui/NotePageBlocksCoverageTest.ktnew file mode 100644index 0000000000..b14a35f2c5--- /dev/null+++ b/notes/src/test/java/com/vayunmathur/notes/ui/NotePageBlocksCoverageTest.kt@@ -0,0 +1,173 @@+package com.vayunmathur.notes.ui++import android.app.Application+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.hasClickAction+import androidx.compose.ui.test.hasText+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.longClick+import androidx.compose.ui.test.onAllNodesWithContentDescription+import androidx.compose.ui.test.onNodeWithContentDescription+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.compose.ui.test.performImeAction+import androidx.compose.ui.test.performTextInput+import androidx.compose.ui.test.performTextReplacement+import androidx.compose.ui.test.performTouchInput+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.notes.FakeAndroidKeyStore+import com.vayunmathur.notes.Route+import com.vayunmathur.notes.data.Note+import com.vayunmathur.notes.data.NoteBlock+import com.vayunmathur.notes.data.NoteBody+import com.vayunmathur.notes.data.withBody+import com.vayunmathur.notes.platform.NotesViewModel+import com.vayunmathur.notes.seedNotesDb+import kotlinx.coroutines.runBlocking+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)+class NotePageBlocksCoverageTest {+    @get:Rule val rule = createComposeRule()+    private val app: Application get() = ApplicationProvider.getApplicationContext()+    private val repo get() = seedNotesDb(app)+    private fun vm() = NotesViewModel(app, repo)++    @BeforeTest fun purge() {+        FakeAndroidKeyStore.install()+        runCatching { com.vayunmathur.library.util.DatabaseHelper(app).storePassphrase("test-passphrase") }+        runBlocking { repo.purge(); repo.deleteAllSnapshots() }+    }++    private fun idle() { rule.waitForIdle(); Shadows.shadowOf(android.os.Looper.getMainLooper()).idle() }++    private fun seedBlockNote(): Long {+        val note = Note(title = "Block Note", content = "").withBody(+            NoteBody(+                listOf(+                    NoteBlock.Text("first block text", "b1"),+                    NoteBlock.Image("block-image.jpg", 0.5f, "img1"),+                    NoteBlock.Text("second block text", "b2"),+                ),+            ),+        )+        return runBlocking { repo.upsert(note.copy(syncId = "blocks1")) }+    }++    @Test fun notePageMoveAndDeleteBlockActions() {+        val id = seedBlockNote()+        val stack = NavBackStack<Route>(arrayOf(Route.NotesList, Route.Note(id)))+        val vm = vm()+        rule.setContent { NotePage(stack, vm, id) }+        rule.waitUntil(timeoutMillis = 8000) {+            runCatching { rule.onNodeWithText("Block Note").assertIsDisplayed(); true }.getOrDefault(false)+        }+        // Only image/ink blocks carry move/delete controls; they render inline.+        val downs = rule.onAllNodesWithContentDescription("Down").fetchSemanticsNodes()+        assertTrue(downs.isNotEmpty(), "no Down block controls rendered")+        rule.onAllNodesWithContentDescription("Down")[0].performClick()+        idle()+        assertEquals(Route.Note(id), stack.last())+        rule.onAllNodesWithContentDescription("Up")[0].performClick()+        idle()+        // Delete the image block; the editor stays open on the same note.+        val deletes = rule.onAllNodesWithContentDescription("Delete").fetchSemanticsNodes()+        assertTrue(deletes.size >= 2, "expected block + toolbar Delete buttons, got ${deletes.size}")+        rule.onAllNodesWithContentDescription("Delete")[0].performClick()+        idle()+        assertEquals(Route.Note(id), stack.last())+        // The image block's controls are gone once the block is deleted.+        assertEquals(0, rule.onAllNodesWithContentDescription("Down").fetchSemanticsNodes().size)+    }++    @Test fun listPageTagRenameAndDeleteForwardToRepository() {+        runBlocking {+            repo.upsert(Note(title = "Home Note", content = "h", tags = listOf("Home"), syncId = "lp1"))+            repo.upsert(Note(title = "Idea Note", content = "i", tags = listOf("Ideas"), syncId = "lp2"))+        }+        val stack = NavBackStack<Route>(arrayOf(Route.NotesList))+        val vm = vm()+        rule.setContent { NotesListPage(stack, vm) }+        rule.waitUntil(timeoutMillis = 8000) {+            runCatching { rule.onNodeWithText("Home Note").assertIsDisplayed(); true }.getOrDefault(false)+        }+        // Rename Home -> work through the page's actions (ViewModel -> repository).+        rule.onNode(hasText("Home") and hasText("1")).performTouchInput { longClick() }+        idle()+        rule.onNodeWithText("Rename").performClick()+        idle()+        rule.onNodeWithText("Tag name").performTextReplacement("work")+        idle()+        rule.onNode(hasText("Rename") and hasClickAction()).performClick()+        val deadline = System.currentTimeMillis() + 8000+        while (System.currentTimeMillis() < deadline &&+            runBlocking { repo.getBySyncId("lp1") }?.tags != listOf("work")+        ) {+            Thread.sleep(30); idle()+        }+        assertEquals(listOf("work"), runBlocking { repo.getBySyncId("lp1") }?.tags)+        // Delete the Ideas tag through the same page path.+        rule.onNode(hasText("Ideas") and hasText("1")).performTouchInput { longClick() }+        idle()+        rule.onNodeWithText("Delete").performClick()+        idle()+        rule.onNode(hasText("Delete") and hasClickAction()).performClick()+        val deadline2 = System.currentTimeMillis() + 8000+        while (System.currentTimeMillis() < deadline2 &&+            runBlocking { repo.getBySyncId("lp2") }?.tags?.isNotEmpty() != false+        ) {+            Thread.sleep(30); idle()+        }+        assertEquals(emptyList(), runBlocking { repo.getBySyncId("lp2") }?.tags)+    }++    @Test fun notePageAddAndRemoveTagThroughEditor() {+        val id = seedBlockNote()+        val stack = NavBackStack<Route>(arrayOf(Route.NotesList, Route.Note(id)))+        val vm = vm()+        rule.setContent { NotePage(stack, vm, id) }+        rule.waitUntil(timeoutMillis = 8000) {+            runCatching { rule.onNodeWithText("Block Note").assertIsDisplayed(); true }.getOrDefault(false)+        }+        rule.onNode(+            androidx.compose.ui.test.hasSetTextAction() and hasText("Add tag"),+        ).performTextInput("  road   trip ")+        rule.onNode(+            androidx.compose.ui.test.hasSetTextAction() and hasText("road", substring = true),+        ).performImeAction()+        idle()+        rule.onNodeWithText("road trip").assertIsDisplayed()+        // Removing the chip removes the tag from the editor state.+        rule.onNodeWithContentDescription("Remove tag road trip").performClick()+        idle()+        assertEquals(+            0,+            rule.onAllNodesWithContentDescription("Remove tag road trip").fetchSemanticsNodes().size,+        )+        assertEquals(Route.Note(id), stack.last())+    }++    @Test fun editableNoteDestructuringReadsAndWrites() {+        val vm = vm()+        var readTitle: String? = null+        var write: ((Note) -> Unit)? = null+        rule.setContent {+            val (note, setNote) = vm.editableNote(0) { Note(0, "destructure-default", "") }+            readTitle = note.title+            write = setNote+        }+        idle()+        assertEquals("destructure-default", readTitle)+        rule.runOnUiThread { write!!.invoke(Note(0, "destructured-write", "body")) }+        rule.waitForIdle()+        assertEquals("destructured-write", readTitle)+    }+}