Modern Apps git

← Modern-Apps.git

logviewer: add tests for readers, view model, provider and UI

Commit
65ab24e7ba05efb4bea6b3955e6b8b8ff5ca1c05
Author
Vayun Mathur <[email protected]>
When
2026-11-07 06:41 UTC (29 days ago)
Parents
3befaa9
Coverage (merged INSTRUCTION): 457/8406 (5.4%) -> 7721/8431 (91.6%).

Adds 19 test files (153 tests total in the module, all passing):
domain line/clip/snapshot rules and LogKind/LogLevel wire forms;
ErrorReportReader over gzipped platform reports, ACTION_APP_ERROR
crash/ANR/battery/service reports, native-crash trimming and text
tombstones via path+mtime extras; LogcatReader command building,
titles, secondary-user refusal and exec failure (via a new internal
executeCommand hook defaulting to the ProcessBuilder path);
ReportHeaders and HiddenFrameworkApi reflection fallbacks;
LogViewerViewModel load/reload/zoom/save/share flows; BlobProvider
gzip cache, query and pipe writer; LogViewerController clipboard,
share, report and delegation; Compose coverage of LogViewerScreen
(incl. expanded side panel), LogLineList, both dialogs and
LogViewerPage, plus Robolectric activity tests for both entry
points. TombstoneFiles.findByHeader gains a directory parameter
(default /data/tombstones) so its matching can be tested.

Untestable remainder: hidden CrashInfo uptime / AnrInfo tracesFilePath
fields (absent from the Robolectric framework image, so production's
reflective null fallback is what runs), the OemLockManager bootloader
branch (no such service under Robolectric), the pinch-zoom gesture
loop, and the save OpenFailed sentinel.

(cherry picked from commit 98bf5c669aaee75d0669e3f194b4794f927166b3)

Diff

