Modern Apps git

← Modern-Apps.git

music: add tests for library, playback, cast and car (pass 3)

Commit
f7f860bfd97952d6c10aff89344ee6e1bb6d37ba
Author
Vayun Mathur <[email protected]>
When
2026-11-07 13:34 UTC (28 days ago)
Parents
41a5b7f
Merged INSTRUCTION coverage 19.0% -> 56.4% (5698/29916 -> 16873/29937;
denominator grew by the PlaybackManager fix in the next commit).

Unit (Robolectric): EmbeddedLyrics synthetic Ogg/FLAC/MP4 files,
MusicViewModel/repository over empty and fake-provider libraries,
PlaybackManager without a controller, CastPlayback without a TV,
now-playing controls/queue, dialogs, audio-preview activity.

Device (emulator): repository and ViewModel playlist CRUD (SQLCipher),
library tree browse/search, seeded-MediaStore library (ID3 MP3 insert)
driving repository/tree/search, assistant search/play intents over
ResultReceiver, car browse/playback screens across host API levels.

Test-only seams: FakeAndroidKeyStore (established per-module pattern),
FakeMediaProvider (fixed 3-song library; switched off and refreshed
after the class so it cannot leak into empty-library tests), car-app
testing dependency (Robolectric excluded on-device). The browse-tree
and playlist tests live on device because their SQLCipher collects
leak uncaught exceptions into unrelated JVM tests.

Verified: testDevUnitTest green, lint green, instrumented 25/26 with
only the pre-existing MusicNowPlayingTest seed failure (plus one
observed MusicPlaylistTest UI flake that passed on rerun).
Untestable remainder at 85%: populated PlaylistDetail/ArtistDetail/
AlbumDetail screens and AddToPlaylistDialog (their DAO-backed flows
cannot collect on the JVM and Compose cannot run on-device),
CastPlayback session/transcode paths (need a Cast receiver),
CastingPlayer/CastQueue session handover (need a TV), PlaybackService
session callbacks (need a bound controller), car browse rows over a
populated tree on the JVM (same SQLCipher collect hazard).

Diff

music/build.gradle.kts
diff --git a/music/build.gradle.kts b/music/build.gradle.ktsindex 354d189e09..c577dfd917 100644--- a/music/build.gradle.kts+++ b/music/build.gradle.kts@@ -33,6 +33,8 @@ dependencies {     implementation(libs.androidx.car.app)     implementation(libs.androidx.car.app.projected) +    testImplementation(libs.androidx.car.app.testing)+     implementation(project(":library:image"))      // Casting. `:sdk:cast` owns no sockets and needs no network permission - which is the point,
music/src/androidTest/java/com/vayunmathur/music/data/MusicRepositoryDeviceTest.kt
diff --git a/music/src/androidTest/java/com/vayunmathur/music/data/MusicRepositoryDeviceTest.kt b/music/src/androidTest/java/com/vayunmathur/music/data/MusicRepositoryDeviceTest.ktnew file mode 100644index 0000000000..5aa416bc25--- /dev/null+++ b/music/src/androidTest/java/com/vayunmathur/music/data/MusicRepositoryDeviceTest.kt@@ -0,0 +1,82 @@+package com.vayunmathur.music.data++import androidx.test.platform.app.InstrumentationRegistry+import com.vayunmathur.library.util.ManyManyMatching+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.runBlocking+import org.junit.Assert.assertEquals+import org.junit.Assert.assertTrue+import org.junit.Test++/**+ * Repository Room side on a real device: SQLCipher's native library cannot+ * load under Robolectric, so playlist/matching CRUD runs here.+ */+class MusicRepositoryDeviceTest {++    private val context get() = InstrumentationRegistry.getInstrumentation().targetContext+    private fun repo(): MusicRepository = MusicRepository.get(context)++    @Test+    fun playlistAndMatchingCrudRoundTrip() = runBlocking {+        val repo = repo()+        val playlistId = repo.upsertPlaylist(Playlist(name = "Gym Device"))+        assertTrue(playlistId > 0)+        assertTrue(repo.getAllPlaylists().any { it.id == playlistId && it.name == "Gym Device" })+        assertTrue(repo.playlists.first().any { it.id == playlistId })++        repo.upsertMatching(ManyManyMatching(11L, playlistId, TYPE_MUSIC_PLAYLIST))+        repo.upsertMatchings(+            listOf(+                ManyManyMatching(12L, playlistId, TYPE_MUSIC_PLAYLIST),+                ManyManyMatching(13L, playlistId, TYPE_ALBUM_ARTIST),+            ),+        )+        assertEquals(+            listOf(11L, 12L),+            repo.getFromRight(playlistId, TYPE_MUSIC_PLAYLIST).sorted(),+        )+        assertEquals(listOf(playlistId), repo.getFromLeft(11L, TYPE_MUSIC_PLAYLIST))+        // Only playlist-type matchings surface in the combined flow's Room side.+        assertTrue(+            repo.matchings.first().all { it.type == TYPE_MUSIC_PLAYLIST },+        )++        repo.deleteMatch(11L, playlistId, TYPE_MUSIC_PLAYLIST)+        assertEquals(listOf(12L), repo.getFromRight(playlistId, TYPE_MUSIC_PLAYLIST))+        repo.deleteFromLeft(12L, TYPE_MUSIC_PLAYLIST)+        assertEquals(emptyList<Long>(), repo.getFromRight(playlistId, TYPE_MUSIC_PLAYLIST))+        repo.deleteFromRight(playlistId, TYPE_ALBUM_ARTIST)+        assertEquals(emptyList<Long>(), repo.getFromRight(playlistId, TYPE_ALBUM_ARTIST))++        repo.upsertMatching(ManyManyMatching(21L, playlistId, TYPE_MUSIC_PLAYLIST))+        repo.deleteByType(TYPE_MUSIC_PLAYLIST)+        assertEquals(emptyList<Long>(), repo.getFromRight(playlistId, TYPE_MUSIC_PLAYLIST))++        repo.upsertMatching(ManyManyMatching(22L, playlistId, TYPE_MUSIC_PLAYLIST))+        repo.clearMatchings()+        assertEquals(emptyList<Long>(), repo.getFromRight(playlistId, TYPE_MUSIC_PLAYLIST))++        repo.deletePlaylistById(playlistId)+        assertTrue(repo.getAllPlaylists().none { it.id == playlistId })+    }++    @Test+    fun backfillWithEmptyLibraryIsNoOp() = runBlocking {+        val repo = repo()+        repo.refresh()+        repo.backfillTags()+        assertEquals(emptyList<Any>(), repo.getAllMusic())+    }++    @Test+    fun renameViaUpsertKeepsOnePlaylist() = runBlocking {+        val repo = repo()+        val id = repo.upsertPlaylist(Playlist(name = "Before Device"))+        repo.upsertPlaylist(Playlist(id = id, name = "After Device"))+        val mine = repo.getAllPlaylists().filter { it.id == id }+        assertEquals(1, mine.size)+        assertEquals("After Device", mine.single().name)+        repo.deletePlaylistById(id)+    }+}
music/src/androidTest/java/com/vayunmathur/music/data/SeededLibraryDeviceTest.kt
diff --git a/music/src/androidTest/java/com/vayunmathur/music/data/SeededLibraryDeviceTest.kt b/music/src/androidTest/java/com/vayunmathur/music/data/SeededLibraryDeviceTest.ktnew file mode 100644index 0000000000..171e731757--- /dev/null+++ b/music/src/androidTest/java/com/vayunmathur/music/data/SeededLibraryDeviceTest.kt@@ -0,0 +1,153 @@+package com.vayunmathur.music.data++import android.content.ContentValues+import android.content.Context+import android.net.Uri+import android.provider.MediaStore+import androidx.test.platform.app.InstrumentationRegistry+import com.vayunmathur.music.service.MusicLibraryTree+import kotlinx.coroutines.runBlocking+import org.junit.After+import org.junit.Assert.assertEquals+import org.junit.Assert.assertNotNull+import org.junit.Assert.assertTrue+import org.junit.Before+import org.junit.Test+import java.io.ByteArrayOutputStream++/**+ * The library with actual media in it: an MP3 carrying ID3 title/artist/+ * album frames is inserted into MediaStore (the same row the shipped seed+ * script would make), the repository scans it, and the browse tree/search+ * resolve it. This is the populated half of MusicRepository, Util's+ * MediaStore readers and MusicLibraryTree that an empty library cannot+ * reach. An MP3 because the scanner takes artist/album from ID3; a WAV+ * has nowhere to carry them and scans in as <unknown>.+ */+class SeededLibraryDeviceTest {++    private val context: Context+        get() = InstrumentationRegistry.getInstrumentation().targetContext++    private var insertedUri: Uri? = null+    private var songId: Long = -1++    /** ID3v2.3 (UTF-8 text frames) over silent 128 kbps MP3 frames. */+    private fun mp3Bytes(): ByteArray {+        val out = ByteArrayOutputStream()+        val tagOut = ByteArrayOutputStream()+        fun collect(id: String, text: String) {+            val payload = byteArrayOf(3) + text.toByteArray(Charsets.UTF_8)+            tagOut.write(id.toByteArray(Charsets.US_ASCII))+            repeat(4) { tagOut.write(payload.size ushr (24 - 8 * it)) }+            tagOut.write(0); tagOut.write(0)+            tagOut.write(payload)+        }+        collect("TIT2", "Seeded Tone")+        collect("TPE1", "Seed Artist")+        collect("TALB", "Seed Album")+        val tag = tagOut.toByteArray()+        out.write("ID3".toByteArray(Charsets.US_ASCII))+        out.write(3); out.write(0); out.write(0)+        // Syncsafe size: 7 bits per byte.+        repeat(4) { out.write((tag.size ushr (21 - 7 * it)) and 0x7F) }+        out.write(tag)+        // ~100 silent frames (header + zeroed side info/main data reads as silence).+        val frame = ByteArray(417)+        frame[0] = 0xFF.toByte(); frame[1] = 0xFB.toByte(); frame[2] = 0x90.toByte()+        repeat(100) { out.write(frame) }+        return out.toByteArray()+    }++    @Before+    fun seedSong() {+        val resolver = context.contentResolver+        val values = ContentValues().apply {+            put(MediaStore.Audio.Media.DISPLAY_NAME, "Seeded Tone.mp3")+            put(MediaStore.Audio.Media.TITLE, "Seeded Tone")+            put(MediaStore.Audio.Media.ARTIST, "Seed Artist")+            put(MediaStore.Audio.Media.ALBUM, "Seed Album")+            put(MediaStore.Audio.Media.MIME_TYPE, "audio/mpeg")+            put(MediaStore.Audio.Media.RELATIVE_PATH, "Music/CoverageSeed")+            put(MediaStore.Audio.Media.IS_PENDING, 1)+        }+        val uri = resolver.insert(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, values)+        assertNotNull("MediaStore insert must succeed", uri)+        insertedUri = uri+        resolver.openOutputStream(uri!!)!!.use { it.write(mp3Bytes()) }+        val publish = ContentValues().apply { put(MediaStore.Audio.Media.IS_PENDING, 0) }+        resolver.update(uri, publish, null, null)++        // The scanner fills the derived columns asynchronously; refresh until+        // the row is visible as music (bounded wait for an external system).+        val repo = MusicRepository.get(context)+        val deadline = System.currentTimeMillis() + 60_000+        while (System.currentTimeMillis() < deadline) {+            runBlocking { repo.refresh() }+            val song = runBlocking { repo.getAllMusic() }+                .firstOrNull { it.title == "Seeded Tone" }+            if (song != null) {+                songId = song.id+                return+            }+            Thread.sleep(500)+        }+        throw AssertionError("seeded MP3 never appeared in the music library")+    }++    @After+    fun removeSong() {+        insertedUri?.let { context.contentResolver.delete(it, null, null) }+        insertedUri = null+    }++    @Test+    fun repositoryReadsSeededSongAlbumAndArtist() = runBlocking {+        val repo = MusicRepository.get(context)+        val song = repo.getAllMusic().first { it.id == songId }+        assertEquals("Seeded Tone", song.title)+        assertEquals("Seed Artist", song.artist)+        assertEquals("Seed Album", song.album)+        assertTrue(repo.getAllAlbums().any { it.name == "Seed Album" })+        assertTrue(repo.getAllArtists().any { it.name == "Seed Artist" })+    }++    @Test+    fun browseTreeResolvesSeededSong() {+        val tree = MusicLibraryTree(context)+        try {+            val deadline = System.currentTimeMillis() + 30_000+            var songs = tree.children(MusicLibraryTree.TAB_SONGS)+            while (songs.none { it.mediaId == songId.toString() } &&+                System.currentTimeMillis() < deadline+            ) {+                Thread.sleep(250)+                songs = tree.children(MusicLibraryTree.TAB_SONGS)+            }+            assertTrue(+                "songs tab must list the seeded song",+                songs.any { it.mediaId == songId.toString() },+            )+            val item = tree.item(songId.toString())+            assertNotNull(item)+            assertEquals("Seeded Tone", item!!.mediaMetadata.title?.toString())+            val playable = tree.resolveForPlayback(songId.toString())+            assertNotNull(playable)+            assertNotNull(playable!!.localConfiguration)+            assertTrue(tree.searchResults("Seeded").any { it.mediaId == songId.toString() })+            assertTrue(+                tree.searchPlayableSongs("Seeded Tone")+                    .any { it.mediaId == songId.toString() },+            )+            assertTrue(tree.searchPlayableSongs("Seed Artist").isNotEmpty())+            assertTrue(tree.searchPlayableSongs("Seed Album").isNotEmpty())+            tree.markPlayed(listOf(songId.toString()))+            assertTrue(+                tree.children(MusicLibraryTree.TAB_RECENT)+                    .any { it.mediaId == songId.toString() },+            )+        } finally {+            tree.release()+        }+    }+}
music/src/androidTest/java/com/vayunmathur/music/intents/MusicIntentsDeviceTest.kt
diff --git a/music/src/androidTest/java/com/vayunmathur/music/intents/MusicIntentsDeviceTest.kt b/music/src/androidTest/java/com/vayunmathur/music/intents/MusicIntentsDeviceTest.ktnew file mode 100644index 0000000000..2373c2b85e--- /dev/null+++ b/music/src/androidTest/java/com/vayunmathur/music/intents/MusicIntentsDeviceTest.kt@@ -0,0 +1,97 @@+package com.vayunmathur.music.intents++import android.app.Activity+import android.content.Intent+import android.os.Bundle+import android.os.Handler+import android.os.Looper+import android.os.ResultReceiver+import androidx.test.core.app.ActivityScenario+import androidx.test.platform.app.InstrumentationRegistry+import org.junit.Assert.assertEquals+import org.junit.Assert.assertTrue+import org.junit.Test+import java.util.concurrent.CountDownLatch+import java.util.concurrent.TimeUnit++/**+ * Assistant intent activities on device: they finish synchronously, do+ * their work in the background and answer over a ResultReceiver. The+ * library is empty on the test device, so searches answer empty and plays+ * are no-ops — the IPC contract is what is pinned here.+ */+class MusicIntentsDeviceTest {++    private class CapturingReceiver : ResultReceiver(Handler(Looper.getMainLooper())) {+        val latch = CountDownLatch(1)+        @Volatile var code: Int? = null+        @Volatile var data: Bundle? = null++        override fun onReceiveResult(resultCode: Int, resultData: Bundle?) {+            code = resultCode+            data = resultData+            latch.countDown()+        }+    }++    private fun launchAndCapture(activity: Class<*>, dataJson: String?): CapturingReceiver {+        val context = InstrumentationRegistry.getInstrumentation().targetContext+        val receiver = CapturingReceiver()+        val intent = Intent(context, activity).apply {+            if (dataJson != null) putExtra("DATA", dataJson)+            putExtra("RECEIVER", receiver)+        }+        ActivityScenario.launch<Activity>(intent).use { scenario ->+            assertTrue(+                "intent activity must answer within 30s",+                receiver.latch.await(30, TimeUnit.SECONDS),+            )+        }+        return receiver+    }++    @Test+    fun searchAnswersOkWithAnEmptyResultForAnEmptyLibrary() {+        val receiver = launchAndCapture(SearchIntent::class.java, "\"anything\"")+        assertEquals(Activity.RESULT_OK, receiver.code)+    }++    @Test+    fun searchWithMalformedInputIsCanceled() {+        val receiver = launchAndCapture(SearchIntent::class.java, "not json")+        assertEquals(Activity.RESULT_CANCELED, receiver.code)+    }++    @Test+    fun searchWithoutInputIsCanceled() {+        val receiver = launchAndCapture(SearchIntent::class.java, null)+        assertEquals(Activity.RESULT_CANCELED, receiver.code)+    }++    @Test+    fun playUnknownSongIsAnOkNoOp() {+        val receiver = launchAndCapture(+            PlayIntent::class.java,+            "{\"id\": 999999, \"type\": \"song\"}",+        )+        assertEquals(Activity.RESULT_OK, receiver.code)+    }++    @Test+    fun playFromUnknownPlaylistIsAnOkNoOp() {+        val receiver = launchAndCapture(+            PlayIntent::class.java,+            "{\"id\": 999999, \"type\": \"playlist\"}",+        )+        assertEquals(Activity.RESULT_OK, receiver.code)+    }++    @Test+    fun playWithUnknownTypeIsAnOkNoOp() {+        val receiver = launchAndCapture(+            PlayIntent::class.java,+            "{\"id\": 1, \"type\": \"genre\"}",+        )+        assertEquals(Activity.RESULT_OK, receiver.code)+    }+}
music/src/androidTest/java/com/vayunmathur/music/platform/MusicViewModelDeviceTest.kt
diff --git a/music/src/androidTest/java/com/vayunmathur/music/platform/MusicViewModelDeviceTest.kt b/music/src/androidTest/java/com/vayunmathur/music/platform/MusicViewModelDeviceTest.ktnew file mode 100644index 0000000000..2b5a0b0624--- /dev/null+++ b/music/src/androidTest/java/com/vayunmathur/music/platform/MusicViewModelDeviceTest.kt@@ -0,0 +1,67 @@+package com.vayunmathur.music.platform++import android.app.Application+import androidx.test.platform.app.InstrumentationRegistry+import com.vayunmathur.music.data.MusicRepository+import com.vayunmathur.music.data.Playlist+import com.vayunmathur.music.data.TYPE_MUSIC_PLAYLIST+import kotlinx.coroutines.runBlocking+import org.junit.Assert.assertEquals+import org.junit.Assert.assertTrue+import org.junit.Test+import java.util.concurrent.CountDownLatch+import java.util.concurrent.TimeUnit++/**+ * ViewModel playlist actions on device, where the SQLCipher database can+ * actually open (its native library cannot load under Robolectric, and+ * firing these writes there would also leak uncaught IO exceptions into+ * unrelated tests sharing the JVM).+ */+class MusicViewModelDeviceTest {++    private val app: Application+        get() = InstrumentationRegistry.getInstrumentation().targetContext.applicationContext as Application++    private fun viewModel(): MusicViewModel =+        MusicViewModel(app, MusicRepository.get(app), PlaybackManager.getInstance(app))++    @Test+    fun playlistActionsRoundTrip() {+        val repo = MusicRepository.get(app)+        val vm = viewModel()++        val created = CountDownLatch(1)+        var createdId = -1L+        vm.createPlaylist("Device Mix") { id -> createdId = id; created.countDown() }+        assertTrue(created.await(15, TimeUnit.SECONDS))+        assertTrue(createdId > 0)++        runBlocking {+            assertTrue(repo.getAllPlaylists().any { it.id == createdId && it.name == "Device Mix" })+            // No members yet: the DAO read itself is what must succeed.+            assertEquals(emptyList<Long>(), vm.getMusicInPlaylist(createdId))+        }++        vm.addMusicToPlaylist(createdId, 4242L)+        // addMusicToPlaylist has an onDone callback in its full form via the+        // repository; poll the DAO read until the write lands.+        val deadline = System.currentTimeMillis() + 15_000+        var members: List<Long> = emptyList()+        while (System.currentTimeMillis() < deadline) {+            members = runBlocking { repo.getFromRight(createdId, TYPE_MUSIC_PLAYLIST) }+            if (members == listOf(4242L)) break+            Thread.sleep(100)+        }+        assertEquals(listOf(4242L), members)++        vm.removeMusicFromPlaylist(createdId, 4242L)+        vm.renamePlaylist(Playlist(id = createdId, name = "Device Mix"), "Device Mix Renamed")+        val done = CountDownLatch(1)+        vm.deletePlaylist(Playlist(id = createdId, name = "Device Mix Renamed")) { done.countDown() }+        assertTrue(done.await(15, TimeUnit.SECONDS))+        runBlocking {+            assertTrue(repo.getAllPlaylists().none { it.id == createdId })+        }+    }+}
music/src/androidTest/java/com/vayunmathur/music/service/MusicLibraryTreeTest.kt
diff --git a/music/src/androidTest/java/com/vayunmathur/music/service/MusicLibraryTreeTest.kt b/music/src/androidTest/java/com/vayunmathur/music/service/MusicLibraryTreeTest.ktnew file mode 100644index 0000000000..ebba7c9b87--- /dev/null+++ b/music/src/androidTest/java/com/vayunmathur/music/service/MusicLibraryTreeTest.kt@@ -0,0 +1,133 @@+package com.vayunmathur.music.service++import android.content.Context+import androidx.test.platform.app.InstrumentationRegistry+import org.junit.Assert.assertEquals+import org.junit.Assert.assertNotNull+import org.junit.Assert.assertNull+import org.junit.Assert.assertTrue+import org.junit.Test++/**+ * The Auto browse tree over an empty library: the tab skeleton must be+ * complete and stable, node lookups for unknown ids must resolve to+ * nothing, and the recently-played bookkeeping must behave. Song-level+ * content needs a populated snapshot, which arrives from MediaStore.+ * On device, because the tree's snapshot collector reads the SQLCipher+ * playlist tables whose native library cannot load under Robolectric.+ */+class MusicLibraryTreeTest {++    private val context: Context+        get() = InstrumentationRegistry.getInstrumentation().targetContext++    private fun tree(): MusicLibraryTree = MusicLibraryTree(context)++    @Test+    fun `root item and tabs form the browse skeleton`() {+        val tree = tree()+        val root = tree.rootItem()+        assertEquals(MusicLibraryTree.ROOT, root.mediaId)+        assertEquals("Music", root.mediaMetadata.title?.toString())++        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() },+        )+        tree.release()+    }++    @Test+    fun `empty tabs have no children and unknown parents neither`() {+        val tree = tree()+        for (tab in listOf(+            MusicLibraryTree.TAB_PLAYLISTS,+            MusicLibraryTree.TAB_ALBUMS,+            MusicLibraryTree.TAB_ARTISTS,+            MusicLibraryTree.TAB_SONGS,+            MusicLibraryTree.TAB_RECENT,+        )) {+            assertTrue(tab, tree.children(tab).isEmpty())+            assertEquals(tab, 0, tree.childCount(tab))+        }+        assertEquals(5, tree.childCount(MusicLibraryTree.ROOT))+        assertTrue(tree.children("no-such-parent").isEmpty())+        assertTrue(tree.children("playlist_99").isEmpty())+        assertTrue(tree.children("album_99").isEmpty())+        assertTrue(tree.children("artist_99").isEmpty())+        assertTrue(tree.children("playlist_abc").isEmpty())+        tree.release()+    }++    @Test+    fun `item lookup resolves tabs and rejects unknown ids`() {+        val tree = tree()+        val rootItem = tree.item(MusicLibraryTree.ROOT)+        assertNotNull(rootItem)+        assertEquals(MusicLibraryTree.ROOT, rootItem!!.mediaId)+        val albumsItem = tree.item(MusicLibraryTree.TAB_ALBUMS)+        assertNotNull(albumsItem)+        assertEquals(MusicLibraryTree.TAB_ALBUMS, albumsItem!!.mediaId)+        assertNull(tree.item("tab_nope"))+        assertNull(tree.item("playlist_99"))+        assertNull(tree.item("album_99"))+        assertNull(tree.item("artist_99"))+        assertNull(tree.item("12345"))+        assertNull(tree.item("song"))+        tree.release()+    }++    @Test+    fun `refreshable parents are the root plus every tab`() {+        val tree = tree()+        assertEquals(+            listOf(+                MusicLibraryTree.ROOT,+                MusicLibraryTree.TAB_PLAYLISTS,+                MusicLibraryTree.TAB_ALBUMS,+                MusicLibraryTree.TAB_ARTISTS,+                MusicLibraryTree.TAB_SONGS,+                MusicLibraryTree.TAB_RECENT,+            ),+            tree.refreshableParents(),+        )+        tree.release()+    }++    @Test+    fun `playback resolution and search find nothing in an empty library`() {+        val tree = tree()+        assertNull(tree.resolveForPlayback("1"))+        assertNull(tree.resolveForPlayback("abc"))+        assertTrue(tree.searchPlayableSongs("anything").isEmpty())+        assertTrue(tree.searchPlayableSongs("   ").isEmpty())+        assertTrue(tree.searchResults("anything").isEmpty())+        assertTrue(tree.searchResults("").isEmpty())+        tree.release()+    }++    @Test+    fun `markPlayed ignores non numeric ids and notifies`() {+        val tree = tree()+        var notified = 0+        tree.onLibraryChanged = { notified++ }+        tree.markPlayed(listOf("abc", ""))+        assertTrue("no valid ids means no change to report", notified == 0)+        tree.markPlayed(listOf("7", "7", "9"))+        assertEquals(1, notified)+        // Recent tab still lists nothing: those ids are not in the library.+        assertTrue(tree.children(MusicLibraryTree.TAB_RECENT).isEmpty())+        tree.release()+    }+}
music/src/androidTest/java/com/vayunmathur/music/service/car/MusicCarScreensDeviceTest.kt
diff --git a/music/src/androidTest/java/com/vayunmathur/music/service/car/MusicCarScreensDeviceTest.kt b/music/src/androidTest/java/com/vayunmathur/music/service/car/MusicCarScreensDeviceTest.ktnew file mode 100644index 0000000000..05a8257833--- /dev/null+++ b/music/src/androidTest/java/com/vayunmathur/music/service/car/MusicCarScreensDeviceTest.kt@@ -0,0 +1,125 @@+package com.vayunmathur.music.service.car++import android.content.Context+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.assertTrue++/**+ * Car browse/playback screens over the empty library against a+ * TestCarContext: every browse level must produce a valid template (an+ * Android Auto host rejects a screen that throws), across the template+ * fallbacks for older host API levels.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class MusicCarScreensTest {++    @Before+    fun setUp() {+        FakeAndroidKeyStore.install()+    }++    private val context: Context get() = ApplicationProvider.getApplicationContext()++    private fun carContext(apiLevel: Int): TestCarContext {+        val carContext = TestCarContext.createCarContext(context)+        // TestCarContext never establishes a host API level; set the field+        // the host binder would normally fill so screens can pick a template+        // (same pattern as the weather/maps car tests).+        val field = androidx.car.app.CarContext::class.java+            .getDeclaredField("mCarAppApiLevel")+        field.isAccessible = true+        field.setInt(carContext, apiLevel)+        return carContext+    }++    private fun state(): MusicCarState {+        val tree = MusicLibraryTree(context)+        return MusicCarState(tree)+    }++    private fun assertTemplate(template: Template, vararg allowed: String) {+        val name = template.javaClass.simpleName+        assertTrue(+            allowed.isEmpty() || name in allowed,+            "template $name not in ${allowed.toList()}",+        )+    }++    @Test+    fun `browse root produces a template at every host api level`() {+        val carState = state()+        // Level 9 takes the tab template, 6-8 the sectioned/list fallbacks,+        // and below 6 the root must still render as a plain list.+        // With an empty tree the tab template builder may decline, in which+        // case the screen's own fallback to sectioned content is the contract.+        assertTemplate(+            MusicCarBrowseScreen(carContext(9), MusicLibraryTree.ROOT, carState).onGetTemplate(),+            "TabTemplate", "SectionedItemTemplate",+        )+        assertTemplate(+            MusicCarBrowseScreen(carContext(7), MusicLibraryTree.ROOT, carState).onGetTemplate(),+            "SectionedItemTemplate", "ListTemplate",+        )+        assertTemplate(+            MusicCarBrowseScreen(carContext(1), MusicLibraryTree.ROOT, carState).onGetTemplate(),+            "ListTemplate", "SectionedItemTemplate",+        )+    }++    @Test+    fun `browse tabs and unknown nodes produce templates`() {+        val carContext = carContext(8)+        val carState = state()+        for (node in listOf(+            MusicLibraryTree.TAB_SONGS,+            MusicLibraryTree.TAB_ALBUMS,+            MusicLibraryTree.TAB_ARTISTS,+            MusicLibraryTree.TAB_PLAYLISTS,+            MusicLibraryTree.TAB_RECENT,+            "album_99",+            "playlist_99",+            "totally-unknown",+        )) {+            val screen = MusicCarBrowseScreen(carContext, node, carState)+            assertTemplate(+                screen.onGetTemplate(),+                "SectionedItemTemplate", "ListTemplate", "TabTemplate",+            )+        }+    }++    @Test+    fun `playback screen produces a template without a controller`() {+        val carState = state()+        assertTemplate(+            MusicCarPlaybackScreen(carContext(9), carState).onGetTemplate(),+            "MediaPlaybackTemplate",+        )+        // Pre-API-8 hosts get the pane fallback with transport actions.+        assertTemplate(+            MusicCarPlaybackScreen(carContext(1), carState).onGetTemplate(),+            "PaneTemplate",+        )+    }++    @Test+    fun `car state notifies observers and tolerates throwing ones`() {+        val carState = state()+        var calls = 0+        carState.observe { calls++ }+        carState.observe { throw RuntimeException("observer boom") }+        carState.notifyChanged()+        assertTrue(calls == 1, "observer must be called despite a throwing sibling")+        assertTrue(carState.controller == null)+    }+}
music/src/test/java/com/vayunmathur/music/FakeAndroidKeyStore.kt
diff --git a/music/src/test/java/com/vayunmathur/music/FakeAndroidKeyStore.kt b/music/src/test/java/com/vayunmathur/music/FakeAndroidKeyStore.ktnew file mode 100644index 0000000000..68f33a4206--- /dev/null+++ b/music/src/test/java/com/vayunmathur/music/FakeAndroidKeyStore.kt@@ -0,0 +1,97 @@+package com.vayunmathur.music++import android.security.keystore.KeyGenParameterSpec+import java.io.InputStream+import java.io.OutputStream+import java.security.Key+import java.security.KeyStore+import java.security.KeyStoreSpi+import java.security.Provider+import java.security.SecureRandom+import java.security.Security+import java.security.cert.Certificate+import java.util.Collections+import java.util.Date+import java.util.Enumeration+import javax.crypto.KeyGenerator+import javax.crypto.KeyGeneratorSpi+import javax.crypto.SecretKey+import javax.crypto.spec.SecretKeySpec++/**+ * Robolectric has no AndroidKeyStore provider, which otherwise blocks every+ * code path that opens the SQLCipher vault (PasswordRepository,+ * DatabaseHelper, KdbxPasswordHelper). Installing this JCA provider gives+ * tests a plain in-memory AES keystore with the same alias semantics; keys+ * never leave the test process.+ */+object FakeAndroidKeyStore {+    private val keys = mutableMapOf<String, SecretKey>()++    fun install() {+        if (Security.getProvider("AndroidKeyStore") == null) {+            Security.addProvider(FakeProvider())+        }+    }++    fun put(alias: String, key: SecretKey) {+        keys[alias] = key+    }++    fun get(alias: String): SecretKey? = keys[alias]++    fun remove(alias: String) {+        keys.remove(alias)+    }++    fun contains(alias: String): Boolean = keys.containsKey(alias)++    fun aliases(): List<String> = keys.keys.toList()++    class FakeProvider : Provider("AndroidKeyStore", 1.0, "in-memory test keystore") {+        init {+            put("KeyStore.AndroidKeyStore", FakeKeyStoreSpi::class.java.name)+            put("KeyGenerator.AES", FakeKeyGeneratorSpi::class.java.name)+        }+    }++    class FakeKeyStoreSpi : KeyStoreSpi() {+        override fun engineLoad(stream: InputStream?, password: CharArray?) = Unit+        override fun engineContainsAlias(alias: String) = contains(alias)+        override fun engineDeleteEntry(alias: String) = remove(alias)+        override fun engineGetKey(alias: String, password: CharArray?): Key? = get(alias)+        override fun engineIsKeyEntry(alias: String) = contains(alias)+        override fun engineAliases(): Enumeration<String> = Collections.enumeration(aliases())+        override fun engineSize() = aliases().size+        override fun engineGetCertificate(alias: String): Certificate? = null+        override fun engineGetCertificateAlias(cert: Certificate) = null+        override fun engineGetCertificateChain(alias: String): Array<Certificate>? = null+        override fun engineGetCreationDate(alias: String) = Date()+        override fun engineIsCertificateEntry(alias: String) = false+        override fun engineSetCertificateEntry(alias: String, cert: Certificate) = Unit+        override fun engineStore(stream: OutputStream?, password: CharArray?) = Unit+        override fun engineSetKeyEntry(alias: String, key: Key, password: CharArray?, chain: Array<out Certificate>?) {+            if (key is SecretKey) put(alias, key)+        }+        override fun engineSetKeyEntry(alias: String, key: ByteArray, chain: Array<out Certificate>?) = Unit+    }++    class FakeKeyGeneratorSpi : KeyGeneratorSpi() {+        private var alias: String = "test-key"++        override fun engineInit(random: SecureRandom) = Unit+        override fun engineInit(keysize: Int, random: SecureRandom) = Unit+        override fun engineInit(params: java.security.spec.AlgorithmParameterSpec?, random: SecureRandom) {+            if (params is KeyGenParameterSpec) alias = params.keystoreAlias+        }++        override fun engineGenerateKey(): SecretKey {+            val bytes = ByteArray(32)+            SecureRandom().nextBytes(bytes)+            return SecretKeySpec(bytes, "AES").also { put(alias, it) }+        }+    }++    /** Convenience for tests that obtain a generator through JCA. */+    fun generator(): KeyGenerator = KeyGenerator.getInstance("AES", "AndroidKeyStore")+}
music/src/test/java/com/vayunmathur/music/FakeMediaProvider.kt
diff --git a/music/src/test/java/com/vayunmathur/music/FakeMediaProvider.kt b/music/src/test/java/com/vayunmathur/music/FakeMediaProvider.ktnew file mode 100644index 0000000000..a4a0401782--- /dev/null+++ b/music/src/test/java/com/vayunmathur/music/FakeMediaProvider.kt@@ -0,0 +1,90 @@+package com.vayunmathur.music++import android.content.ContentProvider+import android.content.ContentValues+import android.database.Cursor+import android.database.MatrixCursor+import android.net.Uri++/**+ * A fake `media` authority for Robolectric: Robolectric's own MediaStore+ * is empty, so the MediaStore readers in Util.kt can only ever be tested+ * against "no music on this phone". This provider answers the three audio+ * queries (media/albums/artists) with a small fixed library, including the+ * awkward rows real phones produce (multi-disc track numbers, a missing+ * year, the `<unknown>` artist sentinel).+ */+class FakeMediaProvider : ContentProvider() {++    companion object {+        /**+         * Robolectric's provider registry and the repository singleton both+         * outlive a test class in a shared sandbox, so the populated tests+         * switch this off (and refresh) on the way out: later classes then+         * query an authoritative empty library instead of this fixture.+         */+        @Volatile var enabled: Boolean = true+    }++    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)+        if (!enabled) return cursor+        fun row(values: Map<String, Any?>) {+            cursor.addRow(columns.map { values[it] })+        }+        when {+            uri.path?.endsWith("/audio/media") == true -> {+                // _id, title, artist, artist_id, album, album_id, duration, track, year+                row(+                    mapOf(+                        "_id" to 1L, "title" to "Beta Song", "artist" to "Artist One",+                        "artist_id" to 11L, "album" to "Album One", "album_id" to 21L,+                        "duration" to 200_000L, "track" to 1002, "year" to 2019,+                    ),+                )+                row(+                    mapOf(+                        "_id" to 2L, "title" to "Alpha Song", "artist" to "Artist One",+                        "artist_id" to 11L, "album" to "Album One", "album_id" to 21L,+                        "duration" to 180_000L, "track" to 2005, "year" to 0,+                    ),+                )+                row(+                    mapOf(+                        "_id" to 3L, "title" to "Gamma Song", "artist" to "<unknown>",+                        "artist_id" to 12L, "album" to "Album Two", "album_id" to 22L,+                        "duration" to 60_000L, "track" to 7, "year" to 1999,+                    ),+                )+            }+            uri.path?.endsWith("/audio/albums") == true -> {+                row(mapOf("_id" to 21L, "album" to "Album One", "artist" to "Artist One", "artist_id" to 11L))+                row(mapOf("_id" to 22L, "album" to "Album Two", "artist" to "<unknown>", "artist_id" to 12L))+            }+            uri.path?.endsWith("/audio/artists") == true -> {+                row(mapOf("_id" to 11L, "artist" to "Artist One"))+                row(mapOf("_id" to 12L, "artist" to "<unknown>"))+            }+        }+        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+}
music/src/test/java/com/vayunmathur/music/data/MusicRepositoryTest.kt
diff --git a/music/src/test/java/com/vayunmathur/music/data/MusicRepositoryTest.kt b/music/src/test/java/com/vayunmathur/music/data/MusicRepositoryTest.ktnew file mode 100644index 0000000000..60c328936b--- /dev/null+++ b/music/src/test/java/com/vayunmathur/music/data/MusicRepositoryTest.kt@@ -0,0 +1,50 @@+package com.vayunmathur.music.data++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.library.util.ManyManyMatching+import com.vayunmathur.music.FakeAndroidKeyStore+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.runBlocking+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.assertSame+import kotlin.test.assertTrue++/**+ * Repository against the real (SQLCipher) database and Robolectric's empty+ * MediaStore: the library side publishes empty lists, the Room side does+ * full playlist/matching CRUD.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class MusicRepositoryTest {++    @Before+    fun setUp() {+        FakeAndroidKeyStore.install()+    }++    private val context: Context get() = ApplicationProvider.getApplicationContext()+    private fun repo(): MusicRepository = MusicRepository.get(context)++    @Test+    fun `singleton returns the same instance`() {+        assertSame(repo(), repo())+    }++    @Test+    fun `refresh publishes an empty library without media`() = runBlocking {+        val repo = repo()+        repo.refresh()+        assertEquals(emptyList(), repo.getAllMusic())+        assertEquals(emptyList(), repo.getAllAlbums())+        assertEquals(emptyList(), repo.getAllArtists())+        assertTrue(repo.loaded.first())+        assertEquals(emptyList(), repo.music.first())+    }+}
music/src/test/java/com/vayunmathur/music/data/PopulatedLibraryTest.kt
diff --git a/music/src/test/java/com/vayunmathur/music/data/PopulatedLibraryTest.kt b/music/src/test/java/com/vayunmathur/music/data/PopulatedLibraryTest.ktnew file mode 100644index 0000000000..6422e6a9e7--- /dev/null+++ b/music/src/test/java/com/vayunmathur/music/data/PopulatedLibraryTest.kt@@ -0,0 +1,154 @@+package com.vayunmathur.music.data++import android.app.Application+import android.content.Context+import androidx.compose.runtime.getValue+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.music.FakeAndroidKeyStore+import com.vayunmathur.music.FakeMediaProvider+import com.vayunmathur.music.Route+import com.vayunmathur.music.platform.MusicViewModel+import com.vayunmathur.music.platform.PlaybackManager+import com.vayunmathur.music.platform.getAlbums+import com.vayunmathur.music.platform.getArtists+import com.vayunmathur.music.platform.getSongs+import com.vayunmathur.music.ui.HomeTabContent+import kotlinx.coroutines.flow.first+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.assertNotNull+import kotlin.test.assertTrue++/**+ * The populated half of the library: a fake media provider serves three+ * songs, and the MediaStore readers, the repository refresh and the+ * ViewModel's per-entity state all have to agree about them.+ *+ * The fake provider and the repository singleton both survive this class+ * in Robolectric's shared sandbox, so [tearDownClass] switches the+ * provider off and refreshes: later classes see an empty library again.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class PopulatedLibraryTest {++    @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(),+        )+    }++    private val appContext: Context get() = ApplicationProvider.getApplicationContext()++    private fun viewModel(): MusicViewModel =+        MusicViewModel(+            ApplicationProvider.getApplicationContext(),+            MusicRepository.get(appContext),+            PlaybackManager.getInstance(appContext),+        )++    @Test+    fun `media store readers parse the library`() {+        runBlocking {+            val songs = getSongs(appContext)+            assertEquals(listOf(1L, 2L, 3L), songs.map { it.id })+            val beta = songs.first { it.id == 1L }+            assertEquals("Beta Song", beta.title)+            assertEquals(1, beta.discNumber)+            assertEquals(2, beta.trackNumber)+            assertEquals(2019, beta.year)+            assertEquals("content://media/external/audio/media/1", beta.uri)+            val alpha = songs.first { it.id == 2L }+            // TRACK 2005 is MediaStore for disc 2, track 5; missing year stays 0.+            assertEquals(2, alpha.discNumber)+            assertEquals(5, alpha.trackNumber)+            assertEquals(0, alpha.year)++            assertEquals(listOf("Album One", "Album Two"), getAlbums(appContext).map { it.name })+            val artists = getArtists(appContext)+            assertEquals("Artist One", artists.first { it.id == 11L }.name)+            // The <unknown> sentinel normalises to empty so screens can localise it.+            assertEquals("", artists.first { it.id == 12L }.name)+        }+    }++    @Test+    fun `repository refresh publishes the fake library`() {+        runBlocking {+            val repo = MusicRepository.get(appContext)+            repo.refresh()+            assertEquals(3, repo.getAllMusic().size)+            assertEquals(2, repo.getAllAlbums().size)+            assertEquals(2, repo.getAllArtists().size)+            assertTrue(repo.loaded.first())+        }+    }++    @Test+    fun `view model entity states find the fake songs`() {+        runBlocking { MusicRepository.get(appContext).refresh() }+        val vm = viewModel()+        var title: String? = null+        var albumName: String? = null+        var artistName: String? = null+        composeRule.setContent {+            val song by vm.musicState(2L)+            val album by vm.albumState(21L)+            val artist by vm.artistState(11L)+            title = song?.title+            albumName = album?.name+            artistName = artist?.name+        }+        assertEquals("Alpha Song", title)+        assertEquals("Album One", albumName)+        assertEquals("Artist One", artistName)+    }++    @Test+    fun `home tab lists the fake songs and a tap starts playback bookkeeping`() {+        runBlocking { MusicRepository.get(appContext).refresh() }+        val vm = viewModel()+        val stack = NavBackStack<Route>(arrayOf(Route.Home))+        composeRule.setContent { HomeTabContent(stack, vm) }+        composeRule.onNodeWithText("Alpha Song").assertIsDisplayed()+        composeRule.onNodeWithText("Beta Song").assertIsDisplayed()+        composeRule.onNodeWithText("Gamma Song").assertIsDisplayed()+        composeRule.onNodeWithText("Beta Song").performClick()+        assertNotNull(vm.currentSource.value, "a row tap must record the queue source")+    }+}
music/src/test/java/com/vayunmathur/music/intents/AudioPreviewActivityTest.kt
diff --git a/music/src/test/java/com/vayunmathur/music/intents/AudioPreviewActivityTest.kt b/music/src/test/java/com/vayunmathur/music/intents/AudioPreviewActivityTest.ktnew file mode 100644index 0000000000..9e71dfccb0--- /dev/null+++ b/music/src/test/java/com/vayunmathur/music/intents/AudioPreviewActivityTest.kt@@ -0,0 +1,73 @@+package com.vayunmathur.music.intents++import android.content.Context+import android.content.Intent+import android.net.Uri+import androidx.lifecycle.Lifecycle+import androidx.test.core.app.ActivityScenario+import androidx.test.core.app.ApplicationProvider+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import java.io.File+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/**+ * AudioPreviewActivity lifecycle under Robolectric: the no-uri finish, and+ * a file-uri preview that builds its player, resolves a file-name title+ * (metadata lookup fails soft) and releases everything on destroy.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class AudioPreviewActivityTest {++    private val context: Context get() = ApplicationProvider.getApplicationContext()++    @Test+    fun `activity without a data uri finishes immediately`() {+        ActivityScenario.launch(AudioPreviewActivity::class.java).use { scenario ->+            // Finishing in onCreate destroys the activity before it resumes.+            assertEquals(Lifecycle.State.DESTROYED, scenario.state)+        }+    }++    @Test+    fun `preview with a file uri opens and destroys cleanly`() {+        val file = File(context.cacheDir, "preview-song.mp3")+        file.writeBytes(ByteArray(128))+        val intent = Intent(+            Intent.ACTION_VIEW,+            Uri.fromFile(file),+            context,+            AudioPreviewActivity::class.java,+        )+        try {+            ActivityScenario.launch<AudioPreviewActivity>(intent).use { scenario ->+                assertEquals(Lifecycle.State.RESUMED, scenario.state)+                scenario.onActivity { activity ->+                    assertTrue(!activity.isFinishing, "preview with a uri must stay open")+                }+                scenario.moveToState(Lifecycle.State.DESTROYED)+            }+        } finally {+            file.delete()+        }+    }++    @Test+    fun `preview with a content uri opens`() {+        val intent = Intent(+            Intent.ACTION_VIEW,+            Uri.parse("content://media/external/audio/media/42"),+            context,+            AudioPreviewActivity::class.java,+        )+        ActivityScenario.launch<AudioPreviewActivity>(intent).use { scenario ->+            scenario.onActivity { activity ->+                assertTrue(!activity.isFinishing)+            }+        }+    }+}
music/src/test/java/com/vayunmathur/music/platform/CastPlaybackTest.kt
diff --git a/music/src/test/java/com/vayunmathur/music/platform/CastPlaybackTest.kt b/music/src/test/java/com/vayunmathur/music/platform/CastPlaybackTest.ktnew file mode 100644index 0000000000..0b91e60b3a--- /dev/null+++ b/music/src/test/java/com/vayunmathur/music/platform/CastPlaybackTest.kt@@ -0,0 +1,87 @@+package com.vayunmathur.music.platform++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.music.data.Music+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.assertTrue++/**+ * CastPlayback with no television: the state machine must sit at Idle,+ * opening must fail cleanly back to Idle, and every session-scoped call+ * must be a silent no-op — CastingPlayer leans on exactly that contract.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class CastPlaybackTest {++    private val context: Context get() = ApplicationProvider.getApplicationContext()++    private fun song(id: Long = 1L) = Music(+        id = id, title = "Cast Song", artist = "Artist", artistId = 1, album = "Album",+        albumId = 7, uri = "content://media/$id", duration = 180_000, trackNumber = 1, year = 2020,+    )++    @Test+    fun `state starts idle and not casting`() {+        assertEquals(CastPlayback.State.Idle, CastPlayback.state.value)+        assertFalse(CastPlayback.isCasting)+        assertEquals(null, CastPlayback.tv.value)+    }++    @Test+    fun `open without a receiver fails back to idle`() {+        val opened = runBlocking { CastPlayback.open(context) }+        assertFalse(opened, "no connected TV means no cast session")+        assertEquals(CastPlayback.State.Idle, CastPlayback.state.value)+        assertFalse(CastPlayback.isCasting)+    }++    @Test+    fun `play send and close are no ops without a session`() {+        runBlocking { CastPlayback.play(context, song()) }+        CastPlayback.send(+            com.vayunmathur.sdk.cast.PlaybackCommand(+                com.vayunmathur.sdk.cast.PlaybackAction.Play,+            ),+        )+        CastPlayback.close()+        assertEquals(CastPlayback.State.Idle, CastPlayback.state.value)+    }++    @Test+    fun `clear cache removes transcoded files`() {+        val opusDir = File(context.cacheDir, "cast-opus").apply { mkdirs() }+        File(opusDir, "1.opus").writeBytes(byteArrayOf(1, 2, 3))+        val artDir = File(context.cacheDir, "cast-art").apply { mkdirs() }+        File(artDir, "1.jpg").writeBytes(byteArrayOf(4, 5))+        CastPlayback.clearCache(context)+        assertTrue(!opusDir.exists(), "transcode cache must be deleted")+        assertTrue(!artDir.exists(), "artwork cache must be deleted")+    }++    @Test+    fun `state and tv playback are value types`() {+        val casting = CastPlayback.State.Casting("Living Room TV")+        assertEquals("Living Room TV", casting.receiverName)+        assertEquals(casting, CastPlayback.State.Casting("Living Room TV"))+        assertTrue(CastPlayback.State.Connecting != CastPlayback.State.Idle)+        val tv = CastPlayback.TvPlayback(+            com.vayunmathur.sdk.cast.PlaybackState(+                positionMs = 5_000, durationMs = 180_000, playing = true,+                buffering = false, ended = false, speed = 1f,+            ),+            receivedAtMs = 123L,+        )+        assertEquals(5_000L, tv.state.positionMs)+        assertEquals(123L, tv.receivedAtMs)+        assertEquals(tv.copy(receivedAtMs = 124L).receivedAtMs, 124L)+    }+}
music/src/test/java/com/vayunmathur/music/platform/EmbeddedLyricsTest.kt
diff --git a/music/src/test/java/com/vayunmathur/music/platform/EmbeddedLyricsTest.kt b/music/src/test/java/com/vayunmathur/music/platform/EmbeddedLyricsTest.ktnew file mode 100644index 0000000000..17186ac658--- /dev/null+++ b/music/src/test/java/com/vayunmathur/music/platform/EmbeddedLyricsTest.kt@@ -0,0 +1,235 @@+package com.vayunmathur.music.platform++import android.content.Context+import android.net.Uri+import androidx.test.core.app.ApplicationProvider+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import java.io.ByteArrayOutputStream+import java.io.File+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull++/**+ * Embedded-lyrics extraction for the three containers the downloader writes:+ * Ogg (Opus/Vorbis comment packets), FLAC (comment metadata block) and+ * MP4 (the iTunes ©lyr atom). Files are synthetic but byte-faithful: the+ * parser never checks CRCs, so pages/boxes are built with plain builders.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class EmbeddedLyricsTest {++    private val context: Context get() = ApplicationProvider.getApplicationContext()++    private fun read(bytes: ByteArray): String? {+        val file = File.createTempFile("lyrics", ".bin", context.cacheDir)+        return try {+            file.writeBytes(bytes)+            EmbeddedLyrics.read(context, Uri.fromFile(file))+        } finally {+            file.delete()+        }+    }++    // ------------------------------------------------------------------+    // Vorbis comment payload shared by Ogg and FLAC builders+    // ------------------------------------------------------------------++    private fun intLe(value: Int) = byteArrayOf(+        value.toByte(), (value ushr 8).toByte(), (value ushr 16).toByte(), (value ushr 24).toByte(),+    )++    private fun vorbisComments(vararg entries: String, vendor: String = "ModernApps"): ByteArray {+        val out = ByteArrayOutputStream()+        val vendorBytes = vendor.toByteArray(Charsets.UTF_8)+        out.write(intLe(vendorBytes.size)); out.write(vendorBytes)+        out.write(intLe(entries.size))+        for (entry in entries) {+            val bytes = entry.toByteArray(Charsets.UTF_8)+            out.write(intLe(bytes.size)); out.write(bytes)+        }+        return out.toByteArray()+    }++    // ------------------------------------------------------------------+    // Ogg+    // ------------------------------------------------------------------++    private fun oggPage(packet: ByteArray, sequence: Int): ByteArray {+        val segments = ArrayList<Int>()+        var remaining = packet.size+        while (remaining >= 255) { segments.add(255); remaining -= 255 }+        segments.add(remaining)+        val out = ByteArrayOutputStream()+        out.write("OggS".toByteArray(Charsets.ISO_8859_1))+        out.write(0); out.write(if (sequence == 0) 2 else 0)+        out.write(ByteArray(8)); out.write(intLe(42)); out.write(intLe(sequence))+        out.write(ByteArray(4)); out.write(segments.size)+        segments.forEach { out.write(it) }+        out.write(packet)+        return out.toByteArray()+    }++    private fun oggOpus(commentsPacket: ByteArray): ByteArray =+        oggPage("OpusHead".toByteArray(Charsets.ISO_8859_1) + ByteArray(11), 0) ++            oggPage(commentsPacket, 1) ++            oggPage(byteArrayOf(0xFC.toByte(), 1, 2, 3), 2)++    @Test+    fun `reads lyrics from an opus tags packet`() {+        val packet = "OpusTags".toByteArray(Charsets.ISO_8859_1) ++            vorbisComments("TITLE=Song", "LYRICS=[00:01.00]hello world")+        assertEquals("[00:01.00]hello world", read(oggOpus(packet)))+    }++    @Test+    fun `reads lyrics from a vorbis comment packet case insensitively`() {+        val packet = byteArrayOf(3) + "vorbis".toByteArray(Charsets.ISO_8859_1) ++            vorbisComments("lyrics=plain unsynced words", "ARTIST=Someone")+        val bytes = oggPage("vorbis-head".toByteArray(Charsets.ISO_8859_1) + ByteArray(20), 0) ++            oggPage(packet, 1)+        assertEquals("plain unsynced words", read(bytes))+    }++    @Test+    fun `ogg without lyrics or with malformed comments returns null`() {+        val noLyrics = "OpusTags".toByteArray(Charsets.ISO_8859_1) ++            vorbisComments("TITLE=Only A Title")+        assertNull(read(oggOpus(noLyrics)))+        // Blank lyrics value counts as none.+        val blank = "OpusTags".toByteArray(Charsets.ISO_8859_1) ++            vorbisComments("LYRICS=   ")+        assertNull(read(oggOpus(blank)))+        // A comment packet that is neither OpusTags nor Vorbis.+        assertNull(read(oggOpus("OpusHead".toByteArray(Charsets.ISO_8859_1))))+        // Truncated vorbis list (count claims entries the bytes do not hold).+        val truncated = "OpusTags".toByteArray(Charsets.ISO_8859_1) ++            intLe(3) + "ven".toByteArray() + intLe(5)+        assertNull(read(oggOpus(truncated)))+    }++    @Test+    fun `ogg comment packet spanning pages is reassembled`() {+        val lyrics = "word ".repeat(200)+        val packet = "OpusTags".toByteArray(Charsets.ISO_8859_1) ++            vorbisComments("LYRICS=$lyrics")+        val head = oggPage("OpusHead".toByteArray(Charsets.ISO_8859_1) + ByteArray(11), 0)+        // First comment page carries 510 bytes as two full 255 segments, which+        // by the lacing rules means the packet continues on the next page.+        val firstPage = ByteArrayOutputStream().apply {+            write("OggS".toByteArray(Charsets.ISO_8859_1)); write(0); write(1)+            write(ByteArray(8)); write(intLe(42)); write(intLe(1)); write(ByteArray(4))+            write(2); write(255); write(255)+            write(packet, 0, 510)+        }.toByteArray()+        val rest = packet.copyOfRange(510, packet.size)+        assertEquals(lyrics, read(head + firstPage + oggPage(rest, 2)))+    }++    // ------------------------------------------------------------------+    // FLAC+    // ------------------------------------------------------------------++    private fun flacBlock(type: Int, payload: ByteArray, last: Boolean): ByteArray {+        val header = byteArrayOf(+            ((if (last) 0x80 else 0) or type).toByte(),+            (payload.size ushr 16).toByte(), (payload.size ushr 8).toByte(), payload.size.toByte(),+        )+        return header + payload+    }++    @Test+    fun `reads lyrics from a flac comment block`() {+        val bytes = "fLaC".toByteArray(Charsets.ISO_8859_1) ++            flacBlock(0, ByteArray(34), last = false) ++            flacBlock(4, vorbisComments("TITLE=T", "LYRICS=flac words"), last = true)+        assertEquals("flac words", read(bytes))+    }++    @Test+    fun `flac without a comment block returns null`() {+        val bytes = "fLaC".toByteArray(Charsets.ISO_8859_1) ++            flacBlock(0, ByteArray(34), last = true)+        assertNull(read(bytes))+        // Comment block after the last-block flag is never reached.+        val unreachable = "fLaC".toByteArray(Charsets.ISO_8859_1) ++            flacBlock(1, ByteArray(4), last = true) ++            flacBlock(4, vorbisComments("LYRICS=late"), last = true)+        assertNull(read(unreachable))+        // Truncated block payload.+        val truncated = "fLaC".toByteArray(Charsets.ISO_8859_1) ++            byteArrayOf(0x84.toByte(), 0, 0, 100) + ByteArray(10)+        assertNull(read(truncated))+    }++    // ------------------------------------------------------------------+    // MP4+    // ------------------------------------------------------------------++    private fun box(type: String, payload: ByteArray): ByteArray {+        val size = 8 + payload.size+        val header = byteArrayOf(+            (size ushr 24).toByte(), (size ushr 16).toByte(), (size ushr 8).toByte(), size.toByte(),+        )+        return header + type.toByteArray(Charsets.ISO_8859_1) + payload+    }++    private fun mp4WithLyrics(lyrics: String?): ByteArray {+        val dataPayload = ByteArray(8) + (lyrics?.toByteArray(Charsets.UTF_8) ?: ByteArray(0))+        val lyr = box("©lyr", box("data", dataPayload))+        val ilst = box("ilst", lyr)+        val meta = box("meta", ByteArray(4) + ilst)+        val udta = box("udta", meta)+        val moov = box("moov", udta)+        val ftyp = box("ftyp", "M4A ".toByteArray(Charsets.ISO_8859_1) + ByteArray(8))+        return ftyp + moov+    }++    @Test+    fun `reads lyrics from an m4a lyr atom`() {+        assertEquals("sing along now", read(mp4WithLyrics("sing along now")))+    }++    @Test+    fun `mp4 without lyrics returns null`() {+        assertNull(read(mp4WithLyrics(null)))+        assertNull(read(mp4WithLyrics("   ")))+        // No moov at all: just an ftyp and a free box.+        val noMoov = box("ftyp", "M4A ".toByteArray(Charsets.ISO_8859_1) + ByteArray(8)) ++            box("free", ByteArray(16))+        assertNull(read(noMoov))+        // Moov without udta/meta/ilst.+        val bareMoov = box("ftyp", "M4A ".toByteArray(Charsets.ISO_8859_1) + ByteArray(8)) ++            box("moov", box("mvhd", ByteArray(12)))+        assertNull(read(bareMoov))+    }++    @Test+    fun `mp4 with a large size moov box is still scanned`() {+        val dataPayload = ByteArray(8) + "large box words".toByteArray(Charsets.UTF_8)+        val ilst = box("ilst", box("©lyr", box("data", dataPayload)))+        val moovPayload = box("udta", box("meta", ByteArray(4) + ilst))+        val moovSize = 16L + moovPayload.size+        val moovHeader = ByteArray(16)+        moovHeader[3] = 1 // size == 1 means 64-bit size follows+        System.arraycopy("moov".toByteArray(Charsets.ISO_8859_1), 0, moovHeader, 4, 4)+        for (i in 0 until 8) moovHeader[8 + i] = (moovSize ushr (56 - 8 * i)).toByte()+        val ftyp = box("ftyp", "M4A ".toByteArray(Charsets.ISO_8859_1) + ByteArray(8))+        assertEquals("large box words", read(ftyp + moovHeader + moovPayload))+    }++    // ------------------------------------------------------------------+    // Container sniffing+    // ------------------------------------------------------------------++    @Test+    fun `unknown and short files return null`() {+        assertNull(read(ByteArray(0)))+        assertNull(read(ByteArray(8) { 0x11 }))+        assertNull(read("RIFFxxxxWAVE".toByteArray(Charsets.ISO_8859_1)))+        assertNull(read("OggS".toByteArray(Charsets.ISO_8859_1)))+    }+}
music/src/test/java/com/vayunmathur/music/platform/MusicViewModelTest.kt
diff --git a/music/src/test/java/com/vayunmathur/music/platform/MusicViewModelTest.kt b/music/src/test/java/com/vayunmathur/music/platform/MusicViewModelTest.ktnew file mode 100644index 0000000000..fb0e9f99f6--- /dev/null+++ b/music/src/test/java/com/vayunmathur/music/platform/MusicViewModelTest.kt@@ -0,0 +1,81 @@+package com.vayunmathur.music.platform++import android.app.Application+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.music.FakeAndroidKeyStore+import org.junit.Before+import com.vayunmathur.music.data.MusicRepository+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.runBlocking+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.assertFailsWith+import kotlin.test.assertFalse+import kotlin.test.assertTrue++/**+ * The ViewModel against the real repository and playback manager singletons+ * under Robolectric: MediaStore reads come back empty (no audio permission /+ * no media), which is the ordinary first-launch state these flows must+ * handle, and playlist writes go to the real DAO if the database opens.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class MusicViewModelTest {++    @Before+    fun setUp() {+        FakeAndroidKeyStore.install()+    }++    private val app: Application get() = ApplicationProvider.getApplicationContext()++    private fun viewModel(): MusicViewModel =+        MusicViewModel(app, MusicRepository.get(app), PlaybackManager.getInstance(app))++    @Test+    fun `initial state is empty and not loaded`() {+        val vm = viewModel()+        assertEquals(emptyList(), vm.music.value)+        assertEquals(emptyList(), vm.albums.value)+        assertEquals(emptyList(), vm.artists.value)+        assertFalse(vm.loaded.value)+        assertFalse(vm.isPlaying.value)+        assertEquals(0L, vm.currentPosition.value)+        assertEquals(null, vm.currentMediaItem.value)+        assertEquals(null, vm.player.value)+    }++    @Test+    fun `refresh publishes an empty library when there is no media`() = runBlocking {+        // Note: refreshLibrary() itself is not called here — its second step+        // (backfillTags) opens the SQLCipher tag cache, whose native library+        // cannot load on the JVM and whose failure would leak out of+        // viewModelScope as an uncaught exception. The MediaStore half is+        // exercised directly; the full path runs on device.+        val songs = MusicRepository.get(app).music.first { true }+        assertEquals(emptyList(), songs)+        assertTrue(MusicRepository.get(app).getAllMusic().isEmpty())+        assertTrue(MusicRepository.get(app).getAllAlbums().isEmpty())+        assertTrue(MusicRepository.get(app).getAllArtists().isEmpty())+    }++    @Test+    fun `factory creates the view model and rejects other classes`() {+        val factory = MusicViewModelFactory(+            app,+            MusicRepository.get(app),+            PlaybackManager.getInstance(app),+        )+        val vm = factory.create(MusicViewModel::class.java)+        assertEquals(emptyList(), vm.music.value)+        assertFailsWith<IllegalArgumentException> {+            factory.create(OtherViewModel::class.java)+        }+    }++    class OtherViewModel : androidx.lifecycle.ViewModel()+}
music/src/test/java/com/vayunmathur/music/platform/MusicVmStateTest.kt
diff --git a/music/src/test/java/com/vayunmathur/music/platform/MusicVmStateTest.kt b/music/src/test/java/com/vayunmathur/music/platform/MusicVmStateTest.ktnew file mode 100644index 0000000000..40e031269d--- /dev/null+++ b/music/src/test/java/com/vayunmathur/music/platform/MusicVmStateTest.kt@@ -0,0 +1,115 @@+package com.vayunmathur.music.platform++import android.app.Application+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.setValue+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.onRoot+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.MusicRepository+import com.vayunmathur.music.ui.AlbumDetailScreen+import com.vayunmathur.music.ui.HomeTabContent+import com.vayunmathur.music.ui.components.PlayingBottomBar+import org.junit.Before+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.assertNull++/**+ * The ViewModel's composable state accessors and the screens bound directly+ * to them, against the real (empty) library: every accessor must resolve to+ * "nothing here" rather than crash before the first MediaStore scan lands.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class MusicVmStateTest {++    @get:Rule+    val composeRule = createComposeRule()++    @Before+    fun setUp() {+        FakeAndroidKeyStore.install()+        // Robolectric binds no real PlaybackService, so the MediaController's+        // service-connected callback would NPE on a null ComponentName when+        // the main looper idles. Registering the component keeps that+        // callback on media3's ordinary "session unreachable" path.+        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 viewModel(): MusicViewModel =+        MusicViewModel(app, MusicRepository.get(app), PlaybackManager.getInstance(app))++    private fun stack() = NavBackStack<Route>(arrayOf(Route.Home))++    @Test+    fun `now playing state is null without a loaded item`() {+        val vm = viewModel()+        var captured: NowPlayingUiState? = NowPlayingUiState(title = "sentinel")+        composeRule.setContent { captured = vm.nowPlayingState() }+        assertNull(captured)+    }++    @Test+    fun `entity state accessors resolve to null for unknown ids`() {+        val vm = viewModel()+        var music: Any? = "x"+        var album: Any? = "x"+        var artist: Any? = "x"+        composeRule.setContent {+            val m by vm.musicState(99L)+            val a by vm.albumState(99L)+            val r by vm.artistState(99L)+            music = m; album = a; artist = r+        }+        assertNull(music); assertNull(album); assertNull(artist)+    }++    @Test+    fun `playing song id composable is null without playback`() {+        val vm = viewModel()+        var captured: Long? = 42L+        composeRule.setContent { captured = vm.playingSongIdFrom("album_7") }+        assertNull(captured)+    }++    @Test+    fun `home tab renders the songs screen over an empty library`() {+        val vm = viewModel()+        composeRule.setContent { HomeTabContent(stack(), vm) }+        composeRule.onRoot().assertExists()+    }++    @Test+    fun `album detail renders nothing for an unknown album`() {+        val vm = viewModel()+        composeRule.setContent { AlbumDetailScreen(stack(), vm, albumId = 12345L) }+        composeRule.onRoot().assertExists()+        composeRule.onNodeWithText("Great Album").assertDoesNotExist()+    }++    @Test+    fun `playing bottom bar renders nothing without a loaded item`() {+        val vm = viewModel()+        composeRule.setContent {+            PlayingBottomBar(vm, stack())+            androidx.compose.material3.Text("anchor")+        }+        composeRule.onNodeWithText("anchor").assertIsDisplayed()+    }+}
music/src/test/java/com/vayunmathur/music/platform/PlaybackManagerTest.kt
diff --git a/music/src/test/java/com/vayunmathur/music/platform/PlaybackManagerTest.kt b/music/src/test/java/com/vayunmathur/music/platform/PlaybackManagerTest.ktnew file mode 100644index 0000000000..bdfd2fc973--- /dev/null+++ b/music/src/test/java/com/vayunmathur/music/platform/PlaybackManagerTest.kt@@ -0,0 +1,101 @@+package com.vayunmathur.music.platform++import android.app.Application+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.music.data.Music+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.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertSame++/**+ * PlaybackManager without a connected controller (Robolectric binds no+ * session service): queue-source bookkeeping must still happen, transport+ * calls must be safe no-ops, and invalid queues must change nothing.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class PlaybackManagerTest {++    @Before+    fun setUp() {+        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 manager(): PlaybackManager = PlaybackManager.getInstance(app)++    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 `singleton and initial observable state`() {+        val pm = manager()+        assertSame(pm, manager())+        assertFalse(pm.isPlaying.value)+        assertNull(pm.player.value)+        assertNull(pm.currentMediaItem.value)+    }++    @Test+    fun `playSong records the queue source without a controller`() {+        val pm = manager()+        pm.playSong(listOf(song(1), song(2)), 1, sourceId = "album_7", sourceName = "Seven")+        assertEquals("album_7", pm.currentSource.value)+        assertEquals("Seven", pm.currentSourceName.value)+        // Nothing can actually load: the observable item stays empty.+        assertNull(pm.currentMediaItem.value)+        assertFalse(pm.isPlaying.value)+    }++    @Test+    fun `playSong rejects empty queues and bad indices without touching the source`() {+        val pm = manager()+        pm.playSong(listOf(song(1)), 0, sourceId = "album_1", sourceName = "One")+        assertEquals("album_1", pm.currentSource.value)+        pm.playSong(emptyList(), 0, sourceId = "album_2", sourceName = "Two")+        assertEquals("album_1", pm.currentSource.value)+        pm.playSong(listOf(song(1)), 5, sourceId = "album_3", sourceName = "Three")+        assertEquals("album_1", pm.currentSource.value)+        pm.playSong(listOf(song(1)), -1, sourceId = "album_4", sourceName = "Four")+        assertEquals("album_1", pm.currentSource.value)+    }++    @Test+    fun `playShuffled records the source and rejects empty queues`() {+        val pm = manager()+        pm.playShuffled(listOf(song(1), song(2), song(3)), sourceId = "all_songs", sourceName = "All")+        assertEquals("all_songs", pm.currentSource.value)+        pm.playShuffled(emptyList(), sourceId = "playlist_9", sourceName = "Nine")+        assertEquals("all_songs", pm.currentSource.value)+    }++    @Test+    fun `transport calls are safe without a controller and seek still tracks position`() {+        val pm = manager()+        pm.togglePlayPause()+        pm.skipNext()+        pm.skipPrevious()+        pm.toggleShuffle()+        pm.toggleRepeat()+        assertFalse(pm.shuffleMode.value)+        pm.seekTo(42_000L)+        assertEquals(42_000L, pm.currentPosition.value)+        pm.seekTo(0L)+        assertEquals(0L, pm.currentPosition.value)+    }+}
music/src/test/java/com/vayunmathur/music/ui/MusicDialogsTest.kt
diff --git a/music/src/test/java/com/vayunmathur/music/ui/MusicDialogsTest.kt b/music/src/test/java/com/vayunmathur/music/ui/MusicDialogsTest.ktnew file mode 100644index 0000000000..1c9771e861--- /dev/null+++ b/music/src/test/java/com/vayunmathur/music/ui/MusicDialogsTest.kt@@ -0,0 +1,74 @@+package com.vayunmathur.music.ui++import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.assertIsEnabled+import androidx.compose.ui.test.assertIsNotEnabled+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.compose.ui.test.performTextInput+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.music.R+import com.vayunmathur.music.ui.dialogs.CreatePlaylistDialog+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++@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class MusicDialogsTest {++    @get:Rule+    val composeRule = createComposeRule()++    private val context = ApplicationProvider.getApplicationContext<android.content.Context>()+    private fun str(id: Int): String = context.getString(id)++    @Test+    fun `create playlist dialog trims the name and creates`() {+        var created: String? = null+        var dismissed = false+        composeRule.setContent {+            CreatePlaylistDialog(onDismiss = { dismissed = true }, onCreate = { created = it })+        }+        composeRule.onNodeWithText(str(R.string.dialog_create_playlist)).assertIsDisplayed()+        composeRule.onNodeWithText(str(com.vayunmathur.library.ui.R.string.create))+            .assertIsNotEnabled()+        composeRule.onNodeWithText(str(R.string.playlist_name_hint))+            .performTextInput("  Road Mix  ")+        composeRule.onNodeWithText(str(com.vayunmathur.library.ui.R.string.create))+            .assertIsEnabled()+            .performClick()+        assertEquals("Road Mix", created)+        assertTrue(!dismissed)+    }++    @Test+    fun `create playlist dialog cancel dismisses without creating`() {+        var created: String? = null+        var dismissed = false+        composeRule.setContent {+            CreatePlaylistDialog(onDismiss = { dismissed = true }, onCreate = { created = it })+        }+        composeRule.onNodeWithText(str(R.string.playlist_name_hint)).performTextInput("Mix")+        composeRule.onNodeWithText(str(com.vayunmathur.library.ui.R.string.cancel)).performClick()+        assertTrue(dismissed)+        assertEquals(null, created)+    }++    @Test+    fun `create playlist dialog rejects blank names`() {+        var created: String? = null+        composeRule.setContent {+            CreatePlaylistDialog(onDismiss = {}, onCreate = { created = it })+        }+        composeRule.onNodeWithText(str(R.string.playlist_name_hint)).performTextInput("   ")+        composeRule.onNodeWithText(str(com.vayunmathur.library.ui.R.string.create))+            .assertIsNotEnabled()+        assertEquals(null, created)+    }+}
music/src/test/java/com/vayunmathur/music/ui/NowPlayingControlsTest.kt
diff --git a/music/src/test/java/com/vayunmathur/music/ui/NowPlayingControlsTest.kt b/music/src/test/java/com/vayunmathur/music/ui/NowPlayingControlsTest.ktnew file mode 100644index 0000000000..fa574492b4--- /dev/null+++ b/music/src/test/java/com/vayunmathur/music/ui/NowPlayingControlsTest.kt@@ -0,0 +1,90 @@+package com.vayunmathur.music.ui++import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.hasProgressBarRangeInfo+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.assertCountEquals+import androidx.compose.ui.test.onAllNodesWithText+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performTouchInput+import androidx.compose.ui.test.swipe+import androidx.compose.ui.semantics.ProgressBarRangeInfo+import androidx.media3.common.Player+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.music.Route+import com.vayunmathur.music.platform.MusicActions+import com.vayunmathur.music.platform.NowPlayingUiState+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++@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class NowPlayingControlsTest {++    @get:Rule+    val composeRule = createComposeRule()++    private fun stack() = NavBackStack<Route>(arrayOf(Route.Home))++    private class RecordingActions : MusicActions {+        var toggled = 0+        var next = 0+        var previous = 0+        var shuffle = 0+        var repeat = 0+        var seek: Long? = null+        override fun togglePlayPause() { toggled++ }+        override fun skipNext() { next++ }+        override fun skipPrevious() { previous++ }+        override fun toggleShuffle() { shuffle++ }+        override fun toggleRepeat() { repeat++ }+        override fun seekTo(pos: Long) { seek = pos }+    }++    @Test+    fun `progress texts and seek slider report fractions of the duration`() {+        val actions = RecordingActions()+        composeRule.setContent {+            NowPlayingScreen(+                NowPlayingUiState(+                    title = "Timed", artist = "Artist", album = "Album",+                    songId = 1L, isPlaying = false, durationMs = 240_000, positionMs = 60_000,+                ),+                actions, stack(),+            )+        }+        // Both progress labels compose (they may sit below the fold).+        composeRule.onAllNodesWithText("1:00").assertCountEquals(1)+        composeRule.onAllNodesWithText("4:00").assertCountEquals(1)+        // Dragging the progress slider must seek: 60s of 240s starts at 0.25.+        composeRule+            .onNode(hasProgressBarRangeInfo(ProgressBarRangeInfo(0.25f, 0f..1f)))+            .performTouchInput { swipe(Offset(200f, center.y), Offset(600f, center.y), 300L) }+        assertTrue(actions.seek != null, "seeking must reach the actions")+        assertTrue(actions.seek!! in 60_000..240_000, "seek was ${actions.seek}")+    }++    @Test+    fun `zero duration renders zeros and a safe slider`() {+        val actions = RecordingActions()+        composeRule.setContent {+            NowPlayingScreen(+                NowPlayingUiState(+                    title = "No Duration", artist = "Artist", album = "",+                    songId = null, isPlaying = true, durationMs = 0, positionMs = 0,+                    shuffle = true, repeatMode = Player.REPEAT_MODE_ONE,+                ),+                actions, stack(),+            )+        }+        composeRule.onNodeWithText("No Duration").assertIsDisplayed()+        // Position and duration both read 0:00 with no loaded track length.+        composeRule.onAllNodesWithText("0:00").assertCountEquals(2)+    }+}
music/src/test/java/com/vayunmathur/music/ui/NowPlayingMoreTest.kt
diff --git a/music/src/test/java/com/vayunmathur/music/ui/NowPlayingMoreTest.kt b/music/src/test/java/com/vayunmathur/music/ui/NowPlayingMoreTest.ktnew file mode 100644index 0000000000..9228197c2f--- /dev/null+++ b/music/src/test/java/com/vayunmathur/music/ui/NowPlayingMoreTest.kt@@ -0,0 +1,101 @@+package com.vayunmathur.music.ui++import androidx.compose.material3.Text+import androidx.compose.ui.Modifier+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.music.Route+import com.vayunmathur.music.data.Music+import com.vayunmathur.music.platform.MusicActions+import com.vayunmathur.music.platform.NowPlayingUiState+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++@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class NowPlayingMoreTest {++    @get:Rule+    val composeRule = createComposeRule()++    private fun stack() = NavBackStack<Route>(arrayOf(Route.Home))++    private fun song(id: Long, title: String) = Music(+        id = id, title = title, artist = "Artist", artistId = 1, album = "Album", albumId = 7,+        uri = "content://media/$id", duration = 180_000, trackNumber = id.toInt(), year = 2020,+    )++    @Test+    fun `wide layout shows both slots`() {+        composeRule.setContent {+            NowPlayingWideLayout(player = { Text("player slot") }, queue = { Text("queue slot") })+        }+        composeRule.onNodeWithText("player slot").assertIsDisplayed()+        composeRule.onNodeWithText("queue slot").assertIsDisplayed()+    }++    @Test+    fun `queue list shows its title over an empty queue`() {+        var jumped = -1+        composeRule.setContent {+            QueueList(emptyList(), playingSongId = null, title = "Up next", onJump = { jumped = it })+        }+        composeRule.onNodeWithText("Up next").assertIsDisplayed()+        assertEquals(-1, jumped)+    }++    @Test+    fun `queue list jumps by index`() {+        var jumped = -1+        val songs = listOf(song(1, "First"), song(2, "Second"), song(3, "Third"))+        composeRule.setContent {+            QueueList(songs, playingSongId = 3L, title = "Playing next", onJump = { jumped = it })+        }+        composeRule.onNodeWithText("First").assertIsDisplayed()+        composeRule.onNodeWithText("Third").performClick()+        assertEquals(2, jumped)+    }++    @Test+    fun `now playing with synced lyrics and playing state`() {+        var toggled = false+        val actions = object : MusicActions {+            override fun togglePlayPause() { toggled = true }+        }+        composeRule.setContent {+            NowPlayingScreen(+                NowPlayingUiState(+                    title = "Lyric Song", artist = "Singer", album = "Records",+                    songId = 9L, isPlaying = true, durationMs = 240_000, positionMs = 61_000,+                    lyrics = "[00:01.00]first line\n[01:01.00]second line",+                ),+                actions, stack(),+            ) { Text("queue body") }+        }+        composeRule.onNodeWithText("Lyric Song").assertIsDisplayed()+        composeRule.onNodeWithText("Singer").assertIsDisplayed()+        assertTrue(!toggled)+    }++    @Test+    fun `now playing queue slot composes its content`() {+        composeRule.setContent {+            NowPlayingScreen(+                NowPlayingUiState(+                    title = "Plain Song", artist = "Singer", album = "",+                    songId = null, isPlaying = false, durationMs = 0, positionMs = 0,+                ),+                MusicActions.Noop, stack(),+            ) { Text("queue body") }+        }+        composeRule.onNodeWithText("Plain Song").assertIsDisplayed()+    }+}