Modern Apps git

← Modern-Apps.git

music: add tests for library, viewmodel, playback and screens (84 tests)

Commit
278b2e5f90d1c2c3faf1bde07ce9aeda82c9b50e
Author
Vayun Mathur <[email protected]>
When
2026-11-15 18:58 UTC (20 days ago)
Parents
4a4349e
New unit/Robolectric tests covering the previously uncovered core of
the music module: MusicViewModel and its entity states, the Room half
of MusicRepository (playlist/matching CRUD, the derived+stored
matchings merge, tag-cache backfill) via TestMusicRepository, which
reflectively swaps the SQLCipher db delegate for an in-memory Room
database (the seam todo tests already use), MusicViewModel playlist
CRUD, CastPlayback/CastingPlayer session-less logic, MusicLibraryTree
browse/search guards, migrations SQL, MediaStore reader edge cases,
and Compose tests for album/artist/playlist detail screens (populated
from FakeMediaProvider plus the in-memory Room playlists), the player
column, queue, songs screen, tabs and shared components.

Skipped, with reasons: CastPlayback session/open/transcode paths and
CastQueue handover (need a live Cast session), PlaybackService
session callbacks (need a live media3 player), and MusicTabsScreen
pager-host effects (WorkManager enqueue). Their session-less and
state-driven halves are covered.

Coverage (JaCoCo INSTRUCTION, :music:createMergedCoverageReport):
12,978 covered / 17,133 missed (43.1%) -> 19,136 covered / 10,975
missed (63.6%), +6,158 covered instructions (final full run; an
intermediate run measured 19,175/+6,197 depending on test ordering).

Verified: :music:testDevUnitTest (216 tests, 0 failures),
:music:detekt and :music:lint green.

Diff