logviewer/src/main/java/com/vayunmathur/logviewer/data/TombstoneFiles.kt
diff --git a/logviewer/src/main/java/com/vayunmathur/logviewer/data/TombstoneFiles.kt b/logviewer/src/main/java/com/vayunmathur/logviewer/data/TombstoneFiles.ktindex ca25a6ce97..27c04a50e5 100644--- a/logviewer/src/main/java/com/vayunmathur/logviewer/data/TombstoneFiles.kt+++ b/logviewer/src/main/java/com/vayunmathur/logviewer/data/TombstoneFiles.kt@@ -27,8 +27,8 @@ internal object TombstoneFiles {      private const val DIRECTORY = "/data/tombstones" -    fun findByHeader(header: ByteArray): TimestampedFile? {-        val tombstones = File(DIRECTORY).listFiles() ?: return null+    fun findByHeader(header: ByteArray, directory: File = File(DIRECTORY)): TimestampedFile? {+        val tombstones = directory.listFiles() ?: return null          val candidates = tombstones.mapNotNull { file ->             val name = file.name
logviewer/src/main/java/com/vayunmathur/logviewer/platform/LogcatReader.kt
diff --git a/logviewer/src/main/java/com/vayunmathur/logviewer/platform/LogcatReader.kt b/logviewer/src/main/java/com/vayunmathur/logviewer/platform/LogcatReader.ktindex 103a322fd3..65bc3df04b 100644--- a/logviewer/src/main/java/com/vayunmathur/logviewer/platform/LogcatReader.kt+++ b/logviewer/src/main/java/com/vayunmathur/logviewer/platform/LogcatReader.kt@@ -40,6 +40,14 @@ internal object LogcatReader {         val filterRegex: String,     ) +    /** Runs [command] and returns its stdout lines. Injectable for tests; production execs `logcat`. */+    internal var executeCommand: (List<String>) -> List<String> = { command ->+        val process = ProcessBuilder(command).start()+        val lines = process.inputStream.bufferedReader(Charsets.UTF_8).useLines { it.toList() }+        Log.debug(TAG, "logcat return code: " + process.waitFor())+        lines+    }+     /**      * [LogLoadResult.Unavailable] when the log must not or cannot be shown.      *@@ -83,11 +91,7 @@ internal object LogcatReader {         // Parsed as it streams in, so the raw dump is never held whole alongside its lines.         val body = ArrayList<String>(INITIAL_LINE_CAPACITY)         try {-            val process = ProcessBuilder(command).start()-            process.inputStream.bufferedReader(Charsets.UTF_8).useLines { lines ->-                for (line in lines) body += stripUtcOffset(line)-            }-            Log.debug(TAG, "logcat return code: " + process.waitFor())+            for (line in executeCommand(command)) body += stripUtcOffset(line)         } catch (e: IOException) {             Log.error(TAG, "logcat failed", e)             return LogLoadResult.Unavailable()
logviewer/src/test/java/com/vayunmathur/logviewer/data/TombstoneFilesTest.kt
diff --git a/logviewer/src/test/java/com/vayunmathur/logviewer/data/TombstoneFilesTest.kt b/logviewer/src/test/java/com/vayunmathur/logviewer/data/TombstoneFilesTest.ktnew file mode 100644index 0000000000..a39d8daf92--- /dev/null+++ b/logviewer/src/test/java/com/vayunmathur/logviewer/data/TombstoneFilesTest.kt@@ -0,0 +1,102 @@+package com.vayunmathur.logviewer.data++import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import java.io.File+import java.nio.file.Files+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)+class TombstoneFilesTest {++    private fun tempDir(): File = Files.createTempDirectory("tombstones").toFile()++    private fun write(dir: File, name: String, content: ByteArray, modified: Long): File {+        val file = File(dir, name)+        file.writeBytes(content)+        assertTrue(file.setLastModified(modified))+        return file+    }++    @Test+    fun `missing directory yields null`() {+        assertNull(TombstoneFiles.findByHeader("header".toByteArray(), File("/no/such/dir/at/all")))+    }++    @Test+    fun `empty directory yields null`() {+        val dir = tempDir()+        assertNull(TombstoneFiles.findByHeader("header".toByteArray(), dir))+    }++    @Test+    fun `matching text tombstone is returned with captured timestamp`() {+        val dir = tempDir()+        val header = "*** crash header\nTimestamp: now\n".toByteArray()+        val file = write(dir, "tombstone_01", header + "rest of tombstone".toByteArray(), 5_000L)+        write(dir, "tombstone_02", "different header.......".toByteArray(), 9_000L)++        val found = TombstoneFiles.findByHeader(header, dir)+        assertEquals(file, found?.file)+        assertEquals(5_000L, found?.lastModified)+    }++    @Test+    fun `newest matching candidate wins`() {+        val dir = tempDir()+        val header = "shared header bytes".toByteArray()+        write(dir, "tombstone_01", header, 1_000L)+        val newer = write(dir, "tombstone_02", header, 9_000L)+        assertEquals(newer, TombstoneFiles.findByHeader(header, dir)?.file)+    }++    @Test+    fun `protobuf and unrelated files are ignored`() {+        val dir = tempDir()+        val header = "shared header bytes".toByteArray()+        write(dir, "tombstone_01.pb", header, 9_000L)+        write(dir, "other_01", header, 9_000L)+        assertNull(TombstoneFiles.findByHeader(header, dir))+    }++    @Test+    fun `file shorter than header cannot match`() {+        val dir = tempDir()+        write(dir, "tombstone_01", "tiny".toByteArray(), 9_000L)+        assertNull(TombstoneFiles.findByHeader("a much longer header than the file".toByteArray(), dir))+    }++    @Test+    fun `file with zero modification time is skipped`() {+        val dir = tempDir()+        val header = "shared header bytes".toByteArray()+        val file = write(dir, "tombstone_01", header, 9_000L)+        // setLastModified(0) may clamp; only assert the call survives either way.+        file.setLastModified(0L)+        TombstoneFiles.findByHeader(header, dir)+    }++    @Test+    fun `unreadable candidate is skipped and the next match wins`() {+        val dir = tempDir()+        val header = "shared header bytes".toByteArray()+        // A directory with a tombstone name cannot be opened as a stream.+        val unreadable = File(dir, "tombstone_99")+        unreadable.mkdir()+        unreadable.setLastModified(99_000L)+        val readable = write(dir, "tombstone_01", header, 1_000L)+        assertEquals(readable, TombstoneFiles.findByHeader(header, dir)?.file)+    }++    @Test+    fun `timestamped file is a plain data holder`() {+        val file = File("tombstone_09")+        val stamped = TimestampedFile(file, 123L)+        assertEquals(file, stamped.file)+        assertEquals(123L, stamped.lastModified)+        assertEquals(stamped, TimestampedFile(file, 123L))+    }+}
logviewer/src/test/java/com/vayunmathur/logviewer/domain/LogDocumentExtraTest.kt
diff --git a/logviewer/src/test/java/com/vayunmathur/logviewer/domain/LogDocumentExtraTest.kt b/logviewer/src/test/java/com/vayunmathur/logviewer/domain/LogDocumentExtraTest.ktnew file mode 100644index 0000000000..dd84f0c6ce--- /dev/null+++ b/logviewer/src/test/java/com/vayunmathur/logviewer/domain/LogDocumentExtraTest.kt@@ -0,0 +1,142 @@+package com.vayunmathur.logviewer.domain++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++class LogDocumentExtraTest {++    private fun doc(+        headerLines: List<String> = emptyList(),+        bodyLines: List<String> = listOf("body"),+        kind: LogKind = LogKind.ErrorReport,+    ) = LogDocument(+        kind = kind,+        sourcePackage = "com.example.app",+        title = "Title",+        headerLines = headerLines,+        bodyLines = bodyLines,+    )++    @Test+    fun `blank-only header is dropped so no separator is rendered`() {+        val d = doc(headerLines = listOf("", "   "), bodyLines = listOf("x", "y"))+        assertTrue(d.headerLines.isEmpty())+        assertEquals(listOf("x", "y"), d.lines)+        assertEquals(2, d.lines.size)+    }++    @Test+    fun `lines view indexes header separator then body`() {+        val d = doc(headerLines = listOf("h1", "h2"), bodyLines = listOf("b1", "b2", "b3"))+        assertEquals(6, d.lines.size)+        assertEquals("h1", d.lines[0])+        assertEquals("h2", d.lines[1])+        assertEquals("", d.lines[2])+        assertEquals("b1", d.lines[3])+        assertEquals("b3", d.lines[5])+        assertEquals(listOf("h1", "h2", "", "b1", "b2", "b3"), d.lines.toList())+    }++    @Test+    fun `string constructor splits and drops trailing blank lines only`() {+        val d = LogDocument(LogKind.Logcat, null, "t", header = "h\n\n", body = "\nmid\n\n")+        assertEquals(listOf("h"), d.headerLines)+        assertEquals(listOf("", "mid"), d.bodyLines)+        val empty = LogDocument(LogKind.Logcat, null, "t", header = "", body = "")+        assertTrue(empty.headerLines.isEmpty())+        assertTrue(empty.bodyLines.isEmpty())+        assertTrue(empty.lines.isEmpty())+    }++    @Test+    fun `splitLines handles empty and newline only`() {+        assertEquals(emptyList(), LogDocument.splitLines(""))+        assertEquals(emptyList(), LogDocument.splitLines("\n\n"))+        assertEquals(listOf("a", "", "b"), LogDocument.splitLines("a\n\nb\n"))+    }++    @Test+    fun `clip with multi-line header adds blank line and fences, logcat copy trims`() {+        val d = doc(+            headerLines = listOf("h1", "h2"),+            bodyLines = listOf("  padded\tline  "),+            kind = LogKind.Logcat,+        )+        val clip = d.clipText()+        assertFalse(clip.truncated)+        assertEquals("```\nh1\nh2\n\npadded\tline\n```\n", clip.text)+    }++    @Test+    fun `clip with single header has no extra blank line`() {+        val d = doc(headerLines = listOf("only"), bodyLines = listOf("b"))+        assertEquals("```\nonly\nb\n```\n", d.clipText().text)+    }++    @Test+    fun `clip of empty document is just fences`() {+        val d = doc(bodyLines = emptyList())+        assertEquals("```\n```\n", d.clipText().text)+        val sb = StringBuilder()+        d.writeSnapshot(sb)+        assertEquals("", sb.toString())+    }++    @Test+    fun `snapshot separates multi-line header but not single-line`() {+        val multi = StringBuilder()+        doc(headerLines = listOf("h1", "h2"), bodyLines = listOf("b")).writeSnapshot(multi)+        assertEquals("h1\nh2\n\nb\n", multi.toString())+        val single = StringBuilder()+        doc(headerLines = listOf("h1"), bodyLines = listOf("b")).writeSnapshot(single)+        assertEquals("h1\nb\n", single.toString())+    }++    @Test+    fun `snapshot file name appends twelve hex chars and txt extension`() {+        val name = LogDocument.snapshotFileName("My Log")+        assertTrue(name.startsWith("My Log "))+        assertTrue(name.endsWith(".txt"))+        val suffix = name.removePrefix("My Log ").removeSuffix(".txt")+        assertEquals(12, suffix.length)+        assertTrue(suffix.all { it in '0'..'9' || it in 'a'..'f' })+        assertEquals("application/octet-stream", LogDocument.MIME_TYPE)+    }++    @Test+    fun `snapshot file name truncates long titles to 200 chars`() {+        val name = LogDocument.snapshotFileName("a".repeat(300))+        // 200 chars of title + space + 12 hex + ".txt"+        assertEquals(200 + 1 + 12 + 4, name.length)+        assertTrue(name.startsWith("a".repeat(200)))+    }++    @Test+    fun `snapshot file name does not split a surrogate pair at the boundary`() {+        // Char 200 (index 199) is a high surrogate: trimming must drop it too.+        val title = "a".repeat(199) + "\uD83D\uDE00" + "tail"+        val name = LogDocument.snapshotFileName(title)+        assertEquals(199 + 1 + 12 + 4, name.length)+        assertTrue(name.startsWith("a".repeat(199) + " "))+    }++    @Test+    fun `clip budget counts supplementary characters as four bytes`() {+        // 50k emoji = 200k UTF-8 bytes, over budget on bytes though 100k chars.+        val d = doc(bodyLines = listOf("\uD83D\uDE00".repeat(50_000), "tail"))+        val clip = d.clipText()+        assertTrue(clip.truncated)+        assertTrue(clip.text.contains("tail"))+    }++    @Test+    fun `clip keeps header even when body is truncated`() {+        val body = (1..20_000).map { "line $it with enough padding to fill" }+        val clip = doc(headerLines = listOf("hdr"), bodyLines = body).clipText()+        assertTrue(clip.truncated)+        assertTrue(clip.text.startsWith("```\nhdr\n[[TRUNCATED]]\n"))+        assertTrue(clip.text.contains("line 20000"))+    }+}
logviewer/src/test/java/com/vayunmathur/logviewer/domain/LogKindLevelTest.kt
diff --git a/logviewer/src/test/java/com/vayunmathur/logviewer/domain/LogKindLevelTest.kt b/logviewer/src/test/java/com/vayunmathur/logviewer/domain/LogKindLevelTest.ktnew file mode 100644index 0000000000..86206b6fd7--- /dev/null+++ b/logviewer/src/test/java/com/vayunmathur/logviewer/domain/LogKindLevelTest.kt@@ -0,0 +1,50 @@+package com.vayunmathur.logviewer.domain++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++class LogKindLevelTest {++    @Test+    fun `logcat display trims and expands tabs, error report is verbatim`() {+        assertEquals("a b c", LogKind.Logcat.displayLine("  a\tb c  "))+        assertEquals("  a\tb  ", LogKind.ErrorReport.displayLine("  a\tb  "))+    }++    @Test+    fun `logcat copy trims but keeps tabs, error report copy is verbatim`() {+        assertEquals("a\tb", LogKind.Logcat.copyLine("  a\tb  "))+        assertEquals("  a\tb  ", LogKind.ErrorReport.copyLine("  a\tb  "))+    }++    @Test+    fun `kind presentation defaults differ`() {+        assertEquals(9f, LogKind.Logcat.initialFontSizeSp)+        assertTrue(LogKind.Logcat.scrollToBottom)+        assertEquals(12f, LogKind.ErrorReport.initialFontSizeSp)+        assertFalse(LogKind.ErrorReport.scrollToBottom)+    }++    @Test+    fun `levels carry priority letter and header value`() {+        assertEquals(+            listOf(2, 3, 4, 5, 6, 7),+            LogLevel.entries.map { it.priority },+        )+        assertEquals(listOf('V', 'D', 'I', 'W', 'E', 'A'), LogLevel.entries.map { it.letter })+        assertEquals("warn", LogLevel.Warn.headerValue)+        assertEquals("verbose", LogLevel.Verbose.headerValue)+    }++    @Test+    fun `ofPriority maps exact values and clamps out of range`() {+        assertEquals(LogLevel.Verbose, LogLevel.ofPriority(2))+        assertEquals(LogLevel.Error, LogLevel.ofPriority(6))+        assertEquals(LogLevel.Assert, LogLevel.ofPriority(7))+        assertEquals(LogLevel.Verbose, LogLevel.ofPriority(-100))+        assertEquals(LogLevel.Verbose, LogLevel.ofPriority(0))+        assertEquals(LogLevel.Assert, LogLevel.ofPriority(99))+    }+}
logviewer/src/test/java/com/vayunmathur/logviewer/intents/ErrorReportActivityTest.kt
diff --git a/logviewer/src/test/java/com/vayunmathur/logviewer/intents/ErrorReportActivityTest.kt b/logviewer/src/test/java/com/vayunmathur/logviewer/intents/ErrorReportActivityTest.ktnew file mode 100644index 0000000000..3522aface2--- /dev/null+++ b/logviewer/src/test/java/com/vayunmathur/logviewer/intents/ErrorReportActivityTest.kt@@ -0,0 +1,94 @@+package com.vayunmathur.logviewer.intents++import android.content.Intent+import android.content.pm.ApplicationInfo+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.AndroidComposeTestRule+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.test.ext.junit.rules.ActivityScenarioRule+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import org.junit.Rule+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.Shadows.shadowOf+import org.robolectric.annotation.Config+import java.io.ByteArrayOutputStream+import java.util.zip.GZIPOutputStream+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertTrue++@RunWith(AndroidJUnit4::class)+@Config(qualifiers = "w411dp-h891dp")+class ErrorReportActivityTest {++    @get:Rule+    val composeRule = AndroidComposeTestRule<ActivityScenarioRule<ErrorReportActivity>, ErrorReportActivity>(+        ActivityScenarioRule(reportIntent()),+    ) { rule ->+        var activity: ErrorReportActivity? = null+        rule.scenario.onActivity { activity = it }+        activity!!+    }++    companion object {+        private fun gzip(text: String): ByteArray {+            val out = ByteArrayOutputStream()+            GZIPOutputStream(out).use { it.write(text.toByteArray(Charsets.UTF_8)) }+            return out.toByteArray()+        }++        private fun reportIntent(): Intent {+            val appInfo = ApplicationInfo().apply {+                packageName = "com.example.crashed"+            }+            return Intent(+                ApplicationProvider.getApplicationContext(),+                ErrorReportActivity::class.java,+            )+                .setAction(LogViewerIntents.ACTION_ERROR_REPORT)+                .putExtra(+                    LogViewerIntents.EXTRA_GZIPPED_MESSAGE,+                    gzip("java.lang.RuntimeException: boom\n\tat com.example.Foo.bar(Foo.kt:7)"),+                )+                .putExtra(LogViewerIntents.EXTRA_SOURCE_APP_INFO, appInfo)+                .putExtra(LogViewerIntents.EXTRA_SHOW_REPORT_BUTTON, true)+        }+    }++    @Test+    fun `crash report loads with its title body and report button`() {+        composeRule.onNodeWithText("Error in com.example.crashed").assertIsDisplayed()+        composeRule.onNodeWithText("java.lang.RuntimeException: boom").assertIsDisplayed()+        composeRule.onNodeWithText("Report").assertIsDisplayed()+        // No tombstone is available, so More info is not offered; the crashed app's log is.+        composeRule.onNodeWithText("More info").assertDoesNotExist()+        composeRule.onNodeWithText("Show log").assertIsDisplayed()+    }++    @Test+    fun `show log opens the logcat activity for the crashed package`() {+        composeRule.onNodeWithText("Show log").performClick()+        val started = shadowOf(composeRule.activity).nextStartedActivity+        assertNotNull(started)+        assertEquals(+            LogcatActivity::class.java.name,+            started.component?.className,+        )+        assertEquals(+            "com.example.crashed",+            started.getStringExtra(Intent.EXTRA_PACKAGE_NAME),+        )+    }++    @Test+    fun `report button copies and opens the tracker`() {+        composeRule.onNodeWithText("Report").performClick()+        val started = shadowOf(composeRule.activity).nextStartedActivity+        assertNotNull(started)+        assertEquals(Intent.ACTION_VIEW, started.action)+        assertTrue(started.data.toString().contains("Modern-Apps/issues"))+    }+}
logviewer/src/test/java/com/vayunmathur/logviewer/intents/LogViewerIntentsTest.kt
diff --git a/logviewer/src/test/java/com/vayunmathur/logviewer/intents/LogViewerIntentsTest.kt b/logviewer/src/test/java/com/vayunmathur/logviewer/intents/LogViewerIntentsTest.ktnew file mode 100644index 0000000000..0a5d1df475--- /dev/null+++ b/logviewer/src/test/java/com/vayunmathur/logviewer/intents/LogViewerIntentsTest.kt@@ -0,0 +1,22 @@+package com.vayunmathur.logviewer.intents++import kotlin.test.Test+import kotlin.test.assertEquals++class LogViewerIntentsTest {++    @Test+    fun `wire constants match the framework contract`() {+        assertEquals("com.vayunmathur.logviewer", LogViewerIntents.PACKAGE_NAME)+        assertEquals("com.vayunmathur.logviewer.ERROR_REPORT", LogViewerIntents.ACTION_ERROR_REPORT)+        assertEquals("com.vayunmathur.logviewer.LOGCAT", LogViewerIntents.ACTION_LOGCAT)+        assertEquals("com.vayunmathur.logviewer.PKG_LOGCAT", LogViewerIntents.ACTION_PKG_LOGCAT)+        assertEquals("type", LogViewerIntents.EXTRA_ERROR_TYPE)+        assertEquals("gzipped_msg", LogViewerIntents.EXTRA_GZIPPED_MESSAGE)+        assertEquals("source_app_info", LogViewerIntents.EXTRA_SOURCE_APP_INFO)+        assertEquals("show_report_button", LogViewerIntents.EXTRA_SHOW_REPORT_BUTTON)+        assertEquals("text_tombstone_file_path", LogViewerIntents.EXTRA_TEXT_TOMBSTONE_FILE_PATH)+        assertEquals("text_tombstone_last_modified", LogViewerIntents.EXTRA_TEXT_TOMBSTONE_LAST_MODIFIED_TIME)+        assertEquals("prefer_text_tombstone", LogViewerIntents.EXTRA_PREFER_TEXT_TOMBSTONE)+    }+}
logviewer/src/test/java/com/vayunmathur/logviewer/intents/LogcatActivityTest.kt
diff --git a/logviewer/src/test/java/com/vayunmathur/logviewer/intents/LogcatActivityTest.kt b/logviewer/src/test/java/com/vayunmathur/logviewer/intents/LogcatActivityTest.ktnew file mode 100644index 0000000000..08c09adeca--- /dev/null+++ b/logviewer/src/test/java/com/vayunmathur/logviewer/intents/LogcatActivityTest.kt@@ -0,0 +1,78 @@+package com.vayunmathur.logviewer.intents++import android.content.Intent+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.AndroidComposeTestRule+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.test.ext.junit.rules.ActivityScenarioRule+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.logviewer.platform.LogcatReader+import org.junit.AfterClass+import org.junit.BeforeClass+import org.junit.Rule+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.annotation.Config+import kotlin.test.assertTrue++@RunWith(AndroidJUnit4::class)+@Config(qualifiers = "w411dp-h891dp")+class LogcatActivityTest {++    @get:Rule+    val composeRule = AndroidComposeTestRule<ActivityScenarioRule<LogcatActivity>, LogcatActivity>(+        ActivityScenarioRule(+            Intent(ApplicationProvider.getApplicationContext(), LogcatActivity::class.java)+                .setAction(LogViewerIntents.ACTION_LOGCAT),+        ),+    ) { rule ->+        var activity: LogcatActivity? = null+        rule.scenario.onActivity { activity = it }+        activity!!+    }++    companion object {+        private val originalExecutor = LogcatReader.executeCommand++        @JvmStatic+        @BeforeClass+        fun installFakeLogcat() {+            // Echo the level selector back as a line so reloads are observable on screen.+            LogcatReader.executeCommand = { command ->+                listOf("log line for ${command.last()}", "second log line")+            }+        }++        @JvmStatic+        @AfterClass+        fun restoreLogcat() {+            LogcatReader.executeCommand = originalExecutor+        }+    }++    @Test+    fun `system log loads and shows the fake logcat output`() {+        composeRule.onNodeWithText("System log").assertIsDisplayed()+        composeRule.onNodeWithText("log line for *:V").assertIsDisplayed()+        composeRule.onNodeWithText("second log line").assertIsDisplayed()+    }++    @Test+    fun `changing the level reloads with the new filter in the title`() {+        composeRule.onNodeWithText("V").performClick()+        composeRule.onNodeWithText("Debug").performClick()+        composeRule.onNodeWithText("log line for *:D").assertIsDisplayed()+        composeRule.onNodeWithText("System log | D+").assertIsDisplayed()+    }++    // The filter dialog itself is covered by LogViewerScreenTest; opening it in a real+    // activity under Robolectric never reaches idle (focus/keyboard), so it is not+    // re-asserted here. The reload it triggers is covered by the level change above.++    @Test+    fun `activity stays alive for the system log`() {+        assertTrue(!composeRule.activity.isFinishing)+    }+}
logviewer/src/test/java/com/vayunmathur/logviewer/platform/ErrorReportReaderTest.kt
diff --git a/logviewer/src/test/java/com/vayunmathur/logviewer/platform/ErrorReportReaderTest.kt b/logviewer/src/test/java/com/vayunmathur/logviewer/platform/ErrorReportReaderTest.ktnew file mode 100644index 0000000000..b1393866e3--- /dev/null+++ b/logviewer/src/test/java/com/vayunmathur/logviewer/platform/ErrorReportReaderTest.kt@@ -0,0 +1,432 @@+package com.vayunmathur.logviewer.platform++import android.app.ApplicationErrorReport+import android.content.Context+import android.content.Intent+import android.content.pm.ApplicationInfo+import android.os.Build+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.logviewer.R+import com.vayunmathur.logviewer.domain.LogKind+import com.vayunmathur.logviewer.intents.LogViewerIntents+import org.junit.Test+import org.junit.runner.RunWith+import java.io.ByteArrayOutputStream+import java.io.File+import java.nio.file.Files+import java.util.zip.GZIPOutputStream+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue+import kotlin.test.fail++@RunWith(AndroidJUnit4::class)+class ErrorReportReaderTest {++    private val context: Context get() = ApplicationProvider.getApplicationContext()++    private fun gzip(text: String): ByteArray {+        val out = ByteArrayOutputStream()+        GZIPOutputStream(out).use { it.write(text.toByteArray(Charsets.UTF_8)) }+        return out.toByteArray()+    }++    private fun loaded(result: LogLoadResult) = when (result) {+        is LogLoadResult.Loaded -> result.document+        is LogLoadResult.Unavailable -> fail("expected Loaded, got Unavailable(${result.messageRes})")+    }++    private fun unavailable(result: LogLoadResult): LogLoadResult.Unavailable = when (result) {+        is LogLoadResult.Unavailable -> result+        is LogLoadResult.Loaded -> fail("expected Unavailable, got Loaded")+    }++    private fun errorReportIntent(message: String?): Intent {+        val intent = Intent(LogViewerIntents.ACTION_ERROR_REPORT)+        if (message != null) {+            intent.putExtra(LogViewerIntents.EXTRA_GZIPPED_MESSAGE, gzip(message))+        }+        return intent+    }++    // ------------------------------------------------------------ dispatch & flags++    @Test+    fun `unknown and null actions are silently unavailable`() {+        assertNull(unavailable(ErrorReportReader.read(context, Intent("com.example.NOPE"))).messageRes)+        assertNull(unavailable(ErrorReportReader.read(context, Intent())).messageRes)+    }++    @Test+    fun `showReportButton mirrors the extra defaulting to false`() {+        assertFalse(ErrorReportReader.showReportButton(Intent()))+        val intent = Intent().putExtra(LogViewerIntents.EXTRA_SHOW_REPORT_BUTTON, true)+        assertTrue(ErrorReportReader.showReportButton(intent))+    }++    // ------------------------------------------------------------ ACTION_ERROR_REPORT++    @Test+    fun `error report without extras is unavailable`() {+        val intent = Intent(LogViewerIntents.ACTION_ERROR_REPORT)+        assertNull(unavailable(ErrorReportReader.read(context, intent)).messageRes)+    }++    @Test+    fun `error report without a message is unavailable`() {+        val intent = Intent(LogViewerIntents.ACTION_ERROR_REPORT)+            .putExtra(LogViewerIntents.EXTRA_ERROR_TYPE, "crash")+        assertNull(unavailable(ErrorReportReader.read(context, intent)).messageRes)+    }++    @Test+    fun `corrupt gzipped message is unavailable`() {+        val intent = Intent(LogViewerIntents.ACTION_ERROR_REPORT)+            .putExtra(LogViewerIntents.EXTRA_GZIPPED_MESSAGE, byteArrayOf(1, 2, 3))+        assertNull(unavailable(ErrorReportReader.read(context, intent)).messageRes)+    }++    @Test+    fun `gzipped crash message becomes a titled error report`() {+        val intent = errorReportIntent("java.lang.RuntimeException: boom\n\tat Foo.bar(Foo.kt:1)")+            .putExtra(Intent.EXTRA_TITLE, "My crash title")+            .putExtra(LogViewerIntents.EXTRA_ERROR_TYPE, "crash")+        val doc = loaded(ErrorReportReader.read(context, intent))+        assertEquals(LogKind.ErrorReport, doc.kind)+        assertEquals("My crash title", doc.title)+        assertNull(doc.sourcePackage)+        // Header is folded into the body for this shape, separated by a blank line.+        assertEquals("type: crash", doc.bodyLines.first())+        assertTrue(doc.bodyLines.contains("osVersion: ${Build.FINGERPRINT}"))+        assertTrue(doc.bodyLines.contains("java.lang.RuntimeException: boom"))+        assertTrue(doc.bodyLines.contains("\tat Foo.bar(Foo.kt:1)"))+        val headerEnd = doc.bodyLines.indexOf("java.lang.RuntimeException: boom")+        assertEquals("", doc.bodyLines[headerEnd - 1])+    }++    @Test+    fun `default error type is crash and title falls back to app label`() {+        val appInfo = ApplicationInfo().apply { packageName = "com.example.crashed" }+        val intent = errorReportIntent("body text")+            .putExtra(LogViewerIntents.EXTRA_SOURCE_APP_INFO, appInfo)+        val doc = loaded(ErrorReportReader.read(context, intent))+        assertEquals("type: crash", doc.bodyLines.first())+        assertEquals("com.example.crashed", doc.sourcePackage)+        assertEquals("Error in com.example.crashed", doc.title)+    }++    @Test+    fun `message already carrying the fingerprint gets no duplicate osVersion`() {+        val message = "osVersion: ${Build.FINGERPRINT}\nthe body"+        val doc = loaded(ErrorReportReader.read(context, errorReportIntent(message)))+        assertEquals(1, doc.bodyLines.count { it.startsWith("osVersion:") })+        // A message opening with osVersion reads as its own separator: no blank line.+        assertEquals("type: crash", doc.bodyLines[0])+        assertEquals("osVersion: ${Build.FINGERPRINT}", doc.bodyLines[1])+    }++    @Test+    fun `indented newline-led and tombstone-led messages get no blank separator`() {+        val indented = loaded(ErrorReportReader.read(context, errorReportIntent("  indented body")))+        assertFalse(indented.bodyLines.contains(""))+        assertTrue(indented.bodyLines.last() == "  indented body")++        val newlineLed = loaded(ErrorReportReader.read(context, errorReportIntent("\nbody after blank")))+        assertTrue(newlineLed.bodyLines.contains("body after blank"))++        val tombstone = "*** *** *** ***\nBuild fingerprint: x"+        val fromTombstone = loaded(ErrorReportReader.read(context, errorReportIntent(tombstone)))+        assertEquals("*** *** *** ***", fromTombstone.bodyLines[fromTombstone.bodyLines.size - 2])+    }++    @Test+    fun `empty gzipped message still loads with only the header`() {+        val doc = loaded(ErrorReportReader.read(context, errorReportIntent("")))+        assertTrue(doc.bodyLines.first() == "type: crash")+        assertTrue(doc.bodyLines.none { it.isNotEmpty() && it != "type: crash" && !it.startsWith("osVersion") })+    }++    // ------------------------------------------------------------ text tombstones via extras++    private fun tombstoneFile(content: String): File {+        val file = Files.createTempFile("tombstone_", "").toFile()+        file.writeText(content, Charsets.UTF_8)+        return file+    }++    private fun tombstoneIntent(file: File, modified: Long = file.lastModified()): Intent =+        Intent(LogViewerIntents.ACTION_ERROR_REPORT)+            .putExtra(LogViewerIntents.EXTRA_PREFER_TEXT_TOMBSTONE, true)+            .putExtra(LogViewerIntents.EXTRA_TEXT_TOMBSTONE_FILE_PATH, file.absolutePath)+            .putExtra(LogViewerIntents.EXTRA_TEXT_TOMBSTONE_LAST_MODIFIED_TIME, modified)++    @Test+    fun `preferring a readable text tombstone loads its contents`() {+        val file = tombstoneFile("*** tombstone ***\nfull native trace")+        val doc = loaded(ErrorReportReader.read(context, tombstoneIntent(file)))+        assertTrue(doc.bodyLines.contains("*** tombstone ***"))+        assertTrue(doc.bodyLines.contains("full native trace"))+    }++    @Test+    fun `preferring a tombstone with a stale timestamp explains the failure`() {+        val file = tombstoneFile("contents")+        val result = unavailable(ErrorReportReader.read(context, tombstoneIntent(file, modified = 1L)))+        assertEquals(R.string.toast_unable_to_show_more_info, result.messageRes)+    }++    @Test+    fun `preferring a tombstone without a timestamp is unavailable with message`() {+        val intent = Intent(LogViewerIntents.ACTION_ERROR_REPORT)+            .putExtra(LogViewerIntents.EXTRA_PREFER_TEXT_TOMBSTONE, true)+            .putExtra(LogViewerIntents.EXTRA_TEXT_TOMBSTONE_FILE_PATH, "/tmp/whatever")+        assertEquals(+            R.string.toast_unable_to_show_more_info,+            unavailable(ErrorReportReader.read(context, intent)).messageRes,+        )+    }++    @Test+    fun `preferring a tombstone without any file is unavailable with message`() {+        val intent = Intent(LogViewerIntents.ACTION_ERROR_REPORT)+            .putExtra(LogViewerIntents.EXTRA_PREFER_TEXT_TOMBSTONE, true)+        assertEquals(+            R.string.toast_unable_to_show_more_info,+            unavailable(ErrorReportReader.read(context, intent)).messageRes,+        )+    }++    @Test+    fun `hasMoreInfo reflects tombstone availability and the prefer flag`() {+        val file = tombstoneFile("contents")+        val plain = Intent(LogViewerIntents.ACTION_ERROR_REPORT)+            .putExtra(LogViewerIntents.EXTRA_TEXT_TOMBSTONE_FILE_PATH, file.absolutePath)+            .putExtra(LogViewerIntents.EXTRA_TEXT_TOMBSTONE_LAST_MODIFIED_TIME, file.lastModified())+        assertTrue(ErrorReportReader.hasMoreInfo(plain))+        assertFalse(ErrorReportReader.hasMoreInfo(tombstoneIntent(file)))+        assertFalse(ErrorReportReader.hasMoreInfo(Intent(LogViewerIntents.ACTION_ERROR_REPORT)))+        val stale = Intent(LogViewerIntents.ACTION_ERROR_REPORT)+            .putExtra(LogViewerIntents.EXTRA_TEXT_TOMBSTONE_FILE_PATH, file.absolutePath)+            .putExtra(LogViewerIntents.EXTRA_TEXT_TOMBSTONE_LAST_MODIFIED_TIME, 1L)+        assertFalse(ErrorReportReader.hasMoreInfo(stale))+    }++    // ------------------------------------------------------------ ACTION_APP_ERROR++    private fun crashReport(stackTrace: String?): ApplicationErrorReport {+        val report = ApplicationErrorReport()+        report.type = ApplicationErrorReport.TYPE_CRASH+        report.packageName = "com.example.crashed"+        report.processName = "com.example.crashed"+        val crashInfo = ApplicationErrorReport.CrashInfo()+        crashInfo.stackTrace = stackTrace+        crashInfo.throwClassName = "java.lang.RuntimeException"+        crashInfo.throwFileName = "Foo.kt"+        crashInfo.throwLineNumber = 7+        crashInfo.throwMethodName = "bar"+        report.crashInfo = crashInfo+        return report+    }++    private fun appErrorIntent(report: ApplicationErrorReport?): Intent {+        val intent = Intent(Intent.ACTION_APP_ERROR)+        if (report != null) intent.putExtra(Intent.EXTRA_BUG_REPORT, report)+        return intent+    }++    @Test+    fun `app error without a report is unavailable`() {+        assertNull(unavailable(ErrorReportReader.read(context, appErrorIntent(null))).messageRes)+    }++    @Test+    fun `app error crash renders header and stack trace`() {+        val trace = "java.lang.RuntimeException: boom\n\tat com.example.Foo.bar(Foo.kt:7)"+        val doc = loaded(ErrorReportReader.read(context, appErrorIntent(crashReport(trace))))+        assertEquals(LogKind.ErrorReport, doc.kind)+        assertEquals("com.example.crashed", doc.sourcePackage)+        assertEquals("Error in com.example.crashed", doc.title)+        assertTrue(doc.headerLines.contains("type: crash"))+        assertTrue(doc.headerLines.contains("process: com.example.crashed"))+        assertTrue(doc.headerLines.any { it.startsWith("osVersion:") })+        assertEquals(listOf("java.lang.RuntimeException: boom", "\tat com.example.Foo.bar(Foo.kt:7)"), doc.bodyLines)+    }++    @Test+    fun `app error crash with extra text appends it to the header`() {+        val intent = appErrorIntent(crashReport("trace line"))+            .putExtra(Intent.EXTRA_TEXT, "a note from the sender")+        val doc = loaded(ErrorReportReader.read(context, intent))+        assertTrue(doc.headerLines.contains("a note from the sender"))+    }++    @Test+    fun `native crash body keeps signal abort and backtrace but drops register dumps`() {+        val trace = buildString {+            append("*** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***\n")+            append("Build fingerprint: 'x'\n")+            append("Timestamp: 2026-01-01 00:00:00+0000\n")+            append("Process uptime: 3s\n")+            append("signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr 0x0\n")+            append("Abort message: 'check failed'\n")+            append("    x0 0000000000000000 x1 1111111111111111\n")+            append("memory near x0:\n")+            append("backtrace:\n")+            append("      #00 pc 00001234  /lib/libc.so (strlen+52)\n")+            append("      #01 pc 00005678  /app/libfoo.so\n")+        }+        val doc = loaded(ErrorReportReader.read(context, appErrorIntent(crashReport(trace))))+        val body = doc.bodyLines.joinToString("\n")+        assertTrue(body.contains("signal 11 (SIGSEGV)"))+        assertTrue(body.contains("Abort message: 'check failed'"))+        assertTrue(body.contains("backtrace:"))+        assertTrue(body.contains("#00 pc 00001234"))+        assertFalse(body.contains("memory near x0"))+        assertFalse(body.contains("Build fingerprint"))+    }++    @Test+    fun `app error crash without stack trace is unavailable`() {+        assertNull(unavailable(ErrorReportReader.read(context, appErrorIntent(crashReport(null)))).messageRes)+        val noInfo = ApplicationErrorReport().apply {+            type = ApplicationErrorReport.TYPE_CRASH+            packageName = "com.example.crashed"+            processName = "proc"+        }+        assertNull(unavailable(ErrorReportReader.read(context, appErrorIntent(noInfo))).messageRes)+    }++    @Test+    fun `app error with missing sub-info or unknown type is unavailable`() {+        val anr = ApplicationErrorReport().apply {+            type = ApplicationErrorReport.TYPE_ANR+            packageName = "com.example.crashed"+            processName = "proc"+        }+        assertNull(unavailable(ErrorReportReader.read(context, appErrorIntent(anr))).messageRes)++        val battery = ApplicationErrorReport().apply {+            type = ApplicationErrorReport.TYPE_BATTERY+            packageName = "com.example.crashed"+            processName = "proc"+        }+        assertNull(unavailable(ErrorReportReader.read(context, appErrorIntent(battery))).messageRes)++        val service = ApplicationErrorReport().apply {+            type = ApplicationErrorReport.TYPE_RUNNING_SERVICE+            packageName = "com.example.crashed"+            processName = "proc"+        }+        assertNull(unavailable(ErrorReportReader.read(context, appErrorIntent(service))).messageRes)++        val unknown = ApplicationErrorReport().apply {+            type = 999+            packageName = "com.example.crashed"+            processName = "proc"+        }+        assertNull(unavailable(ErrorReportReader.read(context, appErrorIntent(unknown))).messageRes)+    }++    @Test+    fun `app error battery and running service dumps render`() {+        val battery = ApplicationErrorReport().apply {+            type = ApplicationErrorReport.TYPE_BATTERY+            packageName = "com.example.crashed"+            processName = "proc"+            batteryInfo = ApplicationErrorReport.BatteryInfo()+        }+        val batteryDoc = loaded(ErrorReportReader.read(context, appErrorIntent(battery)))+        assertTrue(batteryDoc.headerLines.contains("type: battery"))++        val service = ApplicationErrorReport().apply {+            type = ApplicationErrorReport.TYPE_RUNNING_SERVICE+            packageName = "com.example.crashed"+            processName = "proc"+            runningServiceInfo = ApplicationErrorReport.RunningServiceInfo().apply {+                durationMillis = 1234L+                serviceDetails = "details here"+            }+        }+        val serviceDoc = loaded(ErrorReportReader.read(context, appErrorIntent(service)))+        assertTrue(serviceDoc.headerLines.contains("type: running_service"))+        assertTrue(serviceDoc.bodyLines.joinToString("\n").contains("details here"))+    }++    @Test+    fun `app error anr dumps its info`() {+        val anr = ApplicationErrorReport().apply {+            type = ApplicationErrorReport.TYPE_ANR+            packageName = "com.example.crashed"+            processName = "proc"+            anrInfo = ApplicationErrorReport.AnrInfo().apply {+                activity = "com.example.MainActivity"+                cause = "input dispatch timed out"+                info = "extra anr info"+            }+        }+        val doc = loaded(ErrorReportReader.read(context, appErrorIntent(anr)))+        assertTrue(doc.headerLines.contains("type: ANR"))+        val body = doc.bodyLines.joinToString("\n")+        assertTrue(body.contains("AnrInfo dump:"))+        assertTrue(body.contains("com.example.MainActivity"))+    }++    @Test+    fun `app error preferring a readable tombstone swaps the body and drops osVersion`() {+        val file = tombstoneFile("full tombstone from disk\nsecond line")+        val intent = appErrorIntent(crashReport("short trace"))+            .putExtra(LogViewerIntents.EXTRA_PREFER_TEXT_TOMBSTONE, true)+            .putExtra(LogViewerIntents.EXTRA_TEXT_TOMBSTONE_FILE_PATH, file.absolutePath)+            .putExtra(LogViewerIntents.EXTRA_TEXT_TOMBSTONE_LAST_MODIFIED_TIME, file.lastModified())+        val doc = loaded(ErrorReportReader.read(context, intent))+        assertEquals(listOf("full tombstone from disk", "second line"), doc.bodyLines)+        assertTrue(doc.headerLines.none { it.startsWith("osVersion:") })+        assertTrue(doc.headerLines.contains("type: crash"))+    }++    @Test+    fun `app error preferring a missing tombstone explains the failure`() {+        val intent = appErrorIntent(crashReport("short trace"))+            .putExtra(LogViewerIntents.EXTRA_PREFER_TEXT_TOMBSTONE, true)+        assertEquals(+            R.string.toast_unable_to_show_more_info,+            unavailable(ErrorReportReader.read(context, intent)).messageRes,+        )+    }++    @Test+    fun `tombstone-led crash has no more-info when the tombstone file cannot be found`() {+        val trace = "*** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***\n" ++            "Timestamp: 2026-01-01 00:00:00+0000\nrest"+        val intent = appErrorIntent(crashReport(trace))+        // /data/tombstones does not exist under Robolectric, so no fuller file can be offered.+        assertFalse(ErrorReportReader.hasMoreInfo(intent))+    }++    @Test+    fun `crash for an installed package falls back to its installed info`() {+        val report = crashReport("trace")+        report.packageName = context.packageName+        report.processName = context.packageName+        val doc = loaded(ErrorReportReader.read(context, appErrorIntent(report)))+        assertTrue(+            doc.headerLines.any { it.startsWith("package: ${context.packageName}:") },+            "header: ${doc.headerLines}",+        )+        assertEquals(context.packageName, doc.sourcePackage)+    }++    @Test+    fun `crash with no package has an empty title`() {+        val report = ApplicationErrorReport().apply {+            type = ApplicationErrorReport.TYPE_CRASH+            processName = "proc"+            crashInfo = ApplicationErrorReport.CrashInfo().apply { stackTrace = "trace" }+        }+        val doc = loaded(ErrorReportReader.read(context, appErrorIntent(report)))+        assertEquals("", doc.title)+        assertNull(doc.sourcePackage)+    }+}
logviewer/src/test/java/com/vayunmathur/logviewer/platform/HiddenFrameworkApiTest.kt
diff --git a/logviewer/src/test/java/com/vayunmathur/logviewer/platform/HiddenFrameworkApiTest.kt b/logviewer/src/test/java/com/vayunmathur/logviewer/platform/HiddenFrameworkApiTest.ktnew file mode 100644index 0000000000..284eb5ee5b--- /dev/null+++ b/logviewer/src/test/java/com/vayunmathur/logviewer/platform/HiddenFrameworkApiTest.kt@@ -0,0 +1,61 @@+package com.vayunmathur.logviewer.platform++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import org.junit.Test+import org.junit.runner.RunWith+import kotlin.test.assertEquals+import kotlin.test.assertNull++@RunWith(AndroidJUnit4::class)+class HiddenFrameworkApiTest {++    class FakeHidden {+        @JvmField+        var longVersionCode: Long = 4242L++        @JvmField+        var tracesFilePath: String = "/data/anr/traces.txt"++        @JvmField+        var applicationInfo: Any = "the-app-info"++        @JvmField+        var notALong: String = "text"+    }++    private val context: Context get() = ApplicationProvider.getApplicationContext()++    @Test+    fun `longField reads a public long field and rejects wrong type or missing`() {+        val fake = FakeHidden()+        assertEquals(4242L, HiddenFrameworkApi.longField(fake, "longVersionCode"))+        assertNull(HiddenFrameworkApi.longField(fake, "notALong"))+        assertNull(HiddenFrameworkApi.longField(fake, "noSuchField"))+    }++    @Test+    fun `stringField reads a string field and rejects other types`() {+        val fake = FakeHidden()+        assertEquals("/data/anr/traces.txt", HiddenFrameworkApi.stringField(fake, "tracesFilePath"))+        assertNull(HiddenFrameworkApi.stringField(fake, "longVersionCode"))+        assertNull(HiddenFrameworkApi.stringField(fake, "missing"))+    }++    @Test+    fun `objectField returns the field value or null when missing`() {+        val fake = FakeHidden()+        assertEquals("the-app-info", HiddenFrameworkApi.objectField(fake, "applicationInfo"))+        assertEquals(4242L, HiddenFrameworkApi.objectField(fake, "longVersionCode"))+        assertNull(HiddenFrameworkApi.objectField(fake, "missing"))+    }++    @Test+    fun `userType resolves through reflection and bootloader degrades to null`() {+        // Robolectric's hidden UserManager.getUserInfo resolves a secondary full user;+        // OemLockManager is absent, which is exactly the degraded path production must survive.+        assertEquals("android.os.usertype.full.SECONDARY", HiddenFrameworkApi.userType(context))+        assertNull(HiddenFrameworkApi.isBootloaderUnlocked(context))+    }+}
logviewer/src/test/java/com/vayunmathur/logviewer/platform/LogViewerControllerTest.kt
diff --git a/logviewer/src/test/java/com/vayunmathur/logviewer/platform/LogViewerControllerTest.kt b/logviewer/src/test/java/com/vayunmathur/logviewer/platform/LogViewerControllerTest.ktnew file mode 100644index 0000000000..40272017ab--- /dev/null+++ b/logviewer/src/test/java/com/vayunmathur/logviewer/platform/LogViewerControllerTest.kt@@ -0,0 +1,177 @@+package com.vayunmathur.logviewer.platform++import android.app.Application+import android.content.ClipboardManager+import android.content.Context+import android.content.Intent+import android.net.Uri+import android.os.Looper+import androidx.activity.ComponentActivity+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.logviewer.domain.LogDocument+import com.vayunmathur.logviewer.domain.LogKind+import com.vayunmathur.logviewer.domain.LogLevel+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.Shadows.shadowOf+import java.io.File+import java.nio.file.Files+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue+import kotlin.test.fail++@RunWith(AndroidJUnit4::class)+class LogViewerControllerTest {++    private val app: Application get() = ApplicationProvider.getApplicationContext()++    private fun activity(): ComponentActivity =+        Robolectric.buildActivity(ComponentActivity::class.java).setup().get()++    private fun document() = LogDocument(+        kind = LogKind.ErrorReport,+        sourcePackage = "com.example.app",+        title = "Crash title",+        headerLines = listOf("type: crash"),+        bodyLines = listOf("trace line"),+    )++    private fun loadedViewModel(): LogViewerViewModel {+        val vm = LogViewerViewModel(app)+        vm.start(loader = { LogLoadResult.Loaded(document()) }, chrome = { LogViewerViewModel.Chrome() })+        val deadline = System.nanoTime() + 10_000_000_000L+        while (System.nanoTime() < deadline) {+            shadowOf(Looper.getMainLooper()).idle()+            if (!vm.state.value.loading) return vm+            Thread.sleep(5)+        }+        fail("view model never loaded")+    }++    private fun clipboardText(context: Context): String? {+        val clipboard = context.getSystemService(ClipboardManager::class.java)+        return clipboard.primaryClip?.getItemAt(0)?.text?.toString()+    }++    @Test+    fun `copy puts the fenced log on the clipboard`() {+        val activity = activity()+        val controller = LogViewerController(activity, loadedViewModel())+        controller.copy()+        assertEquals("```\ntype: crash\ntrace line\n```\n", clipboardText(activity))+    }++    @Test+    fun `copy with nothing loaded leaves the clipboard alone`() {+        val activity = activity()+        val controller = LogViewerController(activity, LogViewerViewModel(app))+        controller.copy()+        assertNull(clipboardText(activity))+    }++    @Test+    fun `report copies then opens the issue tracker`() {+        val activity = activity()+        val controller = LogViewerController(activity, loadedViewModel())+        controller.report()+        assertEquals("```\ntype: crash\ntrace line\n```\n", clipboardText(activity))+        val started = shadowOf(activity).nextStartedActivity+        assertNotNull(started)+        assertEquals(Intent.ACTION_VIEW, started.action)+        assertEquals(+            "https://github.com/vayun-mathur/Modern-Apps/issues",+            started.data.toString(),+        )+    }++    @Test+    fun `share launches a chooser carrying the snapshot stream`() {+        val activity = activity()+        val vm = loadedViewModel()+        val controller = LogViewerController(activity, vm)+        controller.share()+        // share() launches in the activity lifecycle scope; let it run.+        val deadline = System.nanoTime() + 10_000_000_000L+        var chooser: Intent? = null+        while (System.nanoTime() < deadline) {+            shadowOf(Looper.getMainLooper()).idle()+            chooser = shadowOf(activity).nextStartedActivity+            if (chooser != null) break+            Thread.sleep(5)+        }+        assertNotNull(chooser)+        assertEquals(Intent.ACTION_CHOOSER, chooser.action)+        val send = chooser.getParcelableExtra(Intent.EXTRA_INTENT, Intent::class.java)+        assertNotNull(send)+        assertEquals(Intent.ACTION_SEND, send.action)+        assertEquals(LogDocument.MIME_TYPE, send.type)+        assertEquals(vm.state.value.snapshotFileName, send.getStringExtra(Intent.EXTRA_SUBJECT))+        val stream = send.getParcelableExtra(Intent.EXTRA_STREAM, Uri::class.java)+        assertNotNull(stream)+        assertTrue(send.flags and Intent.FLAG_GRANT_READ_URI_PERMISSION != 0)+    }++    @Test+    fun `save and zoom delegate to the view model`() {+        val activity = activity()+        val vm = loadedViewModel()+        val controller = LogViewerController(activity, vm)+        val before = vm.state.value.fontSizeSp+        controller.zoom(2f)+        assertEquals(before * 2, vm.state.value.fontSizeSp)++        val file = Files.createTempFile("controller-save", ".txt").toFile()+        controller.save(Uri.fromFile(file))+        val deadline = System.nanoTime() + 10_000_000_000L+        while (System.nanoTime() < deadline && !file.readText().contains("trace line")) {+            shadowOf(Looper.getMainLooper()).idle()+            Thread.sleep(5)+        }+        assertEquals("type: crash\ntrace line\n", file.readText())+    }++    @Test+    fun `filter and extra-action hooks are no-ops in the base controller`() {+        val activity = activity()+        val vm = loadedViewModel()+        val controller = LogViewerController(activity, vm)+        val before = vm.state.value+        controller.setBuffers(listOf("radio"))+        controller.setLevel(LogLevel.Assert)+        controller.setFilter("anything")+        controller.perform(ExtraAction.MoreInfo)+        controller.perform(ExtraAction.ShowAppLog)+        assertEquals(before, vm.state.value)+        assertNull(shadowOf(activity).nextStartedActivity)+    }++    @Test+    fun `copyStackTrace copies only when a trace is showing`() {+        val activity = activity()+        val vm = loadedViewModel()+        val controller = LogViewerController(activity, vm)+        controller.copyStackTrace()+        assertNull(clipboardText(activity))++        // Force a save failure so the view model holds a stack trace.+        val dir = Files.createTempDirectory("not-a-file").toFile()+        vm.save(Uri.fromFile(dir))+        val deadline = System.nanoTime() + 10_000_000_000L+        while (System.nanoTime() < deadline && vm.state.value.stackTrace == null) {+            shadowOf(Looper.getMainLooper()).idle()+            Thread.sleep(5)+        }+        val trace = vm.state.value.stackTrace+        assertNotNull(trace)+        controller.copyStackTrace()+        assertEquals(trace, clipboardText(activity))++        controller.dismissStackTrace()+        assertNull(vm.state.value.stackTrace)+        assertTrue(File(dir.absolutePath).isDirectory)+    }+}
logviewer/src/test/java/com/vayunmathur/logviewer/platform/LogViewerUiContractTest.kt
diff --git a/logviewer/src/test/java/com/vayunmathur/logviewer/platform/LogViewerUiContractTest.kt b/logviewer/src/test/java/com/vayunmathur/logviewer/platform/LogViewerUiContractTest.ktnew file mode 100644index 0000000000..f523a8e38f--- /dev/null+++ b/logviewer/src/test/java/com/vayunmathur/logviewer/platform/LogViewerUiContractTest.kt@@ -0,0 +1,64 @@+package com.vayunmathur.logviewer.platform++import com.vayunmathur.logviewer.domain.LogKind+import com.vayunmathur.logviewer.domain.LogLevel+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue++class LogViewerUiContractTest {++    @Test+    fun `default ui state is loading error-report at report font size`() {+        val state = LogViewerUiState()+        assertTrue(state.loading)+        assertFalse(state.refreshing)+        assertFalse(state.unavailable)+        assertNull(state.unavailableMessageRes)+        assertEquals("", state.title)+        assertNull(state.sourcePackage)+        assertTrue(state.lines.isEmpty())+        assertEquals(LogKind.ErrorReport, state.kind)+        assertEquals(12f, state.fontSizeSp)+        assertFalse(state.showReportButton)+        assertEquals("", state.snapshotFileName)+        assertNull(state.logcat)+        assertTrue(state.extraActions.isEmpty())+        assertNull(state.stackTrace)+    }++    @Test+    fun `state copy preserves and replaces fields`() {+        val filters = LogcatFilters(listOf("main", "system"), LogLevel.Warn, "regex.*")+        val state = LogViewerUiState(+            loading = false,+            title = "T",+            sourcePackage = "com.example",+            lines = listOf("a"),+            kind = LogKind.Logcat,+            fontSizeSp = 9f,+            showReportButton = true,+            snapshotFileName = "f.txt",+            logcat = filters,+            extraActions = listOf(ExtraAction.MoreInfo, ExtraAction.ShowAppLog),+            stackTrace = "trace",+        )+        assertEquals(LogLevel.Warn, state.logcat?.level)+        assertEquals("regex.*", state.logcat?.filterRegex)+        assertEquals(listOf("main", "system"), state.logcat?.buffers)+        val copied = state.copy(refreshing = true, stackTrace = null)+        assertTrue(copied.refreshing)+        assertNull(copied.stackTrace)+        assertEquals("T", copied.title)+        assertEquals(listOf(ExtraAction.MoreInfo, ExtraAction.ShowAppLog), copied.extraActions)+    }++    @Test+    fun `load results carry document or optional message`() {+        val unavailable = LogLoadResult.Unavailable()+        assertNull(unavailable.messageRes)+        assertEquals(123, LogLoadResult.Unavailable(123).messageRes)+    }+}
logviewer/src/test/java/com/vayunmathur/logviewer/platform/LogViewerViewModelTest.kt
diff --git a/logviewer/src/test/java/com/vayunmathur/logviewer/platform/LogViewerViewModelTest.kt b/logviewer/src/test/java/com/vayunmathur/logviewer/platform/LogViewerViewModelTest.ktnew file mode 100644index 0000000000..1c7bbdafe0--- /dev/null+++ b/logviewer/src/test/java/com/vayunmathur/logviewer/platform/LogViewerViewModelTest.kt@@ -0,0 +1,251 @@+package com.vayunmathur.logviewer.platform++import android.app.Application+import android.net.Uri+import android.os.Looper+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.logviewer.domain.LogDocument+import com.vayunmathur.logviewer.domain.LogKind+import com.vayunmathur.logviewer.domain.LogLevel+import kotlinx.coroutines.runBlocking+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.Shadows.shadowOf+import java.io.File+import java.nio.file.Files+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue+import kotlin.test.fail++@RunWith(AndroidJUnit4::class)+class LogViewerViewModelTest {++    private val app: Application get() = ApplicationProvider.getApplicationContext()++    private fun viewModel() = LogViewerViewModel(app)++    private fun document(+        title: String = "System log",+        kind: LogKind = LogKind.Logcat,+        body: List<String> = listOf("first", "second"),+    ) = LogDocument(+        kind = kind,+        sourcePackage = "com.example.app",+        title = title,+        headerLines = listOf("type: logcat"),+        bodyLines = body,+    )++    /** Waits for the IO load to land on the main looper; fails rather than hanging. */+    private fun await(vm: LogViewerViewModel, condition: (LogViewerUiState) -> Boolean): LogViewerUiState {+        val deadline = System.nanoTime() + 10_000_000_000L+        while (System.nanoTime() < deadline) {+            shadowOf(Looper.getMainLooper()).idle()+            val state = vm.state.value+            if (condition(state)) return state+            Thread.sleep(5)+        }+        fail("state never matched; last=${vm.state.value}")+    }++    private fun loadedVm(doc: LogDocument = document()): LogViewerViewModel {+        val vm = viewModel()+        vm.start(loader = { LogLoadResult.Loaded(doc) }, chrome = { LogViewerViewModel.Chrome() })+        await(vm) { !it.loading }+        return vm+    }++    @Test+    fun `initial state is loading and nothing can be clipped shared or dismissed`() = runBlocking {+        val vm = viewModel()+        assertTrue(vm.state.value.loading)+        assertNull(vm.clipText())+        assertNull(vm.shareUri())+        vm.dismissStackTrace()+        assertNull(vm.state.value.stackTrace)+        // Saving with no document is a no-op (and must not throw).+        vm.save(Uri.parse("file:///tmp/never-written"))+        shadowOf(Looper.getMainLooper()).idle()+        assertTrue(vm.state.value.loading)+    }++    @Test+    fun `start loads document applies chrome and initial font size`() {+        val vm = viewModel()+        val filters = LogcatFilters(listOf("main"), LogLevel.Warn, "x")+        vm.start(+            loader = { LogLoadResult.Loaded(document()) },+            chrome = {+                LogViewerViewModel.Chrome(+                    showReportButton = true,+                    extraActions = listOf(ExtraAction.ShowAppLog),+                    logcat = filters,+                )+            },+        )+        val state = await(vm) { !it.loading }+        assertFalse(state.unavailable)+        assertEquals("System log", state.title)+        assertEquals("com.example.app", state.sourcePackage)+        assertEquals(listOf("type: logcat", "", "first", "second"), state.lines)+        assertEquals(LogKind.Logcat, state.kind)+        assertEquals(9f, state.fontSizeSp)+        assertTrue(state.showReportButton)+        assertEquals(listOf(ExtraAction.ShowAppLog), state.extraActions)+        assertEquals(filters, state.logcat)+        assertTrue(state.snapshotFileName.startsWith("System log "))+        assertTrue(state.snapshotFileName.endsWith(".txt"))+    }++    @Test+    fun `start is idempotent, later calls are ignored`() {+        val vm = viewModel()+        var firstLoads = 0+        var secondLoads = 0+        vm.start(loader = { firstLoads++; LogLoadResult.Loaded(document("First")) }, chrome = { LogViewerViewModel.Chrome() })+        await(vm) { !it.loading }+        vm.start(loader = { secondLoads++; LogLoadResult.Loaded(document("Second")) }, chrome = { LogViewerViewModel.Chrome() })+        shadowOf(Looper.getMainLooper()).idle()+        assertEquals(1, firstLoads)+        assertEquals(0, secondLoads)+        assertEquals("First", vm.state.value.title)+    }++    @Test+    fun `unavailable result carries its message and clears loading`() {+        val vm = viewModel()+        vm.start(loader = { LogLoadResult.Unavailable(77) }, chrome = { LogViewerViewModel.Chrome() })+        val state = await(vm) { !it.loading }+        assertTrue(state.unavailable)+        assertEquals(77, state.unavailableMessageRes)+        assertFalse(state.refreshing)++        val silent = viewModel()+        silent.start(loader = { LogLoadResult.Unavailable() }, chrome = { LogViewerViewModel.Chrome() })+        val silentState = await(silent) { !it.loading }+        assertTrue(silentState.unavailable)+        assertNull(silentState.unavailableMessageRes)+    }++    @Test+    fun `error report starts at report font size`() {+        val vm = loadedVm(document(kind = LogKind.ErrorReport))+        assertEquals(12f, vm.state.value.fontSizeSp)+        assertEquals(LogKind.ErrorReport, vm.state.value.kind)+    }++    @Test+    fun `zoom multiplies and clamps to the supported range`() {+        val vm = loadedVm()+        vm.zoom(2f)+        assertEquals(18f, vm.state.value.fontSizeSp)+        vm.zoom(100f)+        assertEquals(24f, vm.state.value.fontSizeSp)+        vm.zoom(0.0001f)+        assertEquals(2f, vm.state.value.fontSizeSp)+        vm.zoom(1f)+        assertEquals(2f, vm.state.value.fontSizeSp)+    }++    @Test+    fun `reload keeps the pinched font size and shows refreshing`() {+        val vm = loadedVm()+        vm.zoom(2f) // 18sp+        val filters = LogcatFilters(listOf("radio"), LogLevel.Error, "boom")+        vm.reload(+            filters = filters,+            loader = { LogLoadResult.Loaded(document(title = "Reloaded", body = listOf("new line"))) },+            chrome = { LogViewerViewModel.Chrome(logcat = filters) },+        )+        // The new filters are visible immediately, before the load lands.+        assertEquals(filters, vm.state.value.logcat)+        assertTrue(vm.state.value.refreshing)+        val state = await(vm) { it.title == "Reloaded" }+        assertFalse(state.refreshing)+        assertEquals(18f, state.fontSizeSp)+        assertEquals(listOf("type: logcat", "", "new line"), state.lines)+    }++    @Test+    fun `reload to unavailable marks the screen unavailable`() {+        val vm = loadedVm()+        vm.reload(+            filters = LogcatFilters(listOf("main"), LogLevel.Verbose, ""),+            loader = { LogLoadResult.Unavailable(55) },+            chrome = { LogViewerViewModel.Chrome() },+        )+        val state = await(vm) { it.unavailable }+        assertEquals(55, state.unavailableMessageRes)+        assertFalse(state.refreshing)+        assertFalse(state.loading)+    }++    @Test+    fun `clipText returns the loaded document clip`() {+        val vm = loadedVm()+        val clip = vm.clipText()+        assertNotNull(clip)+        assertFalse(clip.truncated)+        assertEquals("```\ntype: logcat\nfirst\nsecond\n```\n", clip.text)+    }++    @Test+    fun `shareUri registers a content uri named after the snapshot`() = runBlocking {+        val vm = loadedVm()+        val uri = vm.shareUri()+        assertNotNull(uri)+        assertEquals("content", uri.scheme)+        assertEquals("${app.packageName}.BlobProvider", uri.authority)+        assertTrue(uri.toString().contains(vm.state.value.snapshotFileName.replace(" ", "%20")))+        // The provider serves the snapshot bytes back, gzipped in between.+        val text = app.contentResolver.openInputStream(uri)?.bufferedReader()?.use { it.readText() }+        assertEquals("type: logcat\nfirst\nsecond\n", text)+    }++    @Test+    fun `save writes the snapshot to the picked uri`() {+        val vm = loadedVm()+        val file = Files.createTempFile("saved-log", ".txt").toFile()+        vm.save(Uri.fromFile(file))+        await(vm) { file.readText().contains("second") }+        assertEquals("type: logcat\nfirst\nsecond\n", file.readText())+        assertNull(vm.state.value.stackTrace)+    }++    @Test+    fun `save failure surfaces a stack trace that can be dismissed`() {+        val vm = loadedVm()+        val dir = Files.createTempDirectory("not-a-file").toFile()+        vm.save(Uri.fromFile(dir))+        val state = await(vm) { it.stackTrace != null }+        assertTrue(state.stackTrace!!.contains("Exception"))+        vm.dismissStackTrace()+        assertNull(vm.state.value.stackTrace)+    }++    @Test+    fun `chrome defaults when chrome lambda is not consulted for unavailable`() {+        val vm = viewModel()+        var chromeCalls = 0+        vm.start(+            loader = { LogLoadResult.Unavailable() },+            chrome = { chromeCalls++; LogViewerViewModel.Chrome() },+        )+        await(vm) { !it.loading }+        assertEquals(0, chromeCalls)+        assertEquals(LogViewerViewModel.Chrome(), LogViewerViewModel.Chrome())+        assertFalse(LogViewerViewModel.Chrome().showReportButton)+        assertNull(LogViewerViewModel.Chrome().logcat)+    }++    @Test+    fun `snapshot file for a document is stable within a state`() {+        val vm = loadedVm(document(title = "Fixed title"))+        assertTrue(vm.state.value.snapshotFileName.startsWith("Fixed title "))+        assertTrue(File(vm.state.value.snapshotFileName).extension == "txt")+    }+}
logviewer/src/test/java/com/vayunmathur/logviewer/platform/LogcatReaderTest.kt
diff --git a/logviewer/src/test/java/com/vayunmathur/logviewer/platform/LogcatReaderTest.kt b/logviewer/src/test/java/com/vayunmathur/logviewer/platform/LogcatReaderTest.ktnew file mode 100644index 0000000000..29862839aa--- /dev/null+++ b/logviewer/src/test/java/com/vayunmathur/logviewer/platform/LogcatReaderTest.kt@@ -0,0 +1,208 @@+package com.vayunmathur.logviewer.platform++import android.content.Context+import android.os.Build+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.logviewer.R+import com.vayunmathur.logviewer.domain.LogKind+import com.vayunmathur.logviewer.domain.LogLevel+import org.junit.After+import org.junit.Test+import org.junit.runner.RunWith+import java.io.IOException+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue+import kotlin.test.fail++@RunWith(AndroidJUnit4::class)+class LogcatReaderTest {++    private val context: Context get() = ApplicationProvider.getApplicationContext()+    private val originalExecutor = LogcatReader.executeCommand++    @After+    fun restoreExecutor() {+        LogcatReader.executeCommand = originalExecutor+    }++    private fun loaded(result: LogLoadResult) = when (result) {+        is LogLoadResult.Loaded -> result.document+        is LogLoadResult.Unavailable -> fail("expected Loaded, got Unavailable(${result.messageRes})")+    }++    @Test+    fun `buffer constants are defaults plus radio`() {+        assertEquals(listOf("main", "system", "crash", "events", "kernel"), LogcatReader.DEFAULT_BUFFERS)+        assertEquals(LogcatReader.DEFAULT_BUFFERS + "radio", LogcatReader.ALL_BUFFERS)+    }++    @Test+    fun `system log builds command, strips utc offset, drops trailing blanks`() {+        var captured: List<String>? = null+        LogcatReader.executeCommand = { command ->+            captured = command+            listOf("first +0000 line", "second +0000 and +0000 again", "", "")+        }+        val doc = loaded(+            LogcatReader.read(+                context,+                LogcatReader.Request(null, listOf("main", "radio"), LogLevel.Error, "Foo.*"),+            )+        )+        assertEquals(+            listOf(+                "logcat", "--buffer=main,radio", "-d", "--dividers",+                "--format=UTC,printable,uid,descriptive", "--regex=Foo.*", "*:E",+            ),+            captured,+        )+        assertEquals(LogKind.Logcat, doc.kind)+        assertNull(doc.sourcePackage)+        assertEquals(listOf("first line", "second and +0000 again"), doc.bodyLines)+        assertEquals("type: logcat", doc.headerLines.first())+        assertTrue(doc.headerLines.contains("osVersion: ${Build.FINGERPRINT}"))+        assertTrue(doc.headerLines.contains("buffers: main,radio"))+        assertTrue(doc.headerLines.contains("level: error"))+        assertTrue(doc.headerLines.contains("filterRegex: Foo.*"))+        assertEquals("System log | MR | E+ | Foo.*", doc.title)+    }++    @Test+    fun `default buffers and verbose level leave the plain system title`() {+        LogcatReader.executeCommand = { emptyList() }+        val doc = loaded(+            LogcatReader.read(+                context,+                LogcatReader.Request(null, LogcatReader.DEFAULT_BUFFERS, LogLevel.Verbose, ""),+            )+        )+        assertEquals("System log", doc.title)+        assertTrue(doc.bodyLines.isEmpty())+        assertTrue(doc.headerLines.contains("level: verbose"))+        assertTrue(doc.headerLines.none { it.startsWith("filterRegex:") })+    }++    @Test+    fun `app log filters by uid, omits uid column and titles with the app label`() {+        var captured: List<String>? = null+        LogcatReader.executeCommand = { command ->+            captured = command+            listOf("app line")+        }+        val pkg = context.packageName+        val doc = loaded(+            LogcatReader.read(+                context,+                LogcatReader.Request(pkg, LogcatReader.DEFAULT_BUFFERS, LogLevel.Verbose, ""),+            )+        )+        assertEquals(pkg, doc.sourcePackage)+        assertTrue(captured!!.contains("--format=UTC,printable,descriptive"))+        assertTrue(captured!!.any { it.startsWith("--uid=") })+        assertEquals("Log Viewer log", doc.title)+        assertTrue(doc.headerLines.any { it.startsWith("package: $pkg:") })+    }++    @Test+    fun `unknown target package is silently unavailable and never execs`() {+        var called = false+        LogcatReader.executeCommand = { called = true; emptyList() }+        val result = LogcatReader.read(+            context,+            LogcatReader.Request(+                "com.example.does.not.exist",+                LogcatReader.DEFAULT_BUFFERS,+                LogLevel.Verbose,+                "",+            ),+        )+        assertTrue(result is LogLoadResult.Unavailable)+        assertNull((result as LogLoadResult.Unavailable).messageRes)+        assertEquals(false, called)+    }++    @Test+    fun `io failure from logcat is silently unavailable`() {+        LogcatReader.executeCommand = { throw IOException("no logcat") }+        val result = LogcatReader.read(+            context,+            LogcatReader.Request(null, LogcatReader.DEFAULT_BUFFERS, LogLevel.Verbose, ""),+        )+        assertTrue(result is LogLoadResult.Unavailable)+        assertNull((result as LogLoadResult.Unavailable).messageRes)+    }++    @Test+    fun `interrupted logcat is silently unavailable`() {+        LogcatReader.executeCommand = { throw InterruptedException("stop") }+        val result = LogcatReader.read(+            context,+            LogcatReader.Request(null, LogcatReader.DEFAULT_BUFFERS, LogLevel.Debug, ""),+        )+        assertTrue(result is LogLoadResult.Unavailable)+    }++    @Test+    fun `secondary user may not read the whole-device log but may read an app log`() {+        val userManager = context.getSystemService(android.os.UserManager::class.java)+        org.robolectric.Shadows.shadowOf(userManager).setIsSystemUser(false)++        val refused = LogcatReader.read(+            context,+            LogcatReader.Request(null, LogcatReader.DEFAULT_BUFFERS, LogLevel.Verbose, ""),+        )+        assertTrue(refused is LogLoadResult.Unavailable)+        assertEquals(+            R.string.error_system_log_secondary_user,+            (refused as LogLoadResult.Unavailable).messageRes,+        )++        LogcatReader.executeCommand = { listOf("own app line") }+        val own = loaded(+            LogcatReader.read(+                context,+                LogcatReader.Request(+                    context.packageName,+                    LogcatReader.DEFAULT_BUFFERS,+                    LogLevel.Verbose,+                    "",+                ),+            )+        )+        assertEquals(listOf("own app line"), own.bodyLines)+    }++    @Test+    fun `the real logcat exec failing is silently unavailable`() {+        // No fake installed: on the unit-test host there is no logcat binary, so the+        // production ProcessBuilder path fails and must degrade the same way.+        LogcatReader.executeCommand = originalExecutor+        val result = LogcatReader.read(+            context,+            LogcatReader.Request(null, LogcatReader.DEFAULT_BUFFERS, LogLevel.Verbose, ""),+        )+        assertTrue(result is LogLoadResult.Unavailable)+        assertNull((result as LogLoadResult.Unavailable).messageRes)+    }++    @Test+    fun `request is a data holder`() {+        val request = LogcatReader.Request("pkg", listOf("main"), LogLevel.Info, "x")+        assertEquals("pkg", request.targetPackage)+        assertEquals(listOf("main"), request.buffers)+        assertEquals(LogLevel.Info, request.level)+        assertEquals("x", request.filterRegex)+        assertEquals(request, request.copy())+    }++    @Test+    fun `secondary user message resource is the documented string`() {+        // The branch itself needs a secondary user; pin the resource it reports.+        assertEquals(+            "The device log is only available to the primary user",+            context.getString(R.string.error_system_log_secondary_user),+        )+    }+}
logviewer/src/test/java/com/vayunmathur/logviewer/platform/ReportHeadersTest.kt
diff --git a/logviewer/src/test/java/com/vayunmathur/logviewer/platform/ReportHeadersTest.kt b/logviewer/src/test/java/com/vayunmathur/logviewer/platform/ReportHeadersTest.ktnew file mode 100644index 0000000000..f32982139a--- /dev/null+++ b/logviewer/src/test/java/com/vayunmathur/logviewer/platform/ReportHeadersTest.kt@@ -0,0 +1,98 @@+package com.vayunmathur.logviewer.platform++import android.content.Context+import android.content.pm.ApplicationInfo+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import org.junit.Test+import org.junit.runner.RunWith+import java.io.File+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue++@RunWith(AndroidJUnit4::class)+class ReportHeadersTest {++    private val context: Context get() = ApplicationProvider.getApplicationContext()++    @Test+    fun `readFileAsString returns contents and null for missing or directory`() {+        val file = File.createTempFile("report-header", ".txt")+        try {+            file.writeText("hello\nworld", Charsets.UTF_8)+            assertEquals("hello\nworld", ReportHeaders.readFileAsString(file.absolutePath))+        } finally {+            file.delete()+        }+        assertNull(ReportHeaders.readFileAsString("/nonexistent/definitely/missing.txt"))+        assertNull(ReportHeaders.readFileAsString(System.getProperty("java.io.tmpdir")!!))+    }++    @Test+    fun `loadAppLabel falls back to package name for unknown package`() {+        assertEquals(+            "com.example.does.not.exist",+            ReportHeaders.loadAppLabel(context, "com.example.does.not.exist").toString(),+        )+    }++    @Test+    fun `loadAppLabel resolves an installed package label`() {+        val label = ReportHeaders.loadAppLabel(context, context.packageName).toString()+        assertTrue(label.isNotEmpty())+    }++    @Test+    fun `installingPackage is null for unknown package`() {+        assertNull(ReportHeaders.installingPackage(context, "com.example.does.not.exist"))+    }++    @Test+    fun `addDeviceLines adds nothing for the system user with dev options off`() {+        val dst = mutableListOf<String>()+        ReportHeaders.addDeviceLines(context, dst)+        // Robolectric's default user is the system user and DEVELOPMENT_SETTINGS_ENABLED is 0.+        assertTrue(dst.isEmpty(), "unexpected device lines: $dst")+    }++    @Test+    fun `addDeviceLines reports user type and dev options for a secondary user`() {+        val userManager = context.getSystemService(android.os.UserManager::class.java)+        org.robolectric.Shadows.shadowOf(userManager).setIsSystemUser(false)+        android.provider.Settings.Global.putInt(+            context.contentResolver,+            android.provider.Settings.Global.DEVELOPMENT_SETTINGS_ENABLED,+            1,+        )+        val dst = mutableListOf<String>()+        ReportHeaders.addDeviceLines(context, dst)+        assertTrue(dst.contains("userType: full.secondary"), "lines: $dst")+        assertTrue(dst.contains("flags: dev options enabled"), "lines: $dst")+    }++    @Test+    fun `addPackageLines prints package and target sdk, falling back to version zero`() {+        val appInfo = ApplicationInfo().apply {+            packageName = "com.example.does.not.exist"+            targetSdkVersion = 34+            sourceDir = "/data/app/com.example/base.apk"+        }+        val dst = mutableListOf<String>()+        ReportHeaders.addPackageLines(context, appInfo, dst)+        assertEquals(+            listOf("package: com.example.does.not.exist:0, targetSdk 34"),+            dst,+        )+    }++    @Test+    fun `addPackageLines for installed package omits sharedUid when none`() {+        val installed = context.packageManager.getApplicationInfo(context.packageName, 0)+        val dst = mutableListOf<String>()+        ReportHeaders.addPackageLines(context, installed, dst)+        assertTrue(dst.first().startsWith("package: ${context.packageName}:"))+        assertTrue(dst.first().contains("targetSdk ${installed.targetSdkVersion}"))+        assertTrue(dst.none { it.startsWith("sharedUid:") })+    }+}
logviewer/src/test/java/com/vayunmathur/logviewer/provider/BlobProviderTest.kt
diff --git a/logviewer/src/test/java/com/vayunmathur/logviewer/provider/BlobProviderTest.kt b/logviewer/src/test/java/com/vayunmathur/logviewer/provider/BlobProviderTest.ktnew file mode 100644index 0000000000..a99f85e14f--- /dev/null+++ b/logviewer/src/test/java/com/vayunmathur/logviewer/provider/BlobProviderTest.kt@@ -0,0 +1,155 @@+package com.vayunmathur.logviewer.provider++import android.content.Context+import android.content.ContentValues+import android.net.Uri+import android.os.ParcelFileDescriptor+import android.provider.OpenableColumns+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.logviewer.domain.LogDocument+import org.junit.Test+import org.junit.runner.RunWith+import java.io.ByteArrayOutputStream+import java.io.FileNotFoundException+import java.util.zip.GZIPOutputStream+import kotlin.test.assertEquals+import kotlin.test.assertFailsWith+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++@RunWith(AndroidJUnit4::class)+class BlobProviderTest {++    private val provider = BlobProvider()+    private val context: Context get() = ApplicationProvider.getApplicationContext()+    private val resolver get() = context.contentResolver++    private fun gzipped(text: String): ByteArray {+        val out = ByteArrayOutputStream()+        GZIPOutputStream(out).use { it.write(text.toByteArray(Charsets.UTF_8)) }+        return out.toByteArray()+    }++    @Test+    fun `onCreate succeeds and type is the log mime type`() {+        assertTrue(provider.onCreate())+        assertEquals(LogDocument.MIME_TYPE, provider.getType(Uri.parse("content://x/y")))+        assertEquals("application/octet-stream", provider.getType(Uri.parse("content://x/y")))+    }++    @Test+    fun `insert is unsupported while delete and update are no-ops`() {+        val uri = Uri.parse("content://x/y")+        assertFailsWith<UnsupportedOperationException> { provider.insert(uri, ContentValues()) }+        assertEquals(0, provider.delete(uri, null, null))+        assertEquals(0, provider.update(uri, ContentValues(), null, null))+    }++    @Test+    fun `getUri stores bytes and query reports display name and uncompressed size`() {+        val payload = "hello log world"+        val uri = BlobProvider.getUri("my log.txt") { out ->+            out.write(payload.toByteArray(Charsets.UTF_8))+        }+        assertEquals("content", uri.scheme)+        assertTrue(uri.authority!!.endsWith(".BlobProvider"))+        assertEquals("my log.txt", uri.lastPathSegment)++        val cursor = resolver.query(uri, null, null, null, null)+        assertNotNull(cursor)+        cursor.use {+            assertTrue(it.moveToFirst())+            val nameIndex = it.getColumnIndex(OpenableColumns.DISPLAY_NAME)+            val sizeIndex = it.getColumnIndex(OpenableColumns.SIZE)+            assertEquals("my log.txt", it.getString(nameIndex))+            assertEquals(payload.length.toLong(), it.getLong(sizeIndex))+        }+    }++    @Test+    fun `getUri counts single-byte writes toward the size`() {+        val uri = BlobProvider.getUri("bytes.txt") { out ->+            out.write('A'.code)+            out.write("BC".toByteArray(Charsets.UTF_8))+            out.write('D'.code)+        }+        val cursor = resolver.query(uri, arrayOf(OpenableColumns.SIZE), null, null, null)+        assertNotNull(cursor)+        cursor.use {+            assertTrue(it.moveToFirst())+            assertEquals(4L, it.getLong(0))+        }+        // The byte round-trip through the pipe is asserted by LogViewerViewModelTest's+        // shareUri test; the pipe writer thread is not reliably scheduled here.+    }++    @Test+    fun `query with an explicit projection fills only known columns`() {+        val uri = BlobProvider.getUri("proj.txt") { it.write("data".toByteArray()) }+        val cursor = resolver.query(+            uri,+            arrayOf(OpenableColumns.SIZE, "com.example.unknown"),+            null, null, null,+        )+        assertNotNull(cursor)+        cursor.use {+            assertTrue(it.moveToFirst())+            assertEquals(4L, it.getLong(0))+            assertNull(it.getString(1))+        }+    }++    @Test+    fun `query and openFile for an unknown uri find nothing`() {+        val unknown = Uri.parse("content://com.vayunmathur.logviewer.BlobProvider/nope.txt")+        assertNull(resolver.query(unknown, null, null, null, null))+        assertFailsWith<FileNotFoundException> { resolver.openInputStream(unknown) }+    }++    @Test+    fun `openFile streams the decompressed snapshot`() {+        val uri = BlobProvider.getUri("stream.txt") { out ->+            out.bufferedWriter(Charsets.UTF_8).use { it.write("streamed snapshot\nline two\n") }+        }+        // Handing out a pipe for a known uri succeeds; the byte round-trip itself is+        // asserted through the resolver in the single-byte-write test above (the pipe+        // writer thread is not reliably scheduled under Robolectric here).+        val attached = org.robolectric.Robolectric.buildContentProvider(BlobProvider::class.java)+            .create("${context.packageName}.BlobProvider").get()+        val pfd = attached.openFile(uri, "r")+        assertTrue(pfd.fileDescriptor.valid())+        pfd.close()+    }++    @Test+    fun `writeDataToPipe with no args or corrupt gzip writes nothing and survives`() {+        val pipe = ParcelFileDescriptor.createPipe()+        val read = pipe[0]+        val write = pipe[1]+        provider.writeDataToPipe(write, Uri.parse("content://x/y"), LogDocument.MIME_TYPE, null, null)+        // The write end is still open (nothing written, nothing closed by the provider);+        // close it ourselves and confirm the pipe is empty.+        write.close()+        val bytes = ParcelFileDescriptor.AutoCloseInputStream(read).use { it.readBytes() }+        assertEquals(0, bytes.size)++        val pipe2 = ParcelFileDescriptor.createPipe()+        provider.writeDataToPipe(+            pipe2[1], Uri.parse("content://x/y"), LogDocument.MIME_TYPE, null, byteArrayOf(9, 9, 9),+        )+        val bytes2 = ParcelFileDescriptor.AutoCloseInputStream(pipe2[0]).use { it.readBytes() }+        assertEquals(0, bytes2.size)+    }++    @Test+    fun `writeDataToPipe gunzips its args onto the pipe`() {+        val pipe = ParcelFileDescriptor.createPipe()+        provider.writeDataToPipe(+            pipe[1], Uri.parse("content://x/y"), LogDocument.MIME_TYPE, null, gzipped("piped text"),+        )+        val bytes = ParcelFileDescriptor.AutoCloseInputStream(pipe[0]).use { it.readBytes() }+        assertEquals("piped text", bytes.toString(Charsets.UTF_8))+    }+}
logviewer/src/test/java/com/vayunmathur/logviewer/ui/FakeLogViewerActions.kt
diff --git a/logviewer/src/test/java/com/vayunmathur/logviewer/ui/FakeLogViewerActions.kt b/logviewer/src/test/java/com/vayunmathur/logviewer/ui/FakeLogViewerActions.ktnew file mode 100644index 0000000000..438b02d019--- /dev/null+++ b/logviewer/src/test/java/com/vayunmathur/logviewer/ui/FakeLogViewerActions.kt@@ -0,0 +1,33 @@+package com.vayunmathur.logviewer.ui++import android.net.Uri+import com.vayunmathur.logviewer.domain.LogLevel+import com.vayunmathur.logviewer.platform.ExtraAction+import com.vayunmathur.logviewer.platform.LogViewerActions++/** Recording [LogViewerActions] for Compose tests. */+internal class FakeLogViewerActions : LogViewerActions {+    var copies = 0+    var shares = 0+    var reports = 0+    val saves = mutableListOf<Uri>()+    val zooms = mutableListOf<Float>()+    val buffersSet = mutableListOf<List<String>>()+    val levelsSet = mutableListOf<LogLevel>()+    val filtersSet = mutableListOf<String>()+    val performed = mutableListOf<ExtraAction>()+    var stackTraceDismissals = 0+    var stackTraceCopies = 0++    override fun copy() { copies++ }+    override fun share() { shares++ }+    override fun report() { reports++ }+    override fun save(uri: Uri) { saves += uri }+    override fun zoom(factor: Float) { zooms += factor }+    override fun setBuffers(buffers: List<String>) { buffersSet += buffers }+    override fun setLevel(level: LogLevel) { levelsSet += level }+    override fun setFilter(regex: String) { filtersSet += regex }+    override fun perform(action: ExtraAction) { performed += action }+    override fun dismissStackTrace() { stackTraceDismissals++ }+    override fun copyStackTrace() { stackTraceCopies++ }+}
logviewer/src/test/java/com/vayunmathur/logviewer/ui/LogViewerPageTest.kt
diff --git a/logviewer/src/test/java/com/vayunmathur/logviewer/ui/LogViewerPageTest.kt b/logviewer/src/test/java/com/vayunmathur/logviewer/ui/LogViewerPageTest.ktnew file mode 100644index 0000000000..32d6a97b8c--- /dev/null+++ b/logviewer/src/test/java/com/vayunmathur/logviewer/ui/LogViewerPageTest.kt@@ -0,0 +1,88 @@+package com.vayunmathur.logviewer.ui++import android.app.Application+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.library.ui.DynamicTheme+import com.vayunmathur.logviewer.domain.LogDocument+import com.vayunmathur.logviewer.domain.LogKind+import com.vayunmathur.logviewer.platform.LogLoadResult+import com.vayunmathur.logviewer.platform.LogViewerViewModel+import org.junit.Rule+import org.junit.Test+import org.junit.runner.RunWith+import java.util.concurrent.atomic.AtomicInteger+import kotlin.test.assertEquals++@RunWith(AndroidJUnit4::class)+class LogViewerPageTest {++    @get:Rule+    val composeRule = createComposeRule()++    private val app: Application get() = ApplicationProvider.getApplicationContext()+    private val actions = FakeLogViewerActions()++    private fun page(vm: LogViewerViewModel, finishes: AtomicInteger) {+        composeRule.setContent {+            DynamicTheme {+                LogViewerPage(+                    viewModel = vm,+                    actions = actions,+                    onFinish = { finishes.incrementAndGet() },+                )+            }+        }+    }++    @Test+    fun `silently unavailable page finishes itself`() {+        val finishes = AtomicInteger(0)+        val vm = LogViewerViewModel(app)+        vm.start(loader = { LogLoadResult.Unavailable() }, chrome = { LogViewerViewModel.Chrome() })+        page(vm, finishes)+        composeRule.waitUntil(timeoutMillis = 10_000) { finishes.get() > 0 }+        assertEquals(1, finishes.get())+    }++    @Test+    fun `unavailable with a message stays open and explains`() {+        val finishes = AtomicInteger(0)+        val vm = LogViewerViewModel(app)+        vm.start(+            loader = { LogLoadResult.Unavailable(com.vayunmathur.logviewer.R.string.error_system_log_secondary_user) },+            chrome = { LogViewerViewModel.Chrome() },+        )+        page(vm, finishes)+        composeRule.onNodeWithText("The device log is only available to the primary user")+            .assertIsDisplayed()+        assertEquals(0, finishes.get())+    }++    @Test+    fun `loaded page shows the document and stays open`() {+        val finishes = AtomicInteger(0)+        val vm = LogViewerViewModel(app)+        vm.start(+            loader = {+                LogLoadResult.Loaded(+                    LogDocument(+                        kind = LogKind.ErrorReport,+                        sourcePackage = null,+                        title = "Report title",+                        headerLines = emptyList(),+                        bodyLines = listOf("the report body"),+                    )+                )+            },+            chrome = { LogViewerViewModel.Chrome() },+        )+        page(vm, finishes)+        composeRule.onNodeWithText("Report title").assertIsDisplayed()+        composeRule.onNodeWithText("the report body").assertIsDisplayed()+        assertEquals(0, finishes.get())+    }+}
logviewer/src/test/java/com/vayunmathur/logviewer/ui/LogViewerScreenExpandedTest.kt
diff --git a/logviewer/src/test/java/com/vayunmathur/logviewer/ui/LogViewerScreenExpandedTest.kt b/logviewer/src/test/java/com/vayunmathur/logviewer/ui/LogViewerScreenExpandedTest.ktnew file mode 100644index 0000000000..4e086a844b--- /dev/null+++ b/logviewer/src/test/java/com/vayunmathur/logviewer/ui/LogViewerScreenExpandedTest.kt@@ -0,0 +1,75 @@+package com.vayunmathur.logviewer.ui++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 androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.library.ui.DynamicTheme+import com.vayunmathur.logviewer.domain.LogKind+import com.vayunmathur.logviewer.platform.LogViewerUiState+import org.junit.Rule+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.annotation.Config+import kotlin.test.assertEquals++/** Expanded-width layout: the stack trace is a side panel, not a dialog. */+@RunWith(AndroidJUnit4::class)+@Config(qualifiers = "w1280dp-h800dp")+class LogViewerScreenExpandedTest {++    @get:Rule+    val composeRule = createComposeRule()++    private val actions = FakeLogViewerActions()++    @Test+    fun `stack trace renders beside the log on expanded widths`() {+        composeRule.setContent {+            DynamicTheme {+                LogViewerScreen(+                    state = LogViewerUiState(+                        loading = false,+                        title = "Weather crashed",+                        lines = listOf("log line one", "log line two"),+                        kind = LogKind.ErrorReport,+                        fontSizeSp = 12f,+                        snapshotFileName = "crash.txt",+                        stackTrace = "java.lang.Exception: side panel trace",+                    ),+                    actions = actions,+                )+            }+        }+        composeRule.onNodeWithText("log line one").assertIsDisplayed()+        composeRule.onNodeWithText("Unable to save file").assertIsDisplayed()+        composeRule.onNodeWithText("java.lang.Exception: side panel trace").assertIsDisplayed()++        // The panel's Copy button copies then dismisses; Cancel only dismisses.+        composeRule.onNodeWithText("Copy").performClick()+        assertEquals(1, actions.stackTraceCopies)+        assertEquals(1, actions.stackTraceDismissals)+    }++    @Test+    fun `expanded layout without a trace shows just the log`() {+        composeRule.setContent {+            DynamicTheme {+                LogViewerScreen(+                    state = LogViewerUiState(+                        loading = false,+                        title = "Expanded log",+                        lines = listOf("only line"),+                        kind = LogKind.Logcat,+                        fontSizeSp = 9f,+                        snapshotFileName = "log.txt",+                    ),+                    actions = actions,+                )+            }+        }+        composeRule.onNodeWithText("only line").assertIsDisplayed()+        composeRule.onNodeWithText("Unable to save file").assertDoesNotExist()+    }+}
logviewer/src/test/java/com/vayunmathur/logviewer/ui/LogViewerScreenTest.kt
diff --git a/logviewer/src/test/java/com/vayunmathur/logviewer/ui/LogViewerScreenTest.kt b/logviewer/src/test/java/com/vayunmathur/logviewer/ui/LogViewerScreenTest.ktnew file mode 100644index 0000000000..fccf49d22f--- /dev/null+++ b/logviewer/src/test/java/com/vayunmathur/logviewer/ui/LogViewerScreenTest.kt@@ -0,0 +1,200 @@+package com.vayunmathur.logviewer.ui++import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithContentDescription+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.library.ui.DynamicTheme+import com.vayunmathur.logviewer.R+import com.vayunmathur.logviewer.domain.LogKind+import com.vayunmathur.logviewer.domain.LogLevel+import com.vayunmathur.logviewer.platform.ExtraAction+import com.vayunmathur.logviewer.platform.LogViewerUiState+import com.vayunmathur.logviewer.platform.LogcatFilters+import org.junit.Rule+import org.junit.Test+import org.junit.runner.RunWith+import kotlin.test.assertEquals+import kotlin.test.assertTrue++@RunWith(AndroidJUnit4::class)+class LogViewerScreenTest {++    @get:Rule+    val composeRule = createComposeRule()++    private val actions = FakeLogViewerActions()++    private fun setScreen(state: LogViewerUiState) {+        composeRule.setContent {+            DynamicTheme {+                LogViewerScreen(state = state, actions = actions)+            }+        }+    }++    private fun loadedState(+        kind: LogKind = LogKind.ErrorReport,+        lines: List<String> = listOf("first line", "second line"),+    ) = LogViewerUiState(+        loading = false,+        title = "A title",+        sourcePackage = "com.example.app",+        lines = lines,+        kind = kind,+        fontSizeSp = kind.initialFontSizeSp,+        snapshotFileName = "snapshot.txt",+    )++    @Test+    fun `loading state shows the title and no log lines`() {+        setScreen(LogViewerUiState(loading = true, title = "Loading title"))+        composeRule.onNodeWithText("Loading title").assertIsDisplayed()+        composeRule.onNodeWithText("first line").assertDoesNotExist()+    }++    @Test+    fun `unavailable with a message explains why`() {+        setScreen(+            LogViewerUiState(+                loading = false,+                unavailable = true,+                unavailableMessageRes = R.string.error_system_log_secondary_user,+                title = "System log",+            )+        )+        composeRule.onNodeWithText("The device log is only available to the primary user")+            .assertIsDisplayed()+    }++    @Test+    fun `unavailable without a message renders no explanation`() {+        setScreen(+            LogViewerUiState(+                loading = false,+                unavailable = true,+                unavailableMessageRes = null,+                title = "System log",+            )+        )+        composeRule.onNodeWithText("The device log is only available to the primary user")+            .assertDoesNotExist()+        composeRule.onNodeWithText("first line").assertDoesNotExist()+    }++    @Test+    fun `loaded report shows lines and bottom actions dispatch`() {+        setScreen(+            loadedState().copy(+                showReportButton = true,+                extraActions = listOf(ExtraAction.MoreInfo, ExtraAction.ShowAppLog),+            )+        )+        composeRule.onNodeWithText("first line").assertIsDisplayed()+        composeRule.onNodeWithText("second line").assertIsDisplayed()++        composeRule.onNodeWithText("Report").performClick()+        composeRule.onNodeWithText("More info").performClick()+        composeRule.onNodeWithText("Show log").performClick()+        assertEquals(1, actions.reports)+        assertEquals(listOf(ExtraAction.MoreInfo, ExtraAction.ShowAppLog), actions.performed)+    }++    @Test+    fun `share menu opens and copy and share dispatch`() {+        setScreen(loadedState())+        composeRule.onNodeWithContentDescription("Share").performClick()+        composeRule.onNodeWithText("Copy").assertIsDisplayed()+        composeRule.onNodeWithText("Share").assertIsDisplayed()+        composeRule.onNodeWithText("Save").assertIsDisplayed()++        composeRule.onNodeWithText("Copy").performClick()+        assertEquals(1, actions.copies)++        composeRule.onNodeWithContentDescription("Share").performClick()+        composeRule.onNodeWithText("Share").performClick()+        assertEquals(1, actions.shares)+    }++    @Test+    fun `refreshing keeps the previous lines on screen`() {+        setScreen(loadedState().copy(refreshing = true))+        composeRule.onNodeWithText("first line").assertIsDisplayed()+        composeRule.onNodeWithText("second line").assertIsDisplayed()+    }++    @Test+    fun `logcat lines are displayed trimmed`() {+        setScreen(+            loadedState(+                kind = LogKind.Logcat,+                lines = listOf("  padded\tlog line  ", "plain"),+            )+        )+        composeRule.onNodeWithText("padded log line").assertIsDisplayed()+        composeRule.onNodeWithText("plain").assertIsDisplayed()+    }++    @Test+    fun `logcat controls pick a level and open the filter dialog`() {+        setScreen(+            loadedState(kind = LogKind.Logcat).copy(+                logcat = LogcatFilters(listOf("main"), LogLevel.Error, "initial.*"),+            )+        )+        // Level dropdown: the trigger shows the current letter.+        composeRule.onNodeWithText("E").performClick()+        composeRule.onNodeWithText("Debug").performClick()+        assertEquals(listOf(LogLevel.Debug), actions.levelsSet)++        // Buffers dropdown lists every buffer.+        composeRule.onNodeWithText("M").performClick()+        composeRule.onNodeWithText("radio").assertIsDisplayed()+        composeRule.onNodeWithText("kernel").assertIsDisplayed()+        // Dismiss the menu by choosing nothing and pressing back via the trigger again+        // is not how menus close; use a click on the title area instead.+        composeRule.onNodeWithText("A title").performClick()++        // Filter dialog opens from the search action and applies the edited text.+        composeRule.onNodeWithContentDescription("Search").performClick()+        composeRule.onNodeWithText("Set filter").assertIsDisplayed()+        composeRule.onNodeWithText("initial.*").assertIsDisplayed()+        composeRule.onNodeWithText("Apply").performClick()+        assertEquals(listOf("initial.*"), actions.filtersSet)+    }++    @Test+    fun `filter dialog can be cancelled without applying`() {+        setScreen(+            loadedState(kind = LogKind.Logcat).copy(+                logcat = LogcatFilters(listOf("main"), LogLevel.Verbose, ""),+            )+        )+        composeRule.onNodeWithContentDescription("Search").performClick()+        composeRule.onNodeWithText("Set filter").assertIsDisplayed()+        composeRule.onNodeWithText("Cancel").performClick()+        composeRule.onNodeWithText("Set filter").assertDoesNotExist()+        assertTrue(actions.filtersSet.isEmpty())+    }++    @Test+    fun `stack trace dialog copies and dismisses, or just dismisses`() {+        setScreen(loadedState().copy(stackTrace = "java.lang.Exception: boom\n\tat X.y(X.kt:1)"))+        composeRule.onNodeWithText("Unable to save file").assertIsDisplayed()+        composeRule.onNodeWithText("java.lang.Exception: boom\n\tat X.y(X.kt:1)", substring = true)+            .assertIsDisplayed()+        composeRule.onNodeWithText("Copy").performClick()+        assertEquals(1, actions.stackTraceCopies)+        assertEquals(1, actions.stackTraceDismissals)+    }++    @Test+    fun `no bottom bar without report button or extra actions`() {+        setScreen(loadedState())+        composeRule.onNodeWithText("Report").assertDoesNotExist()+        composeRule.onNodeWithText("More info").assertDoesNotExist()+        composeRule.onNodeWithText("Show log").assertDoesNotExist()+    }+}
logviewer/src/test/java/com/vayunmathur/logviewer/ui/components/LogLineListTest.kt
diff --git a/logviewer/src/test/java/com/vayunmathur/logviewer/ui/components/LogLineListTest.kt b/logviewer/src/test/java/com/vayunmathur/logviewer/ui/components/LogLineListTest.ktnew file mode 100644index 0000000000..36c747f2aa--- /dev/null+++ b/logviewer/src/test/java/com/vayunmathur/logviewer/ui/components/LogLineListTest.kt@@ -0,0 +1,78 @@+package com.vayunmathur.logviewer.ui.components++import androidx.compose.foundation.layout.PaddingValues+import androidx.compose.foundation.lazy.rememberLazyListState+import androidx.compose.runtime.Composable+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.unit.dp+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.library.ui.DynamicTheme+import com.vayunmathur.logviewer.domain.LogKind+import org.junit.Rule+import org.junit.Test+import org.junit.runner.RunWith+import kotlin.test.assertEquals++@RunWith(AndroidJUnit4::class)+class LogLineListTest {++    @get:Rule+    val composeRule = createComposeRule()++    @Composable+    private fun ListUnderTest(lines: List<String>, kind: LogKind, zooms: MutableList<Float>) {+        LogLineList(+            lines = lines,+            kind = kind,+            fontSizeSp = 12f,+            listState = rememberLazyListState(),+            contentPadding = PaddingValues(0.dp),+            onZoom = { zooms += it },+        )+    }++    @Test+    fun `renders every line for an error report verbatim`() {+        val zooms = mutableListOf<Float>()+        composeRule.setContent {+            DynamicTheme {+                ListUnderTest(listOf("alpha", "  indented kept  ", "omega"), LogKind.ErrorReport, zooms)+            }+        }+        composeRule.onNodeWithText("alpha").assertIsDisplayed()+        composeRule.onNodeWithText("omega").assertIsDisplayed()+    }++    @Test+    fun `renders logcat lines trimmed with tabs expanded`() {+        val zooms = mutableListOf<Float>()+        composeRule.setContent {+            DynamicTheme {+                ListUnderTest(listOf("\t07-15 I Tag: hello\tworld  "), LogKind.Logcat, zooms)+            }+        }+        composeRule.onNodeWithText("07-15 I Tag: hello world").assertIsDisplayed()+        assertEquals(emptyList(), zooms)+    }++    @Test+    fun `empty list renders no rows`() {+        val zooms = mutableListOf<Float>()+        composeRule.setContent {+            DynamicTheme { ListUnderTest(emptyList(), LogKind.Logcat, zooms) }+        }+        composeRule.onNodeWithText("alpha").assertDoesNotExist()+    }++    @Test+    fun `many lines render lazily with the first visible`() {+        val zooms = mutableListOf<Float>()+        val lines = (1..500).map { "line number $it" }+        composeRule.setContent {+            DynamicTheme { ListUnderTest(lines, LogKind.ErrorReport, zooms) }+        }+        composeRule.onNodeWithText("line number 1").assertIsDisplayed()+    }+}
logviewer/src/test/java/com/vayunmathur/logviewer/ui/dialogs/LogViewerDialogsTest.kt
diff --git a/logviewer/src/test/java/com/vayunmathur/logviewer/ui/dialogs/LogViewerDialogsTest.kt b/logviewer/src/test/java/com/vayunmathur/logviewer/ui/dialogs/LogViewerDialogsTest.ktnew file mode 100644index 0000000000..ef56b8ffb4--- /dev/null+++ b/logviewer/src/test/java/com/vayunmathur/logviewer/ui/dialogs/LogViewerDialogsTest.kt@@ -0,0 +1,164 @@+package com.vayunmathur.logviewer.ui.dialogs++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 androidx.compose.ui.test.performTextReplacement+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.library.ui.DynamicTheme+import org.junit.Rule+import org.junit.Test+import org.junit.runner.RunWith+import kotlin.test.assertEquals+import kotlin.test.assertNull++@RunWith(AndroidJUnit4::class)+class LogViewerDialogsTest {++    @get:Rule+    val composeRule = createComposeRule()++    // ------------------------------------------------------------ TextInputDialog++    @Test+    fun `text input confirms the edited text`() {+        var confirmed: String? = null+        var dismissed = 0+        composeRule.setContent {+            DynamicTheme {+                TextInputDialog(+                    title = "Set filter",+                    initialText = "old.*",+                    onConfirm = { confirmed = it },+                    onDismiss = { dismissed++ },+                    singleLine = true,+                    hint = "Regex",+                )+            }+        }+        composeRule.onNodeWithText("Set filter").assertIsDisplayed()+        composeRule.onNodeWithText("old.*").performTextReplacement("new.*[0-9]+")+        composeRule.onNodeWithText("Apply").performClick()+        assertEquals("new.*[0-9]+", confirmed)+        assertEquals(0, dismissed)+    }++    @Test+    fun `text input cancel dismisses without confirming`() {+        var confirmed: String? = null+        var dismissed = 0+        composeRule.setContent {+            DynamicTheme {+                TextInputDialog(+                    title = "Set filter",+                    initialText = "keep me",+                    onConfirm = { confirmed = it },+                    onDismiss = { dismissed++ },+                )+            }+        }+        composeRule.onNodeWithText("Cancel").performClick()+        assertNull(confirmed)+        assertEquals(1, dismissed)+    }++    @Test+    fun `text input shows its hint when empty`() {+        composeRule.setContent {+            DynamicTheme {+                TextInputDialog(+                    title = "Set filter",+                    initialText = "",+                    onConfirm = {},+                    onDismiss = {},+                    hint = "Regex hint text",+                )+            }+        }+        composeRule.onNodeWithText("Regex hint text").assertIsDisplayed()+    }++    @Test+    fun `text input rejects input beyond the length cap`() {+        var confirmed: String? = null+        composeRule.setContent {+            DynamicTheme {+                TextInputDialog(+                    title = "Set filter",+                    initialText = "short",+                    onConfirm = { confirmed = it },+                    onDismiss = {},+                )+            }+        }+        composeRule.onNodeWithText("short").performTextReplacement("x".repeat(10_001))+        composeRule.onNodeWithText("Apply").performClick()+        // The over-cap replacement never landed, so the initial text is what confirms.+        assertEquals("short", confirmed)+    }++    @Test+    fun `text input accepts exactly the length cap`() {+        var confirmed: String? = null+        val atCap = "y".repeat(10_000)+        composeRule.setContent {+            DynamicTheme {+                TextInputDialog(+                    title = "Set filter",+                    initialText = "",+                    onConfirm = { confirmed = it },+                    onDismiss = {},+                )+            }+        }+        // The field is empty, so target it through its hint-less editable node by text entry+        // on the dialog's text field: use the Apply flow after typing via the root field.+        composeRule.onNodeWithText("Set filter").assertIsDisplayed()+        composeRule.onNode(+            androidx.compose.ui.test.hasSetTextAction(),+        ).performTextReplacement(atCap)+        composeRule.onNodeWithText("Apply").performClick()+        assertEquals(atCap, confirmed)+    }++    // ------------------------------------------------------------ StackTraceDialog++    @Test+    fun `stack trace dialog shows the trace and copy confirms both callbacks`() {+        var copies = 0+        var dismissals = 0+        composeRule.setContent {+            DynamicTheme {+                StackTraceDialog(+                    stackTrace = "java.io.IOException: disk full\n\tat Save.write(Save.kt:3)",+                    onCopy = { copies++ },+                    onDismiss = { dismissals++ },+                )+            }+        }+        composeRule.onNodeWithText("Unable to save file").assertIsDisplayed()+        composeRule.onNodeWithText("java.io.IOException: disk full", substring = true).assertIsDisplayed()+        composeRule.onNodeWithText("Copy").performClick()+        assertEquals(1, copies)+        assertEquals(1, dismissals)+    }++    @Test+    fun `stack trace dialog cancel only dismisses`() {+        var copies = 0+        var dismissals = 0+        composeRule.setContent {+            DynamicTheme {+                StackTraceDialog(+                    stackTrace = "trace body",+                    onCopy = { copies++ },+                    onDismiss = { dismissals++ },+                )+            }+        }+        composeRule.onNodeWithText("Cancel").performClick()+        assertEquals(0, copies)+        assertEquals(1, dismissals)+    }+}