library: add navigation, datastore and markdown tests (#tests)
- Commit
2086dedbc3742af894aa3403a43261d7e4a7532f- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-16 14:40 UTC (20 days ago)
- Parents
743d8a1
Coverage wave 3 for the base library. Baseline measured with createMergedCoverageReport (INSTRUCTION) was 14195 covered / 2208 missed, so the +3000 goal is mathematically unreachable: at most 2208 instructions could ever be gained. These tests maximise the reachable share. LibraryCoverageNav/Data/MarkdownTest cover NavBackStack failure and pop/reset paths, entry-provider matching and metadata, NavigationResults delivery and type filtering, bottom-bar default selection, MainNavigation transitions and message draining, DataStoreUtils sync/async getters, flows, onlyIfAbsent and removeKeys, LocalizedDateNames in several locales, BackupHelper zip/legacy/restore branches and Markdown parsing edges. LibraryWave2Nav/DataTest add the default-locale LocalizedDateNames entry points that wave 1 missed (missed 73 to 7 for that class), shared-element and motion helpers, IntentLauncher failure surfacing, DTO property reads, GameHub compose hooks and IntentHelper providers. Verified: final merged run without ignore-failures gives 14969 covered (+774; 1434 missed remain, largely Kotlin inline-function phantom classes and platform-gesture paths no host test can execute), 189 tests, detekt and lint green. No provably dead code was found, so nothing was deleted.
Diff
library/src/test/java/com/vayunmathur/library/util/LibraryCoverageDataTest.kt
diff --git a/library/src/test/java/com/vayunmathur/library/util/LibraryCoverageDataTest.kt b/library/src/test/java/com/vayunmathur/library/util/LibraryCoverageDataTest.ktnew file mode 100644index 0000000000..513298c0c3--- /dev/null+++ b/library/src/test/java/com/vayunmathur/library/util/LibraryCoverageDataTest.kt@@ -0,0 +1,257 @@+package com.vayunmathur.library.util++import android.content.Context+import androidx.datastore.preferences.core.PreferenceDataStoreFactory+import androidx.test.core.app.ApplicationProvider+import java.io.ByteArrayInputStream+import java.io.ByteArrayOutputStream+import java.io.File+import java.nio.file.Files+import java.util.Locale+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.runBlocking+import kotlinx.coroutines.withTimeout+import kotlinx.coroutines.delay+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue++/** DataStore remaining branches, LocalizedDateNames locales, BackupHelper edges, Util helpers. */[email protected](org.robolectric.RobolectricTestRunner::class)[email protected](sdk = [34])+class LibraryCoverageDataTest {++ private val ctx: Context get() = ApplicationProvider.getApplicationContext()++ private fun newStore(): DataStoreUtils {+ val dir = Files.createTempDirectory("ds-cov").toFile()+ return DataStoreUtils(PreferenceDataStoreFactory.create { File(dir, "t.preferences_pb") })+ }++ // ---- DataStore ----++ @Test fun dataStoreSyncGettersAndOnlyIfAbsentVariants() = runBlocking {+ val store = newStore()+ store.setByteArray("blob", byteArrayOf(9, 8))+ assertTrue(byteArrayOf(9, 8).contentEquals(store.getByteArray("blob")!!))+ store.setByteArray("blob", byteArrayOf(1), onlyIfAbsent = true)+ assertTrue(byteArrayOf(9, 8).contentEquals(store.getByteArrayAwait("blob")!!))+ store.setByteArray("blob", byteArrayOf(7), onlyIfAbsent = false)+ assertTrue(byteArrayOf(7).contentEquals(store.getByteArrayAwait("blob")!!))++ assertNull(store.getLong("nope"))+ store.setLong("n", 5, onlyIfAbsent = true)+ store.setLong("n", 6, onlyIfAbsent = true)+ assertEquals(5L, store.getLong("n"))+ assertEquals(5L, store.getLongAwait("n"))++ assertNull(store.getDouble("nope"))+ store.setDouble("d", 1.25)+ assertEquals(1.25, store.getDouble("d"))++ assertFalse(store.getBoolean("flag", false))+ assertTrue(store.getBoolean("flag", true))+ store.setBoolean("flag", true)+ assertTrue(store.getBoolean("flag", false))+ assertTrue(store.getBooleanAwait("flag", false))+ assertFalse(store.getBooleanAwait("absent", false))+ assertTrue(store.getBooleanAwait("absent", true))+ }++ @Test fun dataStoreFlowsWithAndWithoutDefaults() = runBlocking {+ val store = newStore()+ assertEquals(99L, store.longFlow("missing", 99L).first())+ assertEquals(true, store.booleanFlow("missing", true).first())+ assertEquals(emptySet(), store.stringSetFlow("missing").first())+ store.setLong("count", 3)+ assertEquals(3L, store.longFlow("count").first())+ assertEquals(3L, store.longFlow("count", 0L).first())+ store.setBoolean("on", true)+ assertEquals(true, store.booleanFlow("on").first())+ assertEquals(true, store.booleanFlow("on", false).first())+ store.setString("s", "hello")+ assertEquals("hello", store.stringFlow("s").first())+ store.setDouble("ratio", 0.5)+ assertEquals(0.5, store.doubleFlow("ratio").first())+ }++ @Test fun dataStoreSetOpsAwaitAndRemoveKeysAllTypes() = runBlocking {+ val store = newStore()+ assertTrue(store.addStringToSetIfAbsent("tags", "x"))+ store.removeStringFromSetAwait("tags", "x")+ assertEquals(emptySet(), store.getStringSetAwait("tags"))+ // Fire-and-forget add/remove eventually land.+ store.addStringToSet("tags", "y")+ withTimeout(5_000) { while (!store.getStringSetAwait("tags").contains("y")) delay(20) }+ store.removeStringFromSet("tags", "y")+ withTimeout(5_000) { while (store.getStringSetAwait("tags").isNotEmpty()) delay(20) }++ // removeKeys removes every type stored under a name.+ store.setString("k", "v"); store.setLong("k2", 1); store.setDouble("k3", 2.0)+ store.setBoolean("k4", true); store.setByteArray("k5", byteArrayOf(1))+ store.addStringToSetIfAbsent("k6", "a")+ store.removeKeys(listOf("k", "k2", "k3", "k4", "k5", "k6"))+ assertNull(store.getStringAwait("k"))+ assertNull(store.getLongAwait("k2"))+ assertNull(store.getDouble("k3"))+ assertEquals(false, store.getBooleanAwait("k4", false))+ assertNull(store.getByteArrayAwait("k5"))+ assertEquals(emptySet(), store.getStringSetAwait("k6"))++ // updateString from absent treats current as null.+ store.updateString("fresh") { (it ?: "seed") + "!" }+ assertEquals("seed!", store.getStringAwait("fresh"))+ // setLongIfGreater on absent key: any positive value wins over implicit 0.+ assertTrue(store.setLongIfGreater("high", 10))+ assertFalse(store.setLongIfGreater("high", 10))+ assertTrue(store.setLongIfGreater("high", 11))+ }++ @Test fun dataStoreCopyFromOverwriteAndEmptySourceBranches() = runBlocking {+ val src = newStore(); val dst = newStore()+ src.setString("a", "1"); src.setLong("b", 2)+ assertEquals(0, dst.copyFrom(src, emptyList(), overwrite = false))+ assertEquals(0, dst.copyFrom(newStore(), listOf("a"), overwrite = false))+ assertEquals(2, dst.copyFrom(src, listOf("a", "b", "absent"), overwrite = false))+ assertEquals("1", dst.getStringAwait("a"))+ src.setString("a", "changed")+ assertEquals(0, dst.copyFrom(src, listOf("a"), overwrite = false))+ assertEquals(1, dst.copyFrom(src, listOf("a"), overwrite = true))+ assertEquals("changed", dst.getStringAwait("a"))+ }++ // ---- LocalizedDateNames ----++ @Test fun localizedNamesAcrossLocalesAndStyles() {+ val usMonths = localizedMonthNames(DateNameStyle.FULL, Locale.US)+ assertEquals(12, usMonths.size)+ assertEquals("January", usMonths[0]); assertEquals("December", usMonths[11])+ assertEquals("Jan", localizedMonthNames(DateNameStyle.SHORT, Locale.US)[0])+ assertEquals(12, localizedMonthNames(DateNameStyle.NARROW, Locale.US).size)+ val fr = localizedMonthNames(DateNameStyle.FULL, Locale.FRANCE)+ assertTrue(fr[0].lowercase().startsWith("janv"), fr.toString())+ val deDays = localizedDayOfWeekNames(DateNameStyle.FULL, Locale.GERMANY)+ assertEquals(7, deDays.size)+ assertTrue(deDays[0].startsWith("Montag"), deDays.toString()) // ISO Monday first+ assertEquals("Monday", localizedDayOfWeekNames(DateNameStyle.FULL, Locale.US)[0])+ assertEquals("Sunday", localizedDayOfWeekNames(DateNameStyle.FULL, Locale.US)[6])+ assertEquals("Mon", localizedDayOfWeekNames(DateNameStyle.SHORT, Locale.US)[0])+ assertEquals(7, localizedDayOfWeekNames(DateNameStyle.NARROW, Locale.JAPAN).size)+ }++ @Test fun firstDayOfWeekAndWeekRotationPerLocale() {+ assertEquals(7, localeFirstDayOfWeek(Locale.US)) // Sunday+ assertEquals(1, localeFirstDayOfWeek(Locale.GERMANY)) // Monday+ assertEquals(1, localeFirstDayOfWeek(Locale.FRANCE))+ assertEquals(listOf(7, 1, 2, 3, 4, 5, 6), localeWeekDayNumbers(Locale.US))+ assertEquals(listOf(1, 2, 3, 4, 5, 6, 7), localeWeekDayNumbers(Locale.GERMANY))+ // Every rotation is a permutation of 1..7 starting at the first day.+ for (locale in listOf(Locale.US, Locale.GERMANY, Locale.JAPAN, Locale.UK, Locale.CANADA)) {+ val week = localeWeekDayNumbers(locale)+ assertEquals((1..7).toList(), week.sorted(), "$locale")+ assertEquals(localeFirstDayOfWeek(locale), week.first(), "$locale")+ }+ }++ @Test fun amPmMarkersAndFormatBuilderBothCases() {+ assertEquals("AM" to "PM", localizedAmPmMarkers(Locale.US))+ val ja = localizedAmPmMarkers(Locale.JAPAN)+ assertTrue(ja.first.isNotBlank() && ja.first != ja.second)+ val morning = kotlinx.datetime.LocalTime.Format { localizedAmPmMarker(Locale.US) }+ .format(kotlinx.datetime.LocalTime(9, 5))+ assertTrue(morning.contains("AM"), morning)+ val eveningLower = kotlinx.datetime.LocalTime.Format { localizedAmPmMarker(Locale.US, lowercase = true) }+ .format(kotlinx.datetime.LocalTime(21, 5))+ assertTrue(eveningLower.contains("pm"), eveningLower)+ // DateNameStyle widths are distinct.+ assertTrue(DateNameStyle.SHORT.icuWidth != DateNameStyle.FULL.icuWidth)+ assertTrue(DateNameStyle.NARROW.icuWidth != DateNameStyle.FULL.icuWidth)+ }++ // ---- BackupHelper edges ----++ private class EmptyCodec : DbBackupCodec {+ val imports = mutableListOf<String>()+ override fun exportDatabase(context: Context, dbName: String, password: String, outputFile: File) {+ outputFile.writeBytes(ByteArray(0)) // empty export must be skipped+ }+ override fun importDatabase(context: Context, dbName: String, password: String, inputFile: File) {+ imports += dbName+ }+ }++ @Test fun backupSkipsEmptyCodecExportAndMissingDbOnRestore() {+ val codec = EmptyCodec()+ val out = ByteArrayOutputStream()+ BackupHelper.performFullBackup(ctx, listOf("db1" to "pw"), emptyList(), emptyList(), emptyList(), out, codec)+ val target = Files.createTempDirectory("emptycodec").toFile()+ BackupHelper.unzipFiles(ByteArrayInputStream(out.toByteArray()), target)+ assertFalse(File(target, "db1.db").exists())+ // Restore of that zip: db file absent, so import is never called.+ BackupHelper.performFullRestore(ctx, listOf("db1" to "pw"), emptyList(), emptyList(), emptyMap(), ByteArrayInputStream(out.toByteArray()), codec)+ assertTrue(codec.imports.isEmpty())+ }++ @Test fun backupLegacyDatastorePathAndSingleFileZip() {+ // Legacy layout: filesDir/<name>.preferences_pb (no datastore/ subdir).+ val legacy = File(ctx.filesDir, "legacy.preferences_pb").apply { writeBytes(byteArrayOf(4, 5)) }+ try {+ val out = ByteArrayOutputStream()+ BackupHelper.performFullBackup(ctx, emptyList(), listOf("legacy"), emptyList(), emptyList(), out)+ legacy.delete()+ BackupHelper.performFullRestore(ctx, emptyList(), listOf("legacy"), emptyList(), emptyMap(), ByteArrayInputStream(out.toByteArray()))+ // Named (non-default) stores restore under datastore/, regardless of legacy source.+ assertTrue(byteArrayOf(4, 5).contentEquals(File(ctx.filesDir, "datastore/legacy.preferences_pb").readBytes()))+ } finally { legacy.delete(); File(ctx.filesDir, "datastore/legacy.preferences_pb").delete() }++ val single = File(ctx.cacheDir, "single.txt").apply { writeText("solo") }+ val out2 = ByteArrayOutputStream()+ BackupHelper.zipFiles(listOf(single), ctx.cacheDir, out2)+ val target = Files.createTempDirectory("singleout").toFile()+ BackupHelper.unzipFiles(ByteArrayInputStream(out2.toByteArray()), target)+ assertEquals("solo", File(target, "single.txt").readText())+ }++ @Test fun backupWithNothingToBackupStillProducesReadableZip() {+ val out = ByteArrayOutputStream()+ BackupHelper.performFullBackup(ctx, emptyList(), listOf("ghostds"), listOf("ghostpref"), listOf(File(ctx.cacheDir, "nope.bin")), out)+ assertTrue(out.size() > 0)+ val target = Files.createTempDirectory("nothingout").toFile()+ BackupHelper.unzipFiles(ByteArrayInputStream(out.toByteArray()), target)+ }++ @Test fun restoreExtraFileOverwritesExistingDirectory() {+ val src = File(ctx.cacheDir, "thing.txt").apply { writeText("file-body") }+ val out = ByteArrayOutputStream()+ BackupHelper.performFullBackup(ctx, emptyList(), emptyList(), emptyList(), listOf(src), out)+ val dest = File(ctx.cacheDir, "thing.txt")+ // Replace the file with a directory of the same name; restore must clear it.+ dest.delete(); dest.mkdirs(); File(dest, "stale.txt").writeText("stale")+ BackupHelper.performFullRestore(ctx, emptyList(), emptyList(), emptyList(), mapOf("thing.txt" to dest), ByteArrayInputStream(out.toByteArray()))+ assertTrue(dest.isFile)+ assertEquals("file-body", dest.readText())+ }++ // ---- Util helpers ----++ @Test fun utilHelpersEdgeCases() {+ assertEquals(42, tryOrDefault(42) { 42 })+ assertEquals(42, tryOrDefault(42) { throw IllegalStateException("x") })+ assertEquals(1.23, 1.2345.round(2))+ assertEquals(1.234, 1.2345.round(3)) // binary float: 1.2345*1000 is just under 1234.5+ assertEquals(-2.0, (-1.5).round(0))+ assertEquals(100.0, 99.99.round(1))+ assertEquals("Hello", "hello".firstLetterUppercase())+ assertEquals("Hello", "Hello".firstLetterUppercase())+ assertEquals("", "".firstLetterUppercase())+ assertEquals("123", "123".firstLetterUppercase())+ val tuple = Tuple4("a", 1, true, 2.5)+ assertEquals("a", tuple.first); assertEquals(1, tuple.second)+ assertEquals(true, tuple.third); assertEquals(2.5, tuple.fourth)+ assertEquals(Tuple4("a", 1, true, 2.5), tuple)+ val linesFile = Files.createTempFile("lines", ".txt").toFile().apply { writeText("one\ntwo\nthree") }+ linesFile.inputStream().use { input -> assertEquals(listOf("one", "two", "three"), input.readLines()) }+ }+}
library/src/test/java/com/vayunmathur/library/util/LibraryCoverageMarkdownTest.kt
diff --git a/library/src/test/java/com/vayunmathur/library/util/LibraryCoverageMarkdownTest.kt b/library/src/test/java/com/vayunmathur/library/util/LibraryCoverageMarkdownTest.ktnew file mode 100644index 0000000000..924dc911e8--- /dev/null+++ b/library/src/test/java/com/vayunmathur/library/util/LibraryCoverageMarkdownTest.kt@@ -0,0 +1,167 @@+package com.vayunmathur.library.util++import androidx.compose.ui.graphics.Color+import androidx.compose.ui.text.font.FontFamily+import androidx.compose.ui.text.font.FontStyle+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.text.style.TextDecoration+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++/** Markdown edges not covered elsewhere: empty input, raw modes, math escapes, search bounds, list forms. */[email protected](org.robolectric.RobolectricTestRunner::class)[email protected](sdk = [34])+class LibraryCoverageMarkdownTest {++ @Test fun emptyAndBlankInput() {+ assertEquals("", parseMarkdown("").text)+ assertEquals("", parseMarkdown(" \n\n ").text)+ assertEquals("", parseMarkdown("", showMarkers = false, searchQuery = "x").text)+ val onlyNewlines = parseMarkdown("\n\n\n", process = false, softWrap = false)+ assertEquals("\n\n\n", onlyNewlines.text)+ }++ @Test fun plainTextHasNoStyles() {+ val md = parseMarkdown("just words here")+ assertEquals("just words here", md.text)+ assertTrue(md.spanStyles.isEmpty(), md.spanStyles.toString())+ assertTrue(md.paragraphStyles.isEmpty())+ }++ @Test fun headerRequiresSpaceAndLevelsScale() {+ assertFalse(parseMarkdown("#NoSpace").spanStyles.any { it.item.fontWeight == FontWeight.Bold })+ val sizes = (1..6).map { level ->+ val md = parseMarkdown("${"#".repeat(level)} Title$level")+ md.spanStyles.first { it.item.fontWeight == FontWeight.Bold }.item.fontSize.value+ }+ assertEquals(sizes.sortedDescending(), sizes, "header sizes must descend: $sizes")+ // Shown markers: header marker spans are not hidden.+ val shown = parseMarkdown("# T", showMarkers = true)+ assertFalse(shown.spanStyles.any { it.item.color == Color.Transparent })+ }++ @Test fun listMarkerFormsAndTaskStates() {+ val numberedDot = parseMarkdown("1. first\n2. second", process = true)+ assertTrue(numberedDot.text.contains("first"))+ assertTrue(numberedDot.paragraphStyles.isNotEmpty())+ val unchecked = parseMarkdown("- [ ] todo item")+ assertFalse(unchecked.spanStyles.any { it.item.textDecoration == TextDecoration.LineThrough })+ // Without processing, markers are not normalised to bullets.+ val raw = parseMarkdown("- dash\n* star", process = false, softWrap = false)+ assertTrue(raw.text.startsWith("- dash"), raw.text)+ // Deep indentation keeps content and yields paragraph indent.+ val deep = parseMarkdown("- a\n - deep item")+ assertTrue(deep.text.contains("deep item"))+ assertTrue(deep.paragraphStyles.size >= 2)+ }++ @Test fun blockquoteMultipleLinesAndTrailingContent() {+ val md = parseMarkdown("> first quote\n> second quote\nplain after")+ val italics = md.spanStyles.filter { it.item.fontStyle == FontStyle.Italic }+ assertTrue(italics.size >= 2, italics.toString())+ assertTrue(md.text.contains("plain after"))+ // Blockquote at end of input with no trailing newline.+ val tail = parseMarkdown("intro\n> last line")+ assertTrue(tail.spanStyles.any { it.item.fontStyle == FontStyle.Italic })+ }++ @Test fun inlineFormattingCombinations() {+ val md = parseMarkdown("**bold _inner_ end** and `code` and ~~old~~")+ assertTrue(md.spanStyles.any { it.item.fontWeight == FontWeight.Bold })+ assertTrue(md.spanStyles.any { it.item.fontStyle == FontStyle.Italic })+ assertTrue(md.spanStyles.any { it.item.fontFamily == FontFamily.Monospace })+ assertTrue(md.spanStyles.any { it.item.textDecoration == TextDecoration.LineThrough })+ // Single asterisk inside words does not create spurious bold.+ val star = parseMarkdown("2 * 3 * 4")+ assertEquals("2 * 3 * 4", star.text)+ // Link with shown markers keeps the URL annotation too.+ val link = parseMarkdown("[Label](https://example.com)", showMarkers = true)+ assertEquals(1, link.getLinkAnnotations(0, link.text.length).size)+ }++ @Test fun mathShownMarkersAreNotReformatted() {+ val md = parseMarkdown("$$\\frac{1}{2}$$", showMarkers = true)+ assertTrue(md.text.contains("\\frac{1}{2}"), md.text)+ // Still styled serif, and centred only when processing.+ assertTrue(md.spanStyles.any { it.item.fontFamily == FontFamily.Serif })+ val rawBlock = parseMarkdown("\$\$x\$\$", process = false, softWrap = false)+ assertFalse(rawBlock.paragraphStyles.any { it.item.textAlign == TextAlign.Center })+ }++ @Test fun mathEscapesAndLeftRightCommands() {+ // \leftarrow is a command, not \left + arrow text.+ val arrow = parseMarkdown("$$\\leftarrow x$$", showMarkers = false)+ assertTrue(arrow.text.contains("←"), arrow.text)+ assertFalse(arrow.text.contains("\\left"), arrow.text)+ val parens = parseMarkdown("$$\\left( \\frac{a}{b} \\right)$$", showMarkers = false)+ assertTrue(parens.text.contains("((a)/(b))"), parens.text)+ // Escaped dollar is not inline math.+ val escaped = parseMarkdown("cost is \\$5 today", showMarkers = false)+ assertEquals("cost is \\$5 today", escaped.text)+ // Nested sqrt/fraction formatting.+ val nested = parseMarkdown("$$\\sqrt{\\frac{4}{9}}$$", showMarkers = false)+ assertTrue(nested.text.contains("√(((4)/(9)))"), nested.text)+ }++ @Test fun latexRemainingCommandsAndUnknownCommand() {+ val md = parseMarkdown(+ "\\mathrm{plain} \\mathsf{sans} \\mathit{ital} \\mathbf{bold}",+ showMarkers = false,+ )+ assertTrue(md.spanStyles.any { it.item.fontStyle == FontStyle.Normal })+ assertTrue(md.spanStyles.any { it.item.fontFamily == FontFamily.SansSerif })+ assertTrue(md.spanStyles.any { it.item.fontStyle == FontStyle.Italic })+ val sweep = parseMarkdown(+ "$$\\epsilon \\vartheta \\varphi \\oplus \\otimes \\bullet \\approx \\cong \\equiv \\propto " ++ "\\supset \\ni \\ellnot \\leftrightarrow \\mapsto \\cot \\sec \\csc \\arcsin \\log \\ln " ++ "\\exp \\lim \\max \\min \\det \\gcd \\lfloor z \\rfloor \\partial \\angle \\degree$$",+ showMarkers = false,+ )+ for (expected in listOf("ε", "ϑ", "ϕ", "⊕", "⊗", "•", "≈", "≅", "≡", "∝", "⊃", "∋", "↔", "↦", "cot", "sec", "csc", "arcsin", "log", "ln", "exp", "lim", "max", "min", "det", "gcd", "⌊", "⌋", "∂", "∠", "°")) {+ assertTrue(sweep.text.contains(expected), "missing $expected in ${sweep.text}")+ }+ // \ellnot is not a known command and must pass through untouched (no crash).+ assertTrue(sweep.text.contains("\\ellnot") || sweep.text.contains("¬"), sweep.text)+ }++ @Test fun searchHighlightBoundsAndCase() {+ val beyond = parseMarkdown("cat cat", searchQuery = "cat", searchIndex = 5)+ // No match is "current" when the index is past the last hit: all plain yellow.+ val bgs = beyond.spanStyles.mapNotNull { it.item.background.takeIf { b -> b != Color.Unspecified } }+ assertEquals(2, bgs.size)+ assertTrue(bgs.all { it == Color.Yellow }, bgs.toString())+ val upper = parseMarkdown("Cat CAT cAt", searchQuery = "CAT", searchIndex = 0)+ assertEquals(3, upper.spanStyles.count { it.item.background != Color.Unspecified })+ val negative = parseMarkdown("cat cat", searchQuery = "cat", searchIndex = -1)+ assertTrue(negative.spanStyles.none { it.item.background == Color(0xFFFFA500) })+ val wholeWord = parseMarkdown("concatenate", searchQuery = "cat")+ assertEquals(1, wholeWord.spanStyles.count { it.item.background != Color.Unspecified })+ }++ @Test fun softWrapSpecialLinesAreNotMerged() {+ val md = parseMarkdown("intro line\n# Heading\n- item one\n> quote line\ntail line")+ assertTrue(md.text.contains("# Heading"), md.text)+ assertTrue(md.text.contains("tail line"), md.text)+ // Blank-line collapsing keeps exactly one separator.+ val paras = parseMarkdown("one\n\n\n\n\n\ntwo")+ assertEquals("one\ntwo", paras.text)+ // No soft wrap: lines stay separate even when process is on for lists.+ val noWrap = parseMarkdown("line a\nline b", process = false, softWrap = false)+ assertEquals("line a\nline b", noWrap.text)+ // Hard wrap with a trailing blank line trims in soft-wrap mode.+ assertEquals("end", parseMarkdown("end\n\n\n").text)+ }++ @Test fun fencedBlockWithLanguageAndBlankLinesInside() {+ val md = parseMarkdown("```\nline1\n\nline2\n```", process = false, softWrap = false)+ assertTrue(md.text.contains("line1"))+ assertTrue(md.text.contains("line2"))+ assertTrue(md.spanStyles.any { it.item.fontFamily == FontFamily.Monospace })+ // Inline code after a fence is still styled as code, fence content is not double-styled red.+ val mixed = parseMarkdown("```\nval a = 1\n```\nuse `a` here", process = false, softWrap = false)+ assertTrue(mixed.spanStyles.any { it.item.color == Color(0xFFD32F2F) }, mixed.spanStyles.toString())+ }+}
library/src/test/java/com/vayunmathur/library/util/LibraryCoverageNavTest.kt
diff --git a/library/src/test/java/com/vayunmathur/library/util/LibraryCoverageNavTest.kt b/library/src/test/java/com/vayunmathur/library/util/LibraryCoverageNavTest.ktnew file mode 100644index 0000000000..a023ea26d5--- /dev/null+++ b/library/src/test/java/com/vayunmathur/library/util/LibraryCoverageNavTest.kt@@ -0,0 +1,231 @@+package com.vayunmathur.library.util++import androidx.compose.foundation.layout.Column+import androidx.compose.material3.MaterialTheme+import androidx.compose.material3.Text+import androidx.compose.runtime.CompositionLocalProvider+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.setValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.launch+import kotlinx.serialization.Serializable+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFailsWith+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++/** Extra behaviour for NavBackStack edges, EntryProviderScope typing, BottomNavBar defaults and ResultEffect ordering. */+@RunWith(RobolectricTestRunner::class)[email protected](sdk = [34])+class LibraryCoverageNavTest {++ @get:Rule val rule = createComposeRule()++ @Serializable data class Screen(val route: String) : NavKey+ @Serializable data class Other(val route: String) : NavKey++ // ---- NavBackStack pure behaviour ----++ @Test fun emptyBackStackLastAndSetLastFailButPopIsSafe() {+ val stack = NavBackStack<Screen>(emptyArray())+ assertTrue(stack.backStack.isEmpty())+ stack.pop() // no-op+ assertFailsWith<NoSuchElementException> { stack.last() }+ assertFailsWith<IndexOutOfBoundsException> { stack.setLast(Screen("x")) }+ assertFailsWith<IndexOutOfBoundsException> { stack.set(0, Screen("x")) }+ stack.reset()+ assertTrue(stack.backStack.isEmpty())+ stack.reset(Screen("only"))+ assertEquals("only", stack.last().route)+ }++ @Test fun backStackResetReplacesEntireContentsAndClearEmpties() {+ val stack = NavBackStack(arrayOf(Screen("a"), Screen("b"), Screen("c")))+ stack.set(1, Screen("B"))+ assertEquals(listOf("a", "B", "c"), stack.backStack.map { it.route })+ stack.reset(Screen("z"))+ assertEquals(listOf("z"), stack.backStack.map { it.route })+ stack.add(Screen("y"))+ stack.clear()+ assertTrue(stack.backStack.isEmpty())+ }++ // ---- EntryProviderScope ----++ @Test fun entryProviderMatchesSupertypeAndCarriesMetadata() {+ val scope = EntryProviderScope<NavKey>(Screen("home"))+ var seen: Screen? = null+ scope.entry<NavKey>(metadata = DetailPage()) { seen = it as Screen }+ // entry only records the NavEntry; content lambda is not invoked here.+ assertNotNull(scope.result)+ assertEquals(DetailPage(), scope.result!!.metadata)+ assertNull(seen)+ }++ @Test fun entryProviderMismatchLeavesResultNullAndNoMetadata() {+ val miss = EntryProviderScope<NavKey>(Other("o"))+ miss.entry<Screen>(metadata = ZoomPage()) { }+ assertNull(miss.result)+ val hitDefaultMeta = EntryProviderScope<NavKey>(Screen("s"))+ hitDefaultMeta.entry<Screen> { }+ assertNotNull(hitDefaultMeta.result)+ assertTrue(hitDefaultMeta.result!!.metadata.isEmpty())+ }++ // ---- BottomNavBar default onSelect ----++ @Test fun bottomNavBarDefaultOnSelectResetsAndIgnoresCurrentTab() {+ val stack = NavBackStack(arrayOf(Screen("home"), Screen("detail")))+ var current by mutableStateOf<Screen>(Screen("home"))+ val pages = listOf(+ BottomBarItem<Screen>(name = "HomeTab", route = Screen("home"), icon = { Text("H") }),+ BottomBarItem<Screen>(name = "SettingsTab", route = Screen("settings"), icon = { Text("S") }),+ )+ rule.setContent {+ MaterialTheme {+ // No onSelect: default should reset the stack to the tapped route,+ // except when the tapped route is already last.+ BottomNavBar(backStack = stack, pages = pages, currentPage = current)+ }+ }+ // Tapping the route that is not last resets the 2-entry stack to just it.+ // currentPage is only a selection indicator; the stack is the source of truth.+ rule.onNodeWithText("SettingsTab").performClick()+ rule.waitForIdle()+ assertEquals(listOf("settings"), stack.backStack.map { it.route })+ // Tapping it again is a no-op (already last) — no duplicate push.+ rule.onNodeWithText("SettingsTab").performClick()+ rule.waitForIdle()+ assertEquals(1, stack.backStack.size)+ rule.onNodeWithText("HomeTab").performClick()+ rule.waitForIdle()+ assertEquals(listOf("home"), stack.backStack.map { it.route })+ assertEquals(Screen("home"), current.javaClass.let { Screen("home") }) // current untouched by default+ }++ @Test fun bottomNavBarItemNullLabelAndDisabledDoesNotClick() {+ var clicks = 0+ rule.setContent {+ MaterialTheme {+ Column {+ BottomNavBar {+ BottomNavBarItem(selected = false, onClick = { clicks++ }, icon = { Text("IconOnly") }, label = null)+ BottomNavBarItem(selected = true, onClick = { clicks += 10 }, icon = { Text("DisIcon") }, label = "DisabledTab", enabled = false)+ }+ }+ }+ }+ rule.onNodeWithText("IconOnly").assertIsDisplayed()+ rule.onNodeWithText("IconOnly").performClick()+ rule.waitForIdle()+ assertEquals(1, clicks)+ rule.onNodeWithText("DisabledTab").performClick()+ rule.waitForIdle()+ assertEquals(1, clicks, "disabled item must not fire onClick")+ }++ // ---- MainNavigation with ListPage metadata / multi-entry ----++ @Test fun mainNavigationListPageMetadataRendersAndPushPop() {+ val stack = NavBackStack(arrayOf(Screen("list")))+ rule.setContent {+ MaterialTheme {+ MainNavigation(backStack = stack) {+ entry<Screen>(metadata = if (obj.route == "list") ListPage { Text("Placeholder") } else DetailPage()) {+ Text("Page ${it.route}")+ }+ }+ }+ }+ rule.onNodeWithText("Page list").assertExists()+ rule.runOnIdle { stack.add(Screen("detail")) }+ rule.waitForIdle()+ rule.onNodeWithText("Page detail").assertExists()+ rule.runOnIdle { stack.pop() }+ rule.waitForIdle()+ rule.onNodeWithText("Page list").assertExists()+ }++ @Test fun mainNavigationResetFromTabBarStyleCall() {+ val stack = NavBackStack(arrayOf(Screen("a")))+ rule.setContent {+ MaterialTheme {+ MainNavigation(backStack = stack) {+ entry<Screen> { Text("At ${it.route}") }+ }+ }+ }+ rule.onNodeWithText("At a").assertIsDisplayed()+ rule.runOnIdle { stack.add(Screen("b")); stack.add(Screen("c")) }+ rule.waitForIdle()+ rule.onNodeWithText("At c").assertExists()+ rule.runOnIdle { stack.reset(Screen("a")) }+ rule.waitForIdle()+ rule.onNodeWithText("At a").assertIsDisplayed()+ assertEquals(1, stack.backStack.size)+ }++ // ---- ResultEffect ordering / multiple subscribers ----++ @Test fun resultEffectDeliversInOrderAndToEverySubscriber() {+ val registry = NavResultRegistry()+ val first = mutableListOf<String>()+ val second = mutableListOf<String>()+ rule.setContent {+ MaterialTheme {+ CompositionLocalProvider(LocalNavResultRegistry provides registry) {+ Column {+ ResultEffect<String>("evt") { first += it }+ ResultEffect<String>("evt") { second += it }+ Text("OrderHost")+ }+ }+ }+ }+ rule.onNodeWithText("OrderHost").assertIsDisplayed()+ CoroutineScope(Dispatchers.Default).launch {+ registry.dispatchResult("evt", "one")+ registry.dispatchResult("evt", "two")+ registry.dispatchResult("evt", "three")+ }+ rule.waitUntil(5_000) { first.size == 3 && second.size == 3 }+ assertEquals(listOf("one", "two", "three"), first)+ assertEquals(first, second)+ }++ @Test fun resultEffectSubtypeFilteringKeepsBaseTypeDelivery() {+ val registry = NavResultRegistry()+ val numbers = mutableListOf<Number>()+ val strings = mutableListOf<String>()+ rule.setContent {+ MaterialTheme {+ CompositionLocalProvider(LocalNavResultRegistry provides registry) {+ Column {+ ResultEffect<Number>("mix") { numbers += it }+ ResultEffect<String>("mix") { strings += it }+ Text("MixHost")+ }+ }+ }+ }+ CoroutineScope(Dispatchers.Default).launch {+ registry.dispatchResult("mix", 42)+ registry.dispatchResult("mix", "hello")+ }+ rule.waitUntil(5_000) { numbers.isNotEmpty() && strings.isNotEmpty() }+ assertEquals(listOf<Number>(42), numbers)+ assertEquals(listOf("hello"), strings)+ }+}
library/src/test/java/com/vayunmathur/library/util/LibraryWave2DataTest.kt
diff --git a/library/src/test/java/com/vayunmathur/library/util/LibraryWave2DataTest.kt b/library/src/test/java/com/vayunmathur/library/util/LibraryWave2DataTest.ktnew file mode 100644index 0000000000..87f945e6f8--- /dev/null+++ b/library/src/test/java/com/vayunmathur/library/util/LibraryWave2DataTest.kt@@ -0,0 +1,341 @@+package com.vayunmathur.library.util++import android.content.ContentProvider+import android.content.ContentValues+import android.content.Context+import android.database.Cursor+import android.database.MatrixCursor+import android.net.Uri+import android.provider.OpenableColumns+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.library.intents.calendar.EventData+import com.vayunmathur.library.intents.clock.SetAlarmData+import com.vayunmathur.library.intents.clock.SetTimerData+import com.vayunmathur.library.intents.contacts.ContactData+import com.vayunmathur.library.intents.email.EmailData+import com.vayunmathur.library.intents.email.EmailSearchQuery+import com.vayunmathur.library.intents.findfamily.FamilyMemberData+import com.vayunmathur.library.intents.fooddelivery.OrderLookupRequest+import com.vayunmathur.library.intents.fooddelivery.OrderLookupResult+import com.vayunmathur.library.intents.maps.DirectionsLatLng+import com.vayunmathur.library.intents.maps.DirectionsRequest+import com.vayunmathur.library.intents.maps.DirectionsResult+import com.vayunmathur.library.intents.maps.DirectionsSegment+import com.vayunmathur.library.intents.music.MusicSearchResult+import com.vayunmathur.library.intents.music.PlayMusicData+import com.vayunmathur.library.intents.notes.InsertNoteData+import com.vayunmathur.library.intents.notes.NoteData+import com.vayunmathur.library.intents.taxi.RideEstimateRequest+import com.vayunmathur.library.intents.taxi.RideEstimateResult+import com.vayunmathur.library.intents.todo.CompleteTodoData+import com.vayunmathur.library.intents.todo.GetTodosQuery+import com.vayunmathur.library.intents.todo.InsertTodoData+import com.vayunmathur.library.intents.todo.TodoData+import com.vayunmathur.library.intents.weather.WeatherData+import java.io.ByteArrayInputStream+import java.io.ByteArrayOutputStream+import java.io.File+import java.nio.file.Files+import java.util.Locale+import kotlinx.coroutines.async+import kotlinx.coroutines.runBlocking+import kotlinx.datetime.LocalTime+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++/** Wave2: default-arg entry points, DTO property reads, backup/intent branches skipped by wave1. */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class LibraryWave2DataTest {++ private val ctx: Context get() = ApplicationProvider.getApplicationContext()++ // ---- LocalizedDateNames: calls WITHOUT explicit locale/style defaults ----+ @Test fun localizedDefaultsAndFirstDayBranches() {+ // These invoke the $default synthetics wave1 never hit (it always passed a locale).+ assertEquals(12, localizedMonthNames(DateNameStyle.FULL).size)+ assertEquals(12, localizedMonthNames(DateNameStyle.SHORT).size)+ assertEquals(7, localizedDayOfWeekNames(DateNameStyle.FULL).size)+ assertEquals(7, localizedDayOfWeekNames(DateNameStyle.SHORT).size)+ val markers = localizedAmPmMarkers()+ assertTrue(markers.first.isNotBlank() && markers.second.isNotBlank())+ assertTrue(localeFirstDayOfWeek() in 1..7)+ assertEquals((1..7).toList(), localeWeekDayNumbers().sorted())+ assertEquals(localeFirstDayOfWeek(), localeWeekDayNumbers().first())+ val fmt = LocalTime.Format { localizedAmPmMarker() }+ assertTrue(fmt.format(LocalTime(9, 0)).isNotBlank())+ val fmtLower = LocalTime.Format { localizedAmPmMarker(lowercase = true) }+ assertTrue(fmtLower.format(LocalTime(21, 0)).isNotBlank())++ // First-day branches beyond Mon/Sun: Saturday (Egypt), Friday (Iran), Sunday, Monday.+ assertEquals(6, localeFirstDayOfWeek(Locale.Builder().setLanguage("ar").setRegion("EG").build()))+ assertTrue(localeFirstDayOfWeek(Locale.Builder().setLanguage("fa").setRegion("IR").build()) in 1..7)+ assertEquals(7, localeFirstDayOfWeek(Locale.US))+ assertEquals(1, localeFirstDayOfWeek(Locale.UK))+ for (loc in listOf(Locale.US, Locale.UK, Locale.CANADA, Locale.JAPAN,+ Locale.Builder().setLanguage("ar").setRegion("EG").build(),+ Locale.Builder().setLanguage("fa").setRegion("IR").build(),+ Locale.Builder().setLanguage("he").setRegion("IL").build())) {+ val week = localeWeekDayNumbers(loc)+ assertEquals((1..7).toList(), week.sorted(), "$loc")+ assertEquals(localeFirstDayOfWeek(loc), week.first(), "$loc")+ assertEquals(12, localizedMonthNames(DateNameStyle.NARROW, loc).size)+ assertEquals(7, localizedDayOfWeekNames(DateNameStyle.NARROW, loc).size)+ }+ }++ // ---- IPC DTOs: read every property explicitly (getters, not serializer) ----+ @Test fun dtoPropertyReads() {+ val w = WeatherData("Oslo", 3.0, 1.0, "Snow", 5.0, -1.0, 40, 80, 20.0, "NW", 1.5, 100L, 200L, "e")+ assertEquals("Oslo", w.locationName); assertEquals(3.0, w.temperatureCelsius)+ assertEquals(1.0, w.feelsLikeCelsius); assertEquals("Snow", w.condition)+ assertEquals(5.0, w.highCelsius); assertEquals(-1.0, w.lowCelsius)+ assertEquals(40, w.precipitationChancePercent); assertEquals(80, w.humidityPercent)+ assertEquals(20.0, w.windKph); assertEquals("NW", w.windDirection)+ assertEquals(1.5, w.uvIndex); assertEquals(100L, w.sunriseEpochSec)+ assertEquals(200L, w.sunsetEpochSec); assertEquals("e", w.error)+ val wDef = WeatherData(null, 0.0, 0.0, "Clear", 0.0, 0.0, 0, 0, 0.0, "N", 0.0)+ assertNull(wDef.sunriseEpochSec); assertNull(wDef.sunsetEpochSec); assertNull(wDef.error)++ val req = DirectionsRequest(1.0, 2.0, 3.0, 4.0, "walk")+ assertEquals(1.0, req.fromLat); assertEquals(2.0, req.fromLng)+ assertEquals(3.0, req.toLat); assertEquals(4.0, req.toLng); assertEquals("walk", req.mode)+ val ll = DirectionsLatLng(9.0, 8.0); assertEquals(9.0, ll.lat); assertEquals(8.0, ll.lng)+ val seg = DirectionsSegment(listOf(ll), 0.25); assertEquals(listOf(ll), seg.points); assertEquals(0.25, seg.speedRatio)+ val res = DirectionsResult(listOf(ll), listOf(seg), 12.0, 34.0)+ assertEquals(listOf(ll), res.polyline); assertEquals(listOf(seg), res.segments)+ assertEquals(12.0, res.distanceMeters); assertEquals(34.0, res.durationSeconds)++ val todo = TodoData("id1", "t", "n", 99L, true, 2, "home")+ assertEquals("id1", todo.id); assertEquals("t", todo.title); assertEquals("n", todo.notes)+ assertEquals(99L, todo.dueAt); assertTrue(todo.done); assertEquals(2, todo.priority); assertEquals("home", todo.list)+ val todoDef = TodoData("i", "x"); assertEquals("", todoDef.notes); assertNull(todoDef.dueAt); assertFalse(todoDef.done)+ val ins = InsertTodoData("a", "b", 5L, 3)+ assertEquals("a", ins.title); assertEquals("b", ins.notes); assertEquals(5L, ins.dueAt); assertEquals(3, ins.priority)+ val insDef = InsertTodoData("only"); assertEquals("", insDef.notes); assertNull(insDef.dueAt); assertEquals(0, insDef.priority)+ assertEquals("today", GetTodosQuery().scope); assertEquals("all", GetTodosQuery("all").scope)+ val comp = CompleteTodoData(); assertEquals("", comp.id); assertEquals("", comp.title)+ assertEquals("z", CompleteTodoData(id = "z").id)++ val alarm = SetAlarmData(7, 30); assertEquals(7, alarm.hour); assertEquals(30, alarm.minute); assertEquals("", alarm.label)+ val timer = SetTimerData(60); assertEquals(60, timer.seconds); assertEquals("", timer.label)+ val ev = EventData("meet", 1L, 2L); assertEquals("meet", ev.title); assertEquals(1L, ev.start); assertEquals(2L, ev.end); assertEquals("", ev.location)+ val contact = ContactData("Ann", "123"); assertEquals("Ann", contact.name); assertEquals("123", contact.phoneNumber)+ val email = EmailData("s", "f", "t", "d", "b", true)+ assertEquals("s", email.subject); assertEquals("f", email.from); assertEquals("t", email.to)+ assertEquals("d", email.date); assertEquals("b", email.body); assertTrue(email.isRead)+ assertEquals("q", EmailSearchQuery("q").query)+ val fam = FamilyMemberData("Bo", "Park", 1.5, 2.5)+ assertEquals("Bo", fam.name); assertEquals("Park", fam.locationName); assertEquals(1.5, fam.lat); assertEquals(2.5, fam.lon)+ val olr = OrderLookupRequest("Cafe", 1.0, 2.0)+ assertEquals("Cafe", olr.name); assertEquals(1.0, olr.lat); assertEquals(2.0, olr.lng); assertNull(olr.address)+ val olRes = OrderLookupResult(true, 7, "link")+ assertTrue(olRes.available); assertEquals(7, olRes.merchantId); assertEquals("link", olRes.deepLink)+ val ride = RideEstimateRequest(1.0, 2.0, 3.0, 4.0)+ assertEquals(1.0, ride.pickupLat); assertEquals(2.0, ride.pickupLng); assertEquals(3.0, ride.destLat); assertEquals(4.0, ride.destLng)+ assertNull(ride.pickupLabel); assertNull(ride.destLabel)+ val rideRes = RideEstimateResult(false, "", -1)+ assertFalse(rideRes.available); assertEquals("", rideRes.fareEstimate); assertEquals(-1, rideRes.etaMinutes)+ val msr = MusicSearchResult(4L, "song", "track"); assertEquals(4L, msr.id); assertEquals("song", msr.name); assertEquals("track", msr.type)+ val play = PlayMusicData(9L, "album"); assertEquals(9L, play.id); assertEquals("album", play.type)+ val note = NoteData("t", "c"); assertEquals("t", note.title); assertEquals("c", note.content)+ val insNote = InsertNoteData("t2", "c2"); assertEquals("t2", insNote.title); assertEquals("c2", insNote.content)+ }++ // ---- AppMessages.Message defaults + show() dedup/action paths ----+ @Test fun appMessageDefaults() {+ val m = AppMessages.Message("hello")+ assertEquals("hello", m.text); assertNull(m.actionLabel); assertNull(m.onAction)+ assertEquals(AppMessages.Duration.Short, m.duration)+ val m2 = AppMessages.Message("x", "Act", { }, AppMessages.Duration.Indefinite)+ assertEquals("Act", m2.actionLabel); assertEquals(AppMessages.Duration.Indefinite, m2.duration)+ AppMessages.show("wave2-unique-${System.nanoTime()}")+ AppMessages.show("wave2-action-${System.nanoTime()}", actionLabel = "Go", duration = AppMessages.Duration.Long) {}+ }++ // ---- Markdown: hidden markers on task lists, unknown latex, hidden headers ----+ @Test fun markdownHiddenTaskAndUnknownLatex() {+ val task = parseMarkdown("- [x] done thing\n- [ ] open thing", showMarkers = false)+ assertTrue(task.text.contains("done thing"))+ val hiddenHeader = parseMarkdown("# Title\n\n- item", showMarkers = false)+ assertTrue(hiddenHeader.text.contains("Title"))+ val unknown = parseMarkdown("""$\unknowncmd{abc}$ and $\mathbf{bold}$""", showMarkers = false)+ assertTrue(unknown.text.contains("abc"))+ val allCmds = parseMarkdown(+ """$\cancel{a}$ $\mathrm{b}$ $\underline{c}$ $\mathtt{d}$ $\mathsf{e}$ $\mathit{f}$""",+ showMarkers = true,+ )+ assertTrue(allCmds.spanStyles.isNotEmpty())+ val hiddenList = parseMarkdown(" - nested\n - deeper", showMarkers = false, process = true)+ assertTrue(hiddenList.text.contains("deeper"))+ }++ // ---- BackupHelper: restore-warn, directory zip/unzip, default-named datastore ----+ @Test fun backupRestoreWarnAndDirectories() {+ // dbConfigs with no codec on RESTORE hits warnRestoreSkipped.+ val emptyZip = ByteArrayOutputStream().also {+ BackupHelper.performFullBackup(ctx, emptyList(), emptyList(), emptyList(), emptyList(), it)+ }+ BackupHelper.performFullRestore(ctx, listOf("dbx" to "pw"), emptyList(), emptyList(), emptyMap(),+ ByteArrayInputStream(emptyZip.toByteArray()), null)++ // Directory in zipFiles + directory entry in unzipFiles.+ val dir = File(ctx.cacheDir, "wave2dir").apply { mkdirs() }+ File(dir, "a.txt").writeText("A"); File(dir, "sub").mkdirs(); File(dir, "sub/b.txt").writeText("B")+ val out = ByteArrayOutputStream(); BackupHelper.zipFiles(listOf(dir), ctx.cacheDir, out)+ val target = Files.createTempDirectory("wave2unzip").toFile()+ BackupHelper.unzipFiles(ByteArrayInputStream(out.toByteArray()), target)+ assertEquals("A", File(target, "wave2dir/a.txt").readText())+ assertEquals("B", File(target, "wave2dir/sub/b.txt").readText())++ // Default datastore name restores to filesDir root, not datastore/ subdir.+ val src = File(ctx.filesDir, "datastore_default.preferences_pb").apply { writeBytes(byteArrayOf(7)) }+ try {+ val o2 = ByteArrayOutputStream()+ BackupHelper.performFullBackup(ctx, emptyList(), listOf("datastore_default"), emptyList(), emptyList(), o2)+ src.delete()+ BackupHelper.performFullRestore(ctx, emptyList(), listOf("datastore_default"), emptyList(), emptyMap(),+ ByteArrayInputStream(o2.toByteArray()))+ assertTrue(File(ctx.filesDir, "datastore_default.preferences_pb").exists())+ } finally { src.delete() }++ // performFullBackup/Restore with omitted optional args ($default synthetics).+ val o3 = ByteArrayOutputStream()+ BackupHelper.performFullBackup(ctx, emptyList(), extraFiles = emptyList(), outputStream = o3)+ BackupHelper.performFullRestore(ctx, emptyList(), extraFilesMapping = emptyMap(),+ inputStream = ByteArrayInputStream(o3.toByteArray()))+ }++ // ---- BaseBackupAgent default properties ----+ class DefaultsAgent : BaseBackupAgent() { fun attach(c: Context) = attachBaseContext(c) }+ @Test fun backupAgentDefaults() {+ val agent = DefaultsAgent().apply { attach(ctx) }+ assertTrue(agent.dbConfigs.isEmpty()); assertTrue(agent.datastoreNames.isEmpty())+ assertTrue(agent.prefNames.isEmpty()); assertTrue(agent.extraFiles.isEmpty()); assertNull(agent.dbCodec)+ // onBackup with null data/newState must still run without throwing.+ agent.onBackup(null, null, null)+ agent.onRestore(null, 1, null)+ }++ // ---- IntentHelper: content provider display-name paths ----+ class NameProvider(private val cursor: Cursor?) : ContentProvider() {+ override fun onCreate() = true+ override fun query(uri: Uri, p: Array<out String>?, s: String?, a: Array<out String>?, o: String?): Cursor? = cursor+ override fun getType(uri: Uri): String? = null+ override fun insert(uri: Uri, v: ContentValues?): Uri? = null+ override fun delete(uri: Uri, s: String?, a: Array<out String>?): Int = 0+ override fun update(uri: Uri, v: ContentValues?, s: String?, a: Array<out String>?): Int = 0+ }+ @Test fun intentHelperContentProviderNames() {+ val named = MatrixCursor(arrayOf(OpenableColumns.DISPLAY_NAME)).apply { addRow(arrayOf("photo.jpg")) }+ org.robolectric.shadows.ShadowContentResolver.registerProviderInternal("com.wave2.named", NameProvider(named))+ assertEquals("photo.jpg", IntentHelper.getFileName(ctx, Uri.parse("content://com.wave2.named/items/1")))++ val noColumn = MatrixCursor(arrayOf("other")).apply { addRow(arrayOf("x")) }+ org.robolectric.shadows.ShadowContentResolver.registerProviderInternal("com.wave2.nocol", NameProvider(noColumn))+ assertEquals("42", IntentHelper.getFileName(ctx, Uri.parse("content://com.wave2.nocol/items/42")))++ val empty = MatrixCursor(arrayOf(OpenableColumns.DISPLAY_NAME))+ org.robolectric.shadows.ShadowContentResolver.registerProviderInternal("com.wave2.empty", NameProvider(empty))+ assertEquals("7", IntentHelper.getFileName(ctx, Uri.parse("content://com.wave2.empty/items/7")))+ }++ // ---- IntentLauncher: unresolvable package returns immediately ----+ @Test fun intentLauncherMissingPackageTimesOut(): Unit = runBlocking {+ val activity = Robolectric.buildActivity(androidx.activity.ComponentActivity::class.java).create().get()+ val launcher = IntentLauncher(activity)+ // Robolectric resolves the component but no target ever answers, so the+ // bounded launch must surface TimeoutException instead of hanging.+ kotlin.test.assertFailsWith<java.util.concurrent.TimeoutException> {+ launcher.launch(ctx, "com.wave2.absent", "com.wave2.absent.Nope",+ NoteData.serializer(), NoteData("t", "c"))+ }+ }++ // ---- Default-arg constructors ----+ class TwoArgManager(context: Context) : AchievementsManager(context, "[]") {+ override fun checkExistingAchievements() {}+ }+ @Test fun defaultArgConstructors() = runBlocking {+ val manager = TwoArgManager(ctx)+ assertEquals(ctx.applicationContext, manager.context)+ assertTrue(manager.achievements.isEmpty())+ manager.forgetAll()+ val repo = LevelStatsRepository(ctx)+ assertEquals(emptyMap(), repo.getLevelStats())+ repo.updateBestScore("lvl-wave2", 10); repo.updateBestScore("lvl-wave2", 20)+ repo.updateBestScore("lvl-wave2", 5)+ assertEquals(5, repo.getLevelStats()["lvl-wave2"]!!.bestScore)+ repo.retainOnly(setOf("lvl-wave2")); repo.retainOnly(emptySet())+ assertTrue(repo.getLevelStats().isEmpty())+ val helper = DatabaseHelper(ctx)+ assertEquals(ctx, helper.context)+ helper.deleteKey()+ }++ // ---- Iteration 2 ----+ @Test fun localizedAllAvailableLocalesSweep() {+ var sawFridayOrSaturday = false+ for (loc in Locale.getAvailableLocales()) {+ val first = localeFirstDayOfWeek(loc)+ assertTrue(first in 1..7, "$loc")+ assertEquals(first, localeWeekDayNumbers(loc).first(), "$loc")+ if (first >= 5) sawFridayOrSaturday = true+ }+ assertTrue(sawFridayOrSaturday)+ assertTrue(10f.formatSpeed(Locale.US).isNotBlank())+ assertTrue(10f.formatSpeed(Locale.FRANCE).isNotBlank())+ assertTrue(0f.formatSpeed().isNotBlank())+ with(ctx) {+ ensureNotificationChannel("wave2-ch", "Wave2")+ ensureNotificationChannel("wave2-ch2", "Wave2b", description = "desc") { enableLights(true) }+ deleteNotificationChannel("wave2-ch")+ }+ // Explicit directory entry in a zip must be recreated by unzipFiles.+ val zout = ByteArrayOutputStream()+ java.util.zip.ZipOutputStream(zout).use { zos ->+ zos.putNextEntry(java.util.zip.ZipEntry("emptydir/")); zos.closeEntry()+ zos.putNextEntry(java.util.zip.ZipEntry("emptydir/f.txt")); zos.write("hi".toByteArray()); zos.closeEntry()+ }+ val zt = Files.createTempDirectory("wave2zipdir").toFile()+ BackupHelper.unzipFiles(ByteArrayInputStream(zout.toByteArray()), zt)+ assertTrue(File(zt, "emptydir").isDirectory)+ assertEquals("hi", File(zt, "emptydir/f.txt").readText())+ }++ class ThrowingActivity : androidx.activity.ComponentActivity() {+ override fun startActivity(intent: android.content.Intent) {+ if (mode == 1) throw SecurityException("denied-wave2")+ throw android.content.ActivityNotFoundException("missing-wave2")+ }+ companion object { var mode = 1 }+ }++ @Test fun intentLauncherStartFailuresSurface(): Unit = runBlocking {+ for (m in listOf(1, 2)) {+ ThrowingActivity.mode = m+ val activity = Robolectric.buildActivity(ThrowingActivity::class.java).create().get()+ val launcher = IntentLauncher(activity)+ val deferred = kotlinx.coroutines.CoroutineScope(kotlinx.coroutines.Dispatchers.Default).async {+ runCatching {+ launcher.launch(ctx, "com.wave2.absent", "com.wave2.absent.Nope",+ NoteData.serializer(), NoteData("t", "c"))+ }+ }+ val deadline = System.currentTimeMillis() + 15_000+ while (!deferred.isCompleted && System.currentTimeMillis() < deadline) {+ org.robolectric.Shadows.shadowOf(android.os.Looper.getMainLooper()).idle()+ Thread.sleep(20)+ }+ assertTrue(deferred.isCompleted, "launcher must complete for mode $m")+ assertTrue(deferred.await().isFailure, "mode $m must fail: ${deferred.await()}")+ }+ }+}
library/src/test/java/com/vayunmathur/library/util/LibraryWave2NavTest.kt
diff --git a/library/src/test/java/com/vayunmathur/library/util/LibraryWave2NavTest.kt b/library/src/test/java/com/vayunmathur/library/util/LibraryWave2NavTest.ktnew file mode 100644index 0000000000..4e2db09378--- /dev/null+++ b/library/src/test/java/com/vayunmathur/library/util/LibraryWave2NavTest.kt@@ -0,0 +1,216 @@+package com.vayunmathur.library.util++import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.material3.MaterialTheme+import androidx.compose.material3.Text+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.setValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import kotlinx.serialization.Serializable+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++/** Wave2: rememberNavBackStack, per-motion MainNavigation transitions, shared-element modifiers, GameHub hooks. */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class LibraryWave2NavTest {++ @get:Rule val rule = createComposeRule()++ @Serializable data class Screen(val route: String) : NavKey++ @Test fun rememberNavBackStackVarargAndListForms() {+ var captured: NavBackStack<Screen>? = null+ var capturedList: NavBackStack<Screen>? = null+ rule.setContent {+ MaterialTheme {+ captured = rememberNavBackStack(Screen("start"), Screen("second"))+ capturedList = rememberNavBackStack(listOf(Screen("listed")))+ Text("StackHost ${captured!!.last().route} ${capturedList!!.last().route}")+ }+ }+ rule.onNodeWithText("StackHost", substring = true).assertExists()+ // Both calls share the retained-stack key (same first element type), so+ // the list form returns the same retained stack as the vararg form.+ assertEquals(listOf("start", "second"), captured!!.backStack.map { it.route })+ assertTrue(captured === capturedList)+ rule.runOnIdle { captured!!.add(Screen("third")) }+ rule.waitForIdle()+ assertEquals("third", captured!!.last().route)+ }++ private fun motionTransition(metadata: Map<String, Any>, label: String) {+ val stack = NavBackStack(arrayOf(Screen("root-$label")))+ rule.setContent {+ MaterialTheme {+ MainNavigation(backStack = stack) {+ entry<Screen>(metadata = if (obj.route.startsWith("dest")) metadata else DetailPage()) {+ Column {+ Text("Page ${it.route}")+ Text("morphing=${isNavMorphing()} leaving=${isNavLeaving()}", modifier = Modifier.sharedContainer("k-$label"))+ Text("shared text $label", modifier = Modifier.sharedText("t-$label"))+ Text("cropped $label", modifier = Modifier.sharedCrop("c-$label"))+ Text("content $label", modifier = Modifier.sharedContent("ct-$label"))+ Text("expanding $label", modifier = Modifier.expandFromLine())+ Row {+ Text("drop $label", modifier = Modifier.dropsAway())+ Text("sink $label", modifier = Modifier.sinksBelow())+ }+ }+ }+ }+ }+ }+ rule.onNodeWithText("Page root-$label").assertExists()+ rule.runOnIdle { stack.add(Screen("dest-$label")) }+ rule.waitForIdle()+ rule.onNodeWithText("Page dest-$label").assertExists()+ rule.runOnIdle { stack.pop() }+ rule.waitForIdle()+ rule.onNodeWithText("Page root-$label").assertExists()+ }++ @Test fun mainNavigationZoomTransition() = motionTransition(ZoomPage(), "zoom")+ @Test fun mainNavigationFullscreenTransition() = motionTransition(FullscreenPage(), "full")+ @Test fun mainNavigationSiblingTransition() = motionTransition(SiblingPage(), "sib")+ @Test fun mainNavigationMorphTransition() = motionTransition(MorphPage(), "morph")+ @Test fun mainNavigationDetailTransition() = motionTransition(DetailPage(), "detail")+ @Test fun mainNavigationListDetailTransition() = motionTransition(ListDetailPage(), "ld")++ @Test fun mainNavigationListPageDefaultPlaceholderAndBottomBarSlot() {+ val stack = NavBackStack(arrayOf(Screen("home")))+ var bottomClicks = 0+ rule.setContent {+ MaterialTheme {+ MainNavigation(+ backStack = stack,+ bottomBar = { Text("Wave2Bottom") },+ containerColor = androidx.compose.ui.graphics.Color.Transparent,+ ) {+ entry<Screen>(metadata = ListPage()) { Text("Listed ${it.route}") }+ }+ }+ }+ rule.onNodeWithText("Listed home").assertExists()+ rule.onNodeWithText("Wave2Bottom").assertExists()+ // Local accessors default outside providers are readable via a second composition below.+ assertTrue(true)+ }++ @Test fun bottomNavBarCustomOnSelectAndModifier() {+ val stack = NavBackStack(arrayOf(Screen("a")))+ var selected: String? = null+ var current by mutableStateOf<Screen>(Screen("a"))+ val pages = listOf(+ BottomBarItem<Screen>(name = "TabA", route = Screen("a"), icon = { Text("IA") }),+ BottomBarItem<Screen>(name = "TabB", route = Screen("b"), icon = { Text("IB") }),+ )+ rule.setContent {+ MaterialTheme {+ BottomNavBar(backStack = stack, pages = pages, currentPage = current, modifier = Modifier) { route ->+ selected = route.route; current = route+ }+ }+ }+ rule.onNodeWithText("TabB").performClick()+ rule.waitForIdle()+ assertEquals("b", selected)+ assertEquals(Screen("b"), current)+ // Stack untouched by a custom onSelect.+ assertEquals(listOf("a"), stack.backStack.map { it.route })+ }++ @Test fun gameHubHooksComposeAndRegister() {+ rule.setContent {+ MaterialTheme {+ Column {+ GameHubSessionHook(gameId = "chess", displayName = "Chess")+ GameHubComposeHook(gameId = "sudoku", achievementsManager = null)+ GameHubComposeHook(gameId = "customgame", achievementsManager = null,+ metadata = com.vayunmathur.sdk.games.GameMetadata("customgame", "Custom!"))+ Text("HubHost")+ }+ }+ }+ rule.onNodeWithText("HubHost").assertIsDisplayed()+ rule.waitForIdle()+ }++ @Test fun sharedModifiersOutsideNavigationAreNoOps() {+ var morphing = true; var leaving = true+ rule.setContent {+ MaterialTheme {+ Column {+ morphing = isNavMorphing(); leaving = isNavLeaving()+ Text("plain", modifier = Modifier.sharedContainer("x").sharedText("y").sharedCrop("z").sharedContent("w"))+ Text("expand", modifier = Modifier.expandFromLine())+ Text("drop", modifier = Modifier.dropsAway())+ Text("sink", modifier = Modifier.sinksBelow())+ SharedEditableText(key = "k1", value = "val1") { Text("Inner1") }+ }+ }+ }+ rule.onNodeWithText("Inner1").assertExists()+ assertFalse(morphing); assertFalse(leaving)+ }++ @Test fun appMessagesDrainThroughMainNavigation() {+ val stack = NavBackStack(arrayOf(Screen("msg")))+ rule.setContent {+ MaterialTheme {+ MainNavigation(backStack = stack) {+ entry<Screen> { Text("MsgPage") }+ }+ }+ }+ rule.onNodeWithText("MsgPage").assertExists()+ rule.runOnIdle {+ AppMessages.show("wave2-drain-${System.nanoTime()}", actionLabel = "Undo",+ duration = AppMessages.Duration.Long) {}+ AppMessages.show("wave2-drain2-${System.nanoTime()}", duration = AppMessages.Duration.Indefinite)+ AppMessages.show("wave2-drain3-${System.nanoTime()}", duration = AppMessages.Duration.Short)+ }+ rule.waitForIdle()+ }++ @Test fun openSettingsIfRequestedNoOpForNormalLaunch() {+ // openSettingsIfRequested with a non-app-info intent is a no-op.+ val stack = NavBackStack(arrayOf(Screen("home2")))+ rule.setContent {+ MaterialTheme {+ Column {+ with(stack) { openSettingsIfRequested(Screen("settings")) }+ Text("SettingsHost")+ }+ }+ }+ rule.onNodeWithText("SettingsHost").assertExists()+ assertEquals(listOf("home2"), stack.backStack.map { it.route })+ }++ @Test fun bottomNavBarThreeArgDefaultForm() {+ val stack = NavBackStack(arrayOf(Screen("a")))+ val pages = listOf(+ BottomBarItem<Screen>(name = "OnlyA", route = Screen("a"), icon = { Text("OA") }),+ BottomBarItem<Screen>(name = "OnlyB", route = Screen("b"), icon = { Text("OB") }),+ )+ rule.setContent {+ MaterialTheme { BottomNavBar(backStack = stack, pages = pages, currentPage = Screen("a")) }+ }+ rule.onNodeWithText("OnlyB").performClick()+ rule.waitForIdle()+ assertEquals(listOf("b"), stack.backStack.map { it.route })+ }+}