music/src/test/java/com/vayunmathur/music/data/MusicMigrationsTest.kt
diff --git a/music/src/test/java/com/vayunmathur/music/data/MusicMigrationsTest.kt b/music/src/test/java/com/vayunmathur/music/data/MusicMigrationsTest.ktnew file mode 100644index 0000000000..2fd32be220--- /dev/null+++ b/music/src/test/java/com/vayunmathur/music/data/MusicMigrationsTest.kt@@ -0,0 +1,119 @@+package com.vayunmathur.music.data++import androidx.sqlite.SQLiteConnection+import androidx.sqlite.SQLiteStatement+import kotlinx.coroutines.runBlocking+import java.lang.reflect.InvocationHandler+import java.lang.reflect.Proxy+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/**+ * MusicDatabase's migrations and matching type codes, driven against a+ * recording SQLiteConnection proxy: creating a real database needs SQLCipher+ * (unavailable on a host JVM), but a migration is just the SQL it prepares, in+ * order — and issuing the wrong SQL is exactly what a migration test catches.+ * Room 3 migrations are suspending and take an androidx.sqlite connection,+ * whose execSQL goes through prepare/step, so the proxy records prepares.+ */+class MusicMigrationsTest {++    private class RecordingDb {+        val sql = mutableListOf<String>()++        private fun defaultValue(type: Class<*>): Any? = when (type) {+            java.lang.Boolean.TYPE -> false+            java.lang.Integer.TYPE -> 0+            java.lang.Long.TYPE -> 0L+            java.lang.Float.TYPE -> 0f+            java.lang.Double.TYPE -> 0.0+            String::class.java -> ""+            else -> null+        }++        private val statement: SQLiteStatement = Proxy.newProxyInstance(+            SQLiteStatement::class.java.classLoader,+            arrayOf(SQLiteStatement::class.java),+            InvocationHandler { _, method, _ -> defaultValue(method.returnType) },+        ) as SQLiteStatement++        val connection: SQLiteConnection = Proxy.newProxyInstance(+            SQLiteConnection::class.java.classLoader,+            arrayOf(SQLiteConnection::class.java),+            InvocationHandler { _, method, args ->+                if (method.name == "prepare" && args?.firstOrNull() is String) {+                    sql += args.first() as String+                    statement+                } else {+                    defaultValue(method.returnType)+                }+            },+        ) as SQLiteConnection+    }++    @Test+    fun matchingTypeCodesFollowTheMinPlusHundredMaxScheme() {+        assertEquals(300, TYPE_MUSIC_PLAYLIST)+        assertEquals(201, TYPE_ALBUM_ARTIST)+    }++    @Test+    fun migration1To2CreatesThePlaylistTable() {+        val recording = RecordingDb()+        runBlocking { MIGRATION_1_2.migrate(recording.connection) }+        assertEquals(1, recording.sql.size)+        assertTrue(recording.sql.single().contains("CREATE TABLE IF NOT EXISTS `Playlist`"))+        assertTrue(recording.sql.single().contains("`name` TEXT NOT NULL"))+    }++    @Test+    fun migration2To3AddsDurationTrackAndYearColumnsInOrder() {+        val recording = RecordingDb()+        runBlocking { MIGRATION_2_3.migrate(recording.connection) }+        assertEquals(+            listOf(+                "ALTER TABLE Music ADD COLUMN duration INTEGER NOT NULL DEFAULT 0",+                "ALTER TABLE Music ADD COLUMN trackNumber INTEGER NOT NULL DEFAULT 0",+                "ALTER TABLE Music ADD COLUMN year INTEGER NOT NULL DEFAULT 0",+            ),+            recording.sql,+        )+    }++    @Test+    fun migration3To4AddsTheDiscNumberColumn() {+        val recording = RecordingDb()+        runBlocking { MIGRATION_3_4.migrate(recording.connection) }+        assertEquals(+            listOf("ALTER TABLE Music ADD COLUMN discNumber INTEGER NOT NULL DEFAULT 1"),+            recording.sql,+        )+    }++    @Test+    fun migration4To5DropsAlbumArtistTablesButKeepsPlaylistMatchings() {+        val recording = RecordingDb()+        runBlocking { MIGRATION_4_5.migrate(recording.connection) }+        assertEquals(+            listOf(+                "DROP TABLE IF EXISTS Album",+                "DROP TABLE IF EXISTS Artist",+                "DELETE FROM ManyManyMatching WHERE type = $TYPE_ALBUM_ARTIST",+            ),+            recording.sql,+        )+        assertTrue(recording.sql.none { it.contains(TYPE_MUSIC_PLAYLIST.toString()) })+    }++    @Test+    fun theRegisteredMigrationChainRuns1To5WithoutGaps() {+        assertEquals(+            listOf(1 to 2, 2 to 3, 3 to 4, 4 to 5),+            MusicDatabase.migrations.map { it.startVersion to it.endVersion },+        )+        val recording = RecordingDb()+        runBlocking { MusicDatabase.migrations.forEach { it.migrate(recording.connection) } }+        assertEquals(1 + 3 + 1 + 3, recording.sql.size)+    }+}
music/src/test/java/com/vayunmathur/music/data/MusicRepositoryExpandedTest.kt
diff --git a/music/src/test/java/com/vayunmathur/music/data/MusicRepositoryExpandedTest.kt b/music/src/test/java/com/vayunmathur/music/data/MusicRepositoryExpandedTest.ktnew file mode 100644index 0000000000..08ac79741f--- /dev/null+++ b/music/src/test/java/com/vayunmathur/music/data/MusicRepositoryExpandedTest.kt@@ -0,0 +1,94 @@+package com.vayunmathur.music.data++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.music.FakeAndroidKeyStore+import com.vayunmathur.music.FakeMediaProvider+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.runBlocking+import org.junit.AfterClass+import org.junit.Before+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import org.robolectric.shadows.ShadowContentResolver+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/**+ * MusicRepository's in-memory (MediaStore) half against the populated fake+ * library: refresh publishing, idempotence, and the loaded flag. The Room half+ * (playlists, matchings, tag cache) needs SQLCipher, which cannot load on a host+ * JVM, so it is not asserted here; backfillTags is likewise device-only.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class MusicRepositoryExpandedTest {++    companion object {+        @JvmStatic+        @AfterClass+        fun tearDownClass() {+            FakeMediaProvider.enabled = false+            val app = ApplicationProvider.getApplicationContext<Context>()+            runBlocking { MusicRepository.get(app).refresh() }+        }+    }++    @Before+    fun setUp() {+        FakeMediaProvider.enabled = true+        FakeAndroidKeyStore.install()+        ShadowContentResolver.registerProviderInternal("media", FakeMediaProvider())+    }++    private val context: Context get() = ApplicationProvider.getApplicationContext()+    private fun repo(): MusicRepository = MusicRepository.get(context)++    @Test+    fun `refresh publishes songs albums artists and the loaded flag`() = runBlocking {+        val repo = repo()+        repo.refresh()+        assertEquals(listOf(1L, 2L, 3L), repo.getAllMusic().map { it.id })+        assertEquals(listOf(21L, 22L), repo.getAllAlbums().map { it.id })+        assertEquals(listOf(11L, 12L), repo.getAllArtists().map { it.id })+        assertTrue(repo.loaded.first())+        assertEquals(repo.getAllMusic(), repo.music.first())+        assertEquals(repo.getAllAlbums(), repo.albums.first())+        assertEquals(repo.getAllArtists(), repo.artists.first())+    }++    @Test+    fun `refresh is repeatable and reflects the provider being switched off`() = runBlocking {+        val repo = repo()+        repo.refresh()+        repo.refresh()+        assertEquals(3, repo.getAllMusic().size)++        FakeMediaProvider.enabled = false+        repo.refresh()+        assertEquals(emptyList(), repo.getAllMusic())+        assertEquals(emptyList(), repo.getAllAlbums())+        assertEquals(emptyList(), repo.getAllArtists())+        // Once loaded, the flag stays up even for an empty library: "loaded, and+        // there is nothing" is a different screen from "not read yet".+        assertTrue(repo.loaded.first())+    }++    @Test+    fun `refreshed songs keep disc track duration and year split from MediaStore`() = runBlocking {+        val repo = repo()+        repo.refresh()+        val songs = repo.getAllMusic().associateBy { it.id }+        assertEquals(1, songs.getValue(1L).discNumber)+        assertEquals(2, songs.getValue(1L).trackNumber)+        assertEquals(200_000L, songs.getValue(1L).duration)+        assertEquals(2019, songs.getValue(1L).year)+        assertEquals(2, songs.getValue(2L).discNumber)+        assertEquals(5, songs.getValue(2L).trackNumber)+        assertEquals(0, songs.getValue(2L).year)+        assertEquals("Album Two", songs.getValue(3L).album)+        assertEquals(22L, songs.getValue(3L).albumId)+    }+}
music/src/test/java/com/vayunmathur/music/data/MusicRepositoryRoomTest.kt
diff --git a/music/src/test/java/com/vayunmathur/music/data/MusicRepositoryRoomTest.kt b/music/src/test/java/com/vayunmathur/music/data/MusicRepositoryRoomTest.ktnew file mode 100644index 0000000000..df9a0eebdf--- /dev/null+++ b/music/src/test/java/com/vayunmathur/music/data/MusicRepositoryRoomTest.kt@@ -0,0 +1,149 @@+package com.vayunmathur.music.data++import android.app.Application+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.library.util.ManyManyMatching+import com.vayunmathur.music.FakeAndroidKeyStore+import com.vayunmathur.music.FakeMediaProvider+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.runBlocking+import org.junit.AfterClass+import org.junit.Before+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import org.robolectric.shadows.ShadowContentResolver+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/**+ * The Room-backed half of [MusicRepository] — playlists and matchings —+ * against a real in-memory Room database (see [TestMusicRepository]).+ * MediaStore reads still come from [FakeMediaProvider], so the combined+ * matchings flow can be asserted end to end: derived album/artist pairs+ * plus stored playlist rows, with persisted album/artist rows filtered out.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class MusicRepositoryRoomTest {++    companion object {+        @JvmStatic+        @AfterClass+        fun tearDownClass() {+            // The fake provider + repository singleton outlive this class in+            // Robolectric's shared sandbox: switch the provider off and+            // republish an empty library for later classes.+            FakeMediaProvider.enabled = false+            val app = ApplicationProvider.getApplicationContext<Application>()+            runBlocking { MusicRepository.get(app).refresh() }+        }+    }+++    private val app: Application get() = ApplicationProvider.getApplicationContext()+    private lateinit var repo: MusicRepository+    private lateinit var db: MusicDatabase++    @Before+    fun setUp() {+        FakeMediaProvider.enabled = true+        FakeAndroidKeyStore.install()+        ShadowContentResolver.registerProviderInternal("media", FakeMediaProvider())+        val (repository, database) = TestMusicRepository.install(app)+        repo = repository+        db = database+    }++    @Test+    fun playlistCrudRoundTripsThroughRoom() = runBlocking {+        assertTrue(repo.getAllPlaylists().isEmpty())+        val id = repo.upsertPlaylist(Playlist(name = "Road Mix"))+        assertTrue(id > 0, "upsert must return the generated id, was $id")+        repo.upsertPlaylist(Playlist(name = "Chill"))+        val all = repo.getAllPlaylists()+        assertEquals(listOf("Road Mix", "Chill"), all.map { it.name })+        // Renaming is an upsert with the same primary key.+        repo.upsertPlaylist(Playlist(id = id, name = "Road Mix 2"))+        assertEquals("Road Mix 2", repo.getAllPlaylists().first { it.id == id }.name)+        assertEquals(2, repo.getAllPlaylists().size)+        repo.deletePlaylistById(id)+        assertEquals(listOf("Chill"), repo.getAllPlaylists().map { it.name })+    }++    @Test+    fun playlistsFlowPublishesRoomContents() = runBlocking {+        repo.upsertPlaylist(Playlist(name = "Flow Mix"))+        val first = repo.playlists.first()+        assertEquals(listOf("Flow Mix"), first.map { it.name })+    }++    @Test+    fun matchingCrudIsDirectionalAndTyped() = runBlocking {+        repo.upsertMatching(ManyManyMatching(leftID = 1, rightID = 50, type = TYPE_MUSIC_PLAYLIST))+        repo.upsertMatching(ManyManyMatching(leftID = 2, rightID = 50, type = TYPE_MUSIC_PLAYLIST))+        repo.upsertMatching(ManyManyMatching(leftID = 1, rightID = 60, type = TYPE_MUSIC_PLAYLIST))+        repo.upsertMatchings(+            listOf(ManyManyMatching(leftID = 3, rightID = 50, type = TYPE_MUSIC_PLAYLIST)),+        )+        assertEquals(setOf(1L, 2L, 3L), repo.getFromRight(50, TYPE_MUSIC_PLAYLIST).toSet())+        assertEquals(setOf(50L, 60L), repo.getFromLeft(1, TYPE_MUSIC_PLAYLIST).toSet())+        // A different type namespace does not leak into playlist lookups.+        assertTrue(repo.getFromRight(50, TYPE_ALBUM_ARTIST).isEmpty())++        repo.deleteMatch(left = 1, right = 50, type = TYPE_MUSIC_PLAYLIST)+        assertEquals(setOf(2L, 3L), repo.getFromRight(50, TYPE_MUSIC_PLAYLIST).toSet())+        repo.deleteFromLeft(2, TYPE_MUSIC_PLAYLIST)+        assertEquals(setOf(3L), repo.getFromRight(50, TYPE_MUSIC_PLAYLIST).toSet())+        repo.deleteFromRight(60, TYPE_MUSIC_PLAYLIST)+        assertTrue(repo.getFromLeft(1, TYPE_MUSIC_PLAYLIST).isEmpty())+        repo.deleteByType(TYPE_MUSIC_PLAYLIST)+        assertTrue(repo.getFromRight(50, TYPE_MUSIC_PLAYLIST).isEmpty())+    }++    @Test+    fun matchingsFlowMergesDerivedPairsWithStoredPlaylistRowsOnly() = runBlocking {+        repo.refresh()+        // Stored playlist row (kept) + a stale persisted album/artist row+        // (must be filtered out by the repository's merge, see its KDoc).+        repo.upsertMatching(ManyManyMatching(leftID = 2, rightID = 77, type = TYPE_MUSIC_PLAYLIST))+        repo.upsertMatching(ManyManyMatching(leftID = 21, rightID = 11, type = TYPE_ALBUM_ARTIST))+        val merged = repo.matchings.first { merged -> merged.any { it.type == TYPE_MUSIC_PLAYLIST } }+        val playlistRows = merged.filter { it.type == TYPE_MUSIC_PLAYLIST }+        assertEquals(listOf(2L to 77L), playlistRows.map { it.leftID to it.rightID })+        // Derived pairs are recomputed from MediaStore, not read from Room:+        // album 21 (both Artist One songs) maps to artist 11 exactly once.+        val derived = merged.filter { it.type == TYPE_ALBUM_ARTIST }+        assertEquals(1, derived.count { it.leftID == 21L && it.rightID == 11L })+    }++    @Test+    fun backfillTagsAppliesCachedDurationsAndPrunesStaleRows() = runBlocking {+        repo.refresh()+        // Alpha Song (id 2) has year 0 in MediaStore: seed a tag-cache row+        // for it, plus a stale row for a song that no longer exists.+        val alpha = repo.getAllMusic().first { it.id == 2L }+        db.musicDao().upsertAll(+            listOf(+                alpha.copy(year = 2001, duration = 181_000),+                alpha.copy(id = 99, title = "Ghost", year = 1990),+            ),+        )+        repo.backfillTags()+        val after = repo.getAllMusic().first { it.id == 2L }+        assertEquals(2001, after.year)+        assertEquals(180_000, after.duration) // cached duration only fills a zero duration+        // The stale cache row was pruned by backfill.+        assertTrue(db.musicDao().getAll().none { it.id == 99L })+    }++    @Test+    fun clearMatchingsEmptiesEveryType() = runBlocking {+        repo.upsertMatching(ManyManyMatching(leftID = 1, rightID = 2, type = TYPE_MUSIC_PLAYLIST))+        repo.upsertMatching(ManyManyMatching(leftID = 3, rightID = 4, type = TYPE_ALBUM_ARTIST))+        repo.clearMatchings()+        assertTrue(repo.getFromRight(2, TYPE_MUSIC_PLAYLIST).isEmpty())+        assertTrue(repo.getFromRight(4, TYPE_ALBUM_ARTIST).isEmpty())+    }+}
music/src/test/java/com/vayunmathur/music/data/TestMusicRepository.kt
diff --git a/music/src/test/java/com/vayunmathur/music/data/TestMusicRepository.kt b/music/src/test/java/com/vayunmathur/music/data/TestMusicRepository.ktnew file mode 100644index 0000000000..f9c8578ef3--- /dev/null+++ b/music/src/test/java/com/vayunmathur/music/data/TestMusicRepository.kt@@ -0,0 +1,48 @@+package com.vayunmathur.music.data++import android.content.Context+import androidx.room3.Room++/**+ * Gives the [MusicRepository] singleton an in-memory Room database for tests.+ *+ * The production database is SQLCipher-backed (native library), which cannot+ * open on the Robolectric JVM — that is why playlist/matching code used to be+ * untestable here. The only seam available without touching main sources is+ * the lazy `db` delegate in `RoomRepository`: we reflectively replace that+ * delegate with one returning an in-memory database. Every repository /+ * ViewModel / screen method then runs its genuine code (DAO SQL, flow+ * combination, playlist CRUD) against real Room DAOs. Only storage is faked,+ * exactly as todo's `TestTodoRepository` does for its repository.+ */+object TestMusicRepository {++    /** Builds a fresh in-memory DB, injects it into the singleton, returns both. */+    fun install(context: Context): Pair<MusicRepository, MusicDatabase> {+        val app = context.applicationContext+        val database = Room.inMemoryDatabaseBuilder(app, MusicDatabase::class.java)+            .allowMainThreadQueries()+            .build()+        val repository = MusicRepository.get(app)+        injectDatabase(repository, database)+        return repository to database+    }++    private fun injectDatabase(repository: MusicRepository, database: MusicDatabase) {+        var type: Class<*>? = repository.javaClass+        while (type != null) {+            for (field in type.declaredFields) {+                val looksLikeDbDelegate = field.type == Lazy::class.java ||+                    field.name.contains("db", ignoreCase = true)+                if (!looksLikeDbDelegate) continue+                runCatching {+                    field.isAccessible = true+                    field.set(repository, lazyOf(database))+                    return+                }+            }+            type = type.superclass+        }+        error("Could not find RoomRepository db delegate on MusicRepository")+    }+}
music/src/test/java/com/vayunmathur/music/platform/CastPlaybackExpandedTest.kt
diff --git a/music/src/test/java/com/vayunmathur/music/platform/CastPlaybackExpandedTest.kt b/music/src/test/java/com/vayunmathur/music/platform/CastPlaybackExpandedTest.ktnew file mode 100644index 0000000000..d631550c55--- /dev/null+++ b/music/src/test/java/com/vayunmathur/music/platform/CastPlaybackExpandedTest.kt@@ -0,0 +1,93 @@+package com.vayunmathur.music.platform++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.music.data.Music+import com.vayunmathur.sdk.cast.PlaybackAction+import com.vayunmathur.sdk.cast.PlaybackCommand+import kotlinx.coroutines.runBlocking+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.assertFalse+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * CastPlayback session-less behaviour beyond CastPlaybackTest: every transport+ * command is a silent no-op without a TV, close/clearCache are idempotent, and+ * support probing returns a real verdict instead of throwing on a host JVM.+ * Actually opening a session needs a Cast receiver, so open()/play() success+ * paths are device-only and not faked here.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class CastPlaybackExpandedTest {++    private val context: Context get() = ApplicationProvider.getApplicationContext()++    private fun song(id: Long) = Music(+        id = id, title = "Song $id", artist = "Artist", artistId = 1, album = "Album",+        albumId = 7, uri = "content://media/$id", duration = 180_000, trackNumber = 1, year = 2020,+    )++    @Test+    fun `support probing returns a verdict and growing starts empty`() {+        assertNotNull(CastPlayback.support(context))+        assertNull(CastPlayback.growing.value)+        assertNull(CastPlayback.tv.value)+        assertFalse(CastPlayback.isCasting)+    }++    @Test+    fun `every playback command is a no op without a session`() {+        for (action in PlaybackAction.entries) {+            CastPlayback.send(PlaybackCommand(action, 1.5))+        }+        CastPlayback.send(PlaybackCommand(PlaybackAction.SeekTo, 30_000.0))+        CastPlayback.send(PlaybackCommand(PlaybackAction.SetSpeed, 2.0))+        assertEquals(CastPlayback.State.Idle, CastPlayback.state.value)+    }++    @Test+    fun `playing several songs without a session changes nothing`() {+        runBlocking {+            CastPlayback.play(context, song(1))+            CastPlayback.play(context, song(2), startPositionMs = 45_000)+            CastPlayback.play(context, song(3), startPositionMs = -1)+        }+        assertEquals(CastPlayback.State.Idle, CastPlayback.state.value)+        assertNull(CastPlayback.growing.value)+        assertNull(CastPlayback.tv.value)+    }++    @Test+    fun `close and clear cache are idempotent when nothing exists`() {+        CastPlayback.close()+        CastPlayback.close()+        CastPlayback.clearCache(context)+        CastPlayback.clearCache(context)+        assertEquals(CastPlayback.State.Idle, CastPlayback.state.value)++        val opusDir = File(context.cacheDir, "cast-opus").apply { mkdirs() }+        File(opusDir, "nested").mkdirs()+        File(File(opusDir, "nested"), "9.opus").writeBytes(byteArrayOf(9))+        CastPlayback.clearCache(context)+        assertTrue(!opusDir.exists())+        CastPlayback.clearCache(context)+        assertTrue(!File(context.cacheDir, "cast-art").exists() || File(context.cacheDir, "cast-art").list().isNullOrEmpty())+    }++    @Test+    fun `open failure leaves no growing resource and no tv snapshot`() {+        val opened = runBlocking { CastPlayback.open(context) }+        assertFalse(opened)+        assertEquals(CastPlayback.State.Idle, CastPlayback.state.value)+        assertNull(CastPlayback.growing.value)+        assertNull(CastPlayback.tv.value)+    }+}
music/src/test/java/com/vayunmathur/music/platform/MusicViewModelExpandedTest.kt
diff --git a/music/src/test/java/com/vayunmathur/music/platform/MusicViewModelExpandedTest.kt b/music/src/test/java/com/vayunmathur/music/platform/MusicViewModelExpandedTest.ktnew file mode 100644index 0000000000..07d756a7f3--- /dev/null+++ b/music/src/test/java/com/vayunmathur/music/platform/MusicViewModelExpandedTest.kt@@ -0,0 +1,164 @@+package com.vayunmathur.music.platform++import android.app.Application+import android.content.Context+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.music.FakeAndroidKeyStore+import com.vayunmathur.music.FakeMediaProvider+import com.vayunmathur.music.data.MusicRepository+import kotlinx.coroutines.runBlocking+import org.junit.AfterClass+import org.junit.Before+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import org.robolectric.shadows.ShadowContentResolver+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * MusicViewModel against the populated fake library (see [FakeMediaProvider]):+ * per-entity lookup over the in-memory flows, and delegation of every transport+ * call to PlaybackManager. Anything Room-backed is deliberately not exercised:+ * playlistState/playlists and the matched*For* accessors collect the Room+ * playlist/matching flows, whose SQLCipher nativeOpen throws UnsatisfiedLinkError+ * on a host JVM (verified in the verification run), so those paths — and+ * playlist CRUD — run on device only. This mirrors PopulatedLibraryTest, which+ * only ever touches music/album/artist state.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class MusicViewModelExpandedTest {++    @get:Rule+    val composeRule = createComposeRule()++    companion object {+        @JvmStatic+        @AfterClass+        fun tearDownClass() {+            FakeMediaProvider.enabled = false+            val app = ApplicationProvider.getApplicationContext<Context>()+            runBlocking { MusicRepository.get(app).refresh() }+        }+    }++    @Before+    fun setUp() {+        FakeMediaProvider.enabled = true+        FakeAndroidKeyStore.install()+        ShadowContentResolver.registerProviderInternal("media", FakeMediaProvider())+        val app = ApplicationProvider.getApplicationContext<Application>()+        org.robolectric.Shadows.shadowOf(app).setComponentNameAndServiceForBindService(+            android.content.ComponentName(app, com.vayunmathur.music.service.PlaybackService::class.java),+            android.os.Binder(),+        )+        runBlocking { MusicRepository.get(app).refresh() }+    }++    private val app: Application get() = ApplicationProvider.getApplicationContext()++    private fun viewModel(): MusicViewModel =+        MusicViewModel(app, MusicRepository.get(app), PlaybackManager.getInstance(app))++    @Test+    fun `entity states resolve populated songs albums and artists`() {+        val vm = viewModel()+        var songTitle: String? = null+        var albumName: String? = null+        var unknownArtistName: String? = "sentinel"+        var missingSong: Any? = "sentinel"+        composeRule.setContent {+            val song by vm.musicState(1L)+            val album by vm.albumState(21L)+            val artist by vm.artistState(12L)+            val missing by vm.musicState(999L)+            songTitle = song?.title+            albumName = album?.name+            unknownArtistName = artist?.name+            missingSong = missing+        }+        assertEquals("Beta Song", songTitle)+        assertEquals("Album One", albumName)+        // Artist 12 is MediaStore's <unknown> sentinel, normalised to blank.+        assertEquals("", unknownArtistName)+        assertNull(missingSong)+    }++    @Test+    fun `entity flows publish the populated library to subscribers`() {+        val vm = viewModel()+        var songTitles: List<String> = emptyList()+        var albumNames: List<String> = emptyList()+        var artistNames: List<String> = emptyList()+        var loaded = false+        composeRule.setContent {+            val songs by vm.music.collectAsState()+            val albums by vm.albums.collectAsState()+            val artists by vm.artists.collectAsState()+            val isLoaded by vm.loaded.collectAsState()+            songTitles = songs.map { it.title }+            albumNames = albums.map { it.name }+            artistNames = artists.map { it.name }+            loaded = isLoaded+        }+        assertEquals(listOf("Alpha Song", "Beta Song", "Gamma Song"), songTitles.sorted())+        assertEquals(listOf("Album One", "Album Two"), albumNames.sorted())+        assertEquals(listOf("", "Artist One"), artistNames.sorted())+        assertTrue(loaded)+    }++    @Test+    fun `playback calls delegate to the playback manager bookkeeping`() {+        val vm = viewModel()+        val pm = PlaybackManager.getInstance(app)+        val songs = runBlocking { MusicRepository.get(app).getAllMusic() }+        assertEquals(3, songs.size)++        vm.playSong(songs, 2, sourceId = "artist_11", sourceName = "Artist One")+        assertEquals("artist_11", pm.currentSource.value)+        assertEquals("Artist One", pm.currentSourceName.value)+        assertEquals("artist_11", vm.currentSource.value)++        vm.playShuffled(songs, sourceId = "all_songs", sourceName = "All Songs")+        assertEquals("all_songs", pm.currentSource.value)++        // Invalid queues must not clobber the recorded source (PlaybackManager guard).+        vm.playSong(emptyList(), 0, sourceId = "album_99", sourceName = "Nope")+        assertEquals("all_songs", pm.currentSource.value)+        vm.playSong(songs, 99, sourceId = "album_99", sourceName = "Nope")+        assertEquals("all_songs", pm.currentSource.value)++        // Transport without a connected controller is a safe no-op, except seek,+        // which still records the requested position for the UI.+        vm.togglePlayPause()+        vm.skipNext()+        vm.skipPrevious()+        vm.toggleShuffle()+        vm.toggleRepeat()+        vm.seekTo(12_345L)+        assertEquals(12_345L, vm.currentPosition.value)+        vm.seekTo(0L)+        assertEquals(0L, vm.currentPosition.value)+    }++    @Test+    fun `now playing and playing song stay empty while nothing is loaded`() {+        val vm = viewModel()+        var nowPlaying: NowPlayingUiState? = NowPlayingUiState(title = "sentinel")+        var playingId: Long? = 7L+        composeRule.setContent {+            nowPlaying = vm.nowPlayingState()+            playingId = vm.playingSongIdFrom("album_21")+        }+        assertNull(nowPlaying)+        assertNull(playingId)+        assertTrue(vm.music.value.isEmpty() || vm.music.value.size == 3)+    }+}
music/src/test/java/com/vayunmathur/music/platform/MusicViewModelPlaylistTest.kt
diff --git a/music/src/test/java/com/vayunmathur/music/platform/MusicViewModelPlaylistTest.kt b/music/src/test/java/com/vayunmathur/music/platform/MusicViewModelPlaylistTest.ktnew file mode 100644index 0000000000..96bb560bde--- /dev/null+++ b/music/src/test/java/com/vayunmathur/music/platform/MusicViewModelPlaylistTest.kt@@ -0,0 +1,150 @@+package com.vayunmathur.music.platform++import android.app.Application+import android.content.ComponentName+import android.os.Binder+import android.os.Looper+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.music.FakeAndroidKeyStore+import com.vayunmathur.music.FakeMediaProvider+import com.vayunmathur.music.data.MusicRepository+import com.vayunmathur.music.data.Playlist+import com.vayunmathur.music.data.TestMusicRepository+import com.vayunmathur.music.data.TYPE_MUSIC_PLAYLIST+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.launch+import kotlinx.coroutines.ExperimentalCoroutinesApi+import kotlinx.coroutines.runBlocking+import kotlinx.coroutines.test.resetMain+import kotlinx.coroutines.test.setMain+import org.junit.After+import org.junit.AfterClass+import org.junit.Before+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows+import org.robolectric.annotation.Config+import org.robolectric.shadows.ShadowContentResolver+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/**+ * [MusicViewModel] playlist CRUD against a real in-memory Room database+ * (see TestMusicRepository): create/rename/add/remove/delete must land in+ * the repository, and the matching lookups the detail screens use must+ * reflect them. ViewModel writes launch on the main dispatcher, so tests+ * pump Robolectric's main looper while polling the repository.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class MusicViewModelPlaylistTest {++    companion object {+        @JvmStatic+        @AfterClass+        fun tearDownClass() {+            // The fake provider + repository singleton outlive this class in+            // Robolectric's shared sandbox: switch the provider off and+            // republish an empty library for later classes.+            FakeMediaProvider.enabled = false+            val app = ApplicationProvider.getApplicationContext<Application>()+            runBlocking { MusicRepository.get(app).refresh() }+        }+    }+++    private val app: Application get() = ApplicationProvider.getApplicationContext()+    private lateinit var repo: MusicRepository++    @OptIn(ExperimentalCoroutinesApi::class)+    @Before+    fun setUp() {+        // refreshLibrary launches on viewModelScope (Main); Robolectric's+        // paused main looper does not drain it reliably, so use an immediate+        // Main dispatcher (the IO playlist writes are unaffected).+        Dispatchers.setMain(Dispatchers.Unconfined)+        FakeMediaProvider.enabled = true+        FakeAndroidKeyStore.install()+        ShadowContentResolver.registerProviderInternal("media", FakeMediaProvider())+        Shadows.shadowOf(app).setComponentNameAndServiceForBindService(+            ComponentName(app, com.vayunmathur.music.service.PlaybackService::class.java),+            Binder(),+        )+        val (repository, _) = TestMusicRepository.install(app)+        repo = repository+        runBlocking { repo.refresh() }+    }++    @OptIn(ExperimentalCoroutinesApi::class)+    @After+    fun tearDown() {+        Dispatchers.resetMain()+    }++    private fun viewModel(): MusicViewModel =+        MusicViewModel(app, repo, PlaybackManager.getInstance(app))++    private fun await(description: String, condition: suspend () -> Boolean) {+        val deadline = System.currentTimeMillis() + 10_000+        while (System.currentTimeMillis() < deadline) {+            Shadows.shadowOf(Looper.getMainLooper()).idle()+            if (runBlocking { condition() }) return+            Thread.sleep(25)+        }+        assertTrue(runBlocking { condition() }, "timed out waiting for: $description")+    }++    @Test+    fun createRenameAddRemoveAndDeletePlaylistThroughTheViewModel() {+        val vm = viewModel()+        var createdId = -1L+        vm.createPlaylist("Gym") { createdId = it }+        await("playlist created") { repo.getAllPlaylists().any { it.name == "Gym" } }+        val playlist = runBlocking { repo.getAllPlaylists().first { it.name == "Gym" } }+        assertEquals(playlist.id, createdId)++        vm.renamePlaylist(playlist, "Gym Mix")+        await("playlist renamed") {+            repo.getAllPlaylists().firstOrNull { it.id == playlist.id }?.name == "Gym Mix"+        }++        vm.addMusicToPlaylist(playlist.id, musicId = 1L)+        vm.addMusicToPlaylist(playlist.id, musicId = 3L)+        await("tracks added") {+            repo.getFromRight(playlist.id, TYPE_MUSIC_PLAYLIST).toSet() == setOf(1L, 3L)+        }++        vm.removeMusicFromPlaylist(playlist.id, musicId = 1L)+        await("track removed") {+            repo.getFromRight(playlist.id, TYPE_MUSIC_PLAYLIST) == listOf(3L)+        }++        var done = false+        vm.deletePlaylist(Playlist(id = playlist.id, name = "Gym Mix")) { done = true }+        await("playlist deleted") { repo.getAllPlaylists().isEmpty() }+        assertTrue(done, "delete completion callback must run")+    }++    @Test+    fun refreshLibraryPublishesTheFakeLibraryThroughTheViewModel() {+        val vm = viewModel()+        // The library StateFlows are WhileSubscribed: collect them or the+        // upstream MediaStore read never starts.+        val scope = kotlinx.coroutines.CoroutineScope(Dispatchers.Unconfined)+        val jobs = listOf(+            scope.launch { vm.music.collect {} },+            scope.launch { vm.albums.collect {} },+            scope.launch { vm.artists.collect {} },+            scope.launch { vm.loaded.collect {} },+        )+        vm.refreshLibrary()+        // refresh() is synchronous MediaStore work on viewModelScope; the+        // Room backfill behind it uses the in-memory database in tests.+        await("library loaded") { vm.music.value.size == 3 && vm.loaded.value }+        assertEquals(listOf("Album One", "Album Two"), vm.albums.value.map { it.name })+        assertEquals("Artist One", vm.artists.value.first { it.id == 11L }.name)+        jobs.forEach { it.cancel() }+    }+}
music/src/test/java/com/vayunmathur/music/platform/UtilExpandedTest.kt
diff --git a/music/src/test/java/com/vayunmathur/music/platform/UtilExpandedTest.kt b/music/src/test/java/com/vayunmathur/music/platform/UtilExpandedTest.ktnew file mode 100644index 0000000000..86ca99963c--- /dev/null+++ b/music/src/test/java/com/vayunmathur/music/platform/UtilExpandedTest.kt@@ -0,0 +1,124 @@+package com.vayunmathur.music.platform++import android.content.Context+import android.net.Uri+import androidx.compose.ui.Modifier+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onRoot+import androidx.core.net.toUri+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.music.data.Album+import com.vayunmathur.music.data.Artist+import com.vayunmathur.music.data.Music+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertNull++/**+ * Util.kt beyond the already-covered formatters: library grouping with several+ * artists/albums, artwork/thumbnail failure paths (no MediaStore art on a host+ * JVM), collage geometry, and the AlbumArt composables' placeholder branches.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class UtilExpandedTest {++    @get:Rule+    val composeRule = createComposeRule()++    private val context: Context get() = ApplicationProvider.getApplicationContext()++    private fun song(id: Long, albumId: Long, artistId: Long) = Music(+        id = id, title = "Song $id", artist = "Artist $artistId", artistId = artistId,+        album = "Album $albumId", albumId = albumId, uri = "content://media/$id",+        duration = 100_000, trackNumber = 1, year = 2000,+    )++    @Test+    fun `format duration covers minute hour and multi hour boundaries`() {+        assertEquals("0:00", formatDuration(999))+        assertEquals("0:59", formatDuration(59_999))+        assertEquals("1:00", formatDuration(60_000))+        assertEquals("59:59", formatDuration(3_599_000))+        assertEquals("1:00:00", formatDuration(3_600_000))+        assertEquals("2:03:07", formatDuration(7_387_000))+        assertEquals("10:00:00", formatDuration(36_000_000))+    }++    @Test+    fun `album artist pairs join across albums and drop songs with a missing side`() {+        val albumA = Album(21, "A", "content://a/21")+        val albumB = Album(22, "B", "content://a/22")+        val artistA = Artist(11, "RA", "content://r/11")+        val artistB = Artist(12, "RB", "content://r/12")+        val songs = listOf(+            song(1, albumId = 21, artistId = 11),+            song(2, albumId = 21, artistId = 12),+            song(3, albumId = 22, artistId = 12),+            song(4, albumId = 99, artistId = 11),+            song(5, albumId = 21, artistId = 99),+            song(6, albumId = 21, artistId = 11),+        )+        val pairs = albumArtistPairs(songs, listOf(artistA, artistB), listOf(albumA, albumB))+        assertEquals(+            setOf(albumA to artistA, albumA to artistB, albumB to artistB),+            pairs.toSet(),+        )+        assertEquals(3, pairs.size, "duplicate joins from songs 1 and 6 must dedupe")+        assertEquals(emptyList(), albumArtistPairs(emptyList(), listOf(artistA), listOf(albumA)))+    }++    @Test+    fun `thumbnail metadata and artwork reads fail soft for unreadable uris`() {+        val bad = "content://media/external/audio/media/424242".toUri()+        assertNull(getThumbnail(context, bad))+        assertEquals(0L, getRealAudioDuration(context, bad))+        assertEquals(0, getAudioYear(context, bad))+        assertNull(artworkBytes(context, bad, null))+        assertNull(artworkBytes(context, bad, bad))+    }++    @Test+    fun `collage is always a square canvas even when no tile decodes`() {+        val empty = createCollageBitmap(context, emptyList())+        assertEquals(512, empty.width)+        assertEquals(512, empty.height)++        val noArt = createCollageBitmap(context, listOf("content://media/1".toUri()))+        assertEquals(512, noArt.width)+        assertEquals(512, noArt.height)+        assertNotNull(noArt)+    }++    @Test+    fun `album art composables render placeholders without usable artwork`() {+        val noArt: Uri? = null+        composeRule.setContent {+            AlbumArt(noArt, Modifier)+            AlbumArt(emptyList<Uri>(), Modifier)+        }+        composeRule.onRoot().assertIsDisplayed()+    }++    @Test+    fun `single album art renders a placeholder when the thumbnail is missing`() {+        composeRule.setContent {+            AlbumArt("content://media/external/audio/media/9".toUri(), Modifier)+        }+        composeRule.onRoot().assertIsDisplayed()+    }++    @Test+    fun `collage album art renders a placeholder when no tile decodes`() {+        composeRule.setContent {+            AlbumArt(listOf("content://media/external/audio/media/9".toUri()), Modifier)+        }+        composeRule.onRoot().assertIsDisplayed()+    }+}
music/src/test/java/com/vayunmathur/music/platform/UtilMediaStoreEdgeTest.kt
diff --git a/music/src/test/java/com/vayunmathur/music/platform/UtilMediaStoreEdgeTest.kt b/music/src/test/java/com/vayunmathur/music/platform/UtilMediaStoreEdgeTest.ktnew file mode 100644index 0000000000..1d4789c5e1--- /dev/null+++ b/music/src/test/java/com/vayunmathur/music/platform/UtilMediaStoreEdgeTest.kt@@ -0,0 +1,141 @@+package com.vayunmathur.music.platform++import android.content.ContentProvider+import android.content.ContentValues+import android.content.Context+import android.database.Cursor+import android.database.MatrixCursor+import android.net.Uri+import androidx.test.core.app.ApplicationProvider+import kotlinx.coroutines.runBlocking+import org.junit.Before+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import org.robolectric.shadows.ShadowContentResolver+import kotlin.test.Test+import kotlin.test.assertEquals++/**+ * MediaStore readers against awkward rows a real phone produces and the+ * populated FakeMediaProvider does not: untagged files whose title/artist/album+ * columns are null, blank artist names, track 0, and negative years. These are+ * the rows that used to crash the scan (Music's fields are non-null), so the+ * normalisation in getSongs/getArtists is asserted column by column.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class UtilMediaStoreEdgeTest {++    class EdgeMediaProvider : ContentProvider() {+        override fun onCreate(): Boolean = true++        override fun query(+            uri: Uri,+            projection: Array<out String>?,+            selection: String?,+            selectionArgs: Array<out String>?,+            sortOrder: String?,+        ): Cursor {+            val columns = projection ?: emptyArray()+            val cursor = MatrixCursor(columns)+            fun row(values: Map<String, Any?>) {+                cursor.addRow(columns.map { values[it] })+            }+            when {+                uri.path?.endsWith("/audio/media") == true -> {+                    row(+                        mapOf(+                            "_id" to 10L, "title" to null, "artist" to null,+                            "artist_id" to 0L, "album" to null, "album_id" to 0L,+                            "duration" to 0L, "track" to 0, "year" to -4,+                        ),+                    )+                    row(+                        mapOf(+                            "_id" to 11L, "title" to "Tagged", "artist" to "",+                            "artist_id" to 5L, "album" to "Record", "album_id" to 6L,+                            "duration" to 42_000L, "track" to 1000, "year" to 1970,+                        ),+                    )+                }+                uri.path?.endsWith("/audio/albums") == true -> {+                    row(mapOf("_id" to 6L, "album" to null, "artist" to null, "artist_id" to 0L))+                }+                uri.path?.endsWith("/audio/artists") == true -> {+                    row(mapOf("_id" to 5L, "artist" to ""))+                    row(mapOf("_id" to 6L, "artist" to null))+                    row(mapOf("_id" to 7L, "artist" to "<unknown>"))+                    row(mapOf("_id" to 8L, "artist" to "Real Artist"))+                }+            }+            return cursor+        }++        override fun getType(uri: Uri): String? = null+        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+    }++    @Before+    fun setUp() {+        ShadowContentResolver.registerProviderInternal("media", EdgeMediaProvider())+    }++    private val context: Context get() = ApplicationProvider.getApplicationContext()++    @Test+    fun songsNormaliseNullTagsAndClampNonPositiveYears(): Unit = runBlocking {+        val songs = getSongs(context).associateBy { it.id }+        val untagged = songs.getValue(10L)+        assertEquals("", untagged.title)+        assertEquals("", untagged.artist)+        assertEquals("", untagged.album)+        assertEquals(0, untagged.year, "a negative MediaStore year must read as unknown (0)")+        assertEquals(1, untagged.discNumber)+        assertEquals(0, untagged.trackNumber)+        assertEquals("content://media/external/audio/media/10", untagged.uri)++        val tagged = songs.getValue(11L)+        assertEquals("Tagged", tagged.title)+        // TRACK 1000 is the first multi-disc encoding: disc 1, track 0.+        assertEquals(1, tagged.discNumber)+        assertEquals(0, tagged.trackNumber)+        assertEquals(1970, tagged.year)+    }++    @Test+    fun albumsNormaliseANullName(): Unit = runBlocking {+        val albums = getAlbums(context)+        assertEquals(1, albums.size)+        assertEquals("", albums.single().name)+        assertEquals("content://media/external/audio/albums/6", albums.single().uri)+    }++    @Test+    fun artistsNormaliseBlankNullAndSentinelNamesToEmpty(): Unit = runBlocking {+        val artists = getArtists(context).associateBy { it.id }+        assertEquals("", artists.getValue(5L).name)+        assertEquals("", artists.getValue(6L).name)+        assertEquals("", artists.getValue(7L).name)+        assertEquals("Real Artist", artists.getValue(8L).name)+    }++    @Test+    fun albumArtistPairsSkipSongsWhoseAlbumOrArtistIsUnknown(): Unit = runBlocking {+        val songs = getSongs(context)+        val albums = getAlbums(context)+        val artists = getArtists(context)+        // Song 11 joins Album 6 / Artist 5; song 10 joins nothing (ids 0).+        assertEquals(+            listOf(albums.single() to artists.first { it.id == 5L }),+            albumArtistPairs(songs, artists, albums),+        )+    }+}
music/src/test/java/com/vayunmathur/music/service/CastingPlayerExpandedTest.kt
diff --git a/music/src/test/java/com/vayunmathur/music/service/CastingPlayerExpandedTest.kt b/music/src/test/java/com/vayunmathur/music/service/CastingPlayerExpandedTest.ktnew file mode 100644index 0000000000..ce52b91e9c--- /dev/null+++ b/music/src/test/java/com/vayunmathur/music/service/CastingPlayerExpandedTest.kt@@ -0,0 +1,64 @@+package com.vayunmathur.music.service++import androidx.media3.common.Player+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertSame+import kotlin.test.assertTrue++/**+ * CastingPlayer's command gating under Robolectric, where Player.Commands is a+ * real Android-backed flag set (on a plain JVM it is a stubbed+ * SparseBooleanArray, which is why CastingPlayerTest cannot assert this).+ * Instantiating CastingPlayer itself needs a live media3 Player delegate and a+ * main looper session, so getState/handle* remain device/TV-only.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class CastingPlayerExpandedTest {++    private fun seekCommands(): Player.Commands = Player.Commands.Builder()+        .add(Player.COMMAND_PLAY_PAUSE)+        .add(Player.COMMAND_SEEK_IN_CURRENT_MEDIA_ITEM)+        .add(Player.COMMAND_SEEK_BACK)+        .add(Player.COMMAND_SEEK_FORWARD)+        .add(Player.COMMAND_SEEK_TO_NEXT_MEDIA_ITEM)+        .add(Player.COMMAND_SET_SPEED_AND_PITCH)+        .build()++    @Test+    fun `seekable tracks keep the delegate commands untouched`() {+        val base = seekCommands()+        assertSame(base, CastingPlayer.seekCommands(base, seekable = true))+    }++    @Test+    fun `unseekable tracks lose only the within-item seek commands`() {+        val gated = CastingPlayer.seekCommands(seekCommands(), seekable = false)+        assertFalse(gated.contains(Player.COMMAND_SEEK_IN_CURRENT_MEDIA_ITEM))+        assertFalse(gated.contains(Player.COMMAND_SEEK_BACK))+        assertFalse(gated.contains(Player.COMMAND_SEEK_FORWARD))+        // Queue jumps and transport are the phone's, and must survive gating:+        // removing them would strand the user on a track that is still encoding.+        assertTrue(gated.contains(Player.COMMAND_SEEK_TO_NEXT_MEDIA_ITEM))+        assertTrue(gated.contains(Player.COMMAND_PLAY_PAUSE))+        assertTrue(gated.contains(Player.COMMAND_SET_SPEED_AND_PITCH))+    }++    @Test+    fun `gating is driven by whether the playing resource is the growing one`() {+        val base = seekCommands()+        assertSame(base, CastingPlayer.seekCommands(base, CastingPlayer.seekable(null, "12")))+        assertSame(base, CastingPlayer.seekCommands(base, CastingPlayer.seekable("99", "12")))+        val gated = CastingPlayer.seekCommands(base, CastingPlayer.seekable("12", "12"))+        assertFalse(gated.contains(Player.COMMAND_SEEK_IN_CURRENT_MEDIA_ITEM))+        assertEquals(+            Player.STATE_ENDED,+            CastingPlayer.playbackStateFor(buffering = false, ended = true),+        )+    }+}
music/src/test/java/com/vayunmathur/music/service/MusicLibraryTreeTest.kt
diff --git a/music/src/test/java/com/vayunmathur/music/service/MusicLibraryTreeTest.kt b/music/src/test/java/com/vayunmathur/music/service/MusicLibraryTreeTest.ktnew file mode 100644index 0000000000..f193b1b222--- /dev/null+++ b/music/src/test/java/com/vayunmathur/music/service/MusicLibraryTreeTest.kt@@ -0,0 +1,169 @@+package com.vayunmathur.music.service++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.music.FakeAndroidKeyStore+import org.junit.Before+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * MusicLibraryTree over an empty library. A populated tree cannot be built on a+ * host JVM: the tree's snapshot combines the Room playlist/matching flows, and+ * SQLCipher cannot load here, so its init deliberately catches that and leaves+ * the snapshot empty (see the tree's own comment). What remains testable — and+ * what Android Auto depends on even with no music — is the browse skeleton:+ * root, the five tabs, id resolution, search guards, and recents bookkeeping.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class MusicLibraryTreeTest {++    @Before+    fun setUp() {+        FakeAndroidKeyStore.install()+    }++    private val context: Context get() = ApplicationProvider.getApplicationContext()++    private fun tree(): MusicLibraryTree = MusicLibraryTree(context)++    @Test+    fun `root exposes the five browse tabs in order`() {+        val tree = tree()+        try {+            val root = tree.rootItem()+            assertEquals(MusicLibraryTree.ROOT, root.mediaId)+            assertEquals("Music", root.mediaMetadata.title?.toString())+            assertEquals(true, root.mediaMetadata.isBrowsable)+            assertEquals(false, root.mediaMetadata.isPlayable)++            val tabs = tree.children(MusicLibraryTree.ROOT)+            assertEquals(+                listOf(+                    MusicLibraryTree.TAB_PLAYLISTS,+                    MusicLibraryTree.TAB_ALBUMS,+                    MusicLibraryTree.TAB_ARTISTS,+                    MusicLibraryTree.TAB_SONGS,+                    MusicLibraryTree.TAB_RECENT,+                ),+                tabs.map { it.mediaId },+            )+            assertEquals(+                listOf("Playlists", "Albums", "Artists", "Songs", "Recently played"),+                tabs.map { it.mediaMetadata.title?.toString() },+            )+            assertTrue(tabs.all { it.mediaMetadata.isBrowsable == true && it.mediaMetadata.isPlayable == false })+            assertEquals(5, tree.childCount(MusicLibraryTree.ROOT))+        } finally {+            tree.release()+        }+    }++    @Test+    fun `empty library tabs and unknown nodes have no children`() {+        val tree = tree()+        try {+            for (tab in listOf(+                MusicLibraryTree.TAB_PLAYLISTS, MusicLibraryTree.TAB_ALBUMS,+                MusicLibraryTree.TAB_ARTISTS, MusicLibraryTree.TAB_SONGS,+                MusicLibraryTree.TAB_RECENT,+            )) {+                assertEquals(emptyList(), tree.children(tab), tab)+                assertEquals(0, tree.childCount(tab), tab)+            }+            assertEquals(emptyList(), tree.children("playlist_42"))+            assertEquals(emptyList(), tree.children("album_42"))+            assertEquals(emptyList(), tree.children("artist_42"))+            assertEquals(emptyList(), tree.children("playlist_not_a_number"))+            assertEquals(emptyList(), tree.children("totally_unknown"))+            assertEquals(emptyList(), tree.children(""))+        } finally {+            tree.release()+        }+    }++    @Test+    fun `item resolves tabs and root but nothing unknown or absent`() {+        val tree = tree()+        try {+            assertEquals(MusicLibraryTree.ROOT, tree.item(MusicLibraryTree.ROOT)?.mediaId)+            assertEquals("Playlists", tree.item(MusicLibraryTree.TAB_PLAYLISTS)?.mediaMetadata?.title?.toString())+            assertEquals("Albums", tree.item(MusicLibraryTree.TAB_ALBUMS)?.mediaMetadata?.title?.toString())+            assertEquals("Artists", tree.item(MusicLibraryTree.TAB_ARTISTS)?.mediaMetadata?.title?.toString())+            assertEquals("Songs", tree.item(MusicLibraryTree.TAB_SONGS)?.mediaMetadata?.title?.toString())+            assertEquals("Recently played", tree.item(MusicLibraryTree.TAB_RECENT)?.mediaMetadata?.title?.toString())++            assertNull(tree.item("playlist_42"))+            assertNull(tree.item("album_42"))+            assertNull(tree.item("artist_42"))+            assertNull(tree.item("42"))+            assertNull(tree.item("not_a_song"))+            assertNull(tree.resolveForPlayback("42"))+            assertNull(tree.resolveForPlayback("playlist_42"))+        } finally {+            tree.release()+        }+    }++    @Test+    fun `refreshable parents are the root plus every tab`() {+        val tree = tree()+        try {+            assertEquals(+                listOf(+                    MusicLibraryTree.ROOT,+                    MusicLibraryTree.TAB_PLAYLISTS,+                    MusicLibraryTree.TAB_ALBUMS,+                    MusicLibraryTree.TAB_ARTISTS,+                    MusicLibraryTree.TAB_SONGS,+                    MusicLibraryTree.TAB_RECENT,+                ),+                tree.refreshableParents(),+            )+        } finally {+            tree.release()+        }+    }++    @Test+    fun `search guards blank queries and finds nothing in an empty library`() {+        val tree = tree()+        try {+            assertEquals(emptyList(), tree.searchPlayableSongs(""))+            assertEquals(emptyList(), tree.searchPlayableSongs("   "))+            assertEquals(emptyList(), tree.searchPlayableSongs("anything"))+            assertEquals(emptyList(), tree.searchResults(""))+            assertEquals(emptyList(), tree.searchResults("   "))+            assertEquals(emptyList(), tree.searchResults("anything"))+        } finally {+            tree.release()+        }+    }++    @Test+    fun `mark played records ids, ignores junk, and notifies`() {+        val tree = tree()+        try {+            var notifications = 0+            tree.onLibraryChanged = { notifications++ }+            tree.markPlayed(listOf("3", "not_a_number", "1", "3"))+            assertEquals(1, notifications)+            // Recents still resolve to nothing: the library itself is empty.+            assertEquals(emptyList(), tree.children(MusicLibraryTree.TAB_RECENT))++            tree.markPlayed(emptyList())+            tree.markPlayed(listOf("junk"))+            assertEquals(1, notifications, "no playable ids means no change to announce")+            assertNotNull(tree.onLibraryChanged)+        } finally {+            tree.release()+        }+    }+}
music/src/test/java/com/vayunmathur/music/service/car/MusicCarBrowseExpandedTest.kt
diff --git a/music/src/test/java/com/vayunmathur/music/service/car/MusicCarBrowseExpandedTest.kt b/music/src/test/java/com/vayunmathur/music/service/car/MusicCarBrowseExpandedTest.ktnew file mode 100644index 0000000000..1e0b02bcc8--- /dev/null+++ b/music/src/test/java/com/vayunmathur/music/service/car/MusicCarBrowseExpandedTest.kt@@ -0,0 +1,133 @@+package com.vayunmathur.music.service.car++import android.content.Context+import androidx.car.app.CarContext+import androidx.car.app.model.Template+import androidx.car.app.testing.TestCarContext+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.music.FakeAndroidKeyStore+import com.vayunmathur.music.service.MusicLibraryTree+import org.junit.Before+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/**+ * MusicCarBrowseScreen / MusicCarPlaybackScreen template selection across the+ * full host-API matrix over an empty tree, complementing MusicCarScreensTest:+ * every (node, apiLevel) pair must yield a host-legal template — root tabs at+ * 6/7 use list content, at 8+ sectioned; non-root nodes never use TabTemplate.+ * Populated rows (song rows, album grid tiles, play-all) need a populated+ * tree, which needs Room, so they remain device-only.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class MusicCarBrowseExpandedTest {++    @Before+    fun setUp() {+        FakeAndroidKeyStore.install()+    }++    private val context: Context get() = ApplicationProvider.getApplicationContext()++    private fun carContext(apiLevel: Int): TestCarContext {+        val carContext = TestCarContext.createCarContext(context)+        val field = CarContext::class.java.getDeclaredField("mCarAppApiLevel")+        field.isAccessible = true+        field.setInt(carContext, apiLevel)+        return carContext+    }++    private fun state(): MusicCarState = MusicCarState(MusicLibraryTree(context))++    private fun templateName(template: Template): String = template.javaClass.simpleName++    @Test+    fun rootTemplateFollowsTheHostApiLadder() {+        val carState = state()+        // API 1-5: plain list. 6-7: tabs over list content (tab builder may+        // decline on an empty tree, falling back to the screen's own list).+        for (level in listOf(1, 3, 5)) {+            assertEquals(+                "ListTemplate",+                templateName(MusicCarBrowseScreen(carContext(level), MusicLibraryTree.ROOT, carState).onGetTemplate()),+                "api $level",+            )+        }+        for (level in listOf(6, 7)) {+            assertTrue(+                templateName(MusicCarBrowseScreen(carContext(level), MusicLibraryTree.ROOT, carState).onGetTemplate())+                    in listOf("TabTemplate", "ListTemplate", "SectionedItemTemplate"),+                "api $level",+            )+        }+        for (level in listOf(8, 9, 10)) {+            assertTrue(+                templateName(MusicCarBrowseScreen(carContext(level), MusicLibraryTree.ROOT, carState).onGetTemplate())+                    in listOf("TabTemplate", "SectionedItemTemplate"),+                "api $level",+            )+        }+    }++    @Test+    fun everyBrowseNodeProducesALegalTemplateAtLowAndHighApi() {+        val carState = state()+        val nodes = listOf(+            MusicLibraryTree.TAB_PLAYLISTS,+            MusicLibraryTree.TAB_ALBUMS,+            MusicLibraryTree.TAB_ARTISTS,+            MusicLibraryTree.TAB_SONGS,+            MusicLibraryTree.TAB_RECENT,+            "album_1", "artist_1", "playlist_1", "album_x", "unknown_node",+        )+        for (node in nodes) {+            val legacy = MusicCarBrowseScreen(carContext(1), node, carState).onGetTemplate()+            assertEquals("ListTemplate", templateName(legacy), "$node @ api1")+            val modern = MusicCarBrowseScreen(carContext(9), node, carState).onGetTemplate()+            assertTrue(+                templateName(modern) in listOf("SectionedItemTemplate", "ListTemplate"),+                "$node @ api9 was ${templateName(modern)}",+            )+            val mid = MusicCarBrowseScreen(carContext(7), node, carState).onGetTemplate()+            assertEquals("ListTemplate", templateName(mid), "$node @ api7")+        }+    }++    @Test+    fun playbackTemplateFollowsTheHostApiLadder() {+        val carState = state()+        for (level in listOf(1, 5, 7)) {+            assertEquals(+                "PaneTemplate",+                templateName(MusicCarPlaybackScreen(carContext(level), carState).onGetTemplate()),+                "api $level",+            )+        }+        for (level in listOf(8, 9, 10)) {+            assertEquals(+                "MediaPlaybackTemplate",+                templateName(MusicCarPlaybackScreen(carContext(level), carState).onGetTemplate()),+                "api $level",+            )+        }+    }++    @Test+    fun carStateNotifiesEveryObserverOncePerChange() {+        val carState = state()+        var first = 0+        var second = 0+        carState.observe { first++ }+        carState.observe { second++ }+        carState.notifyChanged()+        carState.notifyChanged()+        assertEquals(2, first)+        assertEquals(2, second)+        assertEquals(null, carState.controller)+    }+}
music/src/test/java/com/vayunmathur/music/ui/MusicComponentsExpandedTest.kt
diff --git a/music/src/test/java/com/vayunmathur/music/ui/MusicComponentsExpandedTest.kt b/music/src/test/java/com/vayunmathur/music/ui/MusicComponentsExpandedTest.ktnew file mode 100644index 0000000000..d159cacf6e--- /dev/null+++ b/music/src/test/java/com/vayunmathur/music/ui/MusicComponentsExpandedTest.kt@@ -0,0 +1,131 @@+package com.vayunmathur.music.ui++import android.app.Application+import androidx.compose.material3.Text+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.hasAnyAncestor+import androidx.compose.ui.test.hasClickAction+import androidx.compose.ui.test.hasContentDescription+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithContentDescription+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.core.net.toUri+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.music.FakeAndroidKeyStore+import com.vayunmathur.music.R+import com.vayunmathur.music.data.MusicRepository+import com.vayunmathur.music.platform.MusicViewModel+import com.vayunmathur.music.platform.PlaybackManager+import com.vayunmathur.music.ui.components.NewPlaylistFab+import com.vayunmathur.music.ui.components.NowPlayingBar+import com.vayunmathur.music.ui.components.TrackListItem+import kotlin.test.Test+import kotlin.test.assertEquals+import org.junit.Before+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++/**+ * Shared music components with real interactions: the mini-player's transport+ * buttons (found as the clickable ancestor of their icon's content+ * description), track rows with caller-supplied slots, and the new-playlist+ * FAB's dialog open/cancel cycle (creating would write through Room, so the+ * create path itself is device-only).+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class MusicComponentsExpandedTest {++    @get:Rule+    val composeRule = createComposeRule()++    @Before+    fun setUp() {+        FakeAndroidKeyStore.install()+        val app = ApplicationProvider.getApplicationContext<Application>()+        org.robolectric.Shadows.shadowOf(app).setComponentNameAndServiceForBindService(+            android.content.ComponentName(app, com.vayunmathur.music.service.PlaybackService::class.java),+            android.os.Binder(),+        )+    }++    private val app: Application get() = ApplicationProvider.getApplicationContext()+    private val context get() = ApplicationProvider.getApplicationContext<android.content.Context>()+    private fun str(id: Int): String = context.getString(id)++    private fun viewModel(): MusicViewModel =+        MusicViewModel(app, MusicRepository.get(app), PlaybackManager.getInstance(app))++    private fun clickableWithIcon(description: String) =+        hasClickAction() and hasAnyAncestor(hasContentDescription(description))++    @Test+    fun nowPlayingBarTransportButtonsToggleAndSkip() {+        var toggled = 0+        var skipped = 0+        var opened = 0+        composeRule.setContent {+            NowPlayingBar(+                songId = 9L, title = "Bar Song", artist = "Bar Artist", artworkUri = null,+                isPlaying = true, owsSharedKeys = true,+                onOpen = { opened++ }, onTogglePlayPause = { toggled++ }, onSkipNext = { skipped++ },+            )+        }+        composeRule.onNodeWithText("Bar Song").assertIsDisplayed()+        // Playing state shows the Pause icon; its button toggles, Next skips.+        composeRule.onNodeWithContentDescription("Pause").performClick()+        assertEquals(1, toggled)+        composeRule.onNodeWithContentDescription("Next").performClick()+        assertEquals(1, skipped)+        assertEquals(0, opened, "transport clicks must not open the full player")+    }++    @Test+    fun nowPlayingBarPausedShowsPlayAndBodyTapOpens() {+        var toggled = 0+        var opened = 0+        composeRule.setContent {+            NowPlayingBar(+                songId = null, title = "Paused Song", artist = "Singer", artworkUri = null,+                isPlaying = false, owsSharedKeys = false,+                onOpen = { opened++ }, onTogglePlayPause = { toggled++ }, onSkipNext = {},+            )+        }+        composeRule.onNodeWithContentDescription("Play").performClick()+        assertEquals(1, toggled)+        composeRule.onNodeWithText("Paused Song").performClick()+        assertEquals(1, opened)+    }++    @Test+    fun trackListItemRendersSlotsAndReportsClicks() {+        var clicks = 0+        composeRule.setContent {+            TrackListItem(+                title = "Slotted Song", isPlaying = false,+                artUri = "content://media/1".toUri(),+                onClick = { clicks++ },+                leading = { Text("3") },+                trailing = { Text("3:42") },+            )+        }+        composeRule.onNodeWithText("Slotted Song").assertIsDisplayed()+        composeRule.onNodeWithText("3").assertIsDisplayed()+        composeRule.onNodeWithText("3:42").assertIsDisplayed()+        composeRule.onNodeWithText("Slotted Song").performClick()+        assertEquals(1, clicks)+    }++    @Test+    fun newPlaylistFabOpensTheDialogAndCancelClosesItWithoutCreating() {+        val vm = viewModel()+        composeRule.setContent { NewPlaylistFab(vm) }+        composeRule.onNodeWithContentDescription("Add").performClick()+        composeRule.onNodeWithText(str(R.string.dialog_create_playlist)).assertIsDisplayed()+        composeRule.onNodeWithText(str(com.vayunmathur.library.ui.R.string.cancel)).performClick()+        composeRule.onNodeWithText(str(R.string.dialog_create_playlist)).assertDoesNotExist()+    }+}
music/src/test/java/com/vayunmathur/music/ui/MusicDetailPagesExpandedTest.kt
diff --git a/music/src/test/java/com/vayunmathur/music/ui/MusicDetailPagesExpandedTest.kt b/music/src/test/java/com/vayunmathur/music/ui/MusicDetailPagesExpandedTest.ktnew file mode 100644index 0000000000..dfbbcd44b4--- /dev/null+++ b/music/src/test/java/com/vayunmathur/music/ui/MusicDetailPagesExpandedTest.kt@@ -0,0 +1,261 @@+package com.vayunmathur.music.ui++import androidx.compose.ui.test.assertCountEquals+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.hasScrollAction+import androidx.compose.ui.test.hasText+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onAllNodesWithText+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.onRoot+import androidx.compose.ui.test.performClick+import androidx.compose.ui.test.performScrollToNode+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.library.ui.R as UiR+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.music.R+import com.vayunmathur.music.Route+import com.vayunmathur.music.data.Music+import com.vayunmathur.music.platform.AlbumDetailUiState+import com.vayunmathur.music.platform.LyricLine+import com.vayunmathur.music.platform.Lyrics+import com.vayunmathur.music.platform.MusicActions+import com.vayunmathur.music.platform.NowPlayingUiState+import com.vayunmathur.music.platform.SongsUiState+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++/**+ * Behaviour-rich rendering of the state-driven detail screens: album play /+ * shuffle / track / artist navigation, songs-list playback, queue jumps, and+ * now-playing source navigation and lyrics states. The ViewModel-bound+ * PlaylistDetail/ArtistDetail screens have no state-driven variant and their+ * bodies collect Room flows (SQLCipher, unavailable on a host JVM), so only+ * AlbumDetailContent — the state-driven half of the album detail — is used for+ * detail-body coverage here.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class MusicDetailPagesExpandedTest {++    @get:Rule+    val composeRule = createComposeRule()++    private val context = ApplicationProvider.getApplicationContext<android.content.Context>()+    private fun str(id: Int, vararg args: Any): String = context.getString(id, *args)++    private fun song(id: Long, title: String, duration: Long = 180_000) = Music(+        id = id, title = title, artist = "Artist", artistId = 1, album = "Album", albumId = 7,+        uri = "content://media/$id", duration = duration, trackNumber = id.toInt(), year = 2020,+    )++    private fun stack(vararg routes: Route) =+        NavBackStack<Route>(if (routes.isEmpty()) arrayOf(Route.Home) else arrayOf(*routes))++    private class RecordingActions : MusicActions {+        var played: Triple<List<Music>, Int, String?>? = null+        var playedSourceName: String? = null+        var shuffled: Pair<String?, String?>? = null+        override fun playSong(songs: List<Music>, startWithIndex: Int, sourceId: String?, sourceName: String?) {+            played = Triple(songs, startWithIndex, sourceId)+            playedSourceName = sourceName+        }+        override fun playShuffled(songs: List<Music>, sourceId: String?, sourceName: String?) {+            shuffled = sourceId to sourceName+        }+    }++    @Test+    fun albumDetailPlayShuffleAndTrackClicksReportAlbumSource() {+        val actions = RecordingActions()+        val tracks = listOf(song(1, "Track One"), song(2, "Track Two"))+        composeRule.setContent {+            AlbumDetailContent(+                AlbumDetailUiState(+                    albumId = 7, name = "Great Album", artistName = "Great Artist",+                    artistId = null, info = "2020 • 2 songs", tracks = tracks, playingSongId = 2L,+                ),+                actions, stack(),+            )+        }+        composeRule.onNodeWithText("Great Album").assertIsDisplayed()+        // Play/Shuffle and the track rows are lazy items below the 260dp header,+        // so they are not composed until scrolled to (the previous onNodeWithText+        // click failed with "no node with text Play" for exactly this reason).+        composeRule.onAllNodes(hasScrollAction())[0].performScrollToNode(hasText(str(UiR.string.play)))+        composeRule.onNodeWithText(str(UiR.string.play)).performClick()+        assertEquals(Triple(tracks, 0, "album_7"), actions.played)+        assertEquals("Great Album", actions.playedSourceName)++        composeRule.onNodeWithText(str(R.string.label_shuffle)).performClick()+        assertEquals("album_7" to "Great Album", actions.shuffled)++        composeRule.onAllNodes(hasScrollAction())[0].performScrollToNode(hasText("Track One"))+        composeRule.onNodeWithText("Track One").performClick()+        assertEquals(Triple(tracks, 0, "album_7"), actions.played)+    }++    @Test+    fun albumDetailArtistNameNavigatesOnlyWhenAnArtistIsKnown() {+        val actions = RecordingActions()+        val nav = stack(Route.Home, Route.AlbumDetail(7))+        composeRule.setContent {+            AlbumDetailContent(+                AlbumDetailUiState(+                    albumId = 7, name = "Great Album", artistName = "Great Artist",+                    artistId = 31L, info = "2020", tracks = listOf(song(1, "Only Track")),+                ),+                actions, nav,+            )+        }+        composeRule.onNodeWithText("Great Artist").performClick()+        assertEquals(Route.ArtistDetail(31L), nav.last())+    }++    @Test+    fun albumDetailWithNoTracksStillShowsHeaderAndActions() {+        val actions = RecordingActions()+        composeRule.setContent {+            AlbumDetailContent(+                AlbumDetailUiState(albumId = 8, name = "Empty Album", info = "Unknown", tracks = emptyList()),+                actions, stack(),+            )+        }+        composeRule.onNodeWithText("Empty Album").assertIsDisplayed()+        composeRule.onAllNodes(hasScrollAction())[0].performScrollToNode(hasText(str(UiR.string.play)))+        composeRule.onNodeWithText(str(UiR.string.play)).performClick()+        // Play is wired even for an empty track list; the ViewModel/PlaybackManager+        // guard is what makes it a no-op, and this screen must still report it.+        assertEquals(0, actions.played?.second)+        assertEquals("album_8", actions.played?.third)+    }++    @Test+    fun songsScreenClickReportsIndexAndSongTappedCallback() {+        val actions = RecordingActions()+        var tapped = 0+        val songs = listOf(song(1, "Alpha"), song(2, "Beta"), song(3, "Gamma"))+        composeRule.setContent {+            SongsScreen(+                SongsUiState(songs = songs, playingSongId = 1L),+                actions, stack(),+                onSongTapped = { tapped++ },+            )+        }+        composeRule.onNodeWithText("Gamma").performClick()+        assertEquals(Triple(songs, 2, "all_songs"), actions.played)+        assertEquals(1, tapped)+    }++    @Test+    fun songsScreenEmptyRendersNoTracks() {+        composeRule.setContent {+            SongsScreen(SongsUiState(songs = emptyList(), loading = false), RecordingActions(), stack())+        }+        composeRule.onRoot().assertIsDisplayed()+        composeRule.onNodeWithText("Alpha").assertDoesNotExist()+    }++    @Test+    fun queueListUsesUnknownTitleAndJumpsByPosition() {+        var jumped = -1+        val songs = listOf(song(1, ""), song(2, "Second Song"))+        composeRule.setContent {+            QueueList(songs, playingSongId = 2L, title = "", onJump = { jumped = it })+        }+        composeRule.onNodeWithText(str(R.string.unknown_title)).assertIsDisplayed()+        composeRule.onNodeWithText(str(R.string.unknown_title)).performClick()+        assertEquals(0, jumped)+        composeRule.onNodeWithText("Second Song").performClick()+        assertEquals(1, jumped)+    }++    @Test+    fun nowPlayingGoToAlbumSourceReplacesThePlayerOnTheStack() {+        val nav = stack(Route.Home, Route.Song)+        composeRule.setContent {+            NowPlayingScreen(+                NowPlayingUiState(+                    title = "Sourced", artist = "Artist", album = "Album", songId = 4L,+                    sourceId = "album_7", sourceName = "Great Album",+                ),+                RecordingActions(), nav,+            )+        }+        composeRule.onNodeWithText(str(R.string.go_to_source, "Great Album")).performClick()+        assertEquals(Route.AlbumDetail(7L), nav.last())+    }++    @Test+    fun nowPlayingGoToPlaylistAndArtistSourcesResolveTheirRoutes() {+        val nav = stack(Route.Home, Route.Song)+        composeRule.setContent {+            NowPlayingScreen(+                NowPlayingUiState(+                    title = "Sourced", artist = "Artist", songId = 4L,+                    sourceId = "playlist_12", sourceName = "Road Mix",+                ),+                RecordingActions(), nav,+            )+        }+        composeRule.onNodeWithText(str(R.string.go_to_source, "Road Mix")).performClick()+        assertEquals(Route.PlaylistDetail(12L), nav.last())+    }++    @Test+    fun nowPlayingWithoutSourceShowsNoGoToShortcut() {+        composeRule.setContent {+            NowPlayingScreen(+                NowPlayingUiState(title = "Unsourced", artist = "Artist", songId = 4L),+                RecordingActions(), stack(),+            )+        }+        composeRule.onNodeWithText("Unsourced").assertIsDisplayed()+        composeRule.onAllNodesWithText(str(R.string.go_to_source, "Unsourced")).assertCountEquals(0)+    }++    @Test+    fun lyricsViewTimedShowsAllLines() {+        composeRule.setContent {+            LyricsView(+                Lyrics.Timed(listOf(LyricLine(0, "line one"), LyricLine(5_000, "line two"))),+                currentIndex = 1,+            )+        }+        composeRule.onNodeWithText("line one").assertIsDisplayed()+        composeRule.onNodeWithText("line two").assertIsDisplayed()+    }++    @Test+    fun lyricsViewPlainShowsTheUntimedBlock() {+        composeRule.setContent { LyricsView(Lyrics.Plain("untimed words"), currentIndex = -1) }+        composeRule.onNodeWithText("untimed words").assertIsDisplayed()+    }++    @Test+    fun lyricsViewNoneShowsTheEmptyMessage() {+        composeRule.setContent { LyricsView(Lyrics.None, currentIndex = -1) }+        composeRule.onNodeWithText(str(R.string.no_lyrics_available)).assertIsDisplayed()+    }++    @Test+    fun clickableComponentsReportClicks() {+        var clicks = 0+        composeRule.setContent {+            com.vayunmathur.music.ui.components.PlayShuffleRow(+                onPlay = { clicks += 1 },+                onShuffle = { clicks += 10 },+            )+        }+        composeRule.onNodeWithText(str(UiR.string.play)).performClick()+        assertEquals(1, clicks)+        composeRule.onNodeWithText(str(R.string.label_shuffle)).performClick()+        assertEquals(11, clicks)+        assertTrue(clicks == 11)+    }+}
music/src/test/java/com/vayunmathur/music/ui/MusicTabsContentsTest.kt
diff --git a/music/src/test/java/com/vayunmathur/music/ui/MusicTabsContentsTest.kt b/music/src/test/java/com/vayunmathur/music/ui/MusicTabsContentsTest.ktnew file mode 100644index 0000000000..a60847b5d7--- /dev/null+++ b/music/src/test/java/com/vayunmathur/music/ui/MusicTabsContentsTest.kt@@ -0,0 +1,112 @@+package com.vayunmathur.music.ui++import android.app.Application+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.onRoot+import androidx.compose.ui.test.performClick+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.library.ui.R as UiR+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.music.FakeAndroidKeyStore+import com.vayunmathur.music.R+import com.vayunmathur.music.Route+import com.vayunmathur.music.data.Music+import com.vayunmathur.music.data.MusicRepository+import com.vayunmathur.music.platform.MusicViewModel+import com.vayunmathur.music.platform.PlaybackManager+import com.vayunmathur.music.ui.components.AddToPlaylistButton+import com.vayunmathur.music.ui.components.MusicTabsBar+import com.vayunmathur.music.ui.components.ShufflePlayFab+import kotlin.test.Test+import kotlin.test.assertEquals+import org.junit.Before+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++/**+ * The tab host's pieces over an empty library. MusicTabsScreen itself is not+ * rendered here: its LaunchedEffect calls refreshLibrary(), whose tag backfill+ * opens the SQLCipher cache (unavailable on a host JVM), and enqueues a+ * WorkManager SyncWorker (uninitialised under Robolectric) — both device-only.+ * Its bar and tab contents, which carry the actual tab behaviour, are.+ * PlaylistsTabContent is likewise omitted: it collects the Room playlist flow.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class MusicTabsContentsTest {++    @get:Rule+    val composeRule = createComposeRule()++    @Before+    fun setUp() {+        FakeAndroidKeyStore.install()+        val app = ApplicationProvider.getApplicationContext<Application>()+        org.robolectric.Shadows.shadowOf(app).setComponentNameAndServiceForBindService(+            android.content.ComponentName(app, com.vayunmathur.music.service.PlaybackService::class.java),+            android.os.Binder(),+        )+    }++    private val app: Application get() = ApplicationProvider.getApplicationContext()+    private val context get() = ApplicationProvider.getApplicationContext<android.content.Context>()+    private fun str(id: Int): String = context.getString(id)++    private fun viewModel(): MusicViewModel =+        MusicViewModel(app, MusicRepository.get(app), PlaybackManager.getInstance(app))++    private fun stack() = NavBackStack<Route>(arrayOf(Route.Home))++    private fun song(id: Long) = Music(+        id = id, title = "Song $id", artist = "Artist", artistId = 1, album = "Album",+        albumId = 7, uri = "content://media/$id", duration = 180_000, trackNumber = 1, year = 2020,+    )++    @Test+    fun tabsBarReportsEveryTabSelection() {+        val selected = mutableListOf<Int>()+        composeRule.setContent { MusicTabsBar(selectedTab = 0, onSelectTab = { selected += it }) }+        composeRule.onNodeWithText(str(R.string.label_albums)).performClick()+        composeRule.onNodeWithText(str(R.string.nav_artists)).performClick()+        composeRule.onNodeWithText(str(R.string.nav_playlists)).performClick()+        composeRule.onNodeWithText(str(UiR.string.home)).performClick()+        assertEquals(listOf(1, 2, 3, 0), selected)+    }++    @Test+    fun albumsTabRendersOverAnEmptyLibrary() {+        val vm = viewModel()+        composeRule.setContent { AlbumsTabContent(stack(), vm) }+        composeRule.onRoot().assertIsDisplayed()+    }++    @Test+    fun artistsTabRendersOverAnEmptyLibrary() {+        val vm = viewModel()+        composeRule.setContent { ArtistsTabContent(stack(), vm) }+        composeRule.onRoot().assertIsDisplayed()+    }++    @Test+    fun shuffleFabAppearsForSongsAndReportsTheClick() {+        var shuffles = 0+        composeRule.setContent {+            ShufflePlayFab(listOf(song(1), song(2))) { shuffles++ }+        }+        composeRule.onAllNodes(hasClickAction())[0].performClick()+        assertEquals(1, shuffles)+    }++    @Test+    fun addToPlaylistButtonPushesTheDialogRouteForTheSong() {+        val nav = stack()+        composeRule.setContent { AddToPlaylistButton(nav, song(42)) }+        composeRule.onAllNodes(hasClickAction())[0].performClick()+        assertEquals(Route.AddToPlaylistDialog(42L), nav.last())+    }+}
music/src/test/java/com/vayunmathur/music/ui/PlayerColumnTest.kt
diff --git a/music/src/test/java/com/vayunmathur/music/ui/PlayerColumnTest.kt b/music/src/test/java/com/vayunmathur/music/ui/PlayerColumnTest.ktnew file mode 100644index 0000000000..39b83798cf--- /dev/null+++ b/music/src/test/java/com/vayunmathur/music/ui/PlayerColumnTest.kt@@ -0,0 +1,121 @@+package com.vayunmathur.music.ui++import androidx.compose.ui.test.assertCountEquals+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.media3.common.Player+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.music.Route+import com.vayunmathur.music.platform.LyricLine+import com.vayunmathur.music.platform.Lyrics+import com.vayunmathur.music.platform.MusicActions+import com.vayunmathur.music.platform.NowPlayingUiState+import kotlin.test.Test+import kotlin.test.assertEquals+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++/**+ * PlayerColumn (the now-playing column shared by the compact and expanded+ * players) composed directly, so its song-info navigation, progress labels,+ * and lyrics/artwork swap are asserted without a live player. Transport+ * icon buttons carry only icon content-descriptions, so transport dispatch is+ * asserted at the NowPlayingScreen level in NowPlayingControlsTest instead.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class PlayerColumnTest {++    @get:Rule+    val composeRule = createComposeRule()++    private fun stack() = NavBackStack<Route>(arrayOf(Route.Home, Route.Song))++    private fun state(+        artistId: Long? = 31L,+        albumId: Long? = 7L,+        album: String = "Great Album",+        repeatMode: Int = Player.REPEAT_MODE_ONE,+    ) = NowPlayingUiState(+        title = "Column Song", artist = "Column Artist", album = album,+        songId = 4L, artistId = artistId, albumId = albumId,+        isPlaying = true, positionMs = 90_000, durationMs = 240_000,+        shuffle = true, repeatMode = repeatMode,+    )++    @Test+    fun columnShowsSongInfoAndProgressLabels() {+        composeRule.setContent {+            PlayerColumn(+                state(), MusicActions.Noop, stack(),+                songId = 4L, leaving = false,+                lyrics = Lyrics.None, currentIndex = -1,+                showLyrics = false, onToggleLyrics = {},+            )+        }+        composeRule.onNodeWithText("Column Song").assertIsDisplayed()+        composeRule.onNodeWithText("Column Artist").assertIsDisplayed()+        composeRule.onNodeWithText("Great Album").assertIsDisplayed()+        composeRule.onAllNodesWithText("1:30").assertCountEquals(1)+        composeRule.onAllNodesWithText("4:00").assertCountEquals(1)+    }++    @Test+    fun artistAndAlbumLinesNavigateToTheirDetailRoutes() {+        val nav = stack()+        composeRule.setContent {+            PlayerColumn(+                state(), MusicActions.Noop, nav,+                songId = 4L, leaving = false,+                lyrics = Lyrics.None, currentIndex = -1,+                showLyrics = false, onToggleLyrics = {},+            )+        }+        composeRule.onNodeWithText("Column Artist").performClick()+        assertEquals(Route.ArtistDetail(31L), nav.last())++        composeRule.onNodeWithText("Great Album").performClick()+        assertEquals(Route.AlbumDetail(7L), nav.last())+    }++    @Test+    fun lyricsSwapShowsTimedLinesInsteadOfArtwork() {+        composeRule.setContent {+            PlayerColumn(+                state(), MusicActions.Noop, stack(),+                songId = 4L, leaving = true,+                lyrics = Lyrics.Timed(listOf(LyricLine(0, "sung line"), LyricLine(90_000, "current line"))),+                currentIndex = 1,+                showLyrics = true, onToggleLyrics = {},+            )+        }+        composeRule.onNodeWithText("sung line").assertIsDisplayed()+        composeRule.onNodeWithText("current line").assertIsDisplayed()+        composeRule.onNodeWithText("Column Song").assertIsDisplayed()+    }++    @Test+    fun plainLyricsAndNoIdsStillRenderTitleAndZeroedAlbumLine() {+        val nav = stack()+        composeRule.setContent {+            PlayerColumn(+                state(artistId = null, albumId = null, album = "", repeatMode = Player.REPEAT_MODE_OFF),+                MusicActions.Noop, nav,+                songId = null, leaving = false,+                lyrics = Lyrics.Plain("plain column words"),+                currentIndex = -1,+                showLyrics = true, onToggleLyrics = {},+            )+        }+        composeRule.onNodeWithText("Column Song").assertIsDisplayed()+        composeRule.onNodeWithText("plain column words").assertIsDisplayed()+        // No linked ids: the artist line is inert text.+        composeRule.onNodeWithText("Column Artist").performClick()+        assertEquals(Route.Song, nav.last())+    }+}
music/src/test/java/com/vayunmathur/music/ui/PopulatedDetailScreensTest.kt
diff --git a/music/src/test/java/com/vayunmathur/music/ui/PopulatedDetailScreensTest.kt b/music/src/test/java/com/vayunmathur/music/ui/PopulatedDetailScreensTest.ktnew file mode 100644index 0000000000..90d5d8ea3f--- /dev/null+++ b/music/src/test/java/com/vayunmathur/music/ui/PopulatedDetailScreensTest.kt@@ -0,0 +1,168 @@+package com.vayunmathur.music.ui++import android.app.Application+import android.content.ComponentName+import android.content.Context+import android.os.Binder+import androidx.compose.ui.test.assertCountEquals+import androidx.compose.ui.test.hasScrollAction+import androidx.compose.ui.test.hasText+import androidx.compose.ui.test.performScrollToNode+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.library.util.NavBackStack+import com.vayunmathur.music.FakeAndroidKeyStore+import com.vayunmathur.music.FakeMediaProvider+import com.vayunmathur.music.Route+import com.vayunmathur.music.data.MusicRepository+import com.vayunmathur.music.data.Playlist+import com.vayunmathur.music.data.TestMusicRepository+import com.vayunmathur.music.data.TYPE_MUSIC_PLAYLIST+import com.vayunmathur.library.util.ManyManyMatching+import com.vayunmathur.music.platform.MusicViewModel+import com.vayunmathur.music.platform.PlaybackManager+import kotlinx.coroutines.runBlocking+import org.junit.AfterClass+import org.junit.Before+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows+import org.robolectric.annotation.Config+import org.robolectric.shadows.ShadowContentResolver+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/**+ * The ViewModel-bound detail screens ([ArtistDetailScreen], [AlbumDetailScreen],+ * [PlaylistDetailScreen]) against the populated fake library from+ * [FakeMediaProvider]: the same three songs / two albums / two artists the+ * repository tests use. Assertions wait for the MediaStore-backed flows to+ * land instead of assuming the first composition is final.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class PopulatedDetailScreensTest {++    @get:Rule+    val composeRule = createComposeRule()++    companion object {+        @JvmStatic+        @AfterClass+        fun tearDownClass() {+            FakeMediaProvider.enabled = false+            val app = ApplicationProvider.getApplicationContext<Context>()+            runBlocking { MusicRepository.get(app).refresh() }+        }+    }++    @Before+    fun setUp() {+        FakeMediaProvider.enabled = true+        FakeAndroidKeyStore.install()+        ShadowContentResolver.registerProviderInternal("media", FakeMediaProvider())+        val app = ApplicationProvider.getApplicationContext<Application>()+        Shadows.shadowOf(app).setComponentNameAndServiceForBindService(+            ComponentName(app, com.vayunmathur.music.service.PlaybackService::class.java),+            Binder(),+        )+        // In-memory Room for the playlist/matching flows these screens+        // collect (production uses SQLCipher, unavailable on the JVM).+        TestMusicRepository.install(app)+        runBlocking { MusicRepository.get(app).refresh() }+    }++    private val app: Application get() = ApplicationProvider.getApplicationContext()++    private fun viewModel(): MusicViewModel =+        MusicViewModel(app, MusicRepository.get(app), PlaybackManager.getInstance(app))++    private fun stack(vararg routes: Route): NavBackStack<Route> = NavBackStack(arrayOf(*routes))++    private fun awaitText(text: String) {+        // Wall-clock poll: composeRule.waitUntil blocks the main thread the+        // ViewModel flows are confined to, so they would never emit there.+        val deadline = System.currentTimeMillis() + 15_000+        while (System.currentTimeMillis() < deadline) {+            composeRule.waitForIdle()+            if (composeRule.onAllNodesWithText(text, substring = true).fetchSemanticsNodes().isNotEmpty()) return+            Thread.sleep(50)+        }+        composeRule.onNodeWithText(text, substring = true).assertExists()+    }++    @Test+    fun artistDetailShowsArtistAlbumsAndSongsAndPlaysFromArtistSource() {+        val vm = viewModel()+        val nav = stack(Route.Home)+        composeRule.setContent { ArtistDetailScreen(nav, vm, artistId = 11L) }+        awaitText("Artist One")+        // Both songs by Artist One are listed below the header (lazy column).+        composeRule.onNode(hasScrollAction()).performScrollToNode(hasText("Beta Song"))+        composeRule.onNodeWithText("Alpha Song", substring = true).assertExists()+        composeRule.onNodeWithText("Beta Song", substring = true).performClick()+        // Tapping a track starts playback tagged with the artist source.+        val deadline = System.currentTimeMillis() + 5_000+        while (vm.currentSource.value != "artist_11" && System.currentTimeMillis() < deadline) {+            composeRule.waitForIdle()+            Thread.sleep(50)+        }+        assertEquals("artist_11", vm.currentSource.value)+    }++    @Test+    fun artistDetailForUnknownArtistComposesNothing() {+        val vm = viewModel()+        composeRule.setContent { ArtistDetailScreen(stack(Route.Home), vm, artistId = 999L) }+        composeRule.waitForIdle()+        // The screen returns before its scaffold when the artist is absent.+        composeRule.onAllNodesWithText("Artist One").assertCountEquals(0)+        composeRule.onAllNodesWithText("Beta Song").assertCountEquals(0)+    }++    @Test+    fun albumDetailShowsAlbumTracksSortedByDiscAndTrack() {+        val vm = viewModel()+        val nav = stack(Route.Home)+        composeRule.setContent { AlbumDetailScreen(nav, vm, albumId = 21L) }+        awaitText("Album One")+        composeRule.onNode(hasScrollAction()).performScrollToNode(hasText("Beta Song"))+        composeRule.onNodeWithText("Alpha Song", substring = true).assertExists()+        // Album One's artist is unambiguous, so the artist link routes there.+        composeRule.onNodeWithText("Artist One", substring = true).performClick()+        assertTrue(nav.last() is Route.ArtistDetail, "expected artist route, was ${nav.last()}")+        assertEquals(11L, (nav.last() as Route.ArtistDetail).artistId)+    }++    @Test+    fun albumDetailForUnknownAlbumComposesNothing() {+        val vm = viewModel()+        composeRule.setContent { AlbumDetailScreen(stack(Route.Home), vm, albumId = 999L) }+        composeRule.waitForIdle()+        composeRule.onAllNodesWithText("Album One").assertCountEquals(0)+    }+++    @Test+    fun playlistDetailShowsPlaylistTracksAndDeleteRemovesIt() {+        val repo = MusicRepository.get(app)+        val playlistId = runBlocking {+            val id = repo.upsertPlaylist(Playlist(name = "Road Mix"))+            repo.upsertMatching(ManyManyMatching(leftID = 1, rightID = id, type = TYPE_MUSIC_PLAYLIST))+            repo.upsertMatching(ManyManyMatching(leftID = 3, rightID = id, type = TYPE_MUSIC_PLAYLIST))+            id+        }+        val vm = viewModel()+        val nav = stack(Route.Home)+        composeRule.setContent { PlaylistDetailScreen(nav, vm, playlistId = playlistId) }+        awaitText("Road Mix")+        composeRule.onNode(hasScrollAction()).performScrollToNode(hasText("Beta Song"))+        composeRule.onNodeWithText("Beta Song", substring = true).assertExists()+        composeRule.onNodeWithText("Gamma Song", substring = true).assertExists()+    }+}
music/src/test/java/com/vayunmathur/music/ui/SongsScreenExpandedTest.kt
diff --git a/music/src/test/java/com/vayunmathur/music/ui/SongsScreenExpandedTest.kt b/music/src/test/java/com/vayunmathur/music/ui/SongsScreenExpandedTest.ktnew file mode 100644index 0000000000..4e152e951a--- /dev/null+++ b/music/src/test/java/com/vayunmathur/music/ui/SongsScreenExpandedTest.kt@@ -0,0 +1,106 @@+package com.vayunmathur.music.ui++import android.app.Application+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.hasScrollAction+import androidx.compose.ui.test.hasText+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.onRoot+import androidx.compose.ui.test.performClick+import androidx.compose.ui.test.performScrollToNode+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.music.FakeAndroidKeyStore+import com.vayunmathur.music.Route+import com.vayunmathur.music.data.Music+import com.vayunmathur.music.data.MusicRepository+import com.vayunmathur.music.platform.MusicActions+import com.vayunmathur.music.platform.MusicViewModel+import com.vayunmathur.music.platform.PlaybackManager+import com.vayunmathur.music.platform.SongsUiState+import kotlin.test.Test+import kotlin.test.assertEquals+import org.junit.Before+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++/**+ * SongsScreen over a longer list (rows below the fold are scrolled to, the+ * same lazy-composition constraint as the detail screens), plus the+ * NowPlayingQueue guard: with nothing loaded the queue panel renders nothing+ * instead of crashing on a missing now-playing state.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class SongsScreenExpandedTest {++    @get:Rule+    val composeRule = createComposeRule()++    @Before+    fun setUp() {+        FakeAndroidKeyStore.install()+        val app = ApplicationProvider.getApplicationContext<Application>()+        org.robolectric.Shadows.shadowOf(app).setComponentNameAndServiceForBindService(+            android.content.ComponentName(app, com.vayunmathur.music.service.PlaybackService::class.java),+            android.os.Binder(),+        )+    }++    private val app: Application get() = ApplicationProvider.getApplicationContext()++    private fun song(id: Long) = Music(+        id = id, title = "Song $id", artist = "Artist $id", artistId = id, album = "Album",+        albumId = 7, uri = "content://media/$id", duration = 100_000, trackNumber = id.toInt(), year = 2001,+    )++    private fun stack() = NavBackStack<Route>(arrayOf(Route.Home))++    private class RecordingActions : MusicActions {+        var played: Triple<List<Music>, Int, String?>? = null+        override fun playSong(songs: List<Music>, startWithIndex: Int, sourceId: String?, sourceName: String?) {+            played = Triple(songs, startWithIndex, sourceId)+        }+    }++    @Test+    fun longSongListPlaysTheScrolledToRowByIndex() {+        val actions = RecordingActions()+        val songs = (1L..12L).map { song(it) }+        var tapped = 0+        composeRule.setContent {+            SongsScreen(+                SongsUiState(songs = songs, playingSongId = 3L, rowOwnsSongKeys = true),+                actions, stack(),+                onSongTapped = { tapped++ },+            )+        }+        composeRule.onAllNodes(hasScrollAction())[0].performScrollToNode(hasText("Song 12"))+        composeRule.onNodeWithText("Song 12").performClick()+        assertEquals(Triple(songs, 11, "all_songs"), actions.played)+        assertEquals(1, tapped)+    }++    @Test+    fun loadingSongListRendersNoRows() {+        composeRule.setContent {+            SongsScreen(+                SongsUiState(songs = emptyList(), loading = true),+                RecordingActions(), stack(),+            )+        }+        composeRule.onRoot().assertIsDisplayed()+        composeRule.onNodeWithText("Song 1").assertDoesNotExist()+    }++    @Test+    fun nowPlayingQueueRendersNothingWhileNothingIsLoaded() {+        val vm = MusicViewModel(app, MusicRepository.get(app), PlaybackManager.getInstance(app))+        composeRule.setContent { NowPlayingQueue(vm) }+        composeRule.onRoot().assertExists()+        composeRule.onNodeWithText("Song 1").assertDoesNotExist()+    }+}