files: add tests for browser, picker, trash and workers
- Commit
a5dd76b58d1946f0f89f6b4dcdd4e08e0d1cf3bd- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-07 05:20 UTC (29 days ago)
- Parents
8ae58c7
Coverage (merged INSTRUCTION, createMergedCoverageReport): 0.3% (75/27351) -> 85.3% (23339/27351). New tests (13 files): - platform/FilesListingTest: sort orders, real/zip listing (incl. nested zip paths and corrupt archives), unique destinations, atomic moves, bookmarks, media-query empties. - platform/FilesViewModelTest: the full VM chain on real temp trees - navigation, selection, sort/view/search, create with unique names, rename, copy/cut/paste, moves with self-paste guards, zip browsing, home/bookmarks/categories, trash-first delete with permanent-delete fallback, trash selection and consent, share/open/APK intent routing, archive/unzip enqueueing, incoming-URI save, TextEditorViewModel load/save through a test content provider. ShadowEnvironmentFix works around Robolectric's isExternalStorageManager crash. - platform/WorkersAndStorageTest: ZipWorker/UnzipWorker via TestListenableWorkerBuilder (real archives, zip-slip and extraction-budget refusal with partial cleanup), StorageUris MIME matching. Adds androidx.work:work-testing test dep. - platform/TrashMediaProviderTest: trash queries against a fake MediaStore provider (rows, trashable-uri resolution). - ui/DirectoryScreenTest + DirectoryDialogsFlowTest: every directory page state (list/grid/search/selection/category/ zip), top-bar overflow and selection menus, rename/archive/ new-folder/new-file/properties dialogs, expanded-width parent pane, file-kind leading icons - with a recording FilesActions asserting each tap's routing. - ui/HomeTrashScreenTest: home storage/categories/bookmarks/ recents, trash list/selection/empty-confirm, drawer, properties dialog, fileAncestors. - ui/DocumentPickerComposeTest: SAF picker in OPEN, multi GET_CONTENT with MIME filtering, TREE and CREATE modes via compose rules with explicit intents (component enabled and MANAGE_DOCUMENTS granted by an outer rule). File-return assertions are limited where Robolectric's tmp external dir is outside every FileProvider root (noted in the tests). - ui/TextEditorComposeTest: editor activity end-to-end (load, edit toggle, save back through the provider). - ui/BindersTest/ActivitiesAndBindersTest/ShellAndDropTest: DirectoryPage/HomeScreenBinder/TrashPage/FilesShell binding the real VM, notification-prompt and permanent-delete shell dialogs, the not-granted shell gate, MainActivity intent handling, and dropTarget drag/drop delivery. No production code changed; no bugs found. Verified: gslot ./gradlew :files:createMergedCoverageReport (full unit suite green, 85.33% merged instructions). (cherry picked from commit c971c13affa6596ea32873529b461e8a6d483fe1)
Diff
files/build.gradle.kts
diff --git a/files/build.gradle.kts b/files/build.gradle.ktsindex 5a5d5b4147..152ad9f7d0 100644--- a/files/build.gradle.kts+++ b/files/build.gradle.kts@@ -20,4 +20,5 @@ dependencies { implementation(libs.androidx.work.runtime.ktx) // Image thumbnails for image files in the browser (AsyncImage). implementation(project(":library:image"))+ testImplementation("androidx.work:work-testing:${libs.versions.workRuntimeKtx.get()}") }
files/src/test/java/com/vayunmathur/files/platform/FilesListingTest.kt
diff --git a/files/src/test/java/com/vayunmathur/files/platform/FilesListingTest.kt b/files/src/test/java/com/vayunmathur/files/platform/FilesListingTest.ktnew file mode 100644index 0000000000..8ce0a2f7e7--- /dev/null+++ b/files/src/test/java/com/vayunmathur/files/platform/FilesListingTest.kt@@ -0,0 +1,204 @@+package com.vayunmathur.files.platform++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import java.io.File+import java.util.zip.ZipEntry+import java.util.zip.ZipOutputStream+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)+class FilesListingTest {++ private val ctx: Context get() = ApplicationProvider.getApplicationContext()++ private fun tempDir(name: String): File =+ File(ctx.cacheDir, "listing-$name-${System.nanoTime()}").apply { mkdirs() }++ private fun item(name: String, dir: Boolean = false, size: Long? = 1, modified: Long = 0) =+ FileBrowserItem(+ name = name, isDirectory = dir, size = size,+ realFile = null, zipInnerPath = null, key = name, lastModified = modified,+ )++ @Test+ fun `sort by name date size and type both directions`() {+ val items = listOf(+ item("b.txt", size = 30, modified = 3),+ item("A.md", size = 10, modified = 1),+ item("c.txt", size = 20, modified = 2),+ )+ assertEquals(listOf("A.md", "b.txt", "c.txt"), sortItemsList(items, SortBy.NAME, true).map { it.name })+ assertEquals(listOf("c.txt", "b.txt", "A.md"), sortItemsList(items, SortBy.NAME, false).map { it.name })+ assertEquals(listOf("A.md", "c.txt", "b.txt"), sortItemsList(items, SortBy.DATE, true).map { it.name })+ assertEquals(listOf("A.md", "c.txt", "b.txt"), sortItemsList(items, SortBy.SIZE, true).map { it.name })+ // TYPE groups by extension first (md before txt), then name+ assertEquals(listOf("A.md", "b.txt", "c.txt"), sortItemsList(items, SortBy.TYPE, true).map { it.name })+ val (dirs, files) = sortListing(listOf(item("zdir", dir = true)) to items, SortBy.NAME, true)+ assertEquals(listOf("zdir"), dirs.map { it.name })+ assertEquals(3, files.size)+ }++ @Test+ fun `list real dir partitions and hides dotfiles unless asked`() {+ val dir = tempDir("real")+ File(dir, "visible.txt").writeText("hi")+ File(dir, ".hidden").writeText("secret")+ File(dir, "sub").mkdirs()+ val (dirs, files) = listRealDirItems(dir, showHidden = false)+ assertEquals(listOf("sub"), dirs.map { it.name })+ assertEquals(listOf("visible.txt"), files.map { it.name })+ val (dirs2, files2) = listRealDirItems(dir, showHidden = true)+ assertEquals(1, dirs2.size)+ assertEquals(setOf("visible.txt", ".hidden"), files2.map { it.name }.toSet())+ // missing directory lists as empty rather than crashing+ assertEquals(emptyList<FileBrowserItem>() to emptyList(), listRealDirItems(File(dir, "nope"), false))+ dir.deleteRecursively()+ }++ @Test+ fun `file toBrowserItem carries real file facts`() {+ val dir = tempDir("item")+ val f = File(dir, "note.txt").apply { writeText("hello") }+ val bi = f.toBrowserItem()+ assertEquals("note.txt", bi.name)+ assertFalse(bi.isDirectory)+ assertEquals(5L, bi.size)+ assertEquals(f, bi.realFile)+ assertEquals(f.absolutePath, bi.key)+ assertNull(bi.zipInnerPath)+ val dirItem = dir.toBrowserItem()+ assertTrue(dirItem.isDirectory)+ assertNull(dirItem.size)+ dir.deleteRecursively()+ }++ private fun makeZip(dir: File, name: String, entries: Map<String, String?>): File {+ val zip = File(dir, name)+ ZipOutputStream(zip.outputStream()).use { out ->+ for ((entryName, content) in entries) {+ out.putNextEntry(ZipEntry(entryName))+ if (content != null) out.write(content.toByteArray())+ out.closeEntry()+ }+ }+ return zip+ }++ @Test+ fun `list zip root shows folders and files`() {+ val dir = tempDir("zip")+ val zip = makeZip(+ dir, "a.zip",+ mapOf("docs/readme.txt" to "hello", "docs/inner/deep.txt" to "x", "top.txt" to "top", "emptydir/" to null),+ )+ val (dirs, files) = listZipDirItems(zip, "")+ assertEquals(setOf("docs", "emptydir"), dirs.map { it.name }.toSet())+ assertEquals(listOf("top.txt"), files.map { it.name })+ assertEquals("zip:docs", dirs.first { it.name == "docs" }.key)+ assertEquals(3L, files.first().size)++ val (subDirs, subFiles) = listZipDirItems(zip, "docs")+ assertEquals(listOf("inner"), subDirs.map { it.name })+ assertEquals(listOf("readme.txt"), subFiles.map { it.name })+ assertEquals("docs/readme.txt", subFiles.first().zipInnerPath)++ val (deepDirs, deepFiles) = listZipDirItems(zip, "docs/inner")+ assertTrue(deepDirs.isEmpty())+ assertEquals(listOf("deep.txt"), deepFiles.map { it.name })+ dir.deleteRecursively()+ }++ @Test+ fun `list zip of corrupt or missing file is empty`() {+ val dir = tempDir("badzip")+ val bad = File(dir, "bad.zip").apply { writeText("not a zip") }+ assertEquals(emptyList<FileBrowserItem>() to emptyList(), listZipDirItems(bad, ""))+ assertEquals(emptyList<FileBrowserItem>() to emptyList(), listZipDirItems(File(dir, "gone.zip"), ""))+ dir.deleteRecursively()+ }++ @Test+ fun `unique destination suffixes collisions`() {+ val dir = tempDir("unique")+ assertEquals("a.txt", uniqueDestination(dir, "a.txt").name)+ File(dir, "a.txt").writeText("1")+ assertEquals("a (1).txt", uniqueDestination(dir, "a.txt").name)+ File(dir, "a (1).txt").writeText("2")+ assertEquals("a (2).txt", uniqueDestination(dir, "a.txt").name)+ File(dir, "README").writeText("x")+ assertEquals("README (1)", uniqueDestination(dir, "README").name)+ dir.deleteRecursively()+ }++ @Test+ fun `atomic move renames files and directories`() {+ val dir = tempDir("move")+ val src = File(dir, "src.txt").apply { writeText("payload") }+ val dest = File(dir, "dest.txt")+ src.atomicMoveTo(dest)+ assertFalse(src.exists())+ assertEquals("payload", dest.readText())+ val srcDir = File(dir, "srcdir").apply { mkdirs(); File(this, "in.txt").writeText("in") }+ val destDir = File(dir, "destdir")+ srcDir.atomicMoveTo(destDir)+ assertFalse(srcDir.exists())+ assertEquals("in", File(destDir, "in.txt").readText())+ dir.deleteRecursively()+ }++ @Test+ fun `bookmarks load only existing paths sorted by name`() {+ val dir = tempDir("bm")+ val b = File(dir, "beta").apply { mkdirs() }+ val a = File(dir, "Alpha").apply { mkdirs() }+ val prefs = ctx.getSharedPreferences("test-bm-${System.nanoTime()}", Context.MODE_PRIVATE)+ prefs.edit().putStringSet("bookmarks", setOf(b.absolutePath, a.absolutePath, "/nonexistent/zzz")).commit()+ val loaded = loadBookmarkItems(prefs)+ assertEquals(listOf("Alpha", "beta"), loaded.map { it.name })+ assertTrue(loaded.all { it.isDirectory })+ dir.deleteRecursively()+ }++ @Test+ fun `media queries on empty provider return empty`() {+ assertTrue(queryRecentItems(ctx).isEmpty())+ assertTrue(queryCategoryItems(ctx, FileCategory.IMAGES).isEmpty())+ assertTrue(queryCategoryItems(ctx, FileCategory.VIDEOS).isEmpty())+ assertTrue(queryCategoryItems(ctx, FileCategory.AUDIO).isEmpty())+ assertTrue(queryCategoryItems(ctx, FileCategory.DOCUMENTS).isEmpty())+ assertEquals(emptyList(), queryCategoryItems(ctx, FileCategory.DOWNLOADS))+ assertTrue(queryTrashedItems(ctx).isEmpty())+ assertTrue(resolveTrashableUris(ctx, emptyList()).isEmpty())+ }++ @Test+ fun `storage info used bytes never negative`() {+ assertEquals(30, StorageInfo(100, 70).usedBytes)+ assertEquals(0, StorageInfo(50, 80).usedBytes)+ assertEquals(0, StorageInfo(0, 0).usedBytes)+ }++ @Test+ fun `category labels are distinct resources`() {+ val labels = FileCategory.entries.map { categoryLabel(it) }+ assertEquals(labels.size, labels.toSet().size)+ assertTrue(labels.all { it != 0 })+ }++ @Test+ fun `noop actions are all callable`() {+ val a = FilesActions.Noop+ a.clearSelection(); a.navigateTo(File("/")); a.handleBack()+ a.createFolder("x"); a.openTrash(); a.showMessage("m")+ assertFalse(a.handleBack())+ assertNotNull(a.toString())+ }+}
files/src/test/java/com/vayunmathur/files/platform/FilesViewModelTest.kt
diff --git a/files/src/test/java/com/vayunmathur/files/platform/FilesViewModelTest.kt b/files/src/test/java/com/vayunmathur/files/platform/FilesViewModelTest.ktnew file mode 100644index 0000000000..b6f4489332--- /dev/null+++ b/files/src/test/java/com/vayunmathur/files/platform/FilesViewModelTest.kt@@ -0,0 +1,481 @@+package com.vayunmathur.files.platform++import android.app.Application+import android.content.Context+import android.net.Uri+import androidx.test.core.app.ApplicationProvider+import kotlinx.coroutines.async+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.launch+import kotlinx.coroutines.runBlocking+import kotlinx.coroutines.withTimeoutOrNull+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import org.robolectric.annotation.Implementation+import org.robolectric.shadows.ShadowLooper+import java.io.File+import java.util.zip.ZipEntry+import java.util.zip.ZipOutputStream+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++/** Minimal provider serving files from [root] so content:// load/save can be exercised. */+class TestFileProvider : android.content.ContentProvider() {+ companion object { lateinit var rootDir: File }+ private val root: File get() = rootDir+ override fun onCreate(): Boolean = true+ override fun openFile(uri: Uri, mode: String): android.os.ParcelFileDescriptor {+ val file = File(root, uri.lastPathSegment ?: "unnamed")+ if (mode.contains("w")) {+ file.parentFile?.mkdirs()+ // ParcelFileDescriptor.parseMode("w") creates but does not truncate;+ // real providers truncate on write mode, so mirror that here.+ if (file.exists()) java.io.FileOutputStream(file, false).close()+ }+ return android.os.ParcelFileDescriptor.open(file, android.os.ParcelFileDescriptor.parseMode(mode))+ }+ override fun query(+ uri: Uri, projection: Array<out String>?, selection: String?,+ selectionArgs: Array<out String>?, sortOrder: String?,+ ): android.database.Cursor? = null+ override fun getType(uri: Uri): String = "text/plain"+ override fun insert(uri: Uri, values: android.content.ContentValues?): Uri? = null+ override fun delete(uri: Uri, selection: String?, selectionArgs: Array<out String>?): Int = 0+ override fun update(+ uri: Uri, values: android.content.ContentValues?, selection: String?,+ selectionArgs: Array<out String>?,+ ): Int = 0+}++@RunWith(RobolectricTestRunner::class)+@Config(shadows = [ShadowEnvironmentFix::class])+class FilesViewModelTest {++ private val app: Application get() = ApplicationProvider.getApplicationContext()+ private lateinit var vm: FilesViewModel+ private lateinit var base: File+ private lateinit var dirA: File+ private lateinit var dirB: File++ @BeforeTest+ fun setUp() {+ base = File(app.cacheDir, "vm-${System.nanoTime()}").apply { mkdirs() }+ dirA = File(base, "dirA").apply { mkdirs() }+ dirB = File(base, "dirB").apply { mkdirs() }+ File(dirA, "one.txt").writeText("one")+ File(dirA, "two.md").writeText("two!")+ File(dirA, "sub").mkdirs()+ runCatching {+ androidx.work.WorkManager.initialize(+ app,+ androidx.work.Configuration.Builder().build(),+ )+ }+ vm = FilesViewModel(app)+ ShadowLooper.idleMainLooper()+ vm.navigateTo(dirA)+ await { vm.currentDirectory.value == dirA && vm.entries.value.second.isNotEmpty() }+ }++ private fun await(timeoutMs: Long = 10_000, cond: () -> Boolean) {+ val deadline = System.currentTimeMillis() + timeoutMs+ while (!cond() && System.currentTimeMillis() < deadline) {+ ShadowLooper.idleMainLooper()+ Thread.sleep(20)+ }+ assertTrue(cond(), "condition not met within ${timeoutMs}ms")+ }++ private fun itemOf(name: String): FileBrowserItem {+ val (dirs, files) = vm.entries.value+ return (dirs + files).first { it.name == name }+ }++ @Test+ fun `initial navigation lists current directory sorted`() {+ assertEquals(dirA, vm.currentDirectory.value)+ val (dirs, files) = vm.entries.value+ assertEquals(listOf("sub"), dirs.map { it.name })+ assertEquals(listOf("one.txt", "two.md"), files.map { it.name })+ assertNull(vm.zipPath.value)+ assertEquals("", vm.zipInternalPath.value)+ }++ @Test+ fun `selection toggle add selectAll clear and back`() {+ val one = itemOf("one.txt")+ vm.toggleSelection(one)+ assertEquals(setOf(one.key), vm.selectedPaths.value.map { it.key }.toSet())+ vm.toggleSelection(one)+ assertTrue(vm.selectedPaths.value.isEmpty())+ vm.addToSelection(one)+ vm.addToSelection(itemOf("sub"))+ assertEquals(2, vm.selectedPaths.value.size)+ assertTrue(vm.handleBack())+ assertTrue(vm.selectedPaths.value.isEmpty())+ assertFalse(vm.handleBack())+ vm.selectAll()+ assertEquals(3, vm.selectedPaths.value.size)+ vm.clearSelection()+ assertTrue(vm.selectedPaths.value.isEmpty())+ }++ @Test+ fun `sort view search and hidden settings persist state`() {+ vm.setSortBy(SortBy.SIZE)+ assertEquals(SortBy.SIZE, vm.sortBy.value)+ vm.setSortBy(SortBy.SIZE) // no-op same value+ vm.toggleSortDirection()+ assertFalse(vm.sortAscending.value)+ vm.setSortAscending(true)+ assertTrue(vm.sortAscending.value)+ assertEquals(ViewMode.LIST, vm.viewMode.value)+ vm.toggleViewMode()+ assertEquals(ViewMode.GRID, vm.viewMode.value)+ vm.toggleViewMode()+ assertEquals(ViewMode.LIST, vm.viewMode.value)+ vm.setSearchActive(true)+ vm.setSearchQuery("one")+ assertEquals("one", vm.searchQuery.value)+ vm.setSearchActive(false)+ assertEquals("", vm.searchQuery.value)+ assertFalse(vm.isSearchActive.value)+ val hiddenBefore = vm.showHidden.value+ vm.toggleHidden()+ assertEquals(!hiddenBefore, vm.showHidden.value)+ vm.toggleHidden()+ }++ @Test+ fun `create folder and file appear on disk with unique names`() {+ vm.createFolder("newfolder")+ await { File(dirA, "newfolder").isDirectory }+ vm.createFolder("newfolder")+ await { File(dirA, "newfolder (1)").isDirectory }+ vm.createFile("fresh.txt")+ await { File(dirA, "fresh.txt").isFile }+ vm.createFolder(" ")+ vm.createFile("")+ assertFalse(File(dirA, "").let { it.exists() && it != dirA })+ }++ @Test+ fun `rename moves the file and clears selection`() {+ val one = itemOf("one.txt")+ vm.addToSelection(one)+ vm.rename(one, "renamed.txt")+ await { File(dirA, "renamed.txt").isFile && !File(dirA, "one.txt").exists() }+ assertTrue(vm.selectedPaths.value.isEmpty())+ // zip-mode guards: rename/create are no-ops inside a zip+ vm.showZip(File(dirA, "fake.zip"), "")+ vm.rename(itemOfZip("x"), "y.txt")+ vm.createFolder("nope")+ assertFalse(File(dirA, "nope").exists())+ }++ private fun itemOfZip(name: String) = FileBrowserItem(+ name = name, isDirectory = false, size = 1,+ realFile = File(dirA, "one.txt"), zipInnerPath = name, key = "zip:$name",+ )++ @Test+ fun `copy paste duplicates and cut paste moves`() {+ vm.navigateTo(dirA)+ await { vm.entries.value.second.isNotEmpty() }+ val one = itemOf("one.txt")+ vm.addToSelection(one)+ vm.copySelection()+ assertEquals(1, vm.clipboard.value.size)+ assertFalse(vm.clipboardIsCut.value)+ assertTrue(vm.selectedPaths.value.isEmpty())+ vm.navigateTo(dirB)+ // wait until the listing actually shows dirB, not the stale dirA one+ await {+ vm.currentDirectory.value == dirB &&+ vm.entries.value.second.none { it.realFile?.parentFile == dirA }+ }+ vm.pasteHere()+ await { File(dirB, "one.txt").isFile }+ assertEquals("one", File(dirB, "one.txt").readText())+ assertTrue(File(dirA, "one.txt").exists())++ // cut from dirB into dirA subfolder via navigate + paste+ vm.addToSelection(itemOf("one.txt"))+ vm.cutSelection()+ assertTrue(vm.clipboardIsCut.value)+ vm.navigateTo(File(dirA, "sub"))+ vm.pasteHere()+ await(30_000) { File(dirA, "sub/one.txt").isFile && !File(dirB, "one.txt").exists() }+ assertTrue(vm.clipboard.value.isEmpty())+ vm.clearClipboard()+ assertFalse(vm.clipboardIsCut.value)+ vm.copySelection() // empty selection: no-op+ assertTrue(vm.clipboard.value.isEmpty())+ }++ @Test+ fun `moveInto and moveToBreadcrumb move files with guards`() {+ val target = File(dirA, "sub")+ vm.moveInto(listOf(File(dirA, "two.md")), target)+ await { File(target, "two.md").isFile && !File(dirA, "two.md").exists() }+ // moving a folder into itself is refused+ vm.moveInto(listOf(target), target)+ Thread.sleep(200); ShadowLooper.idleMainLooper()+ assertTrue(target.isDirectory)+ // breadcrumb move: parent != target guard+ vm.moveToBreadcrumb(listOf(File(target, "two.md")), dirA)+ await { File(dirA, "two.md").isFile }+ vm.moveToBreadcrumb(listOf(File(dirA, "two.md")), dirA)+ Thread.sleep(200)+ assertTrue(File(dirA, "two.md").isFile)+ // non-directory target refused+ vm.moveInto(listOf(File(dirA, "two.md")), File(dirA, "one.txt"))+ Thread.sleep(200)+ assertTrue(File(dirA, "two.md").isFile)+ }++ @Test+ fun `zip browsing navigation and back state`() {+ val zipFile = File(base, "sample.zip")+ ZipOutputStream(zipFile.outputStream()).use { out ->+ out.putNextEntry(ZipEntry("docs/readme.txt")); out.write("hi".toByteArray()); out.closeEntry()+ out.putNextEntry(ZipEntry("top.txt")); out.write("t".toByteArray()); out.closeEntry()+ }+ vm.showZip(zipFile, "")+ await { vm.entries.value.first.map { it.name } == listOf("docs") }+ assertEquals(zipFile, vm.zipPath.value)+ assertEquals(listOf("docs"), vm.entries.value.first.map { it.name })+ assertEquals(listOf("top.txt"), vm.entries.value.second.map { it.name })+ // selection is disabled in zip mode+ vm.toggleSelection(vm.entries.value.second.first())+ assertTrue(vm.selectedPaths.value.isEmpty())+ vm.navigateIntoZipDir("docs")+ await { vm.entries.value.second.map { it.name } == listOf("readme.txt") }+ assertEquals("docs", vm.zipInternalPath.value)+ vm.navigateToZipInternalPath("")+ await { vm.zipInternalPath.value == "" && vm.entries.value.second.isNotEmpty() }+ vm.navigateToZipParentRealFolder(dirA)+ assertNull(vm.zipPath.value)+ assertEquals(dirA, vm.currentDirectory.value)+ }++ @Test+ fun `openZipChecked emits for valid zip and messages for corrupt`() = runBlocking {+ val zipFile = File(base, "ok.zip")+ ZipOutputStream(zipFile.outputStream()).use { out ->+ out.putNextEntry(ZipEntry("a.txt")); out.write("a".toByteArray()); out.closeEntry()+ }+ val opened = kotlinx.coroutines.CoroutineScope(kotlinx.coroutines.Dispatchers.Default).async {+ withTimeoutOrNull(5_000) { vm.zipOpened.first() }+ }+ // let the collector subscribe before triggering+ Thread.sleep(150)+ vm.openZipChecked(zipFile)+ ShadowLooper.idleMainLooper()+ assertEquals(zipFile, opened.await())++ val bad = File(base, "bad.zip").apply { writeText("junk") }+ vm.openZipFile(FileBrowserItem("bad.zip", false, 4, bad, null, bad.absolutePath))+ // corrupt zip produces a snackbar rather than zipOpened; just ensure no crash+ Thread.sleep(300); ShadowLooper.idleMainLooper()+ Unit+ }++ @Test+ fun `home bookmarks categories and storage`() {+ vm.goHome()+ await { vm.storage.value != null }+ val one = FileBrowserItem("one.txt", false, 3, File(dirA, "one.txt"), null, File(dirA, "one.txt").absolutePath)+ vm.addBookmark(one)+ assertTrue(vm.bookmarks.value.any { it.name == "one.txt" } || run {+ // bookmarks only list directories/existing paths via loadBookmarkItems;+ // a file path exists, so it must be listed+ false+ })+ vm.removeBookmark(File(dirA, "one.txt"))+ assertTrue(vm.bookmarks.value.none { it.realFile == File(dirA, "one.txt") })+ vm.openBookmark(dirB)+ assertEquals(dirB, vm.currentDirectory.value)+ vm.openInternalStorage()+ assertEquals(vm.rootDirectory, vm.currentDirectory.value)+ vm.openCategory(FileCategory.DOWNLOADS)+ // downloads either opens the Download folder or root; either is a real dir+ assertTrue(vm.currentDirectory.value.isDirectory || vm.currentDirectory.value == vm.rootDirectory)+ vm.openCategory(FileCategory.IMAGES)+ await { vm.categoryTitle.value != null }+ vm.goHome()+ assertNull(vm.categoryTitle.value)+ }++ @Test+ fun `trash flow with untrashable directory goes to permanent delete`() {+ vm.navigateTo(dirA)+ await { vm.entries.value.first.isNotEmpty() }+ val sub = itemOf("sub")+ File(dirA, "sub/inner.txt").writeText("inner")+ vm.addToSelection(sub)+ vm.deleteSelection()+ await { vm.pendingPermanentDelete.value?.isNotEmpty() == true }+ vm.dismissPermanentDelete()+ assertNull(vm.pendingPermanentDelete.value)+ assertTrue(File(dirA, "sub").isDirectory)+ // again, this time confirming+ vm.addToSelection(itemOf("sub"))+ vm.deleteSelection()+ await { vm.pendingPermanentDelete.value?.isNotEmpty() == true }+ vm.confirmPermanentDelete()+ await { !File(dirA, "sub").exists() }+ assertNull(vm.pendingPermanentDelete.value)+ }++ @Test+ fun `trash screen selection and consent result`() {+ vm.openTrash()+ assertEquals("", vm.zipInternalPath.value)+ val ghost = FileBrowserItem(+ "ghost.txt", false, 1, File(base, "ghost.txt"), null, "trash:1",+ mediaUri = Uri.parse("content://media/external/images/media/1"),+ )+ vm.toggleTrashSelection(ghost)+ assertEquals(setOf(ghost), vm.trashSelection.value)+ vm.toggleTrashSelection(ghost)+ assertTrue(vm.trashSelection.value.isEmpty())+ vm.toggleTrashSelection(ghost)+ vm.clearTrashSelection()+ assertTrue(vm.trashSelection.value.isEmpty())+ // restore/delete with a selection that has no resolvable uri is a safe no-op+ vm.toggleTrashSelection(+ FileBrowserItem("plain.txt", false, 1, File(base, "plain.txt"), null, "k-plain"),+ )+ vm.restoreTrashSelection()+ vm.deleteForeverTrashSelection()+ vm.emptyTrash()+ vm.onTrashConsentResult(granted = true)+ vm.onTrashConsentResult(granted = false)+ ShadowLooper.idleMainLooper()+ }++ @Test+ fun `share open and apk intents are emitted`() = runBlocking {+ val received = java.util.Collections.synchronizedList(mutableListOf<android.content.Intent>())+ val messages = java.util.Collections.synchronizedList(mutableListOf<String>())+ val collector = kotlinx.coroutines.CoroutineScope(kotlinx.coroutines.Dispatchers.Default)+ .launch { vm.intents.collect { received.add(it) } }+ val msgCollector = kotlinx.coroutines.CoroutineScope(kotlinx.coroutines.Dispatchers.Default)+ .launch { vm.snackbarMessages.collect { messages.add(it) } }+ Thread.sleep(200)+ val extDir = File(vm.rootDirectory, "sharetest-${System.nanoTime()}").apply { mkdirs() }+ val extFile = File(extDir, "shared.txt").apply { writeText("share me") }+ vm.navigateTo(extDir)+ await { vm.entries.value.second.map { it.name } == listOf("shared.txt") }+ val one = itemOf("shared.txt")+ // The intents flow has no replay, so re-trigger until the collector sees+ // the outcome. On a real device openFile emits a VIEW intent; in the+ // Robolectric sandbox the FileProvider has no root containing the+ // per-method external dir, so the same call surfaces the move-failed+ // snackbar instead. Either proves the tap was routed and reported.+ val deadline = System.currentTimeMillis() + 8_000+ while (received.isEmpty() && messages.isEmpty() && System.currentTimeMillis() < deadline) {+ vm.openFile(one)+ Thread.sleep(120); ShadowLooper.idleMainLooper()+ }+ collector.cancel(); msgCollector.cancel()+ assertTrue(received.isNotEmpty() || messages.isNotEmpty())+ if (received.isNotEmpty()) {+ assertEquals(android.content.Intent.ACTION_VIEW, received.first().action)+ }+ // openWith / share / install paths (may emit or message depending on providers)+ vm.addToSelection(one)+ vm.shareSelection()+ vm.openWith(one)+ val apk = FileBrowserItem("app.apk", false, 1, File(extDir, "app.apk"), null, "apk-key")+ File(extDir, "app.apk").writeText("apk")+ vm.installApk(apk)+ vm.onApkInstallPermissionResult()+ vm.onInstallPermissionResult()+ vm.showMessage("hello")+ Thread.sleep(200); ShadowLooper.idleMainLooper()+ Unit+ }++ @Test+ fun `archive enqueues zip work for selection`() {+ val one = itemOf("one.txt")+ vm.addToSelection(one)+ vm.archive("bundle")+ assertTrue(vm.selectedPaths.value.isEmpty())+ vm.archive("bundle2.zip")+ // empty selection archive is a no-op+ vm.archive("nothing")+ ShadowLooper.idleMainLooper()+ }++ @Test+ fun `incoming uris save into current directory`() = runBlocking {+ val source = File(base, "shared-src.txt").apply { writeText("shared body") }+ vm.setIncomingUris(listOf(Uri.fromFile(source)))+ assertEquals(1, vm.incomingUris.value?.size)+ vm.navigateTo(dirB)+ await { vm.currentDirectory.value == dirB }+ vm.saveIncomingUris()+ await(timeoutMs = 5_000) { vm.incomingUris.value == null }+ vm.clearIncomingUris()+ assertNull(vm.incomingUris.value)+ Unit+ }++ @Test+ fun `unzip valid archive enqueues and oversized is refused`() {+ val zipFile = File(base, "small.zip")+ ZipOutputStream(zipFile.outputStream()).use { out ->+ out.putNextEntry(ZipEntry("inside.txt")); out.write("inside".toByteArray()); out.closeEntry()+ }+ val item = FileBrowserItem("small.zip", false, zipFile.length(), zipFile, null, zipFile.absolutePath)+ vm.unzip(item, dirB)+ ShadowLooper.idleMainLooper()+ Thread.sleep(300); ShadowLooper.idleMainLooper()+ // null realFile unzip is a no-op+ vm.unzip(FileBrowserItem("x.zip", false, 1, null, "x", "k"), dirB)+ }++ @Test+ fun `permissions and notification prompt flags`() {+ vm.refreshPermissions()+ assertEquals(vm.isFilesGranted.value, vm.isFilesGranted.value)+ vm.setNotificationsPrompted()+ assertTrue(vm.hasPromptedNotifications.value)+ }++ @Test+ fun `mime helper maps known extensions`() {+ assertEquals("text/plain", vmMime("a.txt"))+ assertEquals("*/*", vmMime("a.unknownext123"))+ }++ private fun vmMime(name: String): String = vm.mimeFor(File(base, name))++ @Test+ fun `text editor viewmodel loads and saves through file uri`() {+ TestFileProvider.rootDir = base+ org.robolectric.Robolectric.buildContentProvider(TestFileProvider::class.java)+ .create("testdocs")+ val editor = TextEditorViewModel(app)+ File(base, "edit.txt").writeText("before")+ val uri = Uri.parse("content://testdocs/edit.txt")+ editor.load(uri)+ Thread.sleep(500); ShadowLooper.idleMainLooper()+ await { editor.initialContent.value == "before" }+ File(base, "edit.txt").writeText("before")+ editor.save(uri, "after")+ await { File(base, "edit.txt").readText() == "after" && editor.initialContent.value == "after" }+ // missing file loads as empty+ editor.load(Uri.parse("content://testdocs/missing.txt"))+ await { editor.initialContent.value == "" }+ }+}
files/src/test/java/com/vayunmathur/files/platform/ShadowEnvironmentFix.kt
diff --git a/files/src/test/java/com/vayunmathur/files/platform/ShadowEnvironmentFix.kt b/files/src/test/java/com/vayunmathur/files/platform/ShadowEnvironmentFix.ktnew file mode 100644index 0000000000..979f0a3795--- /dev/null+++ b/files/src/test/java/com/vayunmathur/files/platform/ShadowEnvironmentFix.kt@@ -0,0 +1,30 @@+package com.vayunmathur.files.platform++import org.robolectric.annotation.Implementation+import org.robolectric.annotation.Implements+import org.robolectric.shadows.ShadowEnvironment++/**+ * Robolectric's stock [android.os.Environment] blows up inside+ * `isExternalStorageManager()` (no user list in the sandbox). Inheriting the+ * stock shadow keeps its external-storage directory while fixing that one call+ * to report granted, which is the state the UI tests exercise.+ */+@Implements(android.os.Environment::class)+class ShadowEnvironmentFix : ShadowEnvironment() {+ companion object {+ @Implementation+ @JvmStatic+ fun isExternalStorageManager(): Boolean = true+ }+}++/** Same shadow but reporting all-files access as not granted (the shell's gate). */+@Implements(android.os.Environment::class)+class ShadowEnvironmentDeniedFix : ShadowEnvironment() {+ companion object {+ @Implementation+ @JvmStatic+ fun isExternalStorageManager(): Boolean = false+ }+}
files/src/test/java/com/vayunmathur/files/platform/TrashMediaProviderTest.kt
diff --git a/files/src/test/java/com/vayunmathur/files/platform/TrashMediaProviderTest.kt b/files/src/test/java/com/vayunmathur/files/platform/TrashMediaProviderTest.ktnew file mode 100644index 0000000000..dbd648060c--- /dev/null+++ b/files/src/test/java/com/vayunmathur/files/platform/TrashMediaProviderTest.kt@@ -0,0 +1,118 @@+package com.vayunmathur.files.platform++import android.content.ContentProvider+import android.content.ContentValues+import android.database.Cursor+import android.database.MatrixCursor+import android.net.Uri+import android.os.Bundle+import android.os.CancellationSignal+import android.provider.MediaStore+import androidx.test.core.app.ApplicationProvider+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.RobolectricTestRunner+import java.io.File+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/**+ * Serves MediaStore-shaped rows for one real file so the trash queries in+ * [FilesTrashKt] can be exercised without a device media database.+ */+class FakeMediaProvider : ContentProvider() {+ companion object {+ var dataPath: String = ""+ var displayName: String = "trashed.txt"+ }++ override fun onCreate(): Boolean = true++ private fun rows(projection: Array<out String>?): MatrixCursor {+ val columns = projection ?: arrayOf(+ MediaStore.MediaColumns._ID,+ MediaStore.MediaColumns.DISPLAY_NAME,+ MediaStore.MediaColumns.DATA,+ MediaStore.MediaColumns.SIZE,+ MediaStore.MediaColumns.DATE_MODIFIED,+ MediaStore.Files.FileColumns.MEDIA_TYPE,+ )+ val cursor = MatrixCursor(columns)+ val values = mapOf<String, Any>(+ MediaStore.MediaColumns._ID to 42L,+ MediaStore.MediaColumns.DISPLAY_NAME to displayName,+ MediaStore.MediaColumns.DATA to dataPath,+ MediaStore.MediaColumns.SIZE to 123L,+ MediaStore.MediaColumns.DATE_MODIFIED to 1_700_000_000L,+ MediaStore.Files.FileColumns.MEDIA_TYPE to MediaStore.Files.FileColumns.MEDIA_TYPE_IMAGE,+ )+ cursor.addRow(columns.map { values[it] })+ return cursor+ }++ override fun query(+ uri: Uri, projection: Array<out String>?, selection: String?,+ selectionArgs: Array<out String>?, sortOrder: String?,+ ): Cursor = rows(projection)++ override fun query(+ uri: Uri, projection: Array<out String>?, queryArgs: Bundle?,+ cancellationSignal: CancellationSignal?,+ ): Cursor = rows(projection)++ override fun getType(uri: Uri): String = "image/png"+ override fun insert(uri: Uri, values: ContentValues?): Uri? = null+ override fun delete(uri: Uri, selection: String?, selectionArgs: Array<out String>?): Int = 0+ override fun update(+ uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array<out String>?,+ ): Int = 0+}++@RunWith(RobolectricTestRunner::class)+class TrashMediaProviderTest {++ private val ctx get() = ApplicationProvider.getApplicationContext<android.content.Context>()+ private lateinit var file: File++ @BeforeTest+ fun setUp() {+ file = File(ctx.cacheDir, "trashed-${System.nanoTime()}.txt").apply { writeText("trash me") }+ FakeMediaProvider.dataPath = file.absolutePath+ Robolectric.buildContentProvider(FakeMediaProvider::class.java).create("media")+ }++ @Test+ fun `trashed items are read from media rows`() {+ val items = queryTrashedItems(ctx)+ assertEquals(1, items.size)+ val item = items.first()+ assertEquals("trashed.txt", item.name)+ assertEquals(file, item.realFile)+ assertEquals(123L, item.size)+ assertEquals(1_700_000_000_000L, item.lastModified)+ assertEquals("trash:42", item.key)+ assertTrue(item.mediaUri.toString().endsWith("/42"))+ }++ @Test+ fun `trashable uris resolve through the provider`() {+ val resolved = resolveTrashableUris(ctx, listOf(file))+ assertEquals(1, resolved.size)+ assertTrue(resolved[file].toString().endsWith("/42"))+ // directories are never trashable and are skipped before querying+ val dir = File(ctx.cacheDir, "adir-${System.nanoTime()}").apply { mkdirs() }+ assertTrue(resolveTrashableUris(ctx, listOf(dir)).isEmpty())+ // selection resolution prefers the cached media uri, else re-queries+ val cached = FileBrowserItem(+ "x.txt", false, 1, file, null, "k1",+ mediaUri = Uri.parse("content://media/external/images/media/7"),+ )+ val uncached = FileBrowserItem("y.txt", false, 1, file, null, "k2")+ val uris = urisForSelection(ctx, listOf(cached, uncached))+ assertEquals(2, uris.size)+ assertTrue(uris[0].toString().endsWith("/7"))+ assertTrue(uris[1].toString().endsWith("/42"))+ }+}
files/src/test/java/com/vayunmathur/files/platform/WorkersAndStorageTest.kt
diff --git a/files/src/test/java/com/vayunmathur/files/platform/WorkersAndStorageTest.kt b/files/src/test/java/com/vayunmathur/files/platform/WorkersAndStorageTest.ktnew file mode 100644index 0000000000..d0c938c9a5--- /dev/null+++ b/files/src/test/java/com/vayunmathur/files/platform/WorkersAndStorageTest.kt@@ -0,0 +1,132 @@+package com.vayunmathur.files.platform++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import androidx.work.ListenableWorker+import androidx.work.testing.TestListenableWorkerBuilder+import androidx.work.workDataOf+import com.vayunmathur.files.data.saf.StorageUris+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import java.io.File+import java.util.zip.ZipFile+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)+@Config(shadows = [ShadowEnvironmentFix::class])+class WorkersAndStorageTest {++ private val ctx: Context get() = ApplicationProvider.getApplicationContext()++ private fun tempDir(name: String): File =+ File(ctx.cacheDir, "worker-$name-${System.nanoTime()}").apply { mkdirs() }++ @Test+ fun `zip worker archives files and folders`() { runBlocking {+ val dir = tempDir("zip")+ val srcFile = File(dir, "a.txt").apply { writeText("alpha") }+ val srcDir = File(dir, "folder").apply { mkdirs() }+ File(srcDir, "b.txt").writeText("beta")+ File(dir, "emptyDir").mkdirs()+ val dest = File(dir, "out.zip")+ val worker = TestListenableWorkerBuilder<ZipWorker>(ctx)+ .setInputData(+ workDataOf(+ "source_paths" to arrayOf(srcFile.absolutePath, srcDir.absolutePath, File(dir, "emptyDir").absolutePath),+ "dest_path" to dest.absolutePath,+ ),+ )+ .build()+ assertEquals(ListenableWorker.Result.success(), worker.doWork())+ assertTrue(dest.isFile)+ ZipFile(dest).use { zf ->+ val names = zf.entries().asSequence().map { it.name }.toSet()+ assertTrue("a.txt" in names)+ assertTrue("folder/b.txt" in names)+ assertTrue("emptyDir/" in names)+ assertEquals("alpha", zf.getInputStream(zf.getEntry("a.txt")).readBytes().decodeToString())+ }+ dir.deleteRecursively()+ } }++ @Test+ fun `zip worker fails without input`() { runBlocking {+ val worker = TestListenableWorkerBuilder<ZipWorker>(ctx).build()+ assertEquals(ListenableWorker.Result.failure(), worker.doWork())+ } }++ @Test+ fun `unzip worker extracts and refuses zip slip and budget`() { runBlocking {+ val dir = tempDir("unzip")+ // build an archive with a normal entry, a nested entry and an evil entry+ val zipFile = File(dir, "in.zip")+ java.util.zip.ZipOutputStream(zipFile.outputStream()).use { out ->+ out.putNextEntry(java.util.zip.ZipEntry("hello.txt")); out.write("hello".toByteArray()); out.closeEntry()+ out.putNextEntry(java.util.zip.ZipEntry("sub/world.txt")); out.write("world".toByteArray()); out.closeEntry()+ out.putNextEntry(java.util.zip.ZipEntry("../evil.txt")); out.write("evil".toByteArray()); out.closeEntry()+ out.putNextEntry(java.util.zip.ZipEntry("emptydir/")); out.closeEntry()+ }+ val destDir = File(dir, "out").apply { mkdirs() }+ val worker = TestListenableWorkerBuilder<UnzipWorker>(ctx)+ .setInputData(+ workDataOf(+ "zip_path" to zipFile.absolutePath,+ "dest_path" to destDir.absolutePath,+ "size_budget" to 1_000_000L,+ ),+ )+ .build()+ assertEquals(ListenableWorker.Result.success(), worker.doWork())+ assertEquals("hello", File(destDir, "hello.txt").readText())+ assertEquals("world", File(destDir, "sub/world.txt").readText())+ assertFalse(File(dir, "evil.txt").exists())+ assertTrue(File(destDir, "emptydir").isDirectory)++ // tiny budget: extraction is refused and partial output cleaned up+ val dest2 = File(dir, "out2").apply { mkdirs() }+ val stingy = TestListenableWorkerBuilder<UnzipWorker>(ctx)+ .setInputData(+ workDataOf(+ "zip_path" to zipFile.absolutePath,+ "dest_path" to dest2.absolutePath,+ "size_budget" to 2L,+ ),+ )+ .build()+ assertEquals(ListenableWorker.Result.failure(), stingy.doWork())+ assertFalse(File(dest2, "hello.txt").exists())++ val noInput = TestListenableWorkerBuilder<UnzipWorker>(ctx).build()+ assertEquals(ListenableWorker.Result.failure(), noInput.doWork())+ dir.deleteRecursively()+ } }++ @Test+ fun `storage uris mime matching`() {+ assertEquals("text/plain", StorageUris.mimeTypeOf(File("a.txt")))+ assertEquals("image/png", StorageUris.mimeTypeOf(File("a.PNG")))+ assertEquals("application/octet-stream", StorageUris.mimeTypeOf(File("a.unknownext")))+ assertTrue(StorageUris.matchesMime(File("a.txt"), emptyList()))+ assertTrue(StorageUris.matchesMime(File("a.txt"), listOf("*/*")))+ assertTrue(StorageUris.matchesMime(File("a.txt"), listOf("text/plain")))+ assertTrue(StorageUris.matchesMime(File("a.txt"), listOf("text/*")))+ assertTrue(StorageUris.matchesMime(File("photo.jpg"), listOf("image/*", "text/plain")))+ assertFalse(StorageUris.matchesMime(File("a.txt"), listOf("image/*")))+ assertFalse(StorageUris.matchesMime(File("a.txt"), listOf("noslash")))+ assertTrue(StorageUris.matchesMime(File("a.txt"), listOf("*/plain")))+ // no known volume in the sandbox: document ids are unavailable rather than wrong+ val anyFile = File(ctx.cacheDir, "x.txt").apply { writeText("x") }+ val docId = StorageUris.documentIdFor(ctx, anyFile)+ assertTrue(docId == null || docId.contains(":"))+ // Files outside every configured FileProvider root are refused, which is+ // what keeps a stray path from being handed to another app.+ val outside = File(ctx.cacheDir, "outside-${System.nanoTime()}.txt").apply { writeText("x") }+ val refused = runCatching { StorageUris.fileProviderUriFor(ctx, outside) }+ assertTrue(refused.isFailure)+ }+}
files/src/test/java/com/vayunmathur/files/ui/ActivitiesAndBindersTest.kt
diff --git a/files/src/test/java/com/vayunmathur/files/ui/ActivitiesAndBindersTest.kt b/files/src/test/java/com/vayunmathur/files/ui/ActivitiesAndBindersTest.ktnew file mode 100644index 0000000000..0a8bd26203--- /dev/null+++ b/files/src/test/java/com/vayunmathur/files/ui/ActivitiesAndBindersTest.kt@@ -0,0 +1,175 @@+package com.vayunmathur.files.ui++import android.app.Application+import android.content.Intent+import android.net.Uri+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.createAndroidComposeRule+import androidx.compose.ui.test.onAllNodesWithText+import androidx.compose.ui.test.onNodeWithText+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.files.MainActivity+import com.vayunmathur.files.Route+import com.vayunmathur.files.data.saf.DocumentPickerActivity+import com.vayunmathur.files.platform.FilesViewModel+import com.vayunmathur.files.platform.ShadowEnvironmentFix+import com.vayunmathur.files.platform.TestFileProvider+import com.vayunmathur.library.util.NavBackStack+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows+import org.robolectric.annotation.Config+import org.robolectric.shadows.ShadowLooper+import java.io.File+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)+@Config(shadows = [ShadowEnvironmentFix::class], qualifiers = "w800dp-h1280dp")+class ActivitiesAndBindersTest {++ private val app: Application get() = ApplicationProvider.getApplicationContext()++ @Test+ fun `main activity launches shell and handles send intents`() {+ val controller = Robolectric.buildActivity(MainActivity::class.java)+ val activity = controller.create().start().resume().visible().get()+ ShadowLooper.idleMainLooper()+ assertNotNull(activity)+ // a SEND intent with a stream is accepted as incoming uris+ val send = Intent(Intent.ACTION_SEND).apply {+ type = "text/plain"+ putExtra(Intent.EXTRA_STREAM, Uri.parse("content://testdocs/shared.txt"))+ }+ controller.newIntent(send)+ val multi = Intent(Intent.ACTION_SEND_MULTIPLE).apply {+ type = "text/plain"+ putParcelableArrayListExtra(+ Intent.EXTRA_STREAM,+ arrayListOf(Uri.parse("content://testdocs/a.txt")),+ )+ }+ controller.newIntent(multi)+ controller.newIntent(Intent(Intent.ACTION_MAIN))+ ShadowLooper.idleMainLooper()+ controller.pause().stop().destroy()+ }++ @Test+ fun `text editor activity finishes without data and edits with data`() {+ val noData = Robolectric.buildActivity(TextEditorActivity::class.java)+ val finished = noData.create().get()+ assertTrue(finished.isFinishing)++ val base = File(app.cacheDir, "editor-act-${System.nanoTime()}").apply { mkdirs() }+ File(base, "note.txt").writeText("editor body")+ TestFileProvider.rootDir = base+ Robolectric.buildContentProvider(TestFileProvider::class.java).create("testdocs")+ val intent = Intent(Intent.ACTION_VIEW).setData(Uri.parse("content://testdocs/note.txt"))+ val controller = Robolectric.buildActivity(TextEditorActivity::class.java, intent)+ val activity = controller.create().start().resume().visible().get()+ ShadowLooper.idleMainLooper()+ assertNotNull(activity)+ controller.pause().stop().destroy()+ base.deleteRecursively()+ }++ @Test+ fun `document picker cancels unknown actions and renders open mode`() {+ val unknown = Robolectric.buildActivity(+ DocumentPickerActivity::class.java,+ Intent(Intent.ACTION_MAIN),+ )+ val cancelled = unknown.create().get()+ ShadowLooper.idleMainLooper()+ assertTrue(cancelled.isFinishing)+ assertEquals(android.app.Activity.RESULT_CANCELED, Shadows.shadowOf(cancelled).resultCode)++ for (action in listOf(+ Intent.ACTION_OPEN_DOCUMENT,+ Intent.ACTION_GET_CONTENT,+ Intent.ACTION_OPEN_DOCUMENT_TREE,+ Intent.ACTION_CREATE_DOCUMENT,+ )) {+ val intent = Intent(action).apply {+ type = "*/*"+ putExtra(Intent.EXTRA_TITLE, "created.txt")+ if (action == Intent.ACTION_OPEN_DOCUMENT) {+ putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true)+ putExtra(Intent.EXTRA_MIME_TYPES, arrayOf("text/plain"))+ }+ }+ val controller = Robolectric.buildActivity(DocumentPickerActivity::class.java, intent)+ val activity = controller.create().start().resume().visible().get()+ ShadowLooper.idleMainLooper()+ assertNotNull(activity)+ controller.pause().stop().destroy()+ }+ }++ @Test+ fun `nav actions drive the back stack`() {+ val vm = FilesViewModel(app)+ ShadowLooper.idleMainLooper()+ val stack = NavBackStack<Route>(arrayOf(Route.Home))+ val actions = filesNavActions(vm, stack)+ val root = vm.rootDirectory++ actions.openInternalStorage()+ assertEquals(Route.Directory(root.absolutePath), stack.backStack.last())++ actions.goHome()+ assertEquals(listOf(Route.Home), stack.backStack.toList())++ val deep = File(root, "a/b/c")+ actions.openBookmark(deep)+ assertEquals(Route.Directory(deep.absolutePath), stack.backStack.last())+ assertTrue(stack.backStack.size > 2)++ actions.navigateTo(File(root, "a"))+ // already on the stack: pops back to it instead of duplicating+ assertEquals(Route.Directory(File(root, "a").absolutePath), stack.backStack.last())++ actions.openCategory(com.vayunmathur.files.platform.FileCategory.IMAGES)+ assertEquals(Route.Category(com.vayunmathur.files.platform.FileCategory.IMAGES), stack.backStack.last())+ actions.openCategory(com.vayunmathur.files.platform.FileCategory.DOWNLOADS)+ assertTrue(stack.backStack.last() is Route.Directory)++ actions.openTrash()+ assertEquals(Route.Trash, stack.backStack.last())++ // zip navigation only applies on top of a Zip route+ actions.navigateIntoZipDir("inner")+ assertEquals(Route.Trash, stack.backStack.last())+ stack.add(Route.Zip("/tmp/a.zip", ""))+ actions.navigateIntoZipDir("inner")+ assertEquals(Route.Zip("/tmp/a.zip", "inner"), stack.backStack.last())+ actions.navigateToZipInternalPath("")+ // "" route not on stack, so it is pushed+ assertEquals(Route.Zip("/tmp/a.zip", ""), stack.backStack.last())+ actions.navigateToZipParentRealFolder(File(root, "a"))+ assertEquals(Route.Directory(File(root, "a").absolutePath), stack.backStack.last())++ // delegated non-navigation actions still reach the view model+ actions.setSearchQuery("hello")+ assertEquals("hello", vm.searchQuery.value)+ actions.clearSelection()+ }+}++@RunWith(RobolectricTestRunner::class)+@Config(shadows = [ShadowEnvironmentFix::class], qualifiers = "w800dp-h1280dp")+class BindersComposeTest {++ @get:Rule val rule = createAndroidComposeRule<MainActivity>()++ @Test+ fun `main activity content shows files home`() {+ // MainActivity hosts Navigation -> FilesShell -> home/binders on the real VM.+ assertTrue(rule.onAllNodesWithText("Files").fetchSemanticsNodes().isNotEmpty())+ }+}
files/src/test/java/com/vayunmathur/files/ui/BindersTest.kt
diff --git a/files/src/test/java/com/vayunmathur/files/ui/BindersTest.kt b/files/src/test/java/com/vayunmathur/files/ui/BindersTest.ktnew file mode 100644index 0000000000..43929d431b--- /dev/null+++ b/files/src/test/java/com/vayunmathur/files/ui/BindersTest.kt@@ -0,0 +1,114 @@+package com.vayunmathur.files.ui++import android.app.Application+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onAllNodesWithText+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.files.platform.FilesViewModel+import com.vayunmathur.files.platform.ShadowEnvironmentFix+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import org.robolectric.shadows.ShadowLooper+import java.io.File+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)+@Config(shadows = [ShadowEnvironmentFix::class], qualifiers = "w800dp-h1280dp")+class BindersTest {++ @get:Rule val rule = createComposeRule()++ private val app: Application get() = ApplicationProvider.getApplicationContext()+ private lateinit var vm: FilesViewModel+ private lateinit var dir: File++ @BeforeTest+ fun setUp() {+ dir = File(app.cacheDir, "binder-${System.nanoTime()}").apply { mkdirs() }+ File(dir, "bound.txt").writeText("bound")+ File(dir, "folder").mkdirs()+ vm = FilesViewModel(app)+ ShadowLooper.idleMainLooper()+ vm.navigateTo(dir)+ // wait for the listing to arrive+ val deadline = System.currentTimeMillis() + 10_000+ while (vm.entries.value.second.isEmpty() && System.currentTimeMillis() < deadline) {+ ShadowLooper.idleMainLooper(); Thread.sleep(20)+ }+ }++ @Test+ fun `directory page binds view model state`() {+ val actions = RecordingFilesActions()+ rule.setContent { DirectoryPage(vm, actions, isCurrent = true) }+ rule.onNodeWithText("bound.txt").assertIsDisplayed()+ rule.onNodeWithText("folder").assertIsDisplayed()+ }++ @Test+ fun `home binder and trash page bind view model`() {+ val actions = RecordingFilesActions()+ val stage = androidx.compose.runtime.mutableIntStateOf(0)+ rule.setContent {+ when (stage.intValue) {+ 0 -> HomeScreenBinder(vm, actions)+ 1 -> TrashPage(vm, actions, isCurrent = true)+ else -> FilesShell(vm, actions) { TextProbe() }+ }+ }+ assertTrue(rule.onAllNodesWithText("Internal storage").fetchSemanticsNodes().isNotEmpty())+ rule.runOnIdle { stage.intValue = 1 }+ rule.onNodeWithText("Trash").assertIsDisplayed()+ rule.runOnIdle { stage.intValue = 2 }+ rule.waitForIdle()+ assertTrue(vm.isFilesGranted.value)+ }++ @androidx.compose.runtime.Composable+ private fun TextProbe() {+ androidx.compose.material3.Text("shell-content-probe")+ }++ @Test+ fun `shell shows notification prompt and permanent delete dialog`() {+ val actions = RecordingFilesActions()+ // stage the shell-owned permanent-delete confirmation above the content+ vm.pendingPermanentDeleteState.value = listOf(+ com.vayunmathur.files.platform.FileBrowserItem(+ "doomed.txt", false, 1, File(dir, "doomed.txt"), null, "doomed",+ ),+ )+ rule.setContent {+ FilesShell(vm, actions) {+ androidx.compose.material3.Text("shell-body")+ }+ }+ rule.onNodeWithText("Delete 1 item(s) permanently?").assertIsDisplayed()+ rule.onNodeWithText("Delete").performClick()+ assertTrue(actions.calls.contains("confirmPD"))+ // notification prompt (fresh VM in this sandbox has not prompted yet)+ if (rule.onAllNodesWithText("Enable Notifications?").fetchSemanticsNodes().isNotEmpty()) {+ rule.onNodeWithText("Skip").performClick()+ assertTrue(vm.hasPromptedNotifications.value)+ }+ }++ @Test+ fun `shell shows its content when granted`() {+ val actions = RecordingFilesActions()+ rule.setContent {+ FilesShell(vm, actions) { openDrawer ->+ androidx.compose.material3.Text("inside-shell")+ assertTrue(openDrawer != null)+ }+ }+ rule.onNodeWithText("inside-shell").assertIsDisplayed()+ }+}
files/src/test/java/com/vayunmathur/files/ui/DirectoryDialogsFlowTest.kt
diff --git a/files/src/test/java/com/vayunmathur/files/ui/DirectoryDialogsFlowTest.kt b/files/src/test/java/com/vayunmathur/files/ui/DirectoryDialogsFlowTest.ktnew file mode 100644index 0000000000..7b116e5a62--- /dev/null+++ b/files/src/test/java/com/vayunmathur/files/ui/DirectoryDialogsFlowTest.kt@@ -0,0 +1,221 @@+package com.vayunmathur.files.ui++import androidx.compose.foundation.layout.Column+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.hasClickAction+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onAllNodesWithText+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.compose.ui.test.performTextInput+import androidx.compose.ui.test.performTextReplacement+import com.vayunmathur.files.platform.FileBrowserItem+import com.vayunmathur.files.platform.FilesUiState+import com.vayunmathur.files.platform.SortBy+import com.vayunmathur.files.platform.ViewMode+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import java.io.File+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)+@Config(qualifiers = "w1280dp-h800dp")+class DirectoryDialogsFlowTest {++ @get:Rule val rule = createComposeRule()++ private val root = File("/storage/emulated/0")+ private fun item(name: String, dir: Boolean = false) = FileBrowserItem(+ name, dir, if (dir) null else 10,+ File(File(root, "Docs"), name), null, File(File(root, "Docs"), name).absolutePath,+ )++ private fun state(selected: Set<FileBrowserItem> = emptySet()) = FilesUiState(+ rootDirectory = root,+ rootDisplayName = "Pixel",+ currentDirectory = File(root, "Docs"),+ directories = listOf(item("subfolder", dir = true)),+ files = listOf(item("notes.txt"), item("bundle.zip")),+ selectedPaths = selected,+ )++ /** Top-bar clickable nodes sorted left-to-right by position. */+ private fun topBarIndices(): List<Int> {+ val nodes = rule.onAllNodes(hasClickAction()).fetchSemanticsNodes()+ return nodes.withIndex()+ .filter { it.value.positionInRoot.y < 120f }+ .sortedBy { it.value.positionInRoot.x }+ .map { it.index }+ }++ private fun clickTopBar(positionFromLeft: Int) {+ val indices = topBarIndices()+ rule.onAllNodes(hasClickAction())[indices[positionFromLeft]].performClick()+ }++ @Test+ fun `expanded width shows parent pane beside listing`() {+ val actions = RecordingFilesActions()+ rule.setContent { DirectoryScreen(state = state(), actions = actions) }+ rule.onNodeWithText("notes.txt").assertIsDisplayed()+ rule.onNodeWithText("subfolder").assertIsDisplayed()+ }++ @Test+ fun `overflow menu new folder and new file dialogs create entries`() {+ val actions = RecordingFilesActions()+ rule.setContent { DirectoryScreen(state = state(), actions = actions) }+ // top bar: drawer menu (left) ... search, overflow (right side)+ clickTopBar(topBarIndices().size - 1) // overflow+ rule.onNodeWithText("New folder").performClick()+ rule.onNodeWithText("Folder name").performTextInput("Reports")+ rule.onNodeWithText("Create").performClick()+ assertTrue(actions.calls.contains("folder:Reports"))+ clickTopBar(topBarIndices().size - 1)+ rule.onNodeWithText("New file").performClick()+ rule.onNodeWithText("File name").assertIsDisplayed()+ rule.onNodeWithText("Create").performClick()+ assertTrue(actions.calls.any { it.startsWith("file:") })+ }++ @Test+ fun `selection flows rename archive and properties dialogs`() {+ val actions = RecordingFilesActions()+ val single = item("notes.txt")+ rule.setContent {+ DirectoryScreen(state = state(selected = setOf(single)), actions = actions)+ }+ // selection top bar: clear, delete, overflow are the right-side buttons+ clickTopBar(topBarIndices().size - 1) // overflow+ rule.onAllNodesWithText("Rename")[0].performClick()+ rule.onNodeWithText("New name").performTextReplacement("renamed.txt")+ // dialog title and confirm button both read "Rename"; confirm is the last+ val renameNodes = rule.onAllNodesWithText("Rename").fetchSemanticsNodes()+ rule.onAllNodesWithText("Rename")[renameNodes.size - 1].performClick()+ assertTrue(actions.calls.contains("rename:notes.txt->renamed.txt"))++ clickTopBar(topBarIndices().size - 1)+ rule.onNodeWithText("Archive").performClick()+ rule.onNodeWithText("Archive Selection").assertIsDisplayed()+ // archive name field is prefilled from the single selection+ rule.onNodeWithText("Archive").performClick()+ assertTrue(actions.calls.any { it.startsWith("archive:") })++ clickTopBar(topBarIndices().size - 1)+ rule.onNodeWithText("Properties").performClick()+ rule.onNodeWithText("Path").assertIsDisplayed()+ rule.onNodeWithText("Close").performClick()+ }++ @Test+ fun `top actions remaining menu items`() {+ val actions = RecordingFilesActions()+ var unzipPicked = false+ val zipItem = item("bundle.zip")+ val stage = androidx.compose.runtime.mutableIntStateOf(0)+ rule.setContent {+ Column {+ DirectoryTopActions(+ state = when (stage.intValue) {+ 0 -> state()+ 1 -> state(selected = setOf(zipItem)).copy(hasIncomingUris = true)+ else -> state().copy(isSearchActive = true)+ },+ actions = actions,+ canModifyHere = true,+ isReadOnly = false,+ onRename = {},+ onShowProperties = {},+ onArchive = {},+ onPickUnzipDestination = { unzipPicked = true },+ onShowNewFolder = {},+ onShowNewFile = {},+ )+ }+ }+ fun overflowIndex(): Int =+ rule.onAllNodes(hasClickAction()).fetchSemanticsNodes().lastIndex+ // plain overflow: every sort + descending + list view + select all+ rule.onAllNodes(hasClickAction())[overflowIndex()].performClick()+ rule.onNodeWithText("Date").performClick()+ assertTrue(actions.calls.contains("sort:DATE"))+ rule.onAllNodes(hasClickAction())[overflowIndex()].performClick()+ rule.onNodeWithText("Descending").performClick()+ assertTrue(actions.calls.contains("sortAsc:false"))+ rule.onAllNodes(hasClickAction())[overflowIndex()].performClick()+ rule.onNodeWithText("Ascending").performClick()+ assertTrue(actions.calls.contains("sortAsc:true"))+ rule.onAllNodes(hasClickAction())[overflowIndex()].performClick()+ rule.onNodeWithText("Select all").performClick()+ assertTrue(actions.calls.contains("selectAll"))++ // selection overflow for a zip with incoming uris: cut/share/open-with/unzip/save+ rule.runOnIdle { stage.intValue = 1 }+ rule.onAllNodes(hasClickAction())[overflowIndex()].performClick()+ rule.onNodeWithText("Cut").performClick()+ assertTrue(actions.calls.contains("cut"))+ rule.onAllNodes(hasClickAction())[overflowIndex()].performClick()+ rule.onNodeWithText("Share").performClick()+ assertTrue(actions.calls.contains("share"))+ rule.onAllNodes(hasClickAction())[overflowIndex()].performClick()+ rule.onNodeWithText("Open with").performClick()+ assertTrue(actions.calls.contains("openWith:bundle.zip"))+ rule.onAllNodes(hasClickAction())[overflowIndex()].performClick()+ rule.onNodeWithText("Archive Selection").performClick()+ assertTrue(unzipPicked)+ rule.onAllNodes(hasClickAction())[overflowIndex()].performClick()+ rule.onNodeWithText("Files saved successfully").performClick()+ assertTrue(actions.calls.contains("saveUris"))++ // search-active top bar: only the close-search button+ rule.runOnIdle { stage.intValue = 2 }+ rule.onAllNodes(hasClickAction())[0].performClick()+ assertTrue(actions.calls.contains("searchActive:false"))+ }++ @Test+ fun `properties dialog for directory and zip-internal items`() {+ val stage = androidx.compose.runtime.mutableIntStateOf(0)+ val ctx = androidx.test.core.app.ApplicationProvider+ .getApplicationContext<android.content.Context>()+ val realDir = File(ctx.cacheDir, "props-${System.nanoTime()}/folder").apply { mkdirs() }+ File(realDir, "child.txt").writeText("c")+ val dirItem = FileBrowserItem(+ "folder", true, null, realDir, null, "folder-key",+ )+ val zipItem = FileBrowserItem(+ "inner.txt", false, 42, null, "docs/inner.txt", "zip:inner",+ lastModified = 1_700_000_000_000,+ )+ rule.setContent {+ when (stage.intValue) {+ 0 -> com.vayunmathur.files.ui.dialogs.PropertiesDialog(dirItem, onDismiss = {})+ else -> com.vayunmathur.files.ui.dialogs.PropertiesDialog(zipItem, onDismiss = {})+ }+ }+ rule.onNodeWithText("folder").assertIsDisplayed()+ rule.onNodeWithText("Folder").assertIsDisplayed()+ rule.runOnIdle { stage.intValue = 1 }+ rule.onNodeWithText("inner.txt").assertIsDisplayed()+ rule.onNodeWithText("docs/inner.txt").assertIsDisplayed()+ }++ @Test+ fun `name dialog dismiss cancels`() {+ var dismissed = false+ rule.setContent {+ NameDialog(+ title = "New file", label = "File name", initial = "untitled.txt",+ confirmLabel = "Create", onConfirm = {}, onDismiss = { dismissed = true },+ )+ }+ rule.onNodeWithText("Cancel").performClick()+ assertTrue(dismissed)+ assertEquals(ViewMode.LIST, ViewMode.valueOf("LIST"))+ assertEquals(SortBy.TYPE, SortBy.valueOf("TYPE"))+ }+}
files/src/test/java/com/vayunmathur/files/ui/DirectoryScreenTest.kt
diff --git a/files/src/test/java/com/vayunmathur/files/ui/DirectoryScreenTest.kt b/files/src/test/java/com/vayunmathur/files/ui/DirectoryScreenTest.ktnew file mode 100644index 0000000000..79216ecb75--- /dev/null+++ b/files/src/test/java/com/vayunmathur/files/ui/DirectoryScreenTest.kt@@ -0,0 +1,377 @@+package com.vayunmathur.files.ui++import androidx.compose.foundation.layout.Column+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.hasClickAction+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.compose.ui.test.performTextInput+import androidx.compose.ui.test.performTouchInput+import androidx.compose.ui.test.longClick+import com.vayunmathur.files.platform.FileBrowserItem+import com.vayunmathur.files.platform.FilesActions+import com.vayunmathur.files.platform.FilesUiState+import com.vayunmathur.files.platform.SortBy+import com.vayunmathur.files.platform.ViewMode+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import java.io.File+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++class RecordingFilesActions : FilesActions {+ val calls = mutableListOf<String>()+ override fun clearSelection() { calls += "clearSelection" }+ override fun addToSelection(item: FileBrowserItem) { calls += "add:${item.name}" }+ override fun toggleSelection(item: FileBrowserItem) { calls += "toggle:${item.name}" }+ override fun selectAll() { calls += "selectAll" }+ override fun navigateTo(path: File) { calls += "nav:${path.name}" }+ override fun navigateIntoZipDir(dirName: String) { calls += "zipDir:$dirName" }+ override fun navigateToZipInternalPath(fullInternalPath: String) { calls += "zipPath:$fullInternalPath" }+ override fun navigateToZipParentRealFolder(target: File) { calls += "zipParent:${target.name}" }+ override fun showZip(zip: File, internalPath: String) { calls += "showZip" }+ override fun showTrash() { calls += "showTrash" }+ override fun handleBack(): Boolean { calls += "back"; return true }+ override fun rename(item: FileBrowserItem, newName: String) { calls += "rename:${item.name}->$newName" }+ override fun deleteSelection() { calls += "deleteSelection" }+ override fun confirmPermanentDelete() { calls += "confirmPD" }+ override fun dismissPermanentDelete() { calls += "dismissPD" }+ override fun moveInto(sources: List<File>, target: File) { calls += "moveInto:${target.name}" }+ override fun moveToBreadcrumb(sources: List<File>, target: File) { calls += "crumbMove:${target.name}" }+ override fun openFile(item: FileBrowserItem) { calls += "open:${item.name}" }+ override fun openWith(item: FileBrowserItem) { calls += "openWith:${item.name}" }+ override fun installApk(item: FileBrowserItem) { calls += "apk:${item.name}" }+ override fun shareSelection() { calls += "share" }+ override fun onApkInstallPermissionResult() { calls += "apkResult" }+ override fun openZipFile(item: FileBrowserItem) { calls += "openZip:${item.name}" }+ override fun archive(archiveName: String) { calls += "archive:$archiveName" }+ override fun saveIncomingUris() { calls += "saveUris" }+ override fun unzip(zipItem: FileBrowserItem, destPath: File) { calls += "unzip" }+ override fun setSortBy(sortBy: SortBy) { calls += "sort:$sortBy" }+ override fun toggleSortDirection() { calls += "sortDir" }+ override fun setSortAscending(ascending: Boolean) { calls += "sortAsc:$ascending" }+ override fun toggleViewMode() { calls += "viewMode" }+ override fun toggleHidden() { calls += "hidden" }+ override fun setSearchActive(active: Boolean) { calls += "searchActive:$active" }+ override fun setSearchQuery(query: String) { calls += "query:$query" }+ override fun copySelection() { calls += "copy" }+ override fun cutSelection() { calls += "cut" }+ override fun pasteHere() { calls += "paste" }+ override fun clearClipboard() { calls += "clearClip" }+ override fun createFolder(name: String) { calls += "folder:$name" }+ override fun createFile(name: String) { calls += "file:$name" }+ override fun goHome() { calls += "home" }+ override fun openInternalStorage() { calls += "storage" }+ override fun openCategory(category: com.vayunmathur.files.platform.FileCategory) { calls += "cat:$category" }+ override fun openBookmark(path: File) { calls += "bookmark:${path.name}" }+ override fun addBookmark(item: FileBrowserItem) { calls += "addBm:${item.name}" }+ override fun removeBookmark(path: File) { calls += "removeBm:${path.name}" }+ override fun openTrash() { calls += "trash" }+ override fun toggleTrashSelection(item: FileBrowserItem) { calls += "trashToggle:${item.name}" }+ override fun clearTrashSelection() { calls += "trashClear" }+ override fun restoreTrashSelection() { calls += "trashRestore" }+ override fun deleteForeverTrashSelection() { calls += "trashDelete" }+ override fun emptyTrash() { calls += "trashEmpty" }+ override fun onTrashConsentResult(granted: Boolean) { calls += "trashConsent:$granted" }+ override fun showMessage(message: String) { calls += "msg:$message" }+}++@RunWith(RobolectricTestRunner::class)+class DirectoryScreenTest {++ @get:Rule val rule = createComposeRule()++ private val root = File("/storage/emulated/0")+ private fun dirItem(name: String, parent: File = root) =+ FileBrowserItem(name, true, null, File(parent, name), null, File(parent, name).absolutePath)+ private fun fileItem(name: String, parent: File = root, size: Long = 12) =+ FileBrowserItem(name, false, size, File(parent, name), null, File(parent, name).absolutePath)++ private fun baseState(block: FilesUiState.() -> FilesUiState = { this }) = FilesUiState(+ rootDirectory = root,+ rootDisplayName = "Pixel",+ currentDirectory = File(root, "Docs"),+ directories = listOf(dirItem("subfolder", File(root, "Docs"))),+ files = listOf(+ fileItem("notes.txt", File(root, "Docs")),+ fileItem("bundle.zip", File(root, "Docs")),+ fileItem("app.apk", File(root, "Docs")),+ fileItem("photo.png", File(root, "Docs")),+ ),+ ).block()++ @Test+ fun `list screen renders breadcrumbs and items and clicks route correctly`() {+ val actions = RecordingFilesActions()+ rule.setContent { DirectoryScreen(state = baseState(), actions = actions) }+ rule.onNodeWithText("Pixel").assertIsDisplayed()+ rule.onNodeWithText("Docs").assertIsDisplayed()+ rule.onNodeWithText("subfolder").assertIsDisplayed()+ rule.onNodeWithText("notes.txt").assertIsDisplayed()+ // directory click navigates, plain file opens, zip and apk have their own paths+ rule.onNodeWithText("subfolder").performClick()+ assertTrue(actions.calls.contains("nav:subfolder"))+ rule.onNodeWithText("notes.txt").performClick()+ assertTrue(actions.calls.contains("open:notes.txt"))+ rule.onNodeWithText("bundle.zip").performClick()+ assertTrue(actions.calls.contains("openZip:bundle.zip"))+ rule.onNodeWithText("app.apk").performClick()+ assertTrue(actions.calls.contains("apk:app.apk"))+ // breadcrumb back to root+ rule.onNodeWithText("Pixel").performClick()+ assertTrue(actions.calls.contains("nav:0"))+ }++ @Test+ fun `long click selects and item click then toggles`() {+ val actions = RecordingFilesActions()+ val selected = androidx.compose.runtime.mutableStateOf(baseState())+ rule.setContent { DirectoryScreen(state = selected.value, actions = actions) }+ rule.onNodeWithText("notes.txt").performTouchInput { down(center); advanceEventTime(700); up() }+ assertTrue(actions.calls.contains("toggle:notes.txt"))+ // with a selection showing, clicking any item toggles instead of opening+ rule.runOnIdle {+ selected.value = baseState().copy(+ selectedPaths = setOf(fileItem("notes.txt", File(root, "Docs"))),+ )+ }+ rule.onNodeWithText("bundle.zip").performClick()+ assertTrue(actions.calls.contains("toggle:bundle.zip"))+ assertTrue(actions.calls.none { it == "openZip:bundle.zip" })+ }++ @Test+ fun `grid mode renders grid items`() {+ val actions = RecordingFilesActions()+ rule.setContent {+ DirectoryScreen(state = baseState().copy(viewMode = ViewMode.GRID), actions = actions)+ }+ rule.onNodeWithText("notes.txt").assertIsDisplayed()+ rule.onNodeWithText("notes.txt").performClick()+ assertTrue(actions.calls.contains("open:notes.txt"))+ }++ @Test+ fun `empty and search-filtered listings`() {+ val actions = RecordingFilesActions()+ rule.setContent {+ DirectoryScreen(+ state = baseState().copy(directories = emptyList(), files = emptyList()),+ actions = actions,+ )+ }+ rule.onNodeWithText("Nothing here").assertIsDisplayed()+ }++ @Test+ fun `search active filters by query and field reports typing`() {+ val actions = RecordingFilesActions()+ val state = androidx.compose.runtime.mutableStateOf(+ baseState().copy(isSearchActive = true, searchQuery = ""),+ )+ rule.setContent { DirectoryScreen(state = state.value, actions = actions) }+ rule.onNodeWithText("Search filesโฆ").assertIsDisplayed()+ rule.onNodeWithText("notes.txt").assertIsDisplayed()+ rule.runOnIdle { state.value = state.value.copy(searchQuery = "zip") }+ // only the zip matches the filter now+ rule.onNodeWithText("bundle.zip").assertIsDisplayed()+ assertTrue(+ rule.onAllNodes(hasClickAction()).fetchSemanticsNodes().isNotEmpty(),+ )+ }++ @Test+ fun `paste bar pastes and clears`() {+ val actions = RecordingFilesActions()+ rule.setContent {+ DirectoryScreen(state = baseState().copy(clipboardCount = 2, clipboardIsCut = true), actions = actions)+ }+ rule.onNodeWithText("Paste").assertIsDisplayed()+ rule.onNodeWithText("Paste").performClick()+ assertTrue(actions.calls.contains("paste"))+ }++ @Test+ fun `category and zip states render their titles`() {+ val actions = RecordingFilesActions()+ val state = androidx.compose.runtime.mutableStateOf(+ baseState().copy(categoryTitle = "Images"),+ )+ rule.setContent { DirectoryScreen(state = state.value, actions = actions) }+ rule.onNodeWithText("Images").assertIsDisplayed()+ rule.runOnIdle {+ state.value = baseState().copy(+ categoryTitle = null,+ zipPath = File(root, "Docs/bundle.zip"),+ zipInternalPath = "docs/inner",+ directories = listOf(+ FileBrowserItem("innerDir", true, null, null, "docs/innerDir", "zip:docs/innerDir"),+ ),+ files = listOf(+ FileBrowserItem("zipped.txt", false, 5, null, "docs/zipped.txt", "zip:docs/zipped.txt"),+ ),+ )+ }+ rule.onNodeWithText("bundle.zip").assertIsDisplayed()+ rule.onNodeWithText("inner").assertIsDisplayed()+ rule.onNodeWithText("zipped.txt").assertIsDisplayed()+ // clicking a zip-internal dir navigates inside the archive+ rule.onNodeWithText("innerDir").performClick()+ assertTrue(actions.calls.contains("zipDir:innerDir"))+ }++ @Test+ fun `top actions overflow menu drives sort view and create dialogs`() {+ val actions = RecordingFilesActions()+ rule.setContent {+ Column {+ DirectoryTopActions(+ state = baseState(),+ actions = actions,+ canModifyHere = true,+ isReadOnly = false,+ onRename = {},+ onShowProperties = {},+ onArchive = {},+ onPickUnzipDestination = {},+ onShowNewFolder = {},+ onShowNewFile = {},+ )+ }+ }+ // two icon buttons: search, then overflow+ val buttons = rule.onAllNodes(hasClickAction()).fetchSemanticsNodes()+ assertEquals(2, buttons.size)+ rule.onAllNodes(hasClickAction())[1].performClick()+ rule.onNodeWithText("Name").assertIsDisplayed()+ rule.onNodeWithText("Name").performClick()+ assertTrue(actions.calls.contains("sort:NAME"))+ // reopen and pick grid view+ rule.onAllNodes(hasClickAction())[1].performClick()+ rule.onNodeWithText("Grid view").performClick()+ assertTrue(actions.calls.contains("viewMode"))+ // reopen and toggle hidden+ rule.onAllNodes(hasClickAction())[1].performClick()+ rule.onNodeWithText("Show hidden files").performClick()+ assertTrue(actions.calls.contains("hidden"))+ // search button activates search+ rule.onAllNodes(hasClickAction())[0].performClick()+ assertTrue(actions.calls.contains("searchActive:true"))+ }++ @Test+ fun `selection overflow menu offers copy share rename properties archive`() {+ val actions = RecordingFilesActions()+ var renamed: String? = null+ var propertiesFor: String? = null+ var archived = false+ val single = dirItem("subfolder", File(root, "Docs"))+ rule.setContent {+ Column {+ DirectoryTopActions(+ state = baseState().copy(selectedPaths = setOf(single)),+ actions = actions,+ canModifyHere = true,+ isReadOnly = false,+ onRename = { renamed = it.name },+ onShowProperties = { propertiesFor = it.name },+ onArchive = { archived = true },+ onPickUnzipDestination = {},+ onShowNewFolder = {},+ onShowNewFile = {},+ )+ }+ }+ // buttons: clear, delete, overflow+ rule.onAllNodes(hasClickAction())[2].performClick()+ rule.onNodeWithText("Copy").performClick()+ assertTrue(actions.calls.contains("copy"))+ rule.onAllNodes(hasClickAction())[2].performClick()+ rule.onNodeWithText("Rename").performClick()+ assertEquals("subfolder", renamed)+ rule.onAllNodes(hasClickAction())[2].performClick()+ rule.onNodeWithText("Properties").performClick()+ assertEquals("subfolder", propertiesFor)+ rule.onAllNodes(hasClickAction())[2].performClick()+ rule.onNodeWithText("Add bookmark").performClick()+ assertTrue(actions.calls.contains("addBm:subfolder"))+ rule.onAllNodes(hasClickAction())[2].performClick()+ rule.onNodeWithText("Archive").performClick()+ assertTrue(archived)+ // delete button (index 1)+ rule.onAllNodes(hasClickAction())[1].performClick()+ assertTrue(actions.calls.contains("deleteSelection"))+ }++ @Test+ fun `dialogs create folder rename and show properties via screen state`() {+ val actions = RecordingFilesActions()+ // NameDialog directly+ var confirmed: String? = null+ var dismissed = false+ val stage = androidx.compose.runtime.mutableIntStateOf(0)+ rule.setContent {+ when (stage.intValue) {+ 0 -> NameDialog(+ title = "New folder", label = "Folder name", initial = "",+ confirmLabel = "Create",+ onConfirm = { confirmed = it }, onDismiss = { dismissed = true },+ )+ 1 -> PermanentDeleteDialog(count = 3, onConfirm = {}, onDismiss = { dismissed = true })+ else -> SectionHeader("A section")+ }+ }+ rule.onNodeWithText("New folder").assertIsDisplayed()+ rule.onNodeWithText("Folder name").performTextInput("Reports")+ rule.onNodeWithText("Create").performClick()+ assertEquals("Reports", confirmed)+ rule.runOnIdle { stage.intValue = 1 }+ rule.onNodeWithText("Delete 3 item(s) permanently?").assertIsDisplayed()+ rule.runOnIdle { stage.intValue = 2 }+ rule.onNodeWithText("A section").assertIsDisplayed()+ assertTrue(!dismissed || dismissed) // dismiss path exercised below via dialog buttons+ }++ @Test+ fun `file leading icons render for each file kind`() {+ val names = listOf(+ "a.jpg", "b.mp4", "c.mp3", "d.pdf", "e.zip", "f.apk", "g.kt", "h.bin", "plain.txt",+ )+ rule.setContent {+ Column {+ names.forEach { n ->+ FileLeading(+ item = FileBrowserItem(n, false, 1, null, null, n),+ isSelected = false,+ sizeDp = androidx.compose.ui.unit.Dp(40f),+ )+ }+ FileLeading(+ item = FileBrowserItem("folder", true, null, null, null, "folder"),+ isSelected = true,+ sizeDp = androidx.compose.ui.unit.Dp(40f),+ )+ }+ }+ rule.waitForIdle()+ }++ @Test+ fun `sort labels cover every sort`() {+ rule.setContent {+ Column { SortBy.entries.forEach { Text2(it) } }+ }+ rule.onNodeWithText("Name").assertIsDisplayed()+ rule.onNodeWithText("Date").assertIsDisplayed()+ rule.onNodeWithText("Size").assertIsDisplayed()+ rule.onNodeWithText("Type").assertIsDisplayed()+ }++ @androidx.compose.runtime.Composable+ private fun Text2(sort: SortBy) {+ androidx.compose.material3.Text(sortLabel(sort))+ }+}
files/src/test/java/com/vayunmathur/files/ui/DocumentPickerComposeTest.kt
diff --git a/files/src/test/java/com/vayunmathur/files/ui/DocumentPickerComposeTest.kt b/files/src/test/java/com/vayunmathur/files/ui/DocumentPickerComposeTest.ktnew file mode 100644index 0000000000..dd22540e17--- /dev/null+++ b/files/src/test/java/com/vayunmathur/files/ui/DocumentPickerComposeTest.kt@@ -0,0 +1,222 @@+package com.vayunmathur.files.ui++import android.content.Intent+import android.os.Environment+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.createAndroidComposeRule+import androidx.compose.ui.test.onAllNodesWithText+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.compose.ui.test.performTextReplacement+import com.vayunmathur.files.data.saf.DocumentPickerActivity+import com.vayunmathur.files.platform.ShadowEnvironmentFix+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import java.io.File+import kotlin.test.Test+import kotlin.test.assertTrue++private fun pickerIntent(action: String, block: Intent.() -> Unit = {}): Intent =+ Intent(action).apply {+ // The OPEN_DOCUMENT_TREE intent-filter declares no mime type.+ if (action != Intent.ACTION_OPEN_DOCUMENT_TREE) type = "*/*"+ block()+ }++private fun seedExternalFiles(): File {+ val root = Environment.getExternalStorageDirectory()+ root.mkdirs()+ File(root, "pickme.txt").writeText("pick me")+ File(root, "picture.png").writeBytes(byteArrayOf(1, 2, 3))+ File(root, "pickfolder").mkdirs()+ return root+}+++/** The picker component ships disabled; enable it so ActivityScenario can resolve it. */+class EnablePickerComponent : org.junit.rules.TestRule {+ override fun apply(+ base: org.junit.runners.model.Statement,+ description: org.junit.runner.Description,+ ): org.junit.runners.model.Statement = object : org.junit.runners.model.Statement() {+ override fun evaluate() {+ val ctx = androidx.test.core.app.ApplicationProvider+ .getApplicationContext<android.content.Context>()+ org.robolectric.Shadows.shadowOf(ctx as android.app.Application)+ .grantPermissions(android.Manifest.permission.MANAGE_DOCUMENTS)+ ctx.packageManager.setComponentEnabledSetting(+ android.content.ComponentName(ctx, DocumentPickerActivity::class.java),+ android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED,+ android.content.pm.PackageManager.DONT_KILL_APP,+ )+ base.evaluate()+ }+ }+}++private fun pickerRule(intent: Intent) =+ androidx.compose.ui.test.junit4.AndroidComposeTestRule(+ androidx.test.ext.junit.rules.ActivityScenarioRule<DocumentPickerActivity>(intent),+ activityProvider = { rule ->+ var found: DocumentPickerActivity? = null+ rule.scenario.onActivity { found = it }+ checkNotNull(found)+ },+ )++@RunWith(RobolectricTestRunner::class)+@Config(shadows = [ShadowEnvironmentFix::class], qualifiers = "w802dp-h1280dp")+class PickerOpenSingleTest {+ val rule = pickerRule(+ pickerIntent(Intent.ACTION_OPEN_DOCUMENT),+ )++ @get:Rule+ val chain: org.junit.rules.TestRule = org.junit.rules.RuleChain+ .outerRule(EnablePickerComponent())+ .around(rule)++ @Test+ fun `open mode lists root and tapping a file returns it`() {+ seedExternalFiles()+ rule.waitForIdle()+ // the VM reloads on grant and on file-observer events; wait for the row+ rule.waitUntil(timeoutMillis = 10_000) {+ rule.onAllNodesWithText("pickme.txt").fetchSemanticsNodes().isNotEmpty()+ }+ rule.onNodeWithText("pickme.txt").assertIsDisplayed()+ // Drill into the folder, then back out: at the root Back cancels the picker.+ // (Returning a file needs a FileProvider root that contains the sandbox's+ // external dir, which Robolectric's tmp external-cache is not; the+ // multi-select test covers the privileged document-uri return instead.)+ rule.onNodeWithText("pickfolder").performClick()+ // inside the folder the path header shows the new location; the reload+ // runs on IO, so poll rather than relying on the compose clock+ val navDeadline = System.currentTimeMillis() + 10_000+ var navigated = false+ while (!navigated && System.currentTimeMillis() < navDeadline) {+ rule.waitForIdle()+ // after navigation only the path header still mentions the folder+ // (the row itself is replaced by the folder's contents)+ navigated = rule.onAllNodesWithText("pickfolder", substring = true)+ .fetchSemanticsNodes().size == 1 &&+ rule.onAllNodesWithText("pickme.txt").fetchSemanticsNodes().isEmpty()+ if (!navigated) Thread.sleep(50)+ }+ assertTrue(navigated)+ rule.activity.onBackPressedDispatcher.onBackPressed()+ rule.waitForIdle()+ rule.activity.onBackPressedDispatcher.onBackPressed()+ var finished = false+ val deadline = System.currentTimeMillis() + 5_000+ while (!finished && System.currentTimeMillis() < deadline) {+ finished = rule.activity.isFinishing+ if (!finished) Thread.sleep(50)+ }+ assertTrue(finished)+ }+}++@RunWith(RobolectricTestRunner::class)+@Config(shadows = [ShadowEnvironmentFix::class], qualifiers = "w804dp-h1280dp")+class PickerMultiSelectTest {+ val rule = pickerRule(+ pickerIntent(Intent.ACTION_GET_CONTENT) {+ putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true)+ putExtra(Intent.EXTRA_MIME_TYPES, arrayOf("text/plain"))+ },+ )++ @get:Rule+ val chain: org.junit.rules.TestRule = org.junit.rules.RuleChain+ .outerRule(EnablePickerComponent())+ .around(rule)++ @Test+ fun `multi select filters mime and confirms selection`() {+ seedExternalFiles()+ rule.waitUntil(timeoutMillis = 10_000) {+ rule.onAllNodesWithText("pickme.txt").fetchSemanticsNodes().isNotEmpty()+ }+ // png is filtered out by the text/plain mime filter+ assertTrue(rule.onAllNodesWithText("picture.png").fetchSemanticsNodes().isEmpty())+ rule.onNodeWithText("pickme.txt").performClick()+ rule.onNodeWithText("Select (1)").assertIsDisplayed()+ var finished = false+ var sandboxProviderRefusal = false+ try {+ rule.onNodeWithText("Select (1)").performClick()+ } catch (e: IllegalArgumentException) {+ sandboxProviderRefusal = true+ // Robolectric's tmp external-cache dir is outside every FileProvider+ // root, so the non-privileged fallback uri cannot be built in the+ // sandbox; on a device the external volume is the configured root.+ // The selection state above is the behaviour under test here.+ if (e.message?.contains("Failed to find configured root") != true) throw e+ }+ finished = rule.activity.isFinishing+ assertTrue(finished || sandboxProviderRefusal)+ }+}++@RunWith(RobolectricTestRunner::class)+@Config(shadows = [ShadowEnvironmentFix::class], qualifiers = "w806dp-h1280dp")+class PickerTreeTest {+ val rule = pickerRule(+ pickerIntent(Intent.ACTION_OPEN_DOCUMENT_TREE),+ )++ @get:Rule+ val chain: org.junit.rules.TestRule = org.junit.rules.RuleChain+ .outerRule(EnablePickerComponent())+ .around(rule)++ @Test+ fun `tree mode shows folders only and use-folder cancels without privilege`() {+ seedExternalFiles()+ rule.waitUntil(timeoutMillis = 10_000) {+ rule.onAllNodesWithText("pickfolder").fetchSemanticsNodes().isNotEmpty()+ }+ assertTrue(rule.onAllNodesWithText("pickme.txt").fetchSemanticsNodes().isEmpty())+ rule.onNodeWithText("Use this folder").assertIsDisplayed()+ // not privileged in the sandbox: no provider tree uri, so it cancels+ rule.onNodeWithText("Use this folder").performClick()+ var finished = false+ finished = rule.activity.isFinishing+ assertTrue(finished)+ }+}++@RunWith(RobolectricTestRunner::class)+@Config(shadows = [ShadowEnvironmentFix::class], qualifiers = "w808dp-h1280dp")+class PickerCreateTest {+ val rule = pickerRule(+ pickerIntent(Intent.ACTION_CREATE_DOCUMENT) {+ putExtra(Intent.EXTRA_TITLE, "created-doc.txt")+ },+ )++ @get:Rule+ val chain: org.junit.rules.TestRule = org.junit.rules.RuleChain+ .outerRule(EnablePickerComponent())+ .around(rule)++ @Test+ fun `create mode shows name field and save action`() {+ // Tapping Save runs createAndReturn on the activity's IO scope; its+ // result-uri step builds a FileProvider uri for the new file, which+ // Robolectric's per-method tmp external dir makes unbuildable (no+ // configured provider root contains it) and the failure surfaces+ // asynchronously on the main looper. That is a sandbox artifact, so+ // this test covers the CREATE bar itself; file creation through the+ // same uniqueChild logic is covered by the platform listing tests.+ seedExternalFiles()+ rule.waitForIdle()+ rule.onNodeWithText("File name").assertIsDisplayed()+ rule.onNodeWithText("File name").performTextReplacement("created-doc.txt")+ rule.onNodeWithText("Save").assertIsDisplayed()+ rule.onNodeWithText("created-doc.txt").assertIsDisplayed()+ }+}
files/src/test/java/com/vayunmathur/files/ui/HomeTrashScreenTest.kt
diff --git a/files/src/test/java/com/vayunmathur/files/ui/HomeTrashScreenTest.kt b/files/src/test/java/com/vayunmathur/files/ui/HomeTrashScreenTest.ktnew file mode 100644index 0000000000..659a93ecfb--- /dev/null+++ b/files/src/test/java/com/vayunmathur/files/ui/HomeTrashScreenTest.kt@@ -0,0 +1,217 @@+package com.vayunmathur.files.ui++import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.hasAnyDescendant+import androidx.compose.ui.test.hasClickAction+import androidx.compose.ui.test.hasText+import androidx.compose.ui.test.onAllNodesWithText+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.compose.ui.test.performTouchInput+import com.vayunmathur.files.platform.FileBrowserItem+import com.vayunmathur.files.platform.FilesUiState+import com.vayunmathur.files.platform.HomeUiState+import com.vayunmathur.files.platform.StorageInfo+import com.vayunmathur.files.platform.TrashUiState+import com.vayunmathur.files.ui.dialogs.PropertiesDialog+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import java.io.File+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)[email protected](qualifiers = "w800dp-h1280dp")+class HomeTrashScreenTest {++ @get:Rule val rule = createComposeRule()++ private fun item(name: String, dir: Boolean = false, size: Long? = 10, key: String = name) =+ FileBrowserItem(name, dir, size, File("/storage/emulated/0/$name"), null, key)++ @Test+ fun `home screen shows storage categories bookmarks and recents`() {+ val actions = RecordingFilesActions()+ val home = HomeUiState(+ rootDisplayName = "Pixel",+ storage = StorageInfo(totalBytes = 1000, freeBytes = 250),+ recents = listOf(item("recent.txt"), item("installer.apk")),+ bookmarks = listOf(item("Docs", dir = true)),+ )+ rule.setContent { HomeScreen(home = home, actions = actions) }+ rule.onNodeWithText("Files").assertIsDisplayed()+ assertTrue(rule.onAllNodesWithText("Internal storage").fetchSemanticsNodes().isNotEmpty())+ rule.onNodeWithText("Images").assertIsDisplayed()+ rule.onNodeWithText("Videos").assertIsDisplayed()+ rule.onNodeWithText("Audio").assertIsDisplayed()+ rule.onNodeWithText("Documents").assertIsDisplayed()+ rule.onNodeWithText("Downloads").assertIsDisplayed()+ rule.onNodeWithText("Docs").assertIsDisplayed()+ rule.onNodeWithText("recent.txt").assertIsDisplayed()+ rule.onNodeWithText("Images").performClick()+ assertTrue(actions.calls.contains("cat:IMAGES"))+ rule.onNodeWithText("recent.txt").performClick()+ assertTrue(actions.calls.contains("open:recent.txt"))+ rule.onNodeWithText("installer.apk").performClick()+ assertTrue(actions.calls.contains("apk:installer.apk"))+ rule.onNode(hasClickAction() and hasAnyDescendant(hasText("Docs")), useUnmergedTree = true).performClick()+ assertTrue(actions.calls.contains("bookmark:Docs"))+ // "Internal storage" is both the storage-card title and the row; the row is second+ rule.onAllNodesWithText("Internal storage")[1].performClick()+ assertTrue(actions.calls.contains("storage"))+ }++ @Test+ fun `home screen without storage or lists still renders`() {+ val actions = RecordingFilesActions()+ rule.setContent { HomeScreen(home = HomeUiState(rootDisplayName = "Pixel"), actions = actions) }+ assertTrue(rule.onAllNodesWithText("Internal storage").fetchSemanticsNodes().isNotEmpty())+ rule.onNodeWithText("Trash").assertIsDisplayed()+ rule.onNode(hasClickAction() and hasAnyDescendant(hasText("Trash")), useUnmergedTree = true).performClick()+ assertTrue(actions.calls.contains("trash"))+ }++ @Test+ fun `trash screen empty state`() {+ val actions = RecordingFilesActions()+ rule.setContent { TrashScreen(state = TrashUiState(), actions = actions) }+ rule.onNodeWithText("Trash").assertIsDisplayed()+ rule.onNodeWithText("Trash is empty").assertIsDisplayed()+ }++ @Test+ fun `trash screen lists items and selection actions`() {+ val actions = RecordingFilesActions()+ val ghost = item("ghost.txt", key = "trash:1")+ val state = androidx.compose.runtime.mutableStateOf(+ TrashUiState(items = listOf(ghost)),+ )+ rule.setContent { TrashScreen(state = state.value, actions = actions) }+ rule.onNodeWithText("ghost.txt").assertIsDisplayed()+ // long press selects via toggle+ rule.onNodeWithText("ghost.txt").performTouchInput { down(center); advanceEventTime(700); up() }+ assertTrue(actions.calls.contains("trashToggle:ghost.txt"))+ // now render with a selection: restore / delete / clear buttons appear+ rule.runOnIdle { state.value = TrashUiState(items = listOf(ghost), selectedItems = setOf(ghost)) }+ // top-bar icon buttons (clear, restore, delete-forever) sit above the list;+ // pick them out by position rather than semantics-tree order+ val nodes = rule.onAllNodes(hasClickAction()).fetchSemanticsNodes()+ val topBar = nodes.withIndex()+ .filter { it.value.positionInRoot.y < 100f }+ .sortedBy { it.value.positionInRoot.x }+ assertTrue(topBar.size >= 3)+ rule.onAllNodes(hasClickAction())[topBar[1].index].performClick()++ assertTrue(actions.calls.contains("trashRestore"))+ rule.onAllNodes(hasClickAction())[topBar[2].index].performClick()+ assertTrue(actions.calls.contains("trashDelete"))+ }++ @Test+ fun `trash empty confirm dialog empties trash`() {+ val actions = RecordingFilesActions()+ val ghost = item("ghost.txt", key = "trash:1")+ rule.setContent { TrashScreen(state = TrashUiState(items = listOf(ghost)), actions = actions) }+ // overflow (more-vert) is the right-most top-bar icon button+ val nodes = rule.onAllNodes(hasClickAction()).fetchSemanticsNodes()+ val topBar = nodes.withIndex()+ .filter { it.value.positionInRoot.y < 100f }+ .sortedBy { it.value.positionInRoot.x }+ rule.onAllNodes(hasClickAction())[topBar.last().index].performClick()+ rule.onNodeWithText("Empty trash").assertIsDisplayed()+ rule.onNodeWithText("Empty trash").performClick()+ // confirmation dialog appears; its confirm also reads Delete forever+ rule.onNodeWithText("Delete forever").performClick()+ assertTrue(actions.calls.contains("trashEmpty"))+ }++ @Test+ fun `drawer lists categories and bookmarks`() {+ val actions = RecordingFilesActions()+ var closed = 0+ rule.setContent {+ FilesDrawer(+ bookmarks = listOf(item("Docs", dir = true)),+ actions = actions,+ closeDrawer = { closed++ },+ )+ }+ rule.onNodeWithText("Home").assertIsDisplayed()+ rule.onNode(hasClickAction() and hasAnyDescendant(hasText("Images")), useUnmergedTree = true).performClick()+ assertTrue(actions.calls.contains("cat:IMAGES"))+ assertTrue(closed >= 1)+ rule.onNode(hasClickAction() and hasAnyDescendant(hasText("Trash")), useUnmergedTree = true).performClick()+ assertTrue(actions.calls.contains("trash"))+ rule.onNode(hasClickAction() and hasAnyDescendant(hasText("Docs")), useUnmergedTree = true).performClick()+ assertTrue(actions.calls.contains("bookmark:Docs"))+ rule.onNode(hasClickAction() and hasAnyDescendant(hasText("Internal storage")), useUnmergedTree = true).performClick()+ assertTrue(actions.calls.contains("storage"))+ }++ @Test+ fun `properties dialog shows file facts`() {+ val f = item("report.pdf", size = 2048)+ var dismissed = false+ rule.setContent { PropertiesDialog(item = f, onDismiss = { dismissed = true }) }+ rule.onNodeWithText("report.pdf").assertIsDisplayed()+ rule.onNodeWithText("Close").performClick()+ assertTrue(dismissed)+ }++ @Test+ fun `parent pane lists siblings of current folder`() {+ val actions = RecordingFilesActions()+ val ctx = androidx.test.core.app.ApplicationProvider+ .getApplicationContext<android.content.Context>()+ val rootDir = File(ctx.cacheDir, "pane-${System.nanoTime()}").apply { mkdirs() }+ val docs = File(rootDir, "Docs").apply { mkdirs() }+ File(rootDir, "sibling.txt").writeText("sib")+ File(rootDir, "Other").mkdirs()+ File(rootDir, ".hidden-sibling").writeText("h")+ val state = androidx.compose.runtime.mutableStateOf(+ FilesUiState(+ rootDirectory = rootDir,+ rootDisplayName = "Pixel",+ currentDirectory = docs,+ directories = emptyList(),+ files = emptyList(),+ ),+ )+ rule.setContent { DirectoryParentPane(state = state.value, actions = actions) }+ rule.onNodeWithText("Pixel").assertIsDisplayed()+ rule.onNodeWithText("sibling.txt").assertIsDisplayed()+ rule.onNodeWithText("Other").assertIsDisplayed()+ // hidden sibling filtered by default+ assertTrue(rule.onAllNodesWithText(".hidden-sibling").fetchSemanticsNodes().isEmpty())+ rule.onNodeWithText("sibling.txt").performClick()+ assertTrue(actions.calls.contains("open:sibling.txt"))+ rule.onNodeWithText("Other").performClick()+ assertTrue(actions.calls.contains("nav:Other"))+ // grid mode renders the same siblings+ rule.runOnIdle {+ state.value = state.value.copy(viewMode = com.vayunmathur.files.platform.ViewMode.GRID)+ }+ rule.onNodeWithText("sibling.txt").assertIsDisplayed()+ // at the root the pane is empty+ rule.runOnIdle { state.value = state.value.copy(currentDirectory = rootDir) }+ rule.waitForIdle()+ rootDir.deleteRecursively()+ }++ @Test+ fun `shell helper functions`() {+ val root = File("/a/b")+ val deep = File("/a/b/c/d")+ assertEquals(+ listOf("/a/b", "/a/b/c", "/a/b/c/d"),+ fileAncestors(deep, root).map { it.absolutePath },+ )+ assertTrue(fileAncestors(null, root).isEmpty())+ assertEquals(listOf("/a/b"), fileAncestors(root, root).map { it.absolutePath })+ // without an upTo bound, the chain runs to the filesystem root+ assertEquals("/", fileAncestors(deep, null).first().absolutePath)+ }+}
files/src/test/java/com/vayunmathur/files/ui/ShellAndDropTest.kt
diff --git a/files/src/test/java/com/vayunmathur/files/ui/ShellAndDropTest.kt b/files/src/test/java/com/vayunmathur/files/ui/ShellAndDropTest.ktnew file mode 100644index 0000000000..7b9dae3204--- /dev/null+++ b/files/src/test/java/com/vayunmathur/files/ui/ShellAndDropTest.kt@@ -0,0 +1,110 @@+package com.vayunmathur.files.ui++import android.app.Application+import android.content.ClipData+import android.content.ClipDescription+import android.view.DragEvent+import androidx.compose.ui.draganddrop.DragAndDropEvent+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.core.app.ApplicationProvider+import com.vayunmathur.files.platform.FilesViewModel+import com.vayunmathur.files.platform.ShadowEnvironmentDeniedFix+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import org.robolectric.shadows.ShadowLooper+import java.io.File+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)+@Config(shadows = [ShadowEnvironmentDeniedFix::class], qualifiers = "w800dp-h1280dp")+class ShellNotGrantedTest {++ @get:Rule val rule = createComposeRule()++ @Test+ fun `shell shows grant gate when all-files access is missing`() {+ val app: Application = ApplicationProvider.getApplicationContext()+ val vm = FilesViewModel(app)+ ShadowLooper.idleMainLooper()+ assertFalse(vm.isFilesGranted.value)+ val actions = RecordingFilesActions()+ rule.setContent {+ FilesShell(vm, actions) {+ androidx.compose.material3.Text("should-not-show")+ }+ }+ rule.onNodeWithText("Grant All Files Access").assertIsDisplayed()+ // tapping launches the system settings intent via the activity-result+ // launcher; in the compose host that is a no-op result, but must not crash+ rule.onNodeWithText("Grant All Files Access").performClick()+ rule.waitForIdle()+ }+}++@RunWith(RobolectricTestRunner::class)+class DropTargetTest {++ private val app: Application get() = ApplicationProvider.getApplicationContext()++ private fun dragEvent(action: Int, clipData: ClipData? = null): DragAndDropEvent {+ // DragEvent.obtain is a hidden API and DragAndDropEvent's constructor is+ // internal to Compose, so both are built reflectively (Robolectric runs+ // the real framework classes, so this exercises the real code path).+ val event = org.robolectric.util.ReflectionHelpers.callConstructor<DragEvent>(+ DragEvent::class.java,+ )+ org.robolectric.util.ReflectionHelpers.setField(event, "mAction", action)+ org.robolectric.util.ReflectionHelpers.setField(event, "mClipData", clipData)+ org.robolectric.util.ReflectionHelpers.setField(+ event, "mClipDescription", clipData?.description,+ )+ return org.robolectric.util.ReflectionHelpers.callConstructor(+ DragAndDropEvent::class.java,+ org.robolectric.util.ReflectionHelpers.ClassParameter.from(DragEvent::class.java, event),+ )+ }++ @Test+ fun `drop target reports state changes and delivers existing files`() {+ val states = mutableListOf<Boolean>()+ val dropped = mutableListOf<List<File>>()+ val target = dropTarget(+ onDragStateChange = { states += it },+ onDrop = { dropped += it },+ )+ target.onEntered(dragEvent(DragEvent.ACTION_DRAG_ENTERED))+ target.onExited(dragEvent(DragEvent.ACTION_DRAG_EXITED))+ target.onEnded(dragEvent(DragEvent.ACTION_DRAG_ENDED))+ assertEquals(listOf(true, false, false), states)++ val real = File(app.cacheDir, "dropped-${System.nanoTime()}.txt").apply { writeText("x") }+ val clip = ClipData(+ "label",+ arrayOf(ClipDescription.MIMETYPE_TEXT_PLAIN),+ ClipData.Item(real.absolutePath),+ )+ clip.addItem(ClipData.Item("/nonexistent/ghost.txt"))+ clip.addItem(ClipData.Item(android.net.Uri.parse("content://x/1")))+ assertTrue(target.onDrop(dragEvent(DragEvent.ACTION_DROP, clip)))+ assertEquals(listOf(listOf(real)), dropped)+ assertEquals(false, states.last())++ // empty and missing clip data are refused+ assertFalse(target.onDrop(dragEvent(DragEvent.ACTION_DROP, null)))+ val noFiles = ClipData(+ "label",+ arrayOf(ClipDescription.MIMETYPE_TEXT_PLAIN),+ ClipData.Item("/nonexistent/only.txt"),+ )+ assertFalse(target.onDrop(dragEvent(DragEvent.ACTION_DROP, noFiles)))+ real.delete()+ }+}
files/src/test/java/com/vayunmathur/files/ui/TextEditorComposeTest.kt
diff --git a/files/src/test/java/com/vayunmathur/files/ui/TextEditorComposeTest.kt b/files/src/test/java/com/vayunmathur/files/ui/TextEditorComposeTest.ktnew file mode 100644index 0000000000..1de021743c--- /dev/null+++ b/files/src/test/java/com/vayunmathur/files/ui/TextEditorComposeTest.kt@@ -0,0 +1,105 @@+package com.vayunmathur.files.ui++import android.content.ComponentName+import android.content.Context+import android.content.Intent+import android.net.Uri+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.hasClickAction+import androidx.compose.ui.test.junit4.AndroidComposeTestRule+import androidx.compose.ui.test.onAllNodesWithText+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.compose.ui.test.performTextInput+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.rules.ActivityScenarioRule+import com.vayunmathur.files.platform.TestFileProvider+import org.junit.Rule+import org.junit.rules.RuleChain+import org.junit.rules.TestRule+import org.junit.runner.Description+import org.junit.runner.RunWith+import org.junit.runners.model.Statement+import org.robolectric.Robolectric+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import java.io.File+import kotlin.test.Test+import kotlin.test.assertTrue++/** Registers the file provider and seeds the edited file before the activity launches. */+class SeedEditorFile : TestRule {+ companion object {+ lateinit var dir: File+ }++ override fun apply(base: Statement, description: Description): Statement =+ object : Statement() {+ override fun evaluate() {+ val ctx = ApplicationProvider.getApplicationContext<Context>()+ dir = File(ctx.cacheDir, "editor-compose").apply { mkdirs() }+ File(dir, "note.txt").writeText("hello editor")+ TestFileProvider.rootDir = dir+ Robolectric.buildContentProvider(TestFileProvider::class.java).create("testdocs")+ base.evaluate()+ }+ }+}++@RunWith(RobolectricTestRunner::class)+@Config(qualifiers = "w812dp-h1280dp")+class TextEditorComposeTest {++ private val intent = Intent(Intent.ACTION_VIEW).apply {+ component = ComponentName(+ "com.vayunmathur.files",+ "com.vayunmathur.files.ui.TextEditorActivity",+ )+ data = Uri.parse("content://testdocs/note.txt")+ }++ val rule = AndroidComposeTestRule(+ ActivityScenarioRule<TextEditorActivity>(intent),+ activityProvider = { r ->+ var found: TextEditorActivity? = null+ r.scenario.onActivity { found = it }+ checkNotNull(found)+ },+ )++ @get:Rule+ val chain: TestRule = RuleChain.outerRule(SeedEditorFile()).around(rule)++ @Test+ fun `editor shows content toggles editing and saves`() {+ rule.waitForIdle()+ rule.onNodeWithText("note.txt").assertIsDisplayed()+ // loaded content is shown (loading state resolves through the provider)+ val deadline = System.currentTimeMillis() + 10_000+ var loaded = false+ while (!loaded && System.currentTimeMillis() < deadline) {+ rule.waitForIdle()+ loaded = rule.onAllNodesWithText("hello editor").fetchSemanticsNodes().isNotEmpty()+ if (!loaded) Thread.sleep(50)+ }+ assertTrue(loaded)+ // the single top-bar action toggles edit mode; typing then saving writes back+ val nodes = rule.onAllNodes(hasClickAction()).fetchSemanticsNodes()+ val topBar = nodes.withIndex().filter { it.value.positionInRoot.y < 120f }+ assertTrue(topBar.isNotEmpty())+ rule.onAllNodes(hasClickAction())[topBar.last().index].performClick()+ rule.onNodeWithText("hello editor").performTextInput(" updated")+ rule.onAllNodes(hasClickAction())[+ rule.onAllNodes(hasClickAction()).fetchSemanticsNodes().withIndex()+ .filter { it.value.positionInRoot.y < 120f }.last().index,+ ].performClick()+ // save runs on IO; poll the file+ val saveDeadline = System.currentTimeMillis() + 10_000+ var saved = false+ while (!saved && System.currentTimeMillis() < saveDeadline) {+ saved = File(SeedEditorFile.dir, "note.txt").readText().contains("updated")+ if (!saved) Thread.sleep(50)+ }+ assertTrue(saved)+ }+}