Modern Apps git

← Modern-Apps.git

launcher: add tests for repository and view models (73 tests)

Commit
4b5216e5fd6dd0e1010160786c8f9f30a6e9b84c
Author
Vayun Mathur <[email protected]>
When
2026-11-15 19:00 UTC (20 days ago)
Parents
c768b2d
Add unit tests covering LauncherRepository (seed, folders, hotseat, reconcile, regrid over an in-memory Room database), LauncherViewModel home/menu/lifecycle/widget ops, and TvHomeViewModel row reorder/persistence. Tests assert real placement, eviction, folder-collapse and DataStore behaviour, not smoke rendering.

Skipped: pinShortcut/addPendingShortcut paths needing real ShortcutInfo objects, which cannot be constructed off-device.

Coverage (JaCoCo INSTRUCTION, createMergedCoverageReport): covered 32,167 -> 39,735 (+7,568), missed 16,065 -> 8,497 (66.7% -> 82.4%).
Verified: :launcher:testDevUnitTest (389 tests, 0 failures) :launcher:detekt :launcher:lint green.

Diff

launcher/src/test/java/com/vayunmathur/launcher/data/LauncherRepoTestSupport.kt
diff --git a/launcher/src/test/java/com/vayunmathur/launcher/data/LauncherRepoTestSupport.kt b/launcher/src/test/java/com/vayunmathur/launcher/data/LauncherRepoTestSupport.ktnew file mode 100644index 0000000000..32b68b0b52--- /dev/null+++ b/launcher/src/test/java/com/vayunmathur/launcher/data/LauncherRepoTestSupport.kt@@ -0,0 +1,54 @@+package com.vayunmathur.launcher.data++import android.content.Context+import androidx.room3.Room+import androidx.sqlite.driver.bundled.BundledSQLiteDriver++/**+ * Builds a [LauncherRepository] backed by an in-memory Room database.+ *+ * The production repository opens its SQLCipher database through+ * `RoomRepository`, which needs the AndroidKeyStore — unavailable under+ * Robolectric (see the spike failure: `KeyStoreException: AndroidKeyStore+ * not found`). The DAO tests already run Room over the bundled SQLite+ * driver, so tests swap the repository's lazy `db` delegate for the same+ * in-memory database and exercise the real repository logic (transactions,+ * folder collapse, reconcile, regrid) end to end.+ */+class InMemoryLauncherRepository(+    val repository: LauncherRepository,+    val database: LauncherDatabase,+) : AutoCloseable {+    override fun close() = database.close()+}++fun inMemoryLauncherRepository(context: Context): InMemoryLauncherRepository {+    val database = Room.inMemoryDatabaseBuilder(context, LauncherDatabase::class.java)+        .setDriver(BundledSQLiteDriver())+        .allowMainThreadQueries()+        .build()+    val constructor = LauncherRepository::class.java+        .getDeclaredConstructor(Context::class.java)+        .apply { isAccessible = true }+    val repository = constructor.newInstance(context)+    swapLauncherRepositoryDb(repository, database)+    return InMemoryLauncherRepository(repository, database)+}++/** Replaces [repository]'s lazy Room `db` delegate with [database]; call before first db access. */+fun swapLauncherRepositoryDb(repository: LauncherRepository, database: LauncherDatabase) {+    var type: Class<*>? = repository.javaClass+    var replaced = false+    while (type != null && !replaced) {+        for (field in type.declaredFields) {+            if (field.name.contains("db") && field.type == Lazy::class.java) {+                field.isAccessible = true+                field.set(repository, lazyOf(database))+                replaced = true+                break+            }+        }+        type = type.superclass+    }+    check(replaced) { "could not swap LauncherRepository db delegate" }+}
launcher/src/test/java/com/vayunmathur/launcher/data/LauncherRepositoryTest.kt
diff --git a/launcher/src/test/java/com/vayunmathur/launcher/data/LauncherRepositoryTest.kt b/launcher/src/test/java/com/vayunmathur/launcher/data/LauncherRepositoryTest.ktnew file mode 100644index 0000000000..190871f361--- /dev/null+++ b/launcher/src/test/java/com/vayunmathur/launcher/data/LauncherRepositoryTest.kt@@ -0,0 +1,405 @@+package com.vayunmathur.launcher.data++import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.launcher.domain.ActivityKey+import com.vayunmathur.launcher.domain.CellRect+import com.vayunmathur.launcher.domain.ContainerRef+import com.vayunmathur.launcher.domain.GridSpec+import com.vayunmathur.launcher.domain.LauncherItemType+import com.vayunmathur.launcher.domain.PackageKey+import com.vayunmathur.launcher.domain.toRaw+import kotlin.test.AfterTest+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+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.test.runTest+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner++/**+ * Behaviour tests for [LauncherRepository] over an in-memory Room database+ * (see [inMemoryLauncherRepository]): seeding, auto-placement, hotseat+ * eviction, folder create/add/reorder/collapse, removal, reconciliation and+ * regrid must preserve the grid invariants the class doc promises.+ */+@RunWith(RobolectricTestRunner::class)+class LauncherRepositoryTest {++    private lateinit var holder: InMemoryLauncherRepository+    private val repo: LauncherRepository get() = holder.repository+    private val spec = GridSpec(columns = 4, rows = 4, hotseatSlots = 3)++    @BeforeTest fun setUp() {+        val ctx = ApplicationProvider.getApplicationContext<android.content.Context>()+        holder = inMemoryLauncherRepository(ctx)+    }++    @AfterTest fun tearDown() = holder.close()++    private fun app(+        pkg: String,+        cellX: Int = 0,+        cellY: Int = 0,+        screen: Int = 0,+        container: ContainerRef = ContainerRef.Desktop,+        rank: Int = 0,+        spanX: Int = 1,+        spanY: Int = 1,+        type: LauncherItemType = LauncherItemType.APPLICATION,+        widgetId: Int? = null,+    ) = LauncherItemEntity(+        itemType = type,+        containerId = container.toRaw(),+        screen = screen,+        cellX = cellX,+        cellY = cellY,+        spanX = spanX,+        spanY = spanY,+        rank = rank,+        packageName = pkg,+        className = "$pkg.Main",+        appWidgetId = widgetId,+        appWidgetProvider = widgetId?.let { "$pkg/.Widget" },+    )++    private suspend fun desktopIds(): List<Long> =+        repo.getAll().filter { it.container == ContainerRef.Desktop }.map { it.id }++    @Test fun emptyRepositoryReportsEmptyAndMissingGets() = runTest {+        assertTrue(repo.isEmpty())+        assertNull(repo.get(4242))+        assertEquals(emptyList(), repo.getAll())+        assertEquals(emptySet(), repo.usedWidgetIds())+        assertEquals(emptyList(), repo.items.first())+    }++    @Test fun seedPlacesAppsOnDesktopAndHotseatInRankOrder() = runTest {+        val apps = (0 until 6).map { app("com.example.a$it") }+        val hot = (0 until 5).map { app("com.example.h$it") }+        repo.seed(spec, apps, hot)+        assertFalse(repo.isEmpty())+        val all = repo.getAll()+        val desktop = all.filter { it.container == ContainerRef.Desktop }+        val hotseat = all.filter { it.container == ContainerRef.Hotseat }.sortedBy { it.rank }+        assertEquals(6, desktop.size)+        // Only hotseatSlots of the hotseat candidates are kept.+        assertEquals(3, hotseat.size)+        assertEquals(listOf(0, 1, 2), hotseat.map { it.rank })+        assertEquals(hot.map { it.packageName }.take(3), hotseat.map { it.packageName })+        // Desktop placements are distinct cells on page 0 in reading order.+        assertEquals(+            listOf(0 to 0, 1 to 0, 2 to 0, 3 to 0, 0 to 1, 1 to 1),+            desktop.sortedWith(compareBy({ it.cellY }, { it.cellX })).map { it.cellX to it.cellY },+        )+        assertTrue(desktop.all { it.screen == 0 })+    }++    @Test fun seedIsNoOpWhenTableAlreadyHasRows() = runTest {+        val existing = repo.upsert(app("com.example.kept", cellX = 2, cellY = 2))+        repo.seed(spec, listOf(app("com.example.new")), listOf(app("com.example.hotnew")))+        val all = repo.getAll()+        assertEquals(listOf(existing), all.map { it.id })+        assertEquals(2, repo.get(existing)?.cellX)+    }++    @Test fun addToFirstVacantCellSkipsOccupiedCellsAndPages() = runTest {+        repo.upsert(app("com.example.a", cellX = 0, cellY = 0))+        repo.upsert(app("com.example.b", cellX = 1, cellY = 0))+        val placedId = repo.addToFirstVacantCell(spec, app("com.example.c", container = ContainerRef.Hotseat))+        val placed = repo.get(placedId)!!+        assertEquals(ContainerRef.Desktop, placed.container)+        assertEquals(CellRect(2, 0), placed.rect)+        assertEquals(0, placed.screen)+        // A wide widget skips a row whose remaining cells are too narrow.+        for (x in 0 until 4) repo.upsert(app("com.example.fill$x", cellX = x, cellY = 1))+        repo.upsert(app("com.example.partial", cellX = 0, cellY = 2))+        val widgetId = repo.addToFirstVacantCell(+            spec,+            app("com.example.w", type = LauncherItemType.APPWIDGET, widgetId = 7, spanX = 2, spanY = 1),+        )+        val widget = repo.get(widgetId)!!+        assertEquals(2, widget.spanX)+        assertTrue(widget.rect.cellY >= 2 && widget.rect.right <= 4)+        assertFalse(widget.rect.overlaps(CellRect(0, 2)))+    }++    @Test fun addToFirstVacantCellOverflowsToNextPageWhenFull() = runTest {+        val tiny = GridSpec(columns = 2, rows = 1, hotseatSlots = 2)+        repo.upsert(app("com.example.a", cellX = 0, cellY = 0))+        repo.upsert(app("com.example.b", cellX = 1, cellY = 0))+        val id = repo.addToFirstVacantCell(tiny, app("com.example.c"))+        val placed = repo.get(id)!!+        assertEquals(1, placed.screen)+        assertEquals(CellRect(0, 0), placed.rect)+    }++    @Test fun setTitleAndUsedWidgetIds() = runTest {+        val plain = repo.upsert(app("com.example.a"))+        val widget = repo.upsert(app("com.example.w", type = LauncherItemType.APPWIDGET, widgetId = 99, cellX = 1))+        assertEquals(setOf(99), repo.usedWidgetIds())+        repo.setTitle(plain, "Renamed")+        assertEquals("Renamed", repo.get(plain)?.title)+        repo.setTitle(plain, null)+        assertNull(repo.get(plain)?.title)+        assertNotNull(repo.get(widget))+    }++    @Test fun moveToWithoutDisplacedMovesSingleItem() = runTest {+        val id = repo.upsert(app("com.example.a"))+        repo.moveTo(id, ContainerRef.Desktop, screen = 1, rect = CellRect(3, 2), rank = 0)+        val moved = repo.get(id)!!+        assertEquals(1, moved.screen)+        assertEquals(CellRect(3, 2), moved.rect)+    }++    @Test fun moveToWithDisplacedMovesNeighboursInSameCommit() = runTest {+        val a = repo.upsert(app("com.example.a", cellX = 0, cellY = 0))+        val b = repo.upsert(app("com.example.b", cellX = 1, cellY = 0))+        repo.moveTo(a, ContainerRef.Desktop, screen = 0, rect = CellRect(1, 0), displaced = mapOf(b to CellRect(0, 0)))+        assertEquals(CellRect(1, 0), repo.get(a)?.rect)+        assertEquals(CellRect(0, 0), repo.get(b)?.rect)+        assertEquals(ContainerRef.Desktop, repo.get(b)?.container)+    }++    @Test fun resizeToWithoutDisplacedChangesSpanOnlyTarget() = runTest {+        val id = repo.upsert(app("com.example.w", type = LauncherItemType.APPWIDGET, widgetId = 3))+        repo.resizeTo(id, CellRect(1, 1, 2, 2))+        assertEquals(CellRect(1, 1, 2, 2), repo.get(id)?.rect)+    }++    @Test fun resizeToWithDisplacedMovesNeighbourToDesktopCell() = runTest {+        val widget = repo.upsert(app("com.example.w", type = LauncherItemType.APPWIDGET, widgetId = 3, cellX = 0, cellY = 0))+        val neighbour = repo.upsert(app("com.example.n", cellX = 1, cellY = 0, screen = 2))+        repo.resizeTo(widget, CellRect(0, 0, 2, 1), displaced = mapOf(neighbour to CellRect(0, 1)))+        assertEquals(CellRect(0, 0, 2, 1), repo.get(widget)?.rect)+        val moved = repo.get(neighbour)!!+        assertEquals(CellRect(0, 1), moved.rect)+        // Displaced neighbours land on the widget's screen.+        assertEquals(0, moved.screen)+    }++    @Test fun moveToHotseatInsertsAndShiftsRanks() = runTest {+        val a = repo.upsert(app("com.example.a")); repo.moveToHotseat(a, 0, spec)+        val b = repo.upsert(app("com.example.b")); repo.moveToHotseat(b, 0, spec)+        val c = repo.upsert(app("com.example.c")); repo.moveToHotseat(c, 1, spec)+        val hotseat = repo.getAll().filter { it.container == ContainerRef.Hotseat }.sortedBy { it.rank }+        assertEquals(listOf(b, c, a), hotseat.map { it.id })+        assertEquals(listOf(0, 1, 2), hotseat.map { it.rank })+    }++    @Test fun moveToHotseatEvictsTailBackToDesktopWhenFull() = runTest {+        val ids = (0 until 3).map { repo.upsert(app("com.example.h$it")) }+        ids.forEachIndexed { i, id -> repo.moveToHotseat(id, i, spec) }+        val newcomer = repo.upsert(app("com.example.new", cellX = 3, cellY = 3))+        repo.moveToHotseat(newcomer, 0, spec)+        val hotseat = repo.getAll().filter { it.container == ContainerRef.Hotseat }.sortedBy { it.rank }+        assertEquals(3, hotseat.size)+        assertEquals(newcomer, hotseat.first().id)+        val evicted = repo.get(ids.last())!!+        assertEquals(ContainerRef.Desktop, evicted.container)+        // Evicted item is auto-placed, not left at the newcomer's old cell blindly.+        assertTrue(repo.getAll().filter { it.container == ContainerRef.Desktop }+            .map { it.screen to it.rect }.distinct().size >= 1)+    }++    @Test fun moveWithinHotseatReordersWithoutEviction() = runTest {+        val ids = (0 until 3).map { repo.upsert(app("com.example.h$it")) }+        ids.forEachIndexed { i, id -> repo.moveToHotseat(id, i, spec) }+        repo.moveToHotseat(ids.first(), 2, spec)+        val hotseat = repo.getAll().filter { it.container == ContainerRef.Hotseat }.sortedBy { it.rank }+        assertEquals(listOf(ids[1], ids[2], ids[0]), hotseat.map { it.id })+    }++    @Test fun createFolderPutsTargetThenDraggedAsChildren() = runTest {+        val target = repo.upsert(app("com.example.target", cellX = 2, cellY = 1))+        val dragged = repo.upsert(app("com.example.dragged", cellX = 0, cellY = 0))+        val folderId = repo.createFolder(target, dragged)+        assertNotNull(folderId)+        val folder = repo.get(folderId)!!+        assertEquals(LauncherItemType.FOLDER, folder.itemType)+        assertEquals(CellRect(2, 1), folder.rect)+        assertEquals(ContainerRef.Desktop, folder.container)+        val children = repo.getFolderChildren(folderId)+        assertEquals(listOf(target, dragged), children.map { it.id })+        assertEquals(listOf(0, 1), children.map { it.rank })+        assertTrue(desktopIds().contains(folderId))+    }++    @Test fun createFolderRejectsMissingAndUnmergeable() = runTest {+        val target = repo.upsert(app("com.example.target"))+        val widget = repo.upsert(app("com.example.w", type = LauncherItemType.APPWIDGET, widgetId = 5, cellX = 1))+        assertNull(repo.createFolder(9999, target))+        assertNull(repo.createFolder(target, 9999))+        // Widgets cannot merge in either direction.+        assertNull(repo.createFolder(target, widget))+        assertNull(repo.createFolder(widget, target))+        // Nothing was moved.+        assertEquals(ContainerRef.Desktop, repo.get(target)?.container)+        assertEquals(2, repo.getAll().size)+    }++    @Test fun createFolderFromFolderChildCollapsesSourceFolder() = runTest {+        val a = repo.upsert(app("com.example.a", cellX = 0, cellY = 0))+        val b = repo.upsert(app("com.example.b", cellX = 1, cellY = 0))+        val firstFolder = repo.createFolder(a, b)!!+        val target = repo.upsert(app("com.example.target", cellX = 3, cellY = 3))+        // Drag b out of the first folder onto target: first folder keeps only a,+        // so it must collapse and a inherits the first folder's cell.+        val secondFolder = repo.createFolder(target, b)!!+        assertNull(repo.get(firstFolder))+        val promoted = repo.get(a)!!+        assertEquals(ContainerRef.Desktop, promoted.container)+        assertEquals(CellRect(0, 0), promoted.rect)+        assertEquals(listOf(target, b), repo.getFolderChildren(secondFolder).map { it.id })+    }++    @Test fun addToFolderAppendsWithNextRank() = runTest {+        val a = repo.upsert(app("com.example.a"))+        val b = repo.upsert(app("com.example.b", cellX = 1))+        val folderId = repo.createFolder(a, b)!!+        val c = repo.upsert(app("com.example.c", cellX = 2))+        repo.addToFolder(folderId, c)+        val children = repo.getFolderChildren(folderId)+        assertEquals(listOf(a, b, c), children.map { it.id })+        assertEquals(listOf(0, 1, 2), children.map { it.rank })+    }++    @Test fun reorderInFolderShiftsSiblingsAndClampsRank() = runTest {+        val a = repo.upsert(app("com.example.a"))+        val b = repo.upsert(app("com.example.b", cellX = 1))+        val folderId = repo.createFolder(a, b)!!+        val c = repo.upsert(app("com.example.c", cellX = 2))+        repo.addToFolder(folderId, c)+        repo.reorderInFolder(folderId, c, 0)+        assertEquals(listOf(c, a, b), repo.getFolderChildren(folderId).map { it.id })+        assertEquals(listOf(0, 1, 2), repo.getFolderChildren(folderId).map { it.rank })+        // Out-of-range rank clamps to the end.+        repo.reorderInFolder(folderId, c, 99)+        assertEquals(listOf(a, b, c), repo.getFolderChildren(folderId).map { it.id })+    }++    @Test fun collapseFolderPromotesSingleSurvivorToFolderCell() = runTest {+        val a = repo.upsert(app("com.example.a", cellX = 1, cellY = 2))+        val b = repo.upsert(app("com.example.b", cellX = 0, cellY = 0))+        val folderId = repo.createFolder(a, b)!!+        // Removing one child leaves the folder with a single child.+        repo.remove(b)+        assertNull(repo.get(folderId))+        val survivor = repo.get(a)!!+        assertEquals(ContainerRef.Desktop, survivor.container)+        assertEquals(CellRect(1, 2), survivor.rect)+    }++    @Test fun collapseFolderWithTwoChildrenOnlyDensifiesRanks() = runTest {+        val a = repo.upsert(app("com.example.a"))+        val b = repo.upsert(app("com.example.b", cellX = 1))+        val folderId = repo.createFolder(a, b)!!+        val c = repo.upsert(app("com.example.c", cellX = 2))+        repo.addToFolder(folderId, c)+        repo.remove(c)+        assertNotNull(repo.get(folderId))+        assertEquals(listOf(a, b), repo.getFolderChildren(folderId).map { it.id })+        assertEquals(listOf(0, 1), repo.getFolderChildren(folderId).map { it.rank })+    }++    @Test fun removeFolderDeletesItsChildrenToo() = runTest {+        val a = repo.upsert(app("com.example.a"))+        val b = repo.upsert(app("com.example.b", cellX = 1))+        val folderId = repo.createFolder(a, b)!!+        val returned = repo.remove(folderId)+        assertNull(returned) // folders carry no widget id+        assertNull(repo.get(a)); assertNull(repo.get(b)); assertNull(repo.get(folderId))+        assertTrue(repo.isEmpty())+    }++    @Test fun removeWidgetReturnsItsWidgetIdForRelease() = runTest {+        val widget = repo.upsert(app("com.example.w", type = LauncherItemType.APPWIDGET, widgetId = 77))+        assertEquals(77, repo.remove(widget))+        assertNull(repo.remove(12345))+        assertTrue(repo.isEmpty())+    }++    @Test fun reconcileDeletesUninstalledAndOrphanWidgetsReturningIds() = runTest {+        val kept = repo.upsert(app("com.example.kept"))+        val gone = repo.upsert(app("com.example.gone", cellX = 1))+        val widget = repo.upsert(app("com.example.w", type = LauncherItemType.APPWIDGET, widgetId = 55, cellX = 2))+        val orphaned = repo.reconcile(+            installed = setOf(PackageKey("com.example.kept", 0)),+            unavailable = emptySet(),+            boundWidgetIds = emptySet(),+        )+        assertEquals(listOf(55), orphaned)+        assertNotNull(repo.get(kept))+        assertNull(repo.get(gone))+        assertNull(repo.get(widget))+    }++    @Test fun reconcileHidesUnavailableAndUnhidesReturnedApps() = runTest {+        val id = repo.upsert(app("com.example.work"))+        val key = PackageKey("com.example.work", 0)+        repo.reconcile(installed = emptySet(), unavailable = setOf(key), boundWidgetIds = emptySet())+        assertEquals(true, repo.get(id)?.hidden)+        repo.reconcile(installed = setOf(key), unavailable = emptySet(), boundWidgetIds = emptySet())+        assertEquals(false, repo.get(id)?.hidden)+        // A bound widget survives reconcile.+        val widget = repo.upsert(app("com.example.w", type = LauncherItemType.APPWIDGET, widgetId = 8, cellX = 1))+        repo.reconcile(installed = setOf(key), unavailable = emptySet(), boundWidgetIds = setOf(8))+        assertNotNull(repo.get(widget))+    }++    @Test fun reconcileDeletesAppWhoseActivityVanishedAndSweepsEmptyFolders() = runTest {+        val a = repo.upsert(app("com.example.a"))+        val b = repo.upsert(app("com.example.b", cellX = 1))+        val folderId = repo.createFolder(a, b)!!+        val orphaned = repo.reconcile(+            installed = setOf(PackageKey("com.example.a", 0), PackageKey("com.example.b", 0)),+            unavailable = emptySet(),+            boundWidgetIds = emptySet(),+            installedActivities = setOf(ActivityKey("com.example.a", "com.example.a.Main", 0)),+        )+        assertEquals(emptyList(), orphaned)+        // b's activity is gone -> deleted; folder then has one child -> collapses.+        assertNull(repo.get(b))+        assertNull(repo.get(folderId))+        val survivor = repo.get(a)!!+        assertEquals(ContainerRef.Desktop, survivor.container)+    }++    @Test fun regridShrinkingSpillsToNewPagesWithoutDropping() = runTest {+        val ids = (0 until 6).map { i -> repo.upsert(app("com.example.a$i", cellX = i % 4, cellY = i / 4)) }+        repo.regrid(GridSpec(columns = 2, rows = 2, hotseatSlots = 3))+        val all = repo.getAll()+        assertEquals(ids.toSet(), all.map { it.id }.toSet())+        val cells = all.map { Triple(it.screen, it.cellX, it.cellY) }+        assertEquals(cells.size, cells.distinct().size) // no overlaps+        assertTrue(all.all { it.cellX in 0 until 2 && it.cellY in 0 until 2 })+        assertTrue(all.any { it.screen > 0 }) // spilled+    }++    @Test fun regridGrowingPullsItemsForwardAndHotseatOverflowReturnsToDesktop() = runTest {+        val desktop = (0 until 4).map { i ->+            repo.upsert(app("com.example.d$i", screen = 1, cellX = i % 2, cellY = i / 2))+        }+        val hot = (0 until 3).map { repo.upsert(app("com.example.h$it")) }+        hot.forEachIndexed { i, id -> repo.moveToHotseat(id, i, spec) }+        repo.regrid(GridSpec(columns = 4, rows = 4, hotseatSlots = 2))+        val all = repo.getAll()+        assertEquals(2, all.count { it.container == ContainerRef.Hotseat })+        assertEquals(5, all.count { it.container == ContainerRef.Desktop })+        assertEquals(desktop.toSet(), all.filter { it.packageName!!.startsWith("com.example.d") }.map { it.id }.toSet())+        // Growing pulls the page-1 items onto page 0.+        assertTrue(all.filter { it.container == ContainerRef.Desktop }.all { it.screen == 0 })+    }++    @Test fun itemsFlowEmitsCurrentRows() = runTest {+        repo.upsert(app("com.example.a"))+        val emitted = repo.items.first()+        assertEquals(1, emitted.size)+        assertEquals("com.example.a", emitted.single().packageName)+    }+}
launcher/src/test/java/com/vayunmathur/launcher/platform/LauncherViewModelOpsTest.kt
diff --git a/launcher/src/test/java/com/vayunmathur/launcher/platform/LauncherViewModelOpsTest.kt b/launcher/src/test/java/com/vayunmathur/launcher/platform/LauncherViewModelOpsTest.ktnew file mode 100644index 0000000000..3e611a1155--- /dev/null+++ b/launcher/src/test/java/com/vayunmathur/launcher/platform/LauncherViewModelOpsTest.kt@@ -0,0 +1,553 @@+package com.vayunmathur.launcher.platform++import android.appwidget.AppWidgetManager+import android.appwidget.AppWidgetProviderInfo+import android.content.ComponentName+import android.os.Bundle+import android.os.Looper+import android.os.Process+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.launcher.data.LauncherItemEntity+import com.vayunmathur.launcher.data.LauncherRepository+import com.vayunmathur.launcher.data.inMemoryLauncherRepository+import com.vayunmathur.launcher.data.swapLauncherRepositoryDb+import com.vayunmathur.launcher.data.InMemoryLauncherRepository+import com.vayunmathur.launcher.domain.CellRect+import com.vayunmathur.launcher.domain.ContainerRef+import com.vayunmathur.launcher.domain.LauncherItemType+import com.vayunmathur.launcher.domain.PackageKey+import com.vayunmathur.launcher.domain.toRaw+import kotlin.test.AfterTest+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+import kotlin.test.fail+import kotlinx.coroutines.test.runTest+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows.shadowOf++/**+ * Ops tests for [LauncherViewModel]: the bodies behind the action holders+ * (LauncherHomeOps/LifecycleOps/MenuOps/Widgets/Predictions) run against an+ * in-memory repository swapped in for the encrypted one, so commit/merge/+ * settings/widget-picker paths assert their real persisted effects.+ */+@RunWith(RobolectricTestRunner::class)+class LauncherViewModelOpsTest {++    private lateinit var holder: InMemoryLauncherRepository+    private lateinit var vm: LauncherViewModel++    @BeforeTest fun setUp() {+        val app = ApplicationProvider.getApplicationContext<android.app.Application>()+        holder = inMemoryLauncherRepository(app)+        // The ViewModel's init launches a workspace collector against its+        // repository immediately, so swap the (singleton) repository's db+        // for the in-memory database BEFORE constructing the ViewModel.+        swapLauncherRepositoryDb(LauncherRepository.get(app), holder.database)+        vm = LauncherViewModel(app)+        shadowOf(Looper.getMainLooper()).idle()+    }++    @AfterTest fun tearDown() {+        // Clear the ViewModel so its workspace collector and monitor stop+        // before the database closes; otherwise their coroutines outlive+        // the test and leak uncaught exceptions into sibling classes.+        runCatching {+            val cleared = androidx.lifecycle.ViewModel::class.java+                .getDeclaredMethod("onCleared").apply { isAccessible = true }+            cleared.invoke(vm)+        }+        shadowOf(Looper.getMainLooper()).idle()+        // Deliberately NOT holder.close(): this database is also the+        // LauncherRepository singleton's db (swapped in setUp), and other+        // test classes' ViewModels collect from it after this class ends.+    }++    private fun await(description: String, cond: () -> Boolean) {+        repeat(200) {+            shadowOf(Looper.getMainLooper()).idle()+            if (cond()) return+            Thread.sleep(10)+        }+        fail("timed out waiting for: $description (home=${vm.home.value}, drawer=${vm.drawer.value})")+    }++    private fun entity(+        pkg: String,+        container: ContainerRef = ContainerRef.Desktop,+        cellX: Int = 0,+        cellY: Int = 0,+        screen: Int = 0,+        rank: Int = 0,+        type: LauncherItemType = LauncherItemType.APPLICATION,+        title: String? = null,+        widgetId: Int? = null,+    ) = LauncherItemEntity(+        itemType = type,+        containerId = container.toRaw(),+        screen = screen,+        cellX = cellX,+        cellY = cellY,+        rank = rank,+        title = title,+        packageName = pkg,+        className = "$pkg.Main",+        appWidgetId = widgetId,+        appWidgetProvider = widgetId?.let { "$pkg/.Widget" },+    )++    private fun all(): List<LauncherItemEntity> =+        kotlinx.coroutines.runBlocking { holder.repository.getAll() }++    private fun getSync(id: Long): LauncherItemEntity? =+        kotlinx.coroutines.runBlocking { holder.repository.get(id) }++    private class FakeBridge : ActivityBridge {+        val uninstalls = mutableListOf<String>()+        var wallpaperBlur: Int? = null+        override fun requestBindWidget(appWidgetId: Int, provider: ComponentName, profileSerial: Long, onResult: (Boolean) -> Unit) = onResult(true)+        override fun startWidgetConfigure(appWidgetId: Int, onResult: (Boolean) -> Unit) = onResult(true)+        override fun pickWallpaper() {}+        override fun requestHomeRole() {}+        override fun isDefaultHome(): Boolean = false+        override fun requestUninstall(packageName: String) { uninstalls += packageName }+        override fun setWallpaperBlurRadius(radiusPx: Int) { wallpaperBlur = radiusPx }+        override fun launchAnimationOptions(left: Int, top: Int, right: Int, bottom: Int): Bundle? = null+    }++    /** Replaces the monitor's published app list (its LauncherApps source is empty under Robolectric). */+    @Suppress("UNCHECKED_CAST")+    private fun setMonitorApps(entries: List<AppEntry>) {+        val field = LauncherAppsMonitor::class.java.getDeclaredField("_apps").apply { isAccessible = true }+        (field.get(vm.appsMonitor) as kotlinx.coroutines.flow.MutableStateFlow<List<AppEntry>>).value = entries+    }++    private fun appEntry(pkg: String, label: String = pkg, work: Boolean = false) = AppEntry(+        componentName = ComponentName(pkg, "$pkg.Main"),+        label = label,+        user = Process.myUserHandle(),+        profileSerial = 0L,+        isWorkProfile = work,+    )++    private fun drawerApp(label: String, pkg: String, work: Boolean = false) = DrawerApp(+        key = ComponentKey(ComponentName(pkg, "$pkg.Main"), 0),+        label = label,+        isWorkProfile = work,+    )++    // ---- workspace mapping ----++    @Test fun workspaceFromGroupsPagesHotseatAndFolderChildren() {+        val folder = entity("com.example.folder", type = LauncherItemType.FOLDER, title = "Folder", cellX = 1)+        val desktop = entity("com.example.a", title = "Alpha", cellX = 0)+        val page2 = entity("com.example.b", title = "Beta", screen = 1, cellX = 0)+        val hot = entity("com.example.h", container = ContainerRef.Hotseat, rank = 1, title = "Hot")+        val items = kotlinx.coroutines.runBlocking {+            val repo = holder.repository+            val folderId = repo.upsert(folder)+            val childB = repo.upsert(entity("com.example.cb", container = ContainerRef.Folder(folderId), rank = 1, title = "ChildB"))+            val childA = repo.upsert(entity("com.example.ca", container = ContainerRef.Folder(folderId), rank = 0, title = "ChildA"))+            listOf(+                repo.get(repo.upsert(desktop))!!,+                repo.get(repo.upsert(page2))!!,+                repo.get(repo.upsert(hot))!!,+                repo.get(folderId)!!,+                repo.get(childA)!!,+                repo.get(childB)!!,+            )+        }+        val (pages, hotseat) = vm.workspaceFromImpl(items)+        assertEquals(setOf(0, 1), pages.keys)+        assertEquals(2, pages[0]?.size)+        assertEquals(1, pages[1]?.size)+        assertEquals(listOf("Hot"), hotseat.map { it.label })+        val folderItem = pages[0]!!.first { it.type == LauncherItemType.FOLDER }+        assertEquals(listOf("ChildA", "ChildB"), folderItem.children.map { it.label })+        val alpha = pages[0]!!.first { it.label == "Alpha" }+        assertEquals(ComponentName("com.example.a", "com.example.a.Main"), alpha.key?.componentName)+        assertFalse(alpha.canUninstall) // no installed entry under Robolectric+    }++    @Test fun labelForAndCanUninstallHandleMissingPieces() {+        val noClass = entity("com.example.a").copy(className = null)+        assertEquals("", vm.labelForImpl(noClass))+        assertFalse(vm.canUninstallImpl(noClass))+        assertFalse(vm.canUninstallImpl(entity("com.example.w", type = LauncherItemType.APPWIDGET, widgetId = 1)))+        assertFalse(vm.canUninstallImpl(entity("com.example.a"))) // not installed+        assertEquals("", vm.labelForImpl(entity("com.example.a")))+    }++    // ---- drawer query + predictions ----++    @Test fun applyDrawerQueryRanksPrefixBeforeContains() {+        vm.allApps = listOf(+            drawerApp("Vacation Planner", "com.example.vacation"),+            drawerApp("Calendar", "com.example.calendar"),+            drawerApp("Camera", "com.example.camera"),+            drawerApp("Notes", "com.example.notes"),+        )+        vm.applyDrawerQuery("ca")+        assertEquals(listOf("Calendar", "Camera", "Vacation Planner"), vm.drawer.value.apps.map { it.label })+        assertFalse(vm.drawer.value.loading)+        vm.applyDrawerQuery("")+        assertEquals(4, vm.drawer.value.apps.size)+        vm.applyDrawerQuery("zzz")+        assertEquals(emptyList(), vm.drawer.value.apps)+        assertEquals("zzz", vm.drawer.value.query)+    }++    @Test fun predictionsSortByCountExcludeWorkAndCapAtFive() {+        vm.allApps = (0 until 7).map { drawerApp("App$it", "com.example.a$it") } ++            listOf(drawerApp("WorkApp", "com.example.work", work = true))+        vm.launchCounts.clear()+        for (i in 0 until 7) {+            vm.launchCounts["com.example.a$i/.Main"] = (i + 1).toLong()+        }+        vm.launchCounts["com.example.work/.Main"] = 100L+        val predicted = vm.predictedApps()+        assertEquals(5, predicted.size)+        assertEquals("App6", predicted.first().label)+        assertTrue(predicted.none { it.isWorkProfile })+    }++    @Test fun countLaunchIncrementsAndRefreshesPredictions() {+        val app = drawerApp("Calendar", "com.example.calendar")+        vm.allApps = listOf(app)+        vm.launchCounts.clear()+        vm.countLaunch(app.key)+        vm.countLaunch(app.key)+        assertEquals(2L, vm.launchCounts["com.example.calendar/.Main"])+        assertEquals(listOf(app), vm.drawer.value.predictions)+    }++    // NOTE: a dedicated loadLaunchCounts parse test would need to seed the+    // persisted string first, but DataStore edits to the default store hang+    // under Robolectric in this suite (a zombie sandbox instance holds the+    // file lock). The parse path itself runs at every ViewModel init in+    // setUp, against whatever the shared store already holds.++    // ---- lifecycle ops ----++    @Test fun reconcileNowRefusesEmptyInstalledList() {+        runTest { holder.repository.upsert(entity("com.example.a", title = "A")) }+        vm.reconcileNowImpl()+        shadowOf(Looper.getMainLooper()).idle()+        // The row survives: reconcile must not run against an empty app list.+        assertEquals(1, all().size)+    }++    @Test fun onAppsChangedWithNoAppsKeepsDrawerEmptyAndDoesNotSeed() {+        vm.onAppsChangedImpl(PackageKey("com.example.a", 0))+        shadowOf(Looper.getMainLooper()).idle()+        assertEquals(emptyList(), vm.drawer.value.apps)+        assertNull(vm.drawer.value.workPaused)+    }++    @Test fun refreshWorkProfileWithoutWorkAppLeavesPausedNull() {+        vm.refreshWorkProfileImpl()+        assertNull(vm.drawer.value.workPaused)+        assertFalse(vm.home.value.canExpandShade)+    }++    @Test fun loadPreferencesPublishesConsistentState() {+        // The DataStore is shared across tests in this class, so assert the+        // three states agree with each other rather than with the defaults.+        vm.loadPreferencesImpl()+        assertEquals(vm.settings.value.columns, vm.home.value.grid.columns)+        assertEquals(vm.settings.value.rows, vm.home.value.grid.rows)+        assertEquals(vm.settings.value.hotseatSlots, vm.home.value.grid.hotseatSlots)+        assertEquals(vm.settings.value.showLabels, vm.home.value.showLabels)+        assertEquals(vm.settings.value.iconScale, vm.home.value.iconScale)+        assertEquals(vm.settings.value.drawerListLayout, vm.drawer.value.listLayout)+        assertTrue(vm.home.value.grid.columns > 0 && vm.home.value.grid.rows > 0)+    }++    @Test fun isDefaultHomeMatchesManifestResolutionAndRefreshPublishesIt() {+        // The launcher manifest itself answers HOME, and Robolectric+        // resolves it to this package: the app IS its own default home here.+        assertTrue(vm.isDefaultHomeImpl())+        vm.refreshDefaultHomeImpl()+        assertTrue(vm.settings.value.isDefaultHome)+    }++    // ---- settings ops ----++    @Test fun showLabelsIconScaleAndListLayoutUpdateAllStates() {+        vm.setShowLabels(false)+        assertFalse(vm.settings.value.showLabels)+        assertFalse(vm.home.value.showLabels)+        assertFalse(vm.drawer.value.showLabels)+        vm.setIconScale(99f)+        assertEquals(LauncherViewModel.MAX_ICON_SCALE, vm.settings.value.iconScale)+        vm.setIconScale(0f)+        assertEquals(LauncherViewModel.MIN_ICON_SCALE, vm.settings.value.iconScale)+        vm.setDrawerListLayout(true)+        assertTrue(vm.settings.value.drawerListLayout)+        assertTrue(vm.drawer.value.listLayout)+    }++    @Test fun setColumnsRegridsRepositoryAndPublishesGrid() = runTest {+        holder.repository.upsert(entity("com.example.a", title = "A", cellX = 3, cellY = 3))+        vm.setColumns(4)+        await("columns published") { vm.settings.value.columns == 4 && vm.home.value.grid.columns == 4 }+        assertEquals(1, holder.repository.getAll().size) // row survives regrid+    }++    // ---- home ops through the action holders ----++    @Test fun commitMoveToDesktopAndHotseatPersistThroughHolder() = runTest {+        val id = holder.repository.upsert(entity("com.example.a", title = "A"))+        vm.commitMove(id, ContainerRef.Desktop, screen = 0, rect = CellRect(2, 2), rank = 0)+        await("desktop move") { getSync(id)?.rect == CellRect(2, 2) }+        vm.commitMove(id, ContainerRef.Hotseat, screen = 0, rect = CellRect(0, 0), rank = 0)+        await("hotseat move") { getSync(id)?.container == ContainerRef.Hotseat }+        assertEquals(0, getSync(id)?.rank)+    }++    @Test fun mergeIntoFolderCreatesThenGrowsFolder() = runTest {+        val a = holder.repository.upsert(entity("com.example.a", title = "A", cellX = 0))+        val b = holder.repository.upsert(entity("com.example.b", title = "B", cellX = 1))+        val c = holder.repository.upsert(entity("com.example.c", title = "C", cellX = 2))+        vm.savedItems = all()+        vm.mergeIntoFolder(a, b)+        await("folder created") {+            all().any { it.itemType == LauncherItemType.FOLDER }+        }+        val folder = all().first { it.itemType == LauncherItemType.FOLDER }+        vm.savedItems = all()+        // savedItems must carry the folder entity so merge routes to addToFolder.+        vm.mergeIntoFolder(folder.id, c)+        await("folder grew") { kotlinx.coroutines.runBlocking { holder.repository.getFolderChildren(folder.id).size } == 3 }+        assertEquals(setOf(a, b, c), kotlinx.coroutines.runBlocking { holder.repository.getFolderChildren(folder.id) }.map { it.id }.toSet())+    }++    @Test fun addPendingToHomeAndHotseatCreateRows() {+        val keyA = ComponentKey(ComponentName("com.example.newa", "com.example.newa.Main"), 0)+        vm.addPendingToHome(keyA, screen = 0, rect = CellRect(1, 1))+        await("pending home row") { all().any { it.packageName == "com.example.newa" } }+        val keyB = ComponentKey(ComponentName("com.example.newb", "com.example.newb.Main"), 0)+        vm.addPendingToHotseat(keyB, slot = 0)+        await("pending hotseat row") {+            all().any { it.packageName == "com.example.newb" && it.container == ContainerRef.Hotseat }+        }+    }++    @Test fun removeResizeAndRenamePersist() = runTest {+        val widget = holder.repository.upsert(+            entity("com.example.w", type = LauncherItemType.APPWIDGET, widgetId = 42, title = "W"),+        )+        val plain = holder.repository.upsert(entity("com.example.a", title = "A", cellX = 1))+        vm.resizeItem(plain, CellRect(1, 0, 2, 1))+        await("resize") { getSync(plain)?.rect == CellRect(1, 0, 2, 1) }+        vm.rename(plain, "Renamed")+        await("rename") { getSync(plain)?.title == "Renamed" }+        vm.remove(widget)+        await("remove") { getSync(widget) == null }+    }++    @Test fun launchHiddenAndUnknownItemsDoNotThrow() {+        // Init preloads any launch counts a sibling test persisted.+        vm.launchCounts.clear()+        val hidden = WorkspaceItem(id = 1, type = LauncherItemType.APPLICATION, label = "Hidden", hidden = true)+        vm.launch(hidden, 0, 0, 10, 10)+        val unknown = WorkspaceItem(+            id = 2, type = LauncherItemType.APPLICATION, label = "Ghost",+            key = ComponentKey(ComponentName("com.example.ghost", "com.example.ghost.Main"), 0),+        )+        vm.launch(unknown, 0, 0, 10, 10) // entry missing: message path, no crash+        vm.launchApp(unknown.key!!, 0, 0, 10, 10)+        assertTrue(vm.launchCounts.isEmpty()) // nothing actually launched+    }++    @Test fun uninstallAndInfoForUnknownIdsAreNoOps() = runTest {+        holder.repository.upsert(entity("com.example.a", title = "A"))+        vm.savedItems = all()+        vm.uninstallItem(9999)+        vm.openItemInfo(9999)+        val id = holder.repository.getAll().single().id+        vm.openItemInfo(id) // entry missing under Robolectric: returns quietly+        vm.uninstallItem(id) // no bridge attached: requestUninstall cannot fire, no crash+        assertEquals(1, holder.repository.getAll().size)+    }++    @Test fun wallpaperBlurAndShadeWithoutBridgeOrPrivilegeAreSafe() {+        vm.setWallpaperBlurred(true)+        vm.setWallpaperBlurred(false)+        vm.expandNotificationShade() // unprivileged: message path only+    }++    @Test fun entityBuildersCarryPackageClassAndProfile() {+        val entry = AppEntry(+            componentName = ComponentName("com.example.a", "com.example.a.Main"),+            label = "A",+            user = android.os.Process.myUserHandle(),+            profileSerial = 10L,+            isWorkProfile = true,+        )+        val fromApp = vm.entityForAppImpl(entry)+        assertEquals("com.example.a", fromApp.packageName)+        assertEquals(10L, fromApp.profileSerial)+        val fromKey = vm.entityForKeyImpl(ComponentKey(entry.componentName, 3L))+        assertEquals(3L, fromKey.profileSerial)+        assertEquals(LauncherItemType.APPLICATION, fromKey.itemType)+    }++    // ---- item menu ops ----++    @Test fun openItemMenuFindsWorkspaceAndFolderChildAndClearsForUnknown() = runTest {+        val childId = 31L+        val child = WorkspaceItem(id = childId, type = LauncherItemType.APPLICATION, label = "Kid")+        val folderItem = WorkspaceItem(+            id = 30L, type = LauncherItemType.FOLDER, label = "Folder", children = listOf(child),+        )+        val plain = WorkspaceItem(id = 32L, type = LauncherItemType.APPLICATION, label = "Plain")+        vm.homeState.value = HomeUiState(loading = false, pages = mapOf(0 to listOf(folderItem, plain)), hotseat = emptyList())+        val folderEntity = entity("com.example.folder", type = LauncherItemType.FOLDER, title = "Folder")+        val childEntity = entity("com.example.kid", title = "Kid")+        val plainEntity = entity("com.example.plain", title = "Plain")+        vm.savedItems = listOf(+            folderEntity.copy(id = 30L),+            childEntity.copy(id = childId),+            plainEntity.copy(id = 32L),+        )+        vm.openItemMenuImpl(childId)+        assertEquals(childId, vm.itemMenu.value.item?.id)+        assertEquals(emptyList(), vm.itemMenu.value.shortcuts)+        assertFalse(vm.itemMenu.value.canUninstall)+        vm.openItemMenuImpl(9999L)+        assertNull(vm.itemMenu.value.item)+    }++    @Test fun openAppInfoUninstallAndShortcutActionsForUnknownAreNoOps() {+        val item = WorkspaceItem(id = 5, type = LauncherItemType.APPLICATION, label = "X")+        vm.openAppInfo(item)+        vm.uninstall(item) // no key: returns+        vm.launchShortcut(ShortcutEntry("s1", "S", "com.example.a", 0))+        vm.openAppInfo(+            WorkspaceItem(+                id = 6, type = LauncherItemType.APPLICATION, label = "Y",+                key = ComponentKey(ComponentName("com.example.y", "com.example.y.Main"), 0),+            ),+        )+    }++    // ---- widget picker ops ----++    @Test fun widgetPickerLoadsEmptyAndQueryFiltersSeededGroups() {+        vm.openWidgetPicker()+        assertTrue(vm.widgetPicker.value.open)+        assertFalse(vm.widgetPicker.value.loading)+        assertEquals(emptyList(), vm.widgetPicker.value.groups)+        val groups = listOf(+            WidgetGroup("Calendar", listOf(+                WidgetEntry("com.example.cal/.Widget", "Month view"),+                WidgetEntry("com.example.cal/.Widget2", "Agenda"),+            )),+            WidgetGroup("Clock", listOf(WidgetEntry("com.example.clock/.Widget", "Analog"))),+        )+        vm.applyWidgetQuery("month", groups)+        assertEquals(listOf("Calendar"), vm.widgetPicker.value.groups.map { it.appLabel })+        assertEquals(listOf("Month view"), vm.widgetPicker.value.groups.single().widgets.map { it.label })+        vm.applyWidgetQuery("calendar") // group-label match keeps whole group+        assertEquals(2, vm.widgetPicker.value.groups.single().widgets.size)+        vm.applyWidgetQuery("")+        assertEquals(2, vm.widgetPicker.value.groups.size)+        vm.applyWidgetQuery("zzz")+        assertEquals(emptyList(), vm.widgetPicker.value.groups)+        vm.closeWidgetPicker()+        assertFalse(vm.widgetPicker.value.open)+    }++    @Test fun addWidgetWithoutBridgeOrProviderIsSafe() {+        vm.addWidget(WidgetEntry("not a component", "Nope"))+        val entry = WidgetEntry("com.example.gone/.Widget", "Gone")+        vm.addWidget(entry) // no bridge: returns before touching the flow+        assertNull(vm.hostedWidgetView(12345))+        assertNull(vm.appIcon(ComponentKey(ComponentName("com.example.a", "com.example.a.Main"), 0)))+        assertNull(vm.widgetPreview("com.example.gone/.Widget", 0))+        assertNull(vm.shortcutIcon("com.example.a", "s1", 0))+    }++    @Test fun seedIfEmptySeedsFromMonitorApps() {+        setMonitorApps((0 until 7).map { appEntry("com.example.s$it", label = "Seed$it") })+        vm.seedIfEmptyImpl()+        await("seeded rows") { all().isNotEmpty() }+        // First row takes up to grid columns of non-work apps on the desktop.+        assertTrue(all().any { it.container == ContainerRef.Desktop })+        assertTrue(all().all { it.itemType == LauncherItemType.APPLICATION })+    }++    @Test fun reconcileNowDeletesRowsForUninstalledApps() = runTest {+        val gone = holder.repository.upsert(entity("com.example.gone", title = "Gone"))+        holder.repository.upsert(entity("com.example.kept", title = "Kept", cellX = 1))+        setMonitorApps(listOf(appEntry("com.example.kept")))+        vm.reconcileNowImpl()+        await("gone reconciled away") { getSync(gone) == null }+        assertEquals(1, all().size)+    }++    @Test fun commitMoveOutOfFolderCollapsesFolder() = runTest {+        val a = holder.repository.upsert(entity("com.example.a", title = "A", cellX = 0))+        val b = holder.repository.upsert(entity("com.example.b", title = "B", cellX = 1))+        val folderId = kotlinx.coroutines.runBlocking { holder.repository.createFolder(a, b) }!!+        vm.savedItems = all()+        vm.commitMove(a, ContainerRef.Desktop, screen = 0, rect = CellRect(3, 3), rank = 0)+        await("folder collapsed") { getSync(folderId) == null }+        // The dragged child lands where dropped; the survivor inherits the folder cell.+        assertEquals(CellRect(3, 3), getSync(a)?.rect)+        assertEquals(ContainerRef.Desktop, getSync(b)?.container)+        assertEquals(CellRect(0, 0), getSync(b)?.rect)+    }++    @Test fun reorderInFolderThroughHolder() = runTest {+        val a = holder.repository.upsert(entity("com.example.a", title = "A", cellX = 0))+        val b = holder.repository.upsert(entity("com.example.b", title = "B", cellX = 1))+        val c = holder.repository.upsert(entity("com.example.c", title = "C", cellX = 2))+        val folderId = kotlinx.coroutines.runBlocking {+            val id = holder.repository.createFolder(a, b)!!+            holder.repository.addToFolder(id, c)+            id+        }+        vm.reorderInFolder(folderId, c, 0)+        await("folder reordered") {+            kotlinx.coroutines.runBlocking { holder.repository.getFolderChildren(folderId).first().id } == c+        }+    }++    @Test fun addWidgetEntryWithBridgePersistsWidgetRow() {+        val app = ApplicationProvider.getApplicationContext<android.app.Application>()+        val manager = AppWidgetManager.getInstance(app)+        val shadow = org.robolectric.Shadows.shadowOf(manager)+        val info = AppWidgetProviderInfo().apply {+            provider = ComponentName("com.example", "com.example.Widget")+            minWidth = 100; minHeight = 100+        }+        shadow.addInstalledProvider(info)+        shadow.addInstalledProvidersForProfile(Process.myUserHandle(), info)+        shadow.setAllowedToBindAppWidgets(true)+        setMonitorApps(listOf(appEntry("com.example")))+        vm.bridge = FakeBridge()+        vm.addWidget(WidgetEntry(provider = "com.example/com.example.Widget", label = "Widget", spanX = 2, spanY = 1))+        await("widget row persisted") {+            all().any { it.itemType == LauncherItemType.APPWIDGET && it.appWidgetProvider == "com.example/com.example.Widget" }+        }+        val row = all().first { it.itemType == LauncherItemType.APPWIDGET }+        assertEquals(2, row.spanX)+        assertNotNull(row.appWidgetId)+        // The bridge also receives wallpaper-blur calls through the holder path.+        val bridge = vm.bridge as FakeBridge+        vm.setWallpaperBlurred(true)+        assertEquals(WALLPAPER_BLUR_PX, bridge.wallpaperBlur)+    }++    @Test fun onLocaleChangedClearsIconsWithoutThrowing() {+        vm.onLocaleChangedImpl()+    }+}
launcher/src/test/java/com/vayunmathur/launcher/tv/platform/TvHomeViewModelRowTest.kt
diff --git a/launcher/src/test/java/com/vayunmathur/launcher/tv/platform/TvHomeViewModelRowTest.kt b/launcher/src/test/java/com/vayunmathur/launcher/tv/platform/TvHomeViewModelRowTest.ktnew file mode 100644index 0000000000..6bbd6545b7--- /dev/null+++ b/launcher/src/test/java/com/vayunmathur/launcher/tv/platform/TvHomeViewModelRowTest.kt@@ -0,0 +1,284 @@+package com.vayunmathur.launcher.tv.platform++import android.content.Intent+import android.content.pm.ActivityInfo+import android.content.pm.ApplicationInfo+import android.content.pm.PackageInfo+import android.content.pm.ResolveInfo+import android.os.Looper+import androidx.test.core.app.ApplicationProvider+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue+import kotlin.test.fail+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows+import org.robolectric.Shadows.shadowOf++/**+ * Row-level tests for [TvHomeViewModel]: seeded tiles exercise move/cancel/+ * remove/finish paths that the state-machine tests cannot reach with an+ * empty grid, plus the open-* intent paths and a refresh over shadowed+ * installed leanback apps (the `refreshApps` tile-building lambda).+ */+@RunWith(RobolectricTestRunner::class)+class TvHomeViewModelRowTest {++    private fun vm(): TvHomeViewModel {+        val app = ApplicationProvider.getApplicationContext<android.app.Application>()+        val created = TvHomeViewModel(app)+        // The init refresh runs on IO threads against real dispatchers; let+        // it settle before any test seeds row state, or it would land later+        // and overwrite the seeded rows with an empty Robolectric grid.+        repeat(200) {+            shadowOf(Looper.getMainLooper()).idle()+            if (!created.home.value.loading) return created+            Thread.sleep(10)+        }+        return created+    }++    private fun tile(pkg: String) = TvTile(pkg, pkg.substringAfterLast('.'), null, null, true)++    @Suppress("UNCHECKED_CAST")+    private fun seed(vm: TvHomeViewModel, pkgs: List<String>, persisted: List<String> = pkgs) {+        val homeField = TvHomeViewModel::class.java.getDeclaredField("_home").apply { isAccessible = true }+        val flow = homeField.get(vm) as MutableStateFlow<TvHomeState>+        flow.value = flow.value.copy(rowApps = pkgs.map(::tile), loading = false)+        val persistedField = TvHomeViewModel::class.java+            .getDeclaredField("lastPersistedOrder").apply { isAccessible = true }+        persistedField.set(vm, persisted)+    }++    private fun order(vm: TvHomeViewModel): List<String> = vm.home.value.rowApps.map { it.packageName }++    /** Reads the persisted TV order on a worker thread: collecting the DataStore flow via runBlocking on Robolectric's main thread can deadlock. */+    private fun persistedOrder(): List<String>? {+        val app = ApplicationProvider.getApplicationContext<android.app.Application>()+        var result: List<String>? = null+        val thread = Thread {+            result = runBlocking {+                com.vayunmathur.launcher.tv.data.TvPrefs(app).settings.first().appOrder+            }+        }+        thread.start()+        thread.join(2000)+        return result+    }++    private fun await(vm: TvHomeViewModel, description: String, cond: () -> Boolean) {+        repeat(1000) {+            shadowOf(Looper.getMainLooper()).idle()+            if (cond()) return+            Thread.sleep(10)+        }+        fail("timed out waiting for: $description (state=${vm.home.value})")+    }++    @Test fun moveKeyMovesHeldTileBothWaysAndClampsAtEnds() {+        val v = vm(); seed(v, listOf("a.one", "b.two", "c.three"))+        v.startMove("b.two")+        v.moveKey("b.two", 1)+        assertEquals(listOf("a.one", "c.three", "b.two"), order(v))+        v.moveKey("b.two", 1) // already last: no-op+        assertEquals(listOf("a.one", "c.three", "b.two"), order(v))+        v.moveKey("b.two", -5) // clamps to front via coerce + single-step move semantics+        assertEquals("b.two", order(v).first())+        assertEquals(3, order(v).size)+    }++    @Test fun moveKeyIgnoresUnknownAndUnheldPackages() {+        val v = vm(); seed(v, listOf("a.one", "b.two"))+        v.moveKey("a.one", 1) // not held+        assertEquals(listOf("a.one", "b.two"), order(v))+        v.startMove("a.one")+        v.moveKey("z.missing", 1)+        assertEquals(listOf("a.one", "b.two"), order(v))+    }++    @Test fun cancelMoveRestoresPersistedOrderAndKeepsArmed() {+        val v = vm(); seed(v, listOf("a.one", "b.two", "c.three"))+        v.startMove("a.one")+        v.moveKey("a.one", 1)+        assertEquals(listOf("b.two", "a.one", "c.three"), order(v))+        v.cancelMove()+        assertNull(v.home.value.movingKey)+        assertEquals(listOf("a.one", "b.two", "c.three"), order(v))+        assertTrue(v.home.value.reorderArmed)+    }++    @Test fun toggleOffWhileHoldingRestoresPersistedOrder() {+        val v = vm(); seed(v, listOf("a.one", "b.two", "c.three"))+        v.startMove("b.two")+        v.moveKey("b.two", -1)+        assertEquals(listOf("b.two", "a.one", "c.three"), order(v))+        v.toggleReorder()+        assertFalse(v.home.value.reorderArmed)+        assertNull(v.home.value.movingKey)+        assertEquals(listOf("a.one", "b.two", "c.three"), order(v))+    }++    @Test fun pressTileWhileAnotherIsHeldDoesNothing() {+        val v = vm(); seed(v, listOf("a.one", "b.two"))+        v.startMove("a.one")+        v.pressTile("b.two")+        assertEquals("a.one", v.home.value.movingKey)+        assertEquals(listOf("a.one", "b.two"), order(v))+    }++    @Test fun finishMovePersistsOnScreenOrderAndClearsHold() {+        val v = vm(); seed(v, listOf("a.one", "b.two", "c.three"))+        v.startMove("c.three")+        v.moveKey("c.three", -1)+        v.finishMove()+        await(v, "hold cleared after finishMove") { v.home.value.movingKey == null }+        assertEquals(listOf("a.one", "c.three", "b.two"), order(v))+        assertTrue(v.home.value.reorderArmed) // stays armed for the next move+        assertEquals(listOf("a.one", "c.three", "b.two"), persistedOrder())+    }++    @Test fun removeTileDropsTileClosesMenuAndPersistsKeptOrder() {+        val v = vm(); seed(v, listOf("a.one", "b.two", "c.three"))+        v.openEditMenu("b.two")+        v.removeTile("b.two")+        assertEquals(listOf("a.one", "c.three"), order(v))+        assertNull(v.home.value.editingKey)+        await(v, "removal persisted") { persistedOrder() == listOf("a.one", "c.three") }+    }++    @Test fun openTileForMissingPackageLeavesStateUntouched() {+        val v = vm(); seed(v, listOf("a.one"))+        v.openTile("no.such.package")+        v.openAppStore()+        assertEquals(listOf("a.one"), order(v))+        assertNull(v.home.value.movingKey)+    }++    @Test fun openSettingsAndNetworkSettingsStartActivities() {+        val app = ApplicationProvider.getApplicationContext<android.app.Application>()+        val v = vm()+        v.openSettings()+        val started = shadowOf(app).nextStartedActivity+        assertEquals(android.provider.Settings.ACTION_SETTINGS, started?.action)+        v.openNetworkSettings()+        val network = shadowOf(app).nextStartedActivity+        assertTrue(+            network?.action in listOf(+                android.provider.Settings.ACTION_WIFI_SETTINGS,+                android.provider.Settings.ACTION_WIRELESS_SETTINGS,+                android.provider.Settings.ACTION_SETTINGS,+            ),+        )+    }++    @Test fun uninstallOrInfoForUnknownPackageOpensAppDetailsAndClosesMenu() {+        val app = ApplicationProvider.getApplicationContext<android.app.Application>()+        val v = vm(); seed(v, listOf("a.one"))+        v.openEditMenu("a.one")+        v.uninstallOrInfo("a.one") // not installed per shadow PM: not user-installed+        val started = shadowOf(app).nextStartedActivity+        assertEquals(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS, started?.action)+        assertEquals("package:a.one", started?.dataString)+        assertNull(v.home.value.editingKey)+    }++    @Test fun refreshAppsBuildsTilesFromShadowedLeanbackApps() {+        val app = ApplicationProvider.getApplicationContext<android.app.Application>()+        val pm = app.packageManager+        val shadowPm = shadowOf(pm)+        for (pkg in listOf("com.netflix.ninja", "com.example.alpha", "com.example.beta")) {+            val component = android.content.ComponentName(pkg, "$pkg.Main")+            val resolve = ResolveInfo().apply {+                activityInfo = ActivityInfo().apply {+                    packageName = pkg+                    name = "$pkg.Main"+                }+            }+            shadowPm.addResolveInfoForIntent(+                Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LEANBACK_LAUNCHER),+                resolve,+            )+            shadowPm.addActivityIfNotPresent(component)+            shadowPm.addIntentFilterForActivity(+                component,+                android.content.IntentFilter(Intent.ACTION_MAIN).apply {+                    addCategory(Intent.CATEGORY_LEANBACK_LAUNCHER)+                    addCategory(Intent.CATEGORY_DEFAULT)+                },+            )+            val packageInfo = PackageInfo().apply {+                packageName = pkg+                applicationInfo = ApplicationInfo().apply {+                    packageName = pkg+                    flags = 0+                }+            }+            shadowPm.addPackage(packageInfo)+        }+        // A sibling test may have persisted a row order; a saved order is+        // honoured verbatim (no top-up), so persist one naming these apps.+        val writer = Thread {+            runBlocking {+                com.vayunmathur.launcher.tv.data.TvPrefs(app)+                    .saveOrder(listOf("com.netflix.ninja", "com.example.alpha", "com.example.beta"))+            }+        }+        writer.start(); writer.join(5000)+        // Registration preceded construction, so the init refresh already+        // rebuilds with these apps; no second refreshApps() is needed.+        val v = vm()+        await(v, "tiles built") { v.home.value.rowApps.isNotEmpty() }+        val pkgs = order(v)+        assertTrue("com.netflix.ninja" in pkgs, "expected default-row netflix in $pkgs")+        assertFalse(v.home.value.loading)+        assertEquals(pkgs.size, pkgs.distinct().size)+        // The App Store (reported installed by Robolectric's shadow PM) owns+        // a bottom-row slot, so it must not also appear on the main row.+        assertFalse(TvHomeViewModel.APP_STORE in pkgs)+    }++    @Test fun refreshAppsDoesNotClobberInProgressMove() {+        val v = vm(); seed(v, listOf("a.one", "b.two"))+        v.startMove("a.one")+        v.refreshApps()+        shadowOf(Looper.getMainLooper()).idle()+        assertEquals("a.one", v.home.value.movingKey)+        assertEquals(listOf("a.one", "b.two"), order(v))+    }++    @Test fun openAddMenuShowsMenuEvenWithNoCandidates() {+        val v = vm(); seed(v, listOf("a.one"))+        v.openAddMenu(replaceIndex = 0)+        await(v, "add menu shown") { v.home.value.showAddMenu }+        assertEquals(0, v.home.value.addReplacesIndex)+        assertTrue(v.home.value.addCandidates.none { it.packageName == "a.one" })+    }++    @Test fun pickAddCandidateDismissesAddMenu() {+        val v = vm(); seed(v, listOf("a.one", "b.two"))+        // Simulate an open add menu replacing the first slot.+        val homeField = TvHomeViewModel::class.java.getDeclaredField("_home").apply { isAccessible = true }+        @Suppress("UNCHECKED_CAST")+        val flow = homeField.get(v) as MutableStateFlow<TvHomeState>+        flow.value = flow.value.copy(showAddMenu = true, addReplacesIndex = 0)+        v.pickAddCandidate("z.added")+        await(v, "add menu dismissed") { !v.home.value.showAddMenu }+        assertEquals(-1, v.home.value.addReplacesIndex)+        assertTrue(v.home.value.addCandidates.isEmpty())+    }++    @Test fun refreshDefaultHomeMatchesRoleHelper() {+        val v = vm()+        val activity = org.robolectric.Robolectric.buildActivity(android.app.Activity::class.java).create().get()+        v.refreshDefaultHome(activity)+        // Robolectric resolves HOME to this app's own manifest activity.+        assertEquals(TvHomeRole.isDefaultHome(activity), v.home.value.isDefaultHome)+        v.requestHomeRole(activity) // must not throw when role cannot be taken+    }+}