Modern Apps git

← Modern-Apps.git

uniflix: add tests for domain, data, ViewModels and screens

Commit
f04ae2fb68866fd07ebc81aab59feb269e12700c
Author
Vayun Mathur <[email protected]>
When
2026-11-07 04:35 UTC (29 days ago)
Parents
31601d1
JVM/Robolectric tests across the module: pure domain and image-URL
mapping, in-memory Room DAO CRUD, offline addon/JS provider paths,
ViewModel state behaviour (Detail resolution via fake providers and
custom registry factories, Browse/Search/Home offline states,
TmdbApi offline failures), and Compose screens for phone and TV
(cards, grids, dialogs, pickers, watch overlays and state panels,
navigation graph). Adds a fake AndroidKeyStore JCE provider for
tests so DatabaseHelper-backed ViewModels can be constructed under
Robolectric, plus a Mockito test dependency for ExoPlayer.

Coverage (merged, whole module): 8.3% -> 46.5% instructions
(17783/38206). Bugs fixed: none.

Untestable remainder on the JVM: everything that must open the
SQLCipher Room database (UniflixRepository flows, AddonsViewModel
database paths, and the screens that collect those flows:
Addons/AddonDetail/Lists/ContinueWatching/TvHome/TvMyList/TvWatch/
TvAddonDetail pages, DetailScreen notes section). Robolectric has
no AndroidKeyStore (worked around for ViewModel construction) and
the SQLCipher native driver cannot open on the host JVM
(UnsatisfiedLinkError at SQLiteConnection.nativeOpen); those paths
need emulator instrumented tests, and the app APK is arm64/armv7
only while the shared emulator is x86_64.

Verified with gslot ./gradlew :uniflix:createMergedCoverageReport
(full :uniflix:testDevUnitTest suite passes).

(cherry picked from commit 6b2e97f535b5705c81ec03033b4058cdf4ba430b)

Diff

uniflix/build.gradle.kts
diff --git a/uniflix/build.gradle.kts b/uniflix/build.gradle.ktsindex ed05ef19c6..3fc2d62394 100644--- a/uniflix/build.gradle.kts+++ b/uniflix/build.gradle.kts@@ -35,6 +35,9 @@ dependencies {     // JS plugin runtime: QuickJS engine + pure-Java WASM host (Chicory).     implementation(libs.quickjs.kt)     implementation(libs.chicory.runtime)++    // Mocked ExoPlayer for WatchPlayerState transport tests.+    testImplementation(libs.mockito.core) }  // Desktop JVM unit tests cannot load the Android QuickJS .so: run them against
uniflix/src/test/java/com/vayunmathur/uniflix/NavigationComposeTest.kt
diff --git a/uniflix/src/test/java/com/vayunmathur/uniflix/NavigationComposeTest.kt b/uniflix/src/test/java/com/vayunmathur/uniflix/NavigationComposeTest.ktnew file mode 100644index 0000000000..05a16723e3--- /dev/null+++ b/uniflix/src/test/java/com/vayunmathur/uniflix/NavigationComposeTest.kt@@ -0,0 +1,36 @@+package com.vayunmathur.uniflix++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.ui.DynamicTheme+import kotlin.test.Test+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner++/** The phone navigation graph: Home entry and hub navigation in offline states. */+@RunWith(RobolectricTestRunner::class)+class NavigationComposeTest {++    @get:Rule+    val composeRule = createComposeRule()++    @Test fun homeEntryRendersAndOpensMoviesHub() {+        composeRule.setContent { DynamicTheme { Navigation() } }+        composeRule.onNodeWithText("Uniflix").assertIsDisplayed()+        composeRule.onNodeWithText("Movies").performClick()+        // Movies hub (BrowseViewModel) settles offline without crashing.+        composeRule.waitForIdle()+        composeRule.onNodeWithText("Movies").assertIsDisplayed()+    }++    @Test fun homeEntryOpensSearch() {+        composeRule.setContent { DynamicTheme { Navigation() } }+        composeRule.onNodeWithText("Uniflix").assertIsDisplayed()+        composeRule.onNodeWithText("Series").performClick()+        composeRule.waitForIdle()+        composeRule.onNodeWithText("Series").assertIsDisplayed()+    }+}
uniflix/src/test/java/com/vayunmathur/uniflix/data/AddonStreamProviderOfflineTest.kt
diff --git a/uniflix/src/test/java/com/vayunmathur/uniflix/data/AddonStreamProviderOfflineTest.kt b/uniflix/src/test/java/com/vayunmathur/uniflix/data/AddonStreamProviderOfflineTest.ktnew file mode 100644index 0000000000..008320c98a--- /dev/null+++ b/uniflix/src/test/java/com/vayunmathur/uniflix/data/AddonStreamProviderOfflineTest.kt@@ -0,0 +1,59 @@+package com.vayunmathur.uniflix.data++import com.vayunmathur.uniflix.Route+import com.vayunmathur.uniflix.domain.MediaType+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFailsWith+import kotlin.test.assertFalse+import kotlin.test.assertTrue+import kotlinx.coroutines.test.runTest++/** Offline behaviour of the URL-addon provider plus navigation route shapes. */+class AddonStreamProviderOfflineTest {++    @Test fun providerIdentity() {+        val p = AddonStreamProvider("https://addons.example.com", "My Addon")+        assertEquals("My Addon", p.name)+        assertFalse(p.supports4k)+        assertEquals("https://addons.example.com", p.baseUrl)+    }++    @Test fun resolveFailsWithAddonNameOffline() = runTest {+        val p = AddonStreamProvider("https://addons.invalid", "Offline Addon")+        val err = assertFailsWith<IllegalStateException> {+            p.resolve(42, MediaType.MOVIE)+        }+        assertTrue(err.message!!.contains("Offline Addon"), err.message)+    }++    @Test fun alternatesFailsWithAddonNameOffline() = runTest {+        val p = AddonStreamProvider("https://addons.invalid", "Offline Addon")+        val err = assertFailsWith<IllegalStateException> {+            p.alternates(7, MediaType.TV, season = 1, episode = 2)+        }+        assertTrue(err.message!!.contains("Offline Addon"), err.message)+    }++    @Test fun fetchManifestFailsAsNetworkErrorOffline() = runTest {+        val err = assertFailsWith<com.vayunmathur.uniflix.domain.ManifestError.Network> {+            AddonStreamProvider.fetchManifest("https://addons.invalid/base")+        }+        assertTrue(err.message!!.contains("addons.invalid"), err.message)+    }++    @Test fun routesCarryTheirArguments() {+        assertEquals(Route.Detail("movie", 42), Route.Detail("movie", 42))+        assertTrue(Route.Detail("movie", 42) != Route.Detail("tv", 42))+        val watch = Route.Watch("tv", 7)+        assertEquals(0, watch.season)+        assertEquals(0, watch.episode)+        assertEquals(Route.Watch("tv", 7, 2, 5), Route.Watch("tv", 7, season = 2, episode = 5))+        assertEquals(Route.AddonDetail(9L), Route.AddonDetail(9L))+        // Singleton routes are distinct destinations.+        val routes: List<Route> = listOf(+            Route.Home, Route.Movies, Route.Series, Route.Search,+            Route.Lists, Route.ContinueWatching, Route.PlayerSettings, Route.Addons)+        assertEquals(routes.size, routes.distinct().size)+    }+}
uniflix/src/test/java/com/vayunmathur/uniflix/data/UniflixRepositoryTest.kt
diff --git a/uniflix/src/test/java/com/vayunmathur/uniflix/data/UniflixRepositoryTest.kt b/uniflix/src/test/java/com/vayunmathur/uniflix/data/UniflixRepositoryTest.ktnew file mode 100644index 0000000000..92453c12c7--- /dev/null+++ b/uniflix/src/test/java/com/vayunmathur/uniflix/data/UniflixRepositoryTest.kt@@ -0,0 +1,155 @@+package com.vayunmathur.uniflix.data++import androidx.test.core.app.ApplicationProvider+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.test.runTest++/**+ * DAO CRUD over an in-memory [UniflixDatabase] under Robolectric.+ * (UniflixRepository itself wraps the DB in SQLCipher via AndroidKeyStore,+ * which Robolectric does not provide, so it cannot be opened here.)+ */[email protected](org.robolectric.RobolectricTestRunner::class)+class UniflixRepositoryTest {++    /** Thin DAO facade mirroring the repository calls under test. */+    private class Repo(private val db: UniflixDatabase) {+        val watchlist get() = db.watchlistDao().getAllFlow()+        val continueWatching get() = db.continueWatchingDao().getAllFlow()+        val userLists get() = db.userListDao().getListsFlow()+        fun listItems(listId: Long) = db.userListDao().getItemsFlow(listId)+        fun notesFor(tmdbId: Int, mediaType: String) = db.userListDao().getNotesFlow(tmdbId, mediaType)+        suspend fun isWatchlisted(key: String) = db.watchlistDao().getByKey(key) != null+        suspend fun upsertWatchlist(v: WatchlistEntry) = db.watchlistDao().upsert(v)+        suspend fun removeWatchlist(key: String) = db.watchlistDao().deleteByKey(key)+        suspend fun savePosition(v: ContinueWatchingEntry) = db.continueWatchingDao().upsert(v)+        suspend fun positionFor(key: String) = db.continueWatchingDao().getPosition(key) ?: 0L+        suspend fun clearPosition(key: String) = db.continueWatchingDao().deleteByKey(key)+        suspend fun upsertList(v: UserList) = db.userListDao().upsertList(v)+        suspend fun upsertListItem(v: UserListItem) = db.userListDao().upsertItem(v)+        suspend fun deleteList(v: UserList) = db.userListDao().deleteList(v)+        suspend fun deleteListItem(v: UserListItem) = db.userListDao().deleteItem(v)+        suspend fun upsertNote(v: TitleNote) = db.userListDao().upsertNote(v)+        suspend fun deleteNote(v: TitleNote) = db.userListDao().deleteNote(v)+        val addons get() = db.addonDao().observeAllOrdered()+        val enabledAddons get() = db.addonDao().observeEnabledOrdered()+        suspend fun upsertAddon(v: AddonEntity) = db.addonDao().upsert(v)+        suspend fun addonById(id: Long) = db.addonDao().getById(id)+        suspend fun addonByManifestUrl(u: String) = db.addonDao().getByManifestUrl(u)+        suspend fun addonCount() = db.addonDao().count()+        suspend fun deleteAddon(id: Long) = db.addonDao().deleteById(id)+        suspend fun setAddonEnabled(id: Long, e: Boolean) = db.addonDao().setEnabled(id, e)+        suspend fun swapAddonPriorities(a: AddonEntity, b: AddonEntity) = db.addonDao().swapPriorities(a, b)+        suspend fun setAddonError(id: Long, e: String?) = db.addonDao().setError(id, e)+        suspend fun setAddonConfig(id: Long, c: String) = db.addonDao().setConfig(id, c)+    }++    private fun repo(): Repo {+        val ctx = ApplicationProvider.getApplicationContext<android.content.Context>()+        val db = androidx.room3.Room.inMemoryDatabaseBuilder(ctx, UniflixDatabase::class.java)+            .allowMainThreadQueries().build()+        return Repo(db)+    }++    @Test fun watchKeyFormat() {+        assertEquals("movie:42:0:0", watchKey(42, "movie"))+        assertEquals("tv:7:2:5", watchKey(7, "tv", season = 2, episode = 5))+    }++    @Test fun watchlistAndContinueWatchingCrud() = runTest {+        val repo = repo()+        val key = watchKey(901, "movie")+        repo.removeWatchlist(key)+        assertFalse(repo.isWatchlisted(key))+        repo.upsertWatchlist(+            WatchlistEntry(key, 901, "movie", "Film", "/p.jpg", addedAt = 10L))+        assertTrue(repo.isWatchlisted(key))+        assertEquals(listOf("Film"), repo.watchlist.first().filter { it.key == key }.map { it.title })+        repo.removeWatchlist(key)+        assertFalse(repo.isWatchlisted(key))++        val posKey = watchKey(902, "tv", 1, 3)+        repo.clearPosition(posKey)+        assertEquals(0L, repo.positionFor(posKey))+        repo.savePosition(+            ContinueWatchingEntry(+                posKey, 902, "tv", "Show", null,+                season = 1, episode = 3, positionMs = 55_000L, durationMs = 90_000L))+        assertEquals(55_000L, repo.positionFor(posKey))+        assertTrue(repo.continueWatching.first().any { it.key == posKey && it.episode == 3 })+        repo.clearPosition(posKey)+        assertEquals(0L, repo.positionFor(posKey))+    }++    @Test fun listsItemsAndNotesCrud() = runTest {+        val repo = repo()+        val listId = repo.upsertList(UserList(name = "Favourites", createdAt = 1L))+        assertTrue(listId > 0)+        val itemId = repo.upsertListItem(+            UserListItem(listId = listId, tmdbId = 903, mediaType = "movie", title = "Listed", posterPath = null))+        assertTrue(itemId > 0)+        assertEquals(listOf("Listed"), repo.listItems(listId).first().map { it.title })+        assertTrue(repo.userLists.first().any { it.id == listId && it.name == "Favourites" })++        val noteId = repo.upsertNote(+            TitleNote(tmdbId = 903, mediaType = "movie", body = "great", score = 5))+        assertTrue(noteId > 0)+        val notes = repo.notesFor(903, "movie").first()+        assertEquals(listOf("great"), notes.filter { it.id == noteId }.map { it.body })++        repo.deleteNote(TitleNote(id = noteId, tmdbId = 903, mediaType = "movie", body = "great", score = 5))+        assertTrue(repo.notesFor(903, "movie").first().none { it.id == noteId })+        repo.deleteListItem(+            UserListItem(id = itemId, listId = listId, tmdbId = 903, mediaType = "movie", title = "Listed", posterPath = null))+        assertTrue(repo.listItems(listId).first().isEmpty())+        repo.deleteList(UserList(id = listId, name = "Favourites", createdAt = 1L))+        assertTrue(repo.userLists.first().none { it.id == listId })+    }++    @Test fun addonCrudOrderingAndFlags() = runTest {+        val repo = repo()+        // Clean slate for the shared local database.+        for (addon in repo.addons.first()) repo.deleteAddon(addon.dbId)+        assertEquals(0, repo.addonCount())+        val idA = repo.upsertAddon(+            AddonEntity(+                manifestUrl = "https://a.example/manifest.json", baseUrl = "https://a.example",+                addonId = "a", name = "Alpha", priority = 5))+        val idB = repo.upsertAddon(+            AddonEntity(+                manifestUrl = "https://b.example/manifest.json", baseUrl = "https://b.example",+                addonId = "b", name = "Beta", priority = 1))+        assertEquals(2, repo.addonCount())+        // Ordered by priority, not insertion order.+        assertEquals(listOf("Beta", "Alpha"), repo.addons.first().map { it.name })+        assertEquals("Alpha", repo.addonById(idA)?.name)+        assertEquals("b", repo.addonByManifestUrl("https://b.example/manifest.json")?.addonId)+        assertNull(repo.addonById(999_999L))++        repo.setAddonEnabled(idB, false)+        assertEquals(listOf("Alpha"), repo.enabledAddons.first().map { it.name })+        repo.setAddonError(idA, "boom")+        assertEquals("boom", repo.addonById(idA)?.lastError)+        repo.setAddonError(idA, null)+        assertNull(repo.addonById(idA)?.lastError)+        repo.setAddonConfig(idA, """{"k":1}""")+        assertEquals("""{"k":1}""", repo.addonById(idA)?.configJson)++        val alpha = repo.addonById(idA)!!+        val beta = repo.addonById(idB)!!+        repo.swapAddonPriorities(alpha, beta)+        assertEquals(1, repo.addonById(idA)?.priority)+        assertEquals(5, repo.addonById(idB)?.priority)++        repo.deleteAddon(idA)+        repo.deleteAddon(idB)+        assertEquals(0, repo.addonCount())+        assertNotNull(repo)+    }+}
uniflix/src/test/java/com/vayunmathur/uniflix/domain/AddonModelsImageUrlTest.kt
diff --git a/uniflix/src/test/java/com/vayunmathur/uniflix/domain/AddonModelsImageUrlTest.kt b/uniflix/src/test/java/com/vayunmathur/uniflix/domain/AddonModelsImageUrlTest.ktnew file mode 100644index 0000000000..f59646bdb5--- /dev/null+++ b/uniflix/src/test/java/com/vayunmathur/uniflix/domain/AddonModelsImageUrlTest.kt@@ -0,0 +1,115 @@+package com.vayunmathur.uniflix.domain++import com.vayunmathur.uniflix.data.AddonStreamProvider+import com.vayunmathur.uniflix.data.TmdbImageUrl+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFailsWith+import kotlin.test.assertNull+import kotlin.test.assertTrue++/** Pure mapping helpers: addon stream ids, stream/subtitle conversion, image URLs, base-URL rules. */+class AddonModelsImageUrlTest {++    @Test fun streamIdsForMoviesAndTv() {+        assertEquals("tmdb:42", addonStreamId(42, MediaType.MOVIE))+        assertEquals("tmdb:42", addonStreamId(42, MediaType.MOVIE, season = 1, episode = 2))+        assertEquals("tmdb:7:2:5", addonStreamId(7, MediaType.TV, season = 2, episode = 5))+        assertEquals("tmdb:7:0:0", addonStreamId(7, MediaType.TV))+        assertEquals("movie", addonResourceType(MediaType.MOVIE))+        assertEquals("series", addonResourceType(MediaType.TV))+    }++    @Test fun streamToVideoSourceTitlesAndSubtitles() {+        val src = AddonStream(+            url = "https://cdn.example/v.m3u8", name = "  ",+            subtitles = listOf(+                AddonSubtitle(url = "https://cdn.example/en.vtt", lang = "en", id = "eng"),+                AddonSubtitle(url = "", lang = "fr"),+                AddonSubtitle(url = "https://cdn.example/x.vtt", lang = "", id = null)),+        ).toVideoSource("Fallback")+        assertEquals("https://cdn.example/v.m3u8", src!!.streamUrl)+        // Blank name falls back to the addon display name.+        assertEquals("Fallback", src.title)+        assertEquals(2, src.subtitles.size)+        assertEquals("en", src.subtitles[0].language)+        assertEquals("eng", src.subtitles[0].displayName)+        // No lang and no id defaults the language to en with blank display.+        assertEquals("en", src.subtitles[1].language)+        assertEquals("", src.subtitles[1].displayName)+        val named = AddonStream(url = "u", name = "HD").toVideoSource("F")+        assertEquals("HD", named!!.title)+    }++    @Test fun blankUrlsAreDropped() {+        assertNull(AddonStream(url = "  ").toVideoSource("F"))+        assertNull(AddonSubtitle(url = "").toSubtitleTrack())+        val track = AddonSubtitle(url = "u", lang = "", id = "spa").toSubtitleTrack()+        assertEquals("spa", track!!.language)+        assertEquals("spa", track.displayName)+    }++    @Test fun streamsResponseDefaultsToEmpty() {+        val json = kotlinx.serialization.json.Json { ignoreUnknownKeys = true }+        assertTrue(json.decodeFromString(AddonStreamsResponse.serializer(), "{}").streams.isEmpty())+        val parsed = json.decodeFromString(+            AddonStreamsResponse.serializer(), """{"streams":[{"url":"u","name":"n"}]}""")+        assertEquals("u", parsed.streams.single().url)+        assertEquals(false, AddonBehaviorHints().notWebReady)+    }++    @Test fun mediaModelDefaults() {+        val item = MediaItem(tmdbId = 1, mediaType = MediaType.MOVIE, title = "T")+        assertEquals("", item.overview)+        assertEquals(0.0, item.voteAverage)+        assertNull(item.year)+        val detail = MediaDetail(tmdbId = 2, mediaType = MediaType.TV, title = "S")+        assertTrue(detail.seasons.isEmpty() && detail.recommendations.isEmpty())+        assertEquals(8, SeasonSummary(3, "Season 3", 8).episodeCount)+        assertEquals("Ep", Episode(1, 1, "Ep").name)+    }++    @Test fun imageUrlsUseProxyAndSizes() {+        assertNull(TmdbImageUrl.poster(null))+        assertNull(TmdbImageUrl.backdrop(null))+        assertNull(TmdbImageUrl.still(null))+        assertEquals(+            "https://api.maproj.org/api/tmdb/image/w342/p.jpg", TmdbImageUrl.poster("/p.jpg"))+        assertEquals(+            "https://api.maproj.org/api/tmdb/image/w500/p.jpg", TmdbImageUrl.poster("/p.jpg", "w500"))+        assertEquals(+            "https://api.maproj.org/api/tmdb/image/original/b.jpg", TmdbImageUrl.backdrop("/b.jpg"))+        assertEquals(+            "https://api.maproj.org/api/tmdb/image/w185/s.jpg", TmdbImageUrl.still("/s.jpg"))+    }++    @Test fun normalizeBaseUrlAcceptsBareAndManifestForms() {+        assertEquals("https://addons.example.com", AddonStreamProvider.normalizeBaseUrl("addons.example.com"))+        assertEquals(+            "https://addons.example.com", AddonStreamProvider.normalizeBaseUrl("https://addons.example.com/"))+        assertEquals(+            "https://addons.example.com/base",+            AddonStreamProvider.normalizeBaseUrl("https://addons.example.com/base/manifest.json"))+        assertEquals(+            "http://localhost:8080", AddonStreamProvider.normalizeBaseUrl("http://localhost:8080"))+        assertEquals(+            "http://127.0.0.1:9000/a", AddonStreamProvider.normalizeBaseUrl("http://127.0.0.1:9000/a/"))+        assertEquals(+            "http://192.168.1.5", AddonStreamProvider.normalizeBaseUrl("http://192.168.1.5"))+    }++    @Test fun normalizeBaseUrlRejectsInsecureAndInvalid() {+        assertFailsWith<ManifestError.InsecureUrl> {+            AddonStreamProvider.normalizeBaseUrl("http://addons.example.com")+        }+        assertFailsWith<ManifestError.InsecureUrl> {+            AddonStreamProvider.normalizeBaseUrl("http://8.8.8.8/addon")+        }+        assertFailsWith<ManifestError.Parse> {+            AddonStreamProvider.normalizeBaseUrl("ftp://addons.example.com")+        }+        assertFailsWith<ManifestError.Parse> {+            AddonStreamProvider.normalizeBaseUrl("https://exa mple.com")+        }+    }+}
uniflix/src/test/java/com/vayunmathur/uniflix/platform/AddonsViewModelKeyStoreTest.kt
diff --git a/uniflix/src/test/java/com/vayunmathur/uniflix/platform/AddonsViewModelKeyStoreTest.kt b/uniflix/src/test/java/com/vayunmathur/uniflix/platform/AddonsViewModelKeyStoreTest.ktnew file mode 100644index 0000000000..69d4cf9768--- /dev/null+++ b/uniflix/src/test/java/com/vayunmathur/uniflix/platform/AddonsViewModelKeyStoreTest.kt@@ -0,0 +1,82 @@+package com.vayunmathur.uniflix.platform++import android.app.Application+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.uniflix.data.AddonEntity+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.ExperimentalCoroutinesApi+import kotlinx.coroutines.test.UnconfinedTestDispatcher+import kotlinx.coroutines.test.setMain++/**+ * AddonsViewModel with a fake AndroidKeyStore provider: the ViewModel can be+ * constructed (its init only builds the Room database object; the SQLCipher+ * connection itself is never opened on these paths).+ */[email protected](org.robolectric.RobolectricTestRunner::class)+@OptIn(ExperimentalCoroutinesApi::class)+class AddonsViewModelKeyStoreTest {++    private val app: Application get() = ApplicationProvider.getApplicationContext()++    @BeforeTest fun setUp() {+        FakeAndroidKeyStore.install()+        Dispatchers.setMain(UnconfinedTestDispatcher())+    }++    private fun await(timeoutMs: Long = 15_000, cond: () -> Boolean): Boolean {+        val deadline = System.currentTimeMillis() + timeoutMs+        while (System.currentTimeMillis() < deadline) {+            if (cond()) return true+            Thread.sleep(20)+        }+        return cond()+    }++    private fun entity(id: Long, name: String, kind: String = "http", priority: Int = 0) = AddonEntity(+        dbId = id, manifestUrl = "https://$name.invalid/manifest.json",+        baseUrl = "https://$name.invalid", addonId = name, name = name,+        kind = kind, priority = priority)++    @Test fun blankAndOfflineAddsResetAddingFlag() {+        val vm = AddonsViewModel(app)+        vm.addByUrl("  ")+        assertFalse(vm.adding)+        vm.addByUrl("https://addons.invalid/base")+        assertTrue(await { !vm.adding }, "adding=${vm.adding}")+        vm.addJsPlugin("")+        assertFalse(vm.adding)+        vm.addJsPlugin("not a plugin at all")+        assertTrue(await { !vm.adding }, "adding=${vm.adding}")+        assertFalse(vm.refreshing)+    }++    @Test fun moveGuardsAndJsNotices() {+        val vm = AddonsViewModel(app)+        val a = AddonRow(entity(1, "a", priority = 0), isDefault = false)+        val b = AddonRow(entity(2, "b", priority = 1), isDefault = false)+        val rows = listOf(a, b)+        vm.moveUp(rows, a)+        vm.moveDown(rows, b)+        vm.moveUp(rows, AddonRow(entity(99, "ghost"), isDefault = false))+        vm.moveDown(emptyList(), a)+        // JS rows take the notice path (no network, no database).+        val js = AddonRow(entity(3, "js", kind = "js"), isDefault = false)+        vm.refreshManifest(js)+        assertFalse(vm.refreshing)+    }++    @Test fun defaultPrefsViaViewModel() {+        val vm = AddonsViewModel(app)+        val a = AddonRow(entity(5, "a"), isDefault = false)+        vm.setDefault(a)+        vm.clearDefault()+        assertFalse(vm.adding)+        assertEquals(emptyList(), vm.addons.value)+    }+}
uniflix/src/test/java/com/vayunmathur/uniflix/platform/FakeAndroidKeyStore.kt
diff --git a/uniflix/src/test/java/com/vayunmathur/uniflix/platform/FakeAndroidKeyStore.kt b/uniflix/src/test/java/com/vayunmathur/uniflix/platform/FakeAndroidKeyStore.ktnew file mode 100644index 0000000000..837e48fa95--- /dev/null+++ b/uniflix/src/test/java/com/vayunmathur/uniflix/platform/FakeAndroidKeyStore.kt@@ -0,0 +1,94 @@+package com.vayunmathur.uniflix.platform++import android.security.keystore.KeyGenParameterSpec+import java.io.InputStream+import java.io.OutputStream+import java.security.Key+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.KeyGeneratorSpi+import javax.crypto.SecretKey+import javax.crypto.spec.SecretKeySpec++/**+ * In-memory stand-in for the AndroidKeyStore JCE provider, which Robolectric+ * does not ship. Lets DatabaseHelper generate/store its passphrase key on the+ * JVM so ViewModels backed by the (still unopenable) SQLCipher database can+ * at least be constructed and run their non-database paths.+ */+object FakeAndroidKeyStore {+    private val keys = Collections.synchronizedMap(HashMap<String, Key>())++    fun install() {+        if (Security.getProvider("AndroidKeyStore") == null) {+            Security.addProvider(FakeProvider())+        }+    }++    internal fun put(alias: String, key: Key) {+        keys[alias] = key+    }++    internal fun get(alias: String): Key? = keys[alias]+    internal fun remove(alias: String) {+        keys.remove(alias)+    }++    internal fun contains(alias: String): Boolean = keys.containsKey(alias)+    internal fun aliases(): List<String> = synchronized(keys) { keys.keys.toList() }+}++class FakeProvider : Provider("AndroidKeyStore", 1.0, "fake for tests") {+    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 engineStore(stream: OutputStream?, password: CharArray?) = Unit+    override fun engineGetKey(alias: String, password: CharArray?): Key? = FakeAndroidKeyStore.get(alias)+    override fun engineContainsAlias(alias: String): Boolean = FakeAndroidKeyStore.contains(alias)+    override fun engineDeleteEntry(alias: String) = FakeAndroidKeyStore.remove(alias)+    override fun engineAliases(): Enumeration<String> =+        Collections.enumeration(FakeAndroidKeyStore.aliases())+    override fun engineSize(): Int = FakeAndroidKeyStore.aliases().size+    override fun engineIsKeyEntry(alias: String): Boolean = FakeAndroidKeyStore.contains(alias)+    override fun engineIsCertificateEntry(alias: String): Boolean = false+    override fun engineGetCertificate(alias: String): Certificate? = null+    override fun engineGetCertificateChain(alias: String): Array<Certificate>? = null+    override fun engineGetCertificateAlias(cert: Certificate): String? = null+    override fun engineGetCreationDate(alias: String): Date = Date(0)+    override fun engineSetKeyEntry(alias: String, key: Key, password: CharArray?, chain: Array<out Certificate>?) {+        FakeAndroidKeyStore.put(alias, key)+    }+    override fun engineSetKeyEntry(alias: String, key: ByteArray, chain: Array<out Certificate>?) {+        FakeAndroidKeyStore.put(alias, SecretKeySpec(key, "AES"))+    }+    override fun engineSetCertificateEntry(alias: String, cert: Certificate) = Unit+}++class FakeKeyGeneratorSpi : KeyGeneratorSpi() {+    private var alias: String = "db_no_auth_key"++    override fun engineInit(random: SecureRandom?) = Unit+    override fun engineInit(params: java.security.spec.AlgorithmParameterSpec?, random: SecureRandom?) {+        if (params is KeyGenParameterSpec) alias = params.keystoreAlias+    }+    override fun engineInit(keysize: Int, random: SecureRandom?) = Unit++    override fun engineGenerateKey(): SecretKey {+        val bytes = ByteArray(32)+        SecureRandom().nextBytes(bytes)+        val key = SecretKeySpec(bytes, "AES")+        FakeAndroidKeyStore.put(alias, key)+        return key+    }+}
uniflix/src/test/java/com/vayunmathur/uniflix/platform/UniflixViewModelsTest.kt
diff --git a/uniflix/src/test/java/com/vayunmathur/uniflix/platform/UniflixViewModelsTest.kt b/uniflix/src/test/java/com/vayunmathur/uniflix/platform/UniflixViewModelsTest.ktnew file mode 100644index 0000000000..dbfbd02598--- /dev/null+++ b/uniflix/src/test/java/com/vayunmathur/uniflix/platform/UniflixViewModelsTest.kt@@ -0,0 +1,225 @@+package com.vayunmathur.uniflix.platform++import android.app.Application+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.uniflix.data.TmdbApi+import com.vayunmathur.uniflix.domain.MediaType+import com.vayunmathur.uniflix.domain.StreamProvider+import com.vayunmathur.uniflix.domain.VideoSource+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.ExperimentalCoroutinesApi+import kotlinx.coroutines.test.UnconfinedTestDispatcher+import kotlinx.coroutines.test.resetMain+import kotlinx.coroutines.test.runTest+import kotlinx.coroutines.test.setMain++/**+ * ViewModel behaviour with no network and no Room access: catalog loads fail+ * into their error states, and Detail resolution runs against fake providers+ * via the ViewModel's own `streamProviders` test hook.+ */[email protected](org.robolectric.RobolectricTestRunner::class)+@OptIn(ExperimentalCoroutinesApi::class)+class UniflixViewModelsTest {++    private val app: Application get() = ApplicationProvider.getApplicationContext()++    @BeforeTest fun setUp() { Dispatchers.setMain(UnconfinedTestDispatcher()) }+    @AfterTest fun tearDown() { Dispatchers.resetMain() }++    private fun await(timeoutMs: Long = 15_000, cond: () -> Boolean): Boolean {+        val deadline = System.currentTimeMillis() + timeoutMs+        while (System.currentTimeMillis() < deadline) {+            if (cond()) return true+            Thread.sleep(20)+        }+        return cond()+    }++    private class FakeProvider(+        private val result: Result<VideoSource>,+        private val serverNames: List<String> = emptyList(),+    ) : StreamProvider() {+        override val name: String = "Fake"+        override val supports4k: Boolean = true+        var lastTmdb: Int = -1+        var lastServer: String? = null+        override suspend fun resolve(+            tmdbId: Int, mediaType: MediaType, season: Int, episode: Int, server: String?,+        ): VideoSource {+            lastTmdb = tmdbId+            lastServer = server+            return result.getOrThrow()+        }+        override suspend fun servers(): List<String> = serverNames+    }++    // ---- Detail ----++    @Test fun detailResolveSuccessSetsSource() {+        val vm = DetailViewModel(app)+        val fake = FakeProvider(Result.success(VideoSource("https://x/v.m3u8", "Stream")))+        vm.streamProviders = listOf(fake)+        vm.resolve(MediaType.MOVIE, 42)+        assertTrue(await { vm.state.source != null }, "state=${vm.state}")+        assertEquals("https://x/v.m3u8", vm.state.source?.streamUrl)+        assertFalse(vm.state.resolving)+        assertFalse(vm.state.providerMissing)+        assertEquals(42, fake.lastTmdb)+    }++    @Test fun detailResolveWithNoProvidersMarksMissing() {+        val vm = DetailViewModel(app)+        vm.streamProviders = emptyList()+        vm.resolve(MediaType.TV, 7, season = 1, episode = 2)+        assertTrue(await { vm.state.providerMissing }, "state=${vm.state}")+        assertNull(vm.state.source)+        assertFalse(vm.state.resolving)+    }++    @Test fun detailResolveFailureSurfacesError() {+        val vm = DetailViewModel(app)+        vm.streamProviders = listOf(FakeProvider(Result.failure(IllegalStateException("no streams here"))))+        vm.resolve(MediaType.MOVIE, 3)+        assertTrue(await { vm.state.resolveError != null }, "state=${vm.state}")+        assertEquals("no streams here", vm.state.resolveError)+        assertFalse(vm.state.resolving)+    }++    @Test fun detailLoadServersAndSelectServer() {+        val vm = DetailViewModel(app)+        val fake = FakeProvider(+            Result.success(VideoSource("https://x/v", "S")),+            serverNames = listOf("Alpha", "Beta"))+        vm.streamProviders = listOf(fake)+        vm.loadServers()+        assertTrue(await { vm.state.servers.isNotEmpty() }, "state=${vm.state}")+        assertEquals(listOf("Alpha", "Beta"), vm.state.servers)+        vm.selectServer(MediaType.MOVIE, 9, 0, 0, "Beta")+        assertEquals("Beta", vm.state.selectedServer)+        assertTrue(await { fake.lastServer == "Beta" }, "server=${fake.lastServer}")+        // Re-selecting the same server is a no-op (no second resolve).+        val before = vm.state.source+        vm.selectServer(MediaType.MOVIE, 9, 0, 0, "Beta")+        assertEquals(before, vm.state.source)+    }++    @Test fun detailLoadFailsOfflineIntoErrorState() {+        val vm = DetailViewModel(app)+        vm.load(MediaType.MOVIE, 42)+        assertTrue(await { !vm.state.loading && vm.state.detail == null }, "state=${vm.state}")+        vm.load(MediaType.TV, 42)+        assertTrue(await { !vm.state.loading }, "state=${vm.state}")+        assertNull(vm.state.detail)+    }++    @Test fun detailSeasonAndGuardsOffline() = runTest {+        val vm = DetailViewModel(app)+        vm.selectSeason(MediaType.TV, 7, 3)+        assertTrue(await { vm.state.episodes.isEmpty() })+        assertEquals(1, vm.state.selectedSeason)+        // No detail loaded: watchlist toggle is a no-op.+        vm.toggleWatchlist()+        assertFalse(vm.state.watchlisted)+        // Blank notes are refused before any storage call.+        vm.addNote(MediaType.MOVIE, 1, "   ", 5)+        // Saved-position lookup degrades to 0 when storage is unavailable.+        assertEquals(0L, vm.startPosition(MediaType.MOVIE, 1, 0, 0))+    }++    // ---- Browse / Search / Home / Lists ----++    @Test fun browseLoadsFailOfflineIntoEmptyStates() {+        val vm = BrowseViewModel(app)+        vm.loadMovies()+        assertTrue(await { !vm.movies.loading && vm.movies.items.isEmpty() }, "movies=${vm.movies}")+        vm.loadSeries()+        assertTrue(await { !vm.series.loading && vm.series.items.isEmpty() }, "series=${vm.series}")+    }++    @Test fun searchBlankClearsAndQueryFailsOffline() {+        val vm = SearchViewModel(app)+        vm.onQueryChange("  ")+        assertEquals("  ", vm.state.query)+        assertTrue(vm.state.results.isEmpty())+        assertFalse(vm.state.loading)+        vm.onQueryChange("dune")+        assertEquals("dune", vm.state.query)+        // Debounced search runs against the unreachable catalog and settles empty.+        assertTrue(await { !vm.state.loading && vm.state.results.isEmpty() }, "state=${vm.state}")+        assertEquals("dune", vm.state.query)+    }++    @Test fun homeRefreshFailsOffline() {+        val vm = HomeViewModel(app)+        vm.refresh()+        assertTrue(+            await { !vm.state.loading && vm.state.trendingMovies.isEmpty() },+            "state=${vm.state}")+        assertTrue(vm.state.topMovies.isEmpty() && vm.state.topTv.isEmpty())+    }++    @Test fun listsBlankCreateIsRefused() {+        val vm = ListsViewModel(app)+        vm.createList("   ")+        // No state is exposed; the guard simply returns without launching storage work.+        assertNotNull(vm)+    }++    @Test fun tmdbApiEndpointsFailOffline() = runTest {+        val api = TmdbApi()+        assertTrue(runCatching { api.trendingMovies() }.isFailure)+        assertTrue(runCatching { api.trendingTv() }.isFailure)+        assertTrue(runCatching { api.topRatedMovies() }.isFailure)+        assertTrue(runCatching { api.topRatedTv() }.isFailure)+        assertTrue(runCatching { api.discoverMovies() }.isFailure)+        assertTrue(runCatching { api.discoverTv() }.isFailure)+        assertTrue(runCatching { api.search("a b") }.isFailure)+        assertTrue(runCatching { api.movieDetail(1) }.isFailure)+        assertTrue(runCatching { api.tvDetail(1) }.isFailure)+        assertTrue(runCatching { api.seasonEpisodes(1, 1) }.isFailure)+    }++    @Test fun detailResolveViaCustomRegistryFactory() {+        val vm = DetailViewModel(app)+        val fake = FakeProvider(Result.success(VideoSource("https://x/custom", "Custom")))+        vm.streamProviders = null+        vm.registryFactory = RegistryFactory { _, _ ->+            com.vayunmathur.uniflix.domain.PluginRegistry(listOf("custom-1" to fake))+        }+        vm.resolve(MediaType.MOVIE, 11)+        assertTrue(await { vm.state.source != null }, "state=${vm.state}")+        assertEquals("https://x/custom", vm.state.source?.streamUrl)+        assertEquals(11, fake.lastTmdb)+    }++    @Test fun detailLoadServersFailsGracefullyWithRealFactory() {+        FakeAndroidKeyStore.install()+        val vm = DetailViewModel(app)+        // Default AllInstalled factory reads the addon DB, which cannot open+        // under Robolectric; loadServers must swallow that and keep no servers.+        vm.loadServers()+        Thread.sleep(300)+        assertTrue(vm.state.servers.isEmpty())+        assertFalse(vm.state.resolving)+    }++    @Test fun registryFactoriesAreDistinctObjects() {+        assertTrue(RegistryFactory.HttpAddons !== RegistryFactory.AllInstalled)+        val vm = DetailViewModel(app)+        assertEquals(RegistryFactory.AllInstalled, vm.registryFactory)+        vm.registryFactory = RegistryFactory.HttpAddons+        assertEquals(RegistryFactory.HttpAddons, vm.registryFactory)+        assertEquals(1, DetailUiState().selectedSeason)+        assertEquals(0L, DetailUiState().startPositionMs)+        assertTrue(DetailUiState().episodes.isEmpty() && DetailUiState().servers.isEmpty())+    }+}
uniflix/src/test/java/com/vayunmathur/uniflix/ui/DetailHomeSearchComposeTest.kt
diff --git a/uniflix/src/test/java/com/vayunmathur/uniflix/ui/DetailHomeSearchComposeTest.kt b/uniflix/src/test/java/com/vayunmathur/uniflix/ui/DetailHomeSearchComposeTest.ktnew file mode 100644index 0000000000..8d3c41b355--- /dev/null+++ b/uniflix/src/test/java/com/vayunmathur/uniflix/ui/DetailHomeSearchComposeTest.kt@@ -0,0 +1,127 @@+package com.vayunmathur.uniflix.ui++import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.compose.ui.test.performTextInput+import com.vayunmathur.library.ui.DynamicTheme+import com.vayunmathur.uniflix.domain.MediaItem+import com.vayunmathur.uniflix.domain.MediaType+import com.vayunmathur.uniflix.platform.DetailUiState+import com.vayunmathur.uniflix.platform.HomeUiState+import com.vayunmathur.uniflix.platform.SearchUiState+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++/** Stateless Home / Search / Detail / PlayerSettings screens under Robolectric. */+@RunWith(RobolectricTestRunner::class)+class DetailHomeSearchComposeTest {++    @get:Rule+    val composeRule = createComposeRule()++    private fun item(id: Int, title: String, type: MediaType = MediaType.MOVIE) =+        MediaItem(tmdbId = id, mediaType = type, title = title, year = 2022)++    @Test fun homeShowsRowsAndHubActions() {+        var movies = 0+        var opened: MediaItem? = null+        composeRule.setContent {+            DynamicTheme {+                HomeScreen(+                    state = HomeUiState(+                        trendingMovies = listOf(item(1, "Trending Film")),+                        trendingTv = listOf(item(2, "Trending Show", MediaType.TV))),+                    onRefresh = {},+                    onOpenDetail = { opened = it },+                    onOpenSearch = {}, onOpenMovies = { movies++ },+                    onOpenSeries = {}, onOpenLists = {}, onOpenContinue = {},+                    onOpenAddons = {})+            }+        }+        composeRule.onNodeWithText("Uniflix").assertIsDisplayed()+        composeRule.onNodeWithText("Trending movies").assertIsDisplayed()+        composeRule.onNodeWithText("Trending Film").assertIsDisplayed()+        composeRule.onNodeWithText("Movies").performClick()+        assertEquals(1, movies)+        composeRule.onNodeWithText("Trending Film").performClick()+        assertEquals(1, opened?.tmdbId)+    }++    @Test fun homeLoadingShowsSpinnerOnlyState() {+        composeRule.setContent {+            DynamicTheme {+                HomeScreen(+                    state = HomeUiState(loading = true),+                    onRefresh = {}, onOpenDetail = {}, onOpenSearch = {},+                    onOpenMovies = {}, onOpenSeries = {}, onOpenLists = {},+                    onOpenContinue = {}, onOpenAddons = {})+            }+        }+        composeRule.onNodeWithText("Uniflix").assertIsDisplayed()+        composeRule.onNodeWithText("Series").assertIsDisplayed()+    }++    @Test fun searchTypesQueryAndOpensResult() {+        var query: String? = null+        var opened: MediaItem? = null+        val results = listOf(item(5, "Found Film"))+        composeRule.setContent {+            DynamicTheme {+                SearchScreen(+                    state = SearchUiState(query = "", results = results),+                    onQueryChange = { query = it },+                    onBack = {},+                    onOpenDetail = { opened = it })+            }+        }+        composeRule.onNodeWithText("Search").assertIsDisplayed()+        composeRule.onNodeWithText("Title").performTextInput("found")+        assertEquals("found", query)+        composeRule.onNodeWithText("Found Film").assertIsDisplayed()+        composeRule.onNodeWithText("Found Film").performClick()+        assertEquals(results[0], opened)+    }++    @Test fun detailLoadingAndFailureStates() {+        composeRule.setContent {+            DynamicTheme {+                DetailScreen(+                    state = DetailUiState(loading = true),+                    onBack = {}, onSeasonChange = {}, onToggleWatchlist = {},+                    onPlay = { _, _ -> }, onResolve = { _, _ -> },+                    onAddNote = { _, _ -> }, onOpenDetail = {}, onOpenAddons = {})+            }+        }+        composeRule.onNodeWithText("Detail").assertIsDisplayed()+    }++    @Test fun detailFailureShowsMessage() {+        composeRule.setContent {+            DynamicTheme {+                DetailScreen(+                    state = DetailUiState(loading = false, detail = null),+                    onBack = {}, onSeasonChange = {}, onToggleWatchlist = {},+                    onPlay = { _, _ -> }, onResolve = { _, _ -> },+                    onAddNote = { _, _ -> }, onOpenDetail = {}, onOpenAddons = {})+            }+        }+        composeRule.onNodeWithText("Detail failed to load.").assertIsDisplayed()+    }++    @Test fun playerSettingsShowsPlaybackInfo() {+        composeRule.setContent {+            DynamicTheme { PlayerSettingsScreen(onBack = {}) }+        }+        composeRule.onNodeWithText("Player").assertIsDisplayed()+        composeRule.onNodeWithText("Playback").assertIsDisplayed()+        composeRule.onNodeWithText(+            "Streams play through the configured provider. Subtitle tracks come with the resolved source.")+            .assertIsDisplayed()+    }+}
uniflix/src/test/java/com/vayunmathur/uniflix/ui/UniflixCardsComposeTest.kt
diff --git a/uniflix/src/test/java/com/vayunmathur/uniflix/ui/UniflixCardsComposeTest.kt b/uniflix/src/test/java/com/vayunmathur/uniflix/ui/UniflixCardsComposeTest.ktnew file mode 100644index 0000000000..4cefd2c226--- /dev/null+++ b/uniflix/src/test/java/com/vayunmathur/uniflix/ui/UniflixCardsComposeTest.kt@@ -0,0 +1,92 @@+package com.vayunmathur.uniflix.ui++import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import com.vayunmathur.library.ui.DynamicTheme+import com.vayunmathur.uniflix.data.AddonEntity+import com.vayunmathur.uniflix.domain.Episode+import com.vayunmathur.uniflix.domain.MediaItem+import com.vayunmathur.uniflix.domain.MediaType+import com.vayunmathur.uniflix.platform.AddonRow+import kotlin.test.Test+import kotlin.test.assertEquals+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner++/** Compose-under-Robolectric tests for the small catalog/addon cards. */+@RunWith(RobolectricTestRunner::class)+class UniflixCardsComposeTest {++    @get:Rule+    val composeRule = createComposeRule()++    @Test fun mediaCardShowsTitleYearAndOpens() {+        var opened = 0+        val item = MediaItem(+            tmdbId = 1, mediaType = MediaType.MOVIE, title = "A Film", year = 2024)+        composeRule.setContent {+            DynamicTheme { MediaCard(item = item, onOpen = { opened++ }) }+        }+        composeRule.onNodeWithText("A Film").assertIsDisplayed()+        composeRule.onNodeWithText("2024").assertIsDisplayed()+        composeRule.onNodeWithText("A Film").performClick()+        assertEquals(1, opened)+    }++    @Test fun mediaRowShowsSectionAndItems() {+        val items = listOf(+            MediaItem(tmdbId = 1, mediaType = MediaType.MOVIE, title = "One"),+            MediaItem(tmdbId = 2, mediaType = MediaType.TV, title = "Two"))+        var opened: MediaItem? = null+        composeRule.setContent {+            DynamicTheme { MediaRow(title = "Trending", items = items, onOpen = { opened = it }) }+        }+        composeRule.onNodeWithText("Trending").assertIsDisplayed()+        composeRule.onNodeWithText("One").assertIsDisplayed()+        composeRule.onNodeWithText("Two").performClick()+        assertEquals(items[1], opened)+    }++    @Test fun episodeCardShowsNumberAndPlays() {+        var plays = 0+        composeRule.setContent {+            DynamicTheme {+                EpisodeCard(+                    episode = Episode(1, 3, "Third", overview = "It happens"),+                    onPlay = { plays++ })+            }+        }+        composeRule.onNodeWithText("E3 · Third").assertIsDisplayed()+        composeRule.onNodeWithText("It happens").assertIsDisplayed()+        composeRule.onNodeWithText("E3 · Third").performClick()+        assertEquals(1, plays)+    }++    @Test fun addonCardShowsHealthAndActions() {+        val entity = AddonEntity(+            dbId = 4, manifestUrl = "https://a.example/manifest.json",+            baseUrl = "https://a.example", addonId = "a", name = "Alpha",+            version = "1.2", enabled = true, lastError = "unreachable")+        var toggles = 0+        var details = 0+        composeRule.setContent {+            DynamicTheme {+                AddonCard(+                    row = AddonRow(entity = entity, isDefault = true),+                    onToggle = { toggles++ },+                    onSetDefault = {}, onClearDefault = {},+                    onMoveUp = {}, onMoveDown = {}, onRemove = {},+                    onRefresh = {}, onOpenDetail = { details++ })+            }+        }+        composeRule.onNodeWithText("Alpha").assertIsDisplayed()+        composeRule.onNodeWithText("v1.2").assertIsDisplayed()+        composeRule.onNodeWithText("unreachable").assertIsDisplayed()+        composeRule.onNodeWithText("Details").performClick()+        assertEquals(1, details)+        assertEquals(0, toggles)+    }+}
uniflix/src/test/java/com/vayunmathur/uniflix/ui/UniflixScreensComposeTest.kt
diff --git a/uniflix/src/test/java/com/vayunmathur/uniflix/ui/UniflixScreensComposeTest.kt b/uniflix/src/test/java/com/vayunmathur/uniflix/ui/UniflixScreensComposeTest.ktnew file mode 100644index 0000000000..c174fda663--- /dev/null+++ b/uniflix/src/test/java/com/vayunmathur/uniflix/ui/UniflixScreensComposeTest.kt@@ -0,0 +1,184 @@+package com.vayunmathur.uniflix.ui++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.compose.ui.test.performTextInput+import com.vayunmathur.library.ui.DynamicTheme+import com.vayunmathur.uniflix.data.AddonEntity+import com.vayunmathur.uniflix.domain.MediaItem+import com.vayunmathur.uniflix.domain.MediaType+import com.vayunmathur.uniflix.domain.SeasonSummary+import com.vayunmathur.uniflix.platform.AddonRow+import com.vayunmathur.uniflix.ui.dialogs.AddAddonDialog+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++/** Compose-under-Robolectric tests for stateless Uniflix screens. */+@RunWith(RobolectricTestRunner::class)+class UniflixScreensComposeTest {++    @get:Rule+    val composeRule = createComposeRule()++    private fun item(id: Int, title: String) =+        MediaItem(tmdbId = id, mediaType = MediaType.MOVIE, title = title, year = 2020)++    private fun row(id: Long, name: String, priority: Int = 0, isDefault: Boolean = false) = AddonRow(+        entity = AddonEntity(+            dbId = id, manifestUrl = "https://$name.example/manifest.json",+            baseUrl = "https://$name.example", addonId = name, name = name, priority = priority),+        isDefault = isDefault)++    @Test fun addonsContentEmptyStateActions() {+        var adds = 0+        var imports = 0+        composeRule.setContent {+            DynamicTheme {+                AddonsContent(+                    rows = emptyList(), adding = false, refreshing = false,+                    onBack = {}, onAddClick = { adds++ }, onImportJsClick = { imports++ },+                    onToggle = {}, onSetDefault = {}, onClearDefault = {},+                    onMoveUp = {}, onMoveDown = {}, onRemove = {},+                    onRefresh = {}, onRefreshAll = {}, onOpenDetail = {})+            }+        }+        composeRule.onNodeWithText("Stream addons").assertIsDisplayed()+        composeRule.onNodeWithText("No stream addons yet. Add one to enable playback.").assertIsDisplayed()+        composeRule.onNodeWithText("Add addon").performClick()+        composeRule.onNodeWithText("Import .js").performClick()+        assertEquals(1, adds)+        assertEquals(1, imports)+    }++    @Test fun addonsContentListsRowsAndOpensDetail() {+        var opened: Long? = null+        var toggled: String? = null+        composeRule.setContent {+            DynamicTheme {+                AddonsContent(+                    rows = listOf(row(3, "Alpha", isDefault = true), row(4, "Beta")),+                    adding = false, refreshing = true,+                    onBack = {}, onAddClick = {}, onImportJsClick = {},+                    onToggle = { toggled = it.entity.name }, onSetDefault = {}, onClearDefault = {},+                    onMoveUp = {}, onMoveDown = {}, onRemove = {},+                    onRefresh = {}, onRefreshAll = {}, onOpenDetail = { opened = it })+            }+        }+        composeRule.onNodeWithText("Alpha").assertIsDisplayed()+        composeRule.onNodeWithText("Beta").assertIsDisplayed()+        composeRule.onAllNodesWithText("Details")[0].performClick()+        // First row's Details opens its detail page.+        assertTrue(opened == 3L || opened == 4L, "opened=$opened")+        assertEquals(null, toggled)+    }++    @Test fun mediaGridLoadingShowsTitle() {+        composeRule.setContent {+            DynamicTheme {+                MediaGridScreen(+                    title = "Movies", loading = true, items = emptyList(),+                    onBack = {}, onOpenDetail = {})+            }+        }+        composeRule.onNodeWithText("Movies").assertIsDisplayed()+    }++    @Test fun mediaGridEmptyShowsPlaceholder() {+        composeRule.setContent {+            DynamicTheme {+                MediaGridScreen(+                    title = "Movies", loading = false, items = emptyList(),+                    onBack = {}, onOpenDetail = {})+            }+        }+        composeRule.onNodeWithText("Nothing here yet.").assertIsDisplayed()+    }++    @Test fun mediaGridItemsOpenDetail() {+        var opened: MediaItem? = null+        val items = listOf(item(1, "Grid One"), item(2, "Grid Two"))+        composeRule.setContent {+            DynamicTheme {+                MediaGridScreen(+                    title = "Movies", loading = false, items = items,+                    onBack = {}, onOpenDetail = { opened = it })+            }+        }+        composeRule.onNodeWithText("Grid One").assertIsDisplayed()+        composeRule.onNodeWithText("Grid Two").performClick()+        assertEquals(items[1], opened)+    }++    @Test fun seasonDropdownFiltersSpecialsAndSelects() {+        var selected: Int? = null+        val seasons = listOf(+            SeasonSummary(0, "Specials", 4),+            SeasonSummary(1, "Season 1", 8),+            SeasonSummary(2, "Season 2", 10))+        composeRule.setContent {+            DynamicTheme {+                SeasonDropdown(seasons = seasons, selectedSeason = 1, onSelect = { selected = it })+            }+        }+        composeRule.onNodeWithText("Season 1 · 8 episodes").assertIsDisplayed()+        composeRule.onNodeWithText("Season 1 · 8 episodes").performClick()+        composeRule.onNodeWithText("Season 2 · 10 episodes").assertIsDisplayed()+        composeRule.onNodeWithText("Season 2 · 10 episodes").performClick()+        assertEquals(2, selected)+    }++    @Test fun seasonDropdownWithoutSeasonsShowsFallback() {+        composeRule.setContent {+            DynamicTheme {+                SeasonDropdown(seasons = emptyList(), selectedSeason = 0, onSelect = {})+            }+        }+        composeRule.onNodeWithText("Season").assertIsDisplayed()+    }++    @Test fun addAddonDialogConfirmsTypedUrl() {+        var confirmed: String? = null+        var dismissed = 0+        var imports = 0+        composeRule.setContent {+            DynamicTheme {+                AddAddonDialog(+                    adding = false,+                    onDismiss = { dismissed++ },+                    onConfirm = { confirmed = it },+                    onImportJs = { imports++ })+            }+        }+        composeRule.onNodeWithText("Add stream addon").assertIsDisplayed()+        composeRule.onNodeWithText("Addon URL").performTextInput("https://addons.example/manifest.json")+        composeRule.onNodeWithText("Import .js plugin instead").performClick()+        assertEquals(1, imports)+        composeRule.onNodeWithText("Add").performClick()+        assertEquals("https://addons.example/manifest.json", confirmed)+        assertEquals(0, dismissed)+    }++    @Test fun addAddonDialogCancelDismisses() {+        var dismissed = 0+        composeRule.setContent {+            DynamicTheme {+                AddAddonDialog(+                    adding = true,+                    onDismiss = { dismissed++ },+                    onConfirm = {},+                    onImportJs = {})+            }+        }+        // While adding, Cancel is disabled, so use the dismiss path text check only.+        composeRule.onNodeWithText("Add stream addon").assertIsDisplayed()+        composeRule.onNodeWithText("Cancel").assertIsDisplayed()+        assertEquals(0, dismissed)+    }+}
uniflix/src/test/java/com/vayunmathur/uniflix/ui/WatchControlsComposeTest.kt
diff --git a/uniflix/src/test/java/com/vayunmathur/uniflix/ui/WatchControlsComposeTest.kt b/uniflix/src/test/java/com/vayunmathur/uniflix/ui/WatchControlsComposeTest.ktnew file mode 100644index 0000000000..68c56e953c--- /dev/null+++ b/uniflix/src/test/java/com/vayunmathur/uniflix/ui/WatchControlsComposeTest.kt@@ -0,0 +1,108 @@+package com.vayunmathur.uniflix.ui++import androidx.compose.runtime.mutableLongStateOf+import androidx.compose.runtime.mutableStateOf+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.ui.DynamicTheme+import com.vayunmathur.uniflix.domain.SubtitleTrack+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner++/** Watch overlay bars + player-state holder with no real player attached. */+@RunWith(RobolectricTestRunner::class)+class WatchControlsComposeTest {++    @get:Rule+    val composeRule = createComposeRule()++    private fun playerState(): WatchPlayerState = WatchPlayerState(+        player = null,+        positionState = mutableLongStateOf(65_000L),+        bufferedState = mutableLongStateOf(80_000L),+        durationState = mutableLongStateOf(3_723_000L),+        playingState = mutableStateOf(false),+        bufferingState = mutableStateOf(true),+        draggingState = mutableStateOf(false),+        cuesState = mutableStateOf(emptyList()),+        heightsState = mutableStateOf(listOf(1080, 720)),+        errorState = mutableStateOf<String?>(null),+    )++    @Test fun playerStateWithoutPlayerIsInert() {+        val state = playerState()+        state.togglePlay()+        state.seekTo(-5_000L)+        state.skipBy(10_000L)+        assertEquals(65_000L, state.positionMs)+        assertEquals(3_723_000L, state.durationMs)+        assertEquals(true, state.isBuffering)+        assertEquals(listOf(1080, 720), state.videoHeights)+        assertNull(state.playerError)+        state.playerError = "boom"+        assertEquals("boom", state.playerError)+    }++    @Test fun subtitleMimeVariants() {+        assertEquals("application/x-subrip", subtitleMime("https://x/en.srt"))+        assertEquals("application/ttml+xml", subtitleMime("https://x/en.ttml"))+        assertEquals("application/ttml+xml", subtitleMime("https://x/en.dfxp?tok=1"))+        assertEquals("text/vtt", subtitleMime("https://x/en.vtt"))+    }++    @Test fun topBarShowsChipsAndSelectsHeight() {+        var height: Int? = 720+        var menuOpen: Boolean? = null+        var backed = 0+        val subs = listOf(SubtitleTrack("en", "English", "https://x/en.vtt"))+        composeRule.setContent {+            DynamicTheme {+                WatchTopBar(+                    title = "A Title",+                    serverLabel = "Alpha",+                    servers = listOf("Alpha", "Beta"),+                    onSelectServer = {},+                    videoHeights = listOf(2160, 1080),+                    selectedHeight = height,+                    onSelectHeight = { height = it },+                    subtitles = subs,+                    selectedSubtitle = null,+                    onSelectSubtitle = {},+                    onBack = { backed++ },+                    onAnyMenuOpen = { menuOpen = it })+            }+        }+        composeRule.onNodeWithText("A Title").assertIsDisplayed()+        composeRule.onNodeWithText("720p").assertIsDisplayed()+        composeRule.onNodeWithText("CC").assertIsDisplayed()+        composeRule.onNodeWithText("Alpha").assertIsDisplayed()+        composeRule.onNodeWithText("720p").performClick()+        composeRule.onNodeWithText("4K").assertIsDisplayed()+        composeRule.onNodeWithText("4K").performClick()+        assertEquals(2160, height)+        assertEquals(0, backed)+    }++    @Test fun bottomBarShowsTimes() {+        val state = playerState()+        var fullscreen: Boolean? = null+        composeRule.setContent {+            DynamicTheme {+                WatchBottomBar(+                    playerState = state,+                    isFullscreen = false,+                    onFullscreenChange = { fullscreen = it })+            }+        }+        composeRule.onNodeWithText("1:05").assertIsDisplayed()+        composeRule.onNodeWithText("1:02:03").assertIsDisplayed()+        assertEquals(null, fullscreen)+        assertEquals(80_000L, state.bufferedMs)+    }+}
uniflix/src/test/java/com/vayunmathur/uniflix/ui/WatchPlayerStateMockTest.kt
diff --git a/uniflix/src/test/java/com/vayunmathur/uniflix/ui/WatchPlayerStateMockTest.kt b/uniflix/src/test/java/com/vayunmathur/uniflix/ui/WatchPlayerStateMockTest.ktnew file mode 100644index 0000000000..7ab6aaea8b--- /dev/null+++ b/uniflix/src/test/java/com/vayunmathur/uniflix/ui/WatchPlayerStateMockTest.kt@@ -0,0 +1,84 @@+package com.vayunmathur.uniflix.ui++import androidx.compose.runtime.mutableLongStateOf+import androidx.compose.runtime.mutableStateOf+import androidx.media3.common.text.Cue+import androidx.media3.exoplayer.ExoPlayer+import kotlin.test.Test+import kotlin.test.assertEquals+import org.mockito.Mockito.mock+import org.mockito.Mockito.never+import org.mockito.Mockito.verify+import org.mockito.Mockito.`when`++/** WatchPlayerState transport logic against a mocked ExoPlayer. */+class WatchPlayerStateMockTest {++    private fun state(player: ExoPlayer?): WatchPlayerState = WatchPlayerState(+        player = player,+        positionState = mutableLongStateOf(1_000L),+        bufferedState = mutableLongStateOf(2_000L),+        durationState = mutableLongStateOf(60_000L),+        playingState = mutableStateOf(false),+        bufferingState = mutableStateOf(false),+        draggingState = mutableStateOf(false),+        cuesState = mutableStateOf<List<Cue>>(emptyList()),+        heightsState = mutableStateOf(listOf(1080)),+        errorState = mutableStateOf<String?>(null),+    )++    @Test fun togglePlaysWhenPausedAndPausesWhenPlaying() {+        val player = mock(ExoPlayer::class.java)+        `when`(player.isPlaying).thenReturn(false)+        state(player).togglePlay()+        verify(player).play()+        verify(player, never()).pause()++        val playing = mock(ExoPlayer::class.java)+        `when`(playing.isPlaying).thenReturn(true)+        state(playing).togglePlay()+        verify(playing).pause()+        verify(playing, never()).play()+    }++    @Test fun seekClampsNegativeToZero() {+        val player = mock(ExoPlayer::class.java)+        val s = state(player)+        s.seekTo(-500L)+        verify(player).seekTo(0L)+        s.seekTo(12_345L)+        verify(player).seekTo(12_345L)+    }++    @Test fun skipClampsToDurationAndZero() {+        val player = mock(ExoPlayer::class.java)+        `when`(player.duration).thenReturn(60_000L)+        `when`(player.currentPosition).thenReturn(55_000L)+        state(player).skipBy(10_000L)+        verify(player).seekTo(60_000L)++        val atStart = mock(ExoPlayer::class.java)+        `when`(atStart.duration).thenReturn(60_000L)+        `when`(atStart.currentPosition).thenReturn(5_000L)+        state(atStart).skipBy(-10_000L)+        verify(atStart).seekTo(0L)+    }++    @Test fun skipWithUnknownDurationDoesNotClampEnd() {+        val player = mock(ExoPlayer::class.java)+        `when`(player.duration).thenReturn(-1L)+        `when`(player.currentPosition).thenReturn(5_000L)+        state(player).skipBy(10_000L)+        verify(player).seekTo(15_000L)+    }++    @Test fun stateDelegatesReflectSnapshots() {+        val s = state(null)+        assertEquals(1_000L, s.positionMs)+        s.positionMs = 42L+        assertEquals(42L, s.positionMs)+        assertEquals(listOf(1080), s.videoHeights)+        s.isDragging = true+        assertEquals(true, s.isDragging)+    }+}
uniflix/src/test/java/com/vayunmathur/uniflix/ui/WatchScreenComposeTest.kt
diff --git a/uniflix/src/test/java/com/vayunmathur/uniflix/ui/WatchScreenComposeTest.kt b/uniflix/src/test/java/com/vayunmathur/uniflix/ui/WatchScreenComposeTest.ktnew file mode 100644index 0000000000..82d963b398--- /dev/null+++ b/uniflix/src/test/java/com/vayunmathur/uniflix/ui/WatchScreenComposeTest.kt@@ -0,0 +1,90 @@+package com.vayunmathur.uniflix.ui++import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import com.vayunmathur.library.ui.DynamicTheme+import com.vayunmathur.uniflix.domain.MediaDetail+import com.vayunmathur.uniflix.domain.MediaType+import com.vayunmathur.uniflix.platform.DetailUiState+import kotlin.test.Test+import kotlin.test.assertEquals+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner++/** WatchScreen state panels (no playable source, so no real player is built). */+@RunWith(RobolectricTestRunner::class)+class WatchScreenComposeTest {++    @get:Rule+    val composeRule = createComposeRule()++    private fun watch(state: DetailUiState, onBack: () -> Unit = {}, onRetry: () -> Unit = {}, onOpenAddons: () -> Unit = {}) {+        composeRule.setContent {+            DynamicTheme {+                WatchScreen(+                    state = state,+                    mediaType = MediaType.MOVIE,+                    season = 0, episode = 0,+                    onBack = onBack,+                    onRetry = onRetry,+                    onOpenAddons = onOpenAddons,+                    onSelectServer = {},+                    onSavePosition = { _, _ -> })+            }+        }+    }++    @Test fun loadingStateShowsWatchChrome() {+        watch(DetailUiState(resolving = true))+        composeRule.onNodeWithText("Watch").assertIsDisplayed()+    }++    @Test fun noAddonsPanelLinksToManager() {+        var addons = 0+        var backs = 0+        watch(+            DetailUiState(providerMissing = true),+            onBack = { backs++ }, onOpenAddons = { addons++ })+        composeRule.onNodeWithText(+            "No stream addons installed. Add one to watch this title.").assertIsDisplayed()+        composeRule.onNodeWithText("Open addon manager").performClick()+        assertEquals(1, addons)+        composeRule.onNodeWithText("Back").performClick()+        assertEquals(1, backs)+    }++    @Test fun loadFailedPanelOffersRetry() {+        var retries = 0+        watch(+            DetailUiState(+                detail = MediaDetail(42, MediaType.MOVIE, "The Film"),+                resolveError = "Addon exploded"),+            onRetry = { retries++ })+        composeRule.onNodeWithText("Addon exploded").assertIsDisplayed()+        composeRule.onNodeWithText("Retry").performClick()+        assertEquals(1, retries)+    }++    @Test fun sourceStateBuildsPlayerChrome() {+        watch(+            DetailUiState(+                detail = MediaDetail(42, MediaType.MOVIE, "The Film"),+                source = com.vayunmathur.uniflix.domain.VideoSource(+                    streamUrl = "https://addons.invalid/v.m3u8",+                    title = "Addon Stream",+                    subtitles = listOf(+                        com.vayunmathur.uniflix.domain.SubtitleTrack(+                            "en", "English", "https://addons.invalid/en.vtt")))))+        // Player is built (media3 under Robolectric) and the top chrome shows+        // the detail title; playback itself fails offline into playerError.+        composeRule.onNodeWithText("The Film").assertIsDisplayed()+    }++    @Test fun loadFailedWithoutErrorUsesFallbackMessage() {+        watch(DetailUiState(detail = MediaDetail(42, MediaType.MOVIE, "The Film")))+        composeRule.onNodeWithText("No stream available for this title.").assertIsDisplayed()+    }+}
uniflix/src/test/java/com/vayunmathur/uniflix/ui/tv/TvCardsAndRoutesTest.kt
diff --git a/uniflix/src/test/java/com/vayunmathur/uniflix/ui/tv/TvCardsAndRoutesTest.kt b/uniflix/src/test/java/com/vayunmathur/uniflix/ui/tv/TvCardsAndRoutesTest.ktnew file mode 100644index 0000000000..6bfde3e129--- /dev/null+++ b/uniflix/src/test/java/com/vayunmathur/uniflix/ui/tv/TvCardsAndRoutesTest.kt@@ -0,0 +1,190 @@+package com.vayunmathur.uniflix.ui.tv++import androidx.compose.ui.focus.FocusRequester+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.hasClickAction+import androidx.compose.ui.test.performSemanticsAction+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.ui.DynamicTheme+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.uniflix.data.ContinueWatchingEntry+import com.vayunmathur.uniflix.data.WatchlistEntry+import com.vayunmathur.uniflix.domain.Episode+import com.vayunmathur.uniflix.domain.MediaDetail+import com.vayunmathur.uniflix.domain.MediaItem+import com.vayunmathur.uniflix.domain.MediaType+import com.vayunmathur.uniflix.domain.StreamProvider+import com.vayunmathur.uniflix.domain.VideoSource+import com.vayunmathur.uniflix.platform.DetailUiState+import com.vayunmathur.uniflix.platform.DetailViewModel+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner++/** TV routes, media-card mapping helpers, and TV card composables. */+@RunWith(RobolectricTestRunner::class)+class TvCardsAndRoutesTest {++    @get:Rule+    val composeRule = createComposeRule()++    @Test fun routesAndTabConstants() {+        assertEquals(TV_TAB_HOME, TvRoute.Main().initialTab)+        assertEquals(0, TvRoute.Watch("tv", 7).season)+        assertEquals(TvRoute.Detail("movie", 3), TvRoute.Detail("movie", 3))+        assertEquals(TvRoute.Grid(TV_GRID_CONTINUE), TvRoute.Grid("continue"))+        assertEquals(TvRoute.AddonDetail(4L), TvRoute.AddonDetail(4L))+        assertEquals(+            listOf(0, 1, 2, 3, 4, 5),+            listOf(TV_TAB_SEARCH, TV_TAB_HOME, TV_TAB_MOVIES, TV_TAB_SHOWS, TV_TAB_MY_LIST, TV_TAB_ADDONS))+        assertEquals(+            listOf("continue", "trending-movies", "trending-tv", "top-movies", "top-tv"),+            listOf(+                TV_GRID_CONTINUE, TV_GRID_TRENDING_MOVIES, TV_GRID_TRENDING_TV,+                TV_GRID_TOP_MOVIES, TV_GRID_TOP_TV))+    }++    @Test fun mediaTypeOfParsesRawStrings() {+        assertEquals(MediaType.TV, mediaTypeOf("tv"))+        assertEquals(MediaType.MOVIE, mediaTypeOf("movie"))+        assertEquals(MediaType.MOVIE, mediaTypeOf(""))+        assertEquals(MediaType.MOVIE, mediaTypeOf("TV"))+    }++    @Test fun entryMappingHelpers() {+        val cont = ContinueWatchingEntry(+            key = "tv:7:1:2", tmdbId = 7, mediaType = "tv", title = "Show",+            posterPath = "/p.jpg", season = 1, episode = 2, positionMs = 30_000L, durationMs = 60_000L)+        val asItem = cont.toMediaItem()+        assertEquals(MediaType.TV, asItem.mediaType)+        assertEquals("Show", asItem.title)+        assertEquals("/p.jpg", asItem.posterPath)+        val watch = WatchlistEntry(+            key = "movie:8:0:0", tmdbId = 8, mediaType = "movie", title = "Film",+            posterPath = null, addedAt = 1L)+        assertEquals(MediaType.MOVIE, watch.toMediaItem().mediaType)+        assertEquals("MOVIE:8", mediaKey(MediaItem(8, MediaType.MOVIE, "Film")))+        assertEquals("TV:7", mediaKey(asItem))+    }++    @Test fun resumeProgressClampsAndRejectsZeroDuration() {+        assertEquals(0.5f, resumeProgress(30_000L, 60_000L))+        assertEquals(1f, resumeProgress(90_000L, 60_000L))+        assertEquals(0f, resumeProgress(-5L, 60_000L))+        assertNull(resumeProgress(10L, 0L))+        assertNull(resumeProgress(10L, -1L))+    }++    @Test fun posterCardRendersAndOpens() {+        var opened = 0+        composeRule.setContent {+            DynamicTheme {+                MediaPosterCard(+                    item = MediaItem(1, MediaType.MOVIE, "Poster Film", year = 2023),+                    onOpen = { opened++ })+            }+        }+        composeRule.onNodeWithText("Poster Film").assertExists()+        composeRule.onNodeWithText("2023").assertExists()+        composeRule.onNode(hasClickAction()).performSemanticsAction(androidx.compose.ui.semantics.SemanticsActions.OnClick)+        assertEquals(1, opened)+    }++    @Test fun continueCardRendersAndResumes() {+        var resumed = 0+        composeRule.setContent {+            DynamicTheme {+                ContinueEntryCard(+                    entry = ContinueWatchingEntry(+                        key = "tv:7:1:2", tmdbId = 7, mediaType = "tv", title = "Resume Show",+                        posterPath = null, season = 1, episode = 2,+                        positionMs = 10_000L, durationMs = 20_000L),+                    onResume = { resumed++ })+            }+        }+        composeRule.onNodeWithText("Resume Show").assertExists()+        composeRule.onNode(hasClickAction()).performSemanticsAction(androidx.compose.ui.semantics.SemanticsActions.OnClick)+        assertEquals(1, resumed)+    }++    @Test fun episodeCardRendersAndPlays() {+        var plays = 0+        composeRule.setContent {+            DynamicTheme {+                TvEpisodeCard(+                    episode = Episode(1, 3, "Third", overview = "Things happen"),+                    progress = 0.25f,+                    onPlay = { plays++ })+            }+        }+        composeRule.onNodeWithText("E3 · Third").assertExists()+        composeRule.onNodeWithText("Things happen").assertExists()+        composeRule.onNode(hasClickAction()).performSemanticsAction(androidx.compose.ui.semantics.SemanticsActions.OnClick)+        assertEquals(1, plays)+    }++    private class FakeProvider : StreamProvider() {+        override val name: String = "Fake"+        override val supports4k: Boolean = false+        override suspend fun resolve(+            tmdbId: Int, mediaType: MediaType, season: Int, episode: Int, server: String?,+        ): VideoSource = VideoSource("https://x/v", "S")+    }++    @Test fun detailPlayButtonNavigatesToWatch() {+        val app = ApplicationProvider.getApplicationContext<android.app.Application>()+        val vm = DetailViewModel(app)+        vm.streamProviders = listOf(FakeProvider())+        val stack = NavBackStack<TvRoute>(arrayOf(TvRoute.Main()))+        val detail = MediaDetail(tmdbId = 42, mediaType = MediaType.MOVIE, title = "Film")+        composeRule.setContent {+            DynamicTheme {+                TvDetailPlayButton(+                    state = DetailUiState(),+                    detail = detail,+                    type = MediaType.MOVIE,+                    tmdbId = 42,+                    mediaType = "movie",+                    backStack = stack,+                    vm = vm,+                    playFocus = FocusRequester())+            }+        }+        composeRule.onNodeWithText("Play").assertExists()+        composeRule.onNode(hasClickAction()).performSemanticsAction(androidx.compose.ui.semantics.SemanticsActions.OnClick)+        assertEquals(TvRoute.Watch("movie", 42), stack.backStack.last())+        assertEquals(2, stack.backStack.size)+    }++    @Test fun detailPlayButtonForShowUsesFirstEpisode() {+        val app = ApplicationProvider.getApplicationContext<android.app.Application>()+        val vm = DetailViewModel(app)+        vm.streamProviders = listOf(FakeProvider())+        val stack = NavBackStack<TvRoute>(arrayOf(TvRoute.Main()))+        val detail = MediaDetail(tmdbId = 7, mediaType = MediaType.TV, title = "Show")+        composeRule.setContent {+            DynamicTheme {+                TvDetailPlayButton(+                    state = DetailUiState(+                        episodes = listOf(Episode(2, 4, "Ep")), selectedSeason = 2),+                    detail = detail,+                    type = MediaType.TV,+                    tmdbId = 7,+                    mediaType = "tv",+                    backStack = stack,+                    vm = vm,+                    playFocus = FocusRequester())+            }+        }+        composeRule.onNode(hasClickAction()).performSemanticsAction(androidx.compose.ui.semantics.SemanticsActions.OnClick)+        assertEquals(TvRoute.Watch("tv", 7, season = 2, episode = 4), stack.backStack.last())+        assertTrue(stack.backStack.size == 2)+    }+}
uniflix/src/test/java/com/vayunmathur/uniflix/ui/tv/TvPagesComposeTest.kt
diff --git a/uniflix/src/test/java/com/vayunmathur/uniflix/ui/tv/TvPagesComposeTest.kt b/uniflix/src/test/java/com/vayunmathur/uniflix/ui/tv/TvPagesComposeTest.ktnew file mode 100644index 0000000000..9d03148dbc--- /dev/null+++ b/uniflix/src/test/java/com/vayunmathur/uniflix/ui/tv/TvPagesComposeTest.kt@@ -0,0 +1,58 @@+package com.vayunmathur.uniflix.ui.tv++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.performSemanticsAction+import com.vayunmathur.library.ui.DynamicTheme+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.uniflix.domain.MediaType+import kotlin.test.Test+import kotlin.test.assertEquals+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner++/** TV tab/detail pages in their offline (empty/failed) states. */+@RunWith(RobolectricTestRunner::class)+class TvPagesComposeTest {++    @get:Rule+    val composeRule = createComposeRule()++    @Test fun browseTabRendersOffline() {+        composeRule.setContent {+            DynamicTheme { TvBrowseTab(mediaType = MediaType.MOVIE, onOpenDetail = {}) }+        }+        // Catalog is unreachable, so the tab settles into its empty/loading shell+        // without crashing; reaching idle is the assertion.+        composeRule.waitForIdle()+    }++    @Test fun browseSeriesTabRendersOffline() {+        composeRule.setContent {+            DynamicTheme { TvBrowseTab(mediaType = MediaType.TV, onOpenDetail = {}) }+        }+        composeRule.waitForIdle()+    }++    @Test fun searchTabRendersOffline() {+        composeRule.setContent {+            DynamicTheme { TvSearchTab(onOpenDetail = {}) }+        }+        composeRule.waitForIdle()+    }++    @Test fun detailPageShowsFailureAndBackPops() {+        val stack = NavBackStack<TvRoute>(arrayOf(TvRoute.Main(), TvRoute.Detail("movie", 42)))+        composeRule.setContent {+            DynamicTheme { TvDetailPage(backStack = stack, mediaType = "movie", tmdbId = 42) }+        }+        composeRule.onNodeWithText("Detail failed to load.").assertIsDisplayed()+        composeRule.onNode(hasClickAction())+            .performSemanticsAction(androidx.compose.ui.semantics.SemanticsActions.OnClick)+        assertEquals(TvRoute.Main(), stack.backStack.last())+        assertEquals(1, stack.backStack.size)+    }+}
uniflix/src/test/java/com/vayunmathur/uniflix/ui/tv/TvPickersAndPrefsTest.kt
diff --git a/uniflix/src/test/java/com/vayunmathur/uniflix/ui/tv/TvPickersAndPrefsTest.kt b/uniflix/src/test/java/com/vayunmathur/uniflix/ui/tv/TvPickersAndPrefsTest.ktnew file mode 100644index 0000000000..f23f5e481d--- /dev/null+++ b/uniflix/src/test/java/com/vayunmathur/uniflix/ui/tv/TvPickersAndPrefsTest.kt@@ -0,0 +1,140 @@+package com.vayunmathur.uniflix.ui.tv++import android.net.Uri+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.performSemanticsAction+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.library.ui.DynamicTheme+import com.vayunmathur.uniflix.data.AddonEntity+import com.vayunmathur.uniflix.data.AddonPrefs+import com.vayunmathur.uniflix.data.RemoteImageFetchers+import com.vayunmathur.uniflix.domain.SubtitleTrack+import com.vayunmathur.uniflix.platform.AddonRow+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.test.runTest+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner++/** TV picker dialogs, TV addon card, addon prefs, and image-fetcher routing. */+@RunWith(RobolectricTestRunner::class)+class TvPickersAndPrefsTest {++    @get:Rule+    val composeRule = createComposeRule()++    private val context get() = ApplicationProvider.getApplicationContext<android.content.Context>()++    @Test fun resolutionLabels() {+        assertEquals("4K", resolutionLabel(2160))+        assertEquals("1080p", resolutionLabel(1080))+        assertEquals("720p", resolutionLabel(720))+        assertEquals("480p", resolutionLabel(480))+        assertEquals("360p", resolutionLabel(360))+        assertEquals("4K", resolutionLabel(4000))+    }++    @Test fun serverPickerSelectsRow() {+        var selected: String? = null+        composeRule.setContent {+            DynamicTheme {+                TvServerPickerDialog(+                    servers = listOf("Alpha", "Beta"),+                    selectedTitle = "Alpha",+                    onDismiss = {},+                    onSelect = { selected = it })+            }+        }+        composeRule.onNodeWithText("Alpha").assertIsDisplayed()+        composeRule.onNodeWithText("Beta").assertIsDisplayed()+        composeRule.onNode(+            androidx.compose.ui.test.hasText("Beta") and hasClickAction())+            .performSemanticsAction(androidx.compose.ui.semantics.SemanticsActions.OnClick)+        assertEquals("Beta", selected)+    }++    @Test fun subtitlePickerOffersOffAndTracks() {+        var selected: SubtitleTrack? = SubtitleTrack("en", "English", "https://x/en.vtt")+        var touched = false+        composeRule.setContent {+            DynamicTheme {+                TvSubtitlePickerDialog(+                    subtitles = listOf(SubtitleTrack("en", "English", "https://x/en.vtt")),+                    selected = selected,+                    onDismiss = {},+                    onSelect = { selected = it; touched = true })+            }+        }+        composeRule.onNodeWithText("English").assertIsDisplayed()+        composeRule.onNode(+            androidx.compose.ui.test.hasText("Off") and hasClickAction())+            .performSemanticsAction(androidx.compose.ui.semantics.SemanticsActions.OnClick)+        assertTrue(touched)+        assertNull(selected)+    }++    @Test fun qualityPickerSelectsHeight() {+        var selected: Int? = null+        var touched = false+        composeRule.setContent {+            DynamicTheme {+                TvQualityPickerDialog(+                    heights = listOf(1080, 720),+                    selectedHeight = null,+                    onDismiss = {},+                    onSelect = { selected = it; touched = true })+            }+        }+        composeRule.onNodeWithText("1080p").assertIsDisplayed()+        composeRule.onNode(+            androidx.compose.ui.test.hasText("720p") and hasClickAction())+            .performSemanticsAction(androidx.compose.ui.semantics.SemanticsActions.OnClick)+        assertTrue(touched)+        assertEquals(720, selected)+    }++    @Test fun tvAddonCardShowsBadgesAndError() {+        var opened = 0+        val entity = AddonEntity(+            dbId = 2, manifestUrl = "https://a.example/manifest.json",+            baseUrl = "https://a.example", addonId = "a", name = "Alpha",+            version = "2.0", enabled = false, lastError = "broken", kind = "js")+        composeRule.setContent {+            DynamicTheme {+                TvAddonCard(row = AddonRow(entity, isDefault = true), onOpenDetail = { opened++ })+            }+        }+        composeRule.onNodeWithText("Alpha").assertIsDisplayed()+        composeRule.onNodeWithText("broken").assertIsDisplayed()+        composeRule.onNode(hasClickAction())+            .performSemanticsAction(androidx.compose.ui.semantics.SemanticsActions.OnClick)+        assertEquals(1, opened)+    }++    @Test fun addonPrefsDefaultRoundTrip() = runTest {+        val prefs = AddonPrefs(context)+        prefs.setDefaultAddonDbId(null)+        assertNull(prefs.defaultAddonDbId.first())+        prefs.setDefaultAddonDbId(77L)+        assertEquals(77L, prefs.defaultAddonDbId.first())+        prefs.setDefaultAddonDbId(null)+        assertNull(prefs.defaultAddonDbId.first())+    }++    @Test fun remoteFetcherRejectsNonHttpData() = runTest {+        assertNull(RemoteImageFetchers.network(null, context))+        assertNull(RemoteImageFetchers.network(42, context))+        assertNull(RemoteImageFetchers.network("file:///tmp/x.png", context))+        assertNull(RemoteImageFetchers.network(Uri.parse("content://media/1"), context))+        assertNull(RemoteImageFetchers.network(Uri.parse("file:///tmp/x.png"), context))+        // An unreachable https URL fails (throw or IOException), never returns bytes.+        assertTrue(runCatching { RemoteImageFetchers.network("https://addons.invalid/x.png", context) }.isFailure)+    }+}
uniflix/src/test/java/com/vayunmathur/uniflix/ui/tv/TvWatchOverlayTest.kt
diff --git a/uniflix/src/test/java/com/vayunmathur/uniflix/ui/tv/TvWatchOverlayTest.kt b/uniflix/src/test/java/com/vayunmathur/uniflix/ui/tv/TvWatchOverlayTest.ktnew file mode 100644index 0000000000..c19927a2ea--- /dev/null+++ b/uniflix/src/test/java/com/vayunmathur/uniflix/ui/tv/TvWatchOverlayTest.kt@@ -0,0 +1,123 @@+package com.vayunmathur.uniflix.ui.tv++import androidx.compose.runtime.mutableLongStateOf+import androidx.compose.runtime.mutableStateOf+import androidx.compose.ui.focus.FocusRequester+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.hasClickAction+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.compose.ui.test.performSemanticsAction+import androidx.compose.ui.test.performTextInput+import com.vayunmathur.library.ui.DynamicTheme+import com.vayunmathur.uniflix.ui.WatchPlayerState+import kotlin.test.Test+import kotlin.test.assertEquals+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner++/** TV watch overlay and TV add-addon dialog with a player-less state holder. */+@RunWith(RobolectricTestRunner::class)+class TvWatchOverlayTest {++    @get:Rule+    val composeRule = createComposeRule()++    private fun playerState(): WatchPlayerState = WatchPlayerState(+        player = null,+        positionState = mutableLongStateOf(65_000L),+        bufferedState = mutableLongStateOf(80_000L),+        durationState = mutableLongStateOf(600_000L),+        playingState = mutableStateOf(false),+        bufferingState = mutableStateOf(false),+        draggingState = mutableStateOf(false),+        cuesState = mutableStateOf(emptyList()),+        heightsState = mutableStateOf(listOf(1080)),+        errorState = mutableStateOf<String?>(null),+    )++    @Test fun overlayShowsTitleChipsAndTimes() {+        var server = 0+        var subs = 0+        var quality = 0+        composeRule.setContent {+            DynamicTheme {+                TvWatchOverlay(+                    title = "The Show",+                    serverLabel = "Alpha",+                    showServerPicker = true,+                    onOpenServerPicker = { server++ },+                    playerState = playerState(),+                    subtitleLabel = "English",+                    showSubtitlePicker = true,+                    onOpenSubtitlePicker = { subs++ },+                    qualityLabel = "1080p",+                    showQualityPicker = true,+                    onOpenQualityPicker = { quality++ },+                    playFocus = FocusRequester(),+                    onBack = {})+            }+        }+        composeRule.onNodeWithText("The Show").assertIsDisplayed()+        composeRule.onNodeWithText("Alpha").assertIsDisplayed()+        composeRule.onNodeWithText("English").assertIsDisplayed()+        composeRule.onNodeWithText("1080p").assertIsDisplayed()+        composeRule.onNodeWithText("1:05").assertIsDisplayed()+        composeRule.onNodeWithText("10:00").assertIsDisplayed()+        composeRule.onNode(androidx.compose.ui.test.hasText("Alpha") and hasClickAction())+            .performSemanticsAction(androidx.compose.ui.semantics.SemanticsActions.OnClick)+        assertEquals(1, server)+        assertEquals(0, subs)+        assertEquals(0, quality)+    }++    @Test fun overlayHidesChipsWhenPickersDisabled() {+        composeRule.setContent {+            DynamicTheme {+                TvWatchOverlay(+                    title = "Film",+                    serverLabel = "Alpha",+                    showServerPicker = false,+                    onOpenServerPicker = {},+                    playerState = playerState(),+                    subtitleLabel = "English",+                    showSubtitlePicker = false,+                    onOpenSubtitlePicker = {},+                    qualityLabel = "1080p",+                    showQualityPicker = false,+                    onOpenQualityPicker = {},+                    playFocus = FocusRequester(),+                    onBack = {})+            }+        }+        composeRule.onNodeWithText("Film").assertIsDisplayed()+        composeRule.onNodeWithText("1:05").assertIsDisplayed()+    }++    @Test fun tvAddAddonDialogConfirmsUrl() {+        var confirmed: String? = null+        var imports = 0+        composeRule.setContent {+            DynamicTheme {+                TvAddAddonDialog(+                    adding = false,+                    onDismiss = {},+                    onConfirm = { confirmed = it },+                    onImportJs = { imports++ })+            }+        }+        composeRule.onNodeWithText("Add addon").assertIsDisplayed()+        // The dialog's text field is the only editable node.+        composeRule.onNode(+            androidx.compose.ui.test.hasSetTextAction())+            .performTextInput("https://addons.example/manifest.json")+        composeRule.onNode(androidx.compose.ui.test.hasText("Import .js") and hasClickAction())+            .performSemanticsAction(androidx.compose.ui.semantics.SemanticsActions.OnClick)+        assertEquals(1, imports)+        composeRule.onNode(androidx.compose.ui.test.hasText("Add") and hasClickAction())+            .performSemanticsAction(androidx.compose.ui.semantics.SemanticsActions.OnClick)+        assertEquals("https://addons.example/manifest.json", confirmed)+    }+}