Yokan / rebuild
Course 1 8624561

PlayerViewModelTest.kt

composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/player/PlayerViewModelTest.kt

test / fixture209 lines
1package eu.friedcutlet.yokan.ui.screens.player23import eu.friedcutlet.yokan.data.DefaultYokanRepository4import eu.friedcutlet.yokan.data.LibraryIndexStore5import eu.friedcutlet.yokan.data.SettingsStore6import eu.friedcutlet.yokan.database.DbChapter7import eu.friedcutlet.yokan.database.DbItemType8import eu.friedcutlet.yokan.database.DbManga9import eu.friedcutlet.yokan.database.DbVideo10import eu.friedcutlet.yokan.database.InMemoryYokanDatabase11import eu.friedcutlet.yokan.database.seedDatabaseSnapshot12import eu.friedcutlet.yokan.database.withPlayer13import eu.friedcutlet.yokan.domain.Chapter14import eu.friedcutlet.yokan.domain.ItemType15import eu.friedcutlet.yokan.domain.Source16import eu.friedcutlet.yokan.domain.testManga17import eu.friedcutlet.yokan.services.http.HttpService18import eu.friedcutlet.yokan.services.media.cast.CastController19import eu.friedcutlet.yokan.services.media.cast.CastDevice20import eu.friedcutlet.yokan.services.media.cast.CastMedia21import eu.friedcutlet.yokan.services.media.cast.CastStatus22import eu.friedcutlet.yokan.services.media.cast.CastTextStyle23import eu.friedcutlet.yokan.ui.ViewModelTestHost24import kotlin.test.AfterTest25import kotlin.test.Test26import kotlin.test.assertEquals27import kotlin.test.assertNull28import kotlin.test.assertTrue29import kotlinx.coroutines.CoroutineScope30import kotlinx.coroutines.flow.MutableStateFlow31import kotlinx.coroutines.flow.first32import kotlinx.coroutines.launch33import kotlinx.coroutines.test.runTest3435class PlayerViewModelTest {36    private val database = InMemoryYokanDatabase(37        seedDatabaseSnapshot().copy(38            mangas = listOf(DbManga(id = 1, name = "Show", link = "/s", source = "Src", itemType = DbItemType.Anime, favorite = true)),39            chapters = (1L..5L).map { DbChapter(id = it, mangaId = 1, url = "/e$it", name = "Episode $it") },40        ),41    )42    private val repository = DefaultYokanRepository(database)43    private val host = ViewModelTestHost()44    private val manga = testManga(1, name = "Show", itemType = ItemType.Anime)45    private val noHttp = HttpService { error("no seek previews in these tests") }46    private val cast = RecordingCast()47    private val sd = DbVideo(url = "https://cdn.example/sd.m3u8", quality = "480p", originalUrl = "")48    private val hd = DbVideo(url = "https://cdn.example/hd.m3u8", quality = "1080p", originalUrl = "")4950    @AfterTest51    fun tearDown() = host.close()5253    private fun episode(id: Long, lastPageRead: String = "") =54        Chapter(id = id, mangaId = 1, name = "Episode $id", url = "/e$id", lastPageRead = lastPageRead)5556    private fun viewModel(57        scope: CoroutineScope,58        chapter: Chapter = episode(3),59        settings: SettingsStore = SettingsStore(repository, scope, onSchedulingChanged = {}),60        loadVideos: suspend (Source?, Chapter) -> List<DbVideo>,61    ): PlayerViewModel = host.create {62        PlayerViewModel(63            manga = manga,64            chapter = chapter,65            repository = repository,66            settings = settings,67            libraryIndex = LibraryIndexStore(repository, scope),68            http = noHttp,69            loadVideos = loadVideos,70            aniSkipMarkers = { _, _ -> emptyList() },71            openExternalPlayer = { _, _ -> false },72            cast = cast,73            workDispatcher = host.dispatcher,74        )75    }7677    private fun CoroutineScope.effectsOf(vm: PlayerViewModel): List<PlayerEffect> =78        mutableListOf<PlayerEffect>().also { effects -> launch(host.dispatcher) { vm.effects.collect { effects += it } } }7980    @Test81    fun loadingSelectsTheFirstStreamAtTheSavedPosition() = runTest {82        val requested = mutableListOf<Long>()83        val vm = viewModel(backgroundScope, chapter = episode(3, lastPageRead = "65000")) { _, chapter ->84            requested += chapter.id85            listOf(sd, hd)86        }8788        val loaded = vm.state.first { !it.loading }8990        assertEquals(listOf(3L), requested)91        assertEquals(listOf(sd, hd), loaded.videos)92        assertEquals(sd, loaded.selectedVideo)93        assertEquals(65_000L, loaded.startPositionMs)94        assertTrue(loaded.autoplay)95        assertNull(loaded.error)96    }9798    @Test99    fun failedOrEmptyLoadsReportAnErrorWithoutAStream() = runTest {100        val failed = viewModel(backgroundScope) { _, _ -> error("extension crashed") }.state.first { !it.loading }101        val empty = viewModel(backgroundScope) { _, _ -> emptyList() }.state.first { !it.loading }102103        assertEquals("extension crashed", failed.error)104        assertNull(failed.selectedVideo)105        assertEquals("No streams were returned by this source.", empty.error)106        assertNull(empty.selectedVideo)107    }108109    @Test110    fun playbackFailureSwitchesToEachRemainingStreamOnceThenReports() = runTest {111        val settings = SettingsStore(repository, backgroundScope, onSchedulingChanged = {})112        settings.updateDb { db -> db.withPlayer { it.copy(switchStreamOnFailure = true) } }113        val vm = viewModel(backgroundScope, settings = settings) { _, _ -> listOf(sd, hd) }114        val effects = backgroundScope.effectsOf(vm)115        vm.state.first { !it.loading }116117        vm.onEvent(PlayerEvent.PlaybackFailed("decoder", positionMs = 42_000))118        val switched = vm.state.value119        vm.onEvent(PlayerEvent.PlaybackFailed("decoder", positionMs = 50_000))120121        assertEquals(hd, switched.selectedVideo)122        assertEquals(42_000L, switched.startPositionMs)123        assertEquals(hd, vm.state.value.selectedVideo)124        assertEquals(125            listOf(126                PlayerEffect.ShowNotice("Stream failed; switching to 1080p"),127                PlayerEffect.ShowNotice("Playback failed: decoder"),128            ),129            effects,130        )131    }132133    @Test134    fun playbackFailureWithoutFailoverOnlyReports() = runTest {135        val vm = viewModel(backgroundScope) { _, _ -> listOf(sd, hd) }136        val effects = backgroundScope.effectsOf(vm)137        vm.state.first { !it.loading }138139        vm.onEvent(PlayerEvent.PlaybackFailed("decoder", positionMs = 42_000))140141        assertEquals(sd, vm.state.value.selectedVideo)142        assertEquals(listOf(PlayerEffect.ShowNotice("Playback failed: decoder")), effects)143    }144145    @Test146    fun castingQueuesThisEpisodeThenTheNextTwoInTitleOrder() = runTest {147        val vm = viewModel(backgroundScope) { _, chapter ->148            listOf(DbVideo(url = "https://cdn.example/${chapter.id}.mp4", quality = "720p", originalUrl = ""))149        }150        val episodes = vm.state.first { !it.loading && it.episodes.size == 5 }.episodes.map { it.id }151        val following = episodes.dropWhile { it != 3L }.drop(1).take(2)152153        vm.onEvent(PlayerEvent.StartCasting(device = null, startPositionMs = 12_000, subtitleFile = null))154155        assertEquals(2, following.size)156        assertEquals(listOf("connect"), cast.calls)157        assertEquals(listOf("3"), cast.loaded.map { it.itemKey })158        assertEquals(12_000L, cast.loadedAtMs)159        assertEquals(following.map { it.toString() }, cast.appended.map { it.itemKey })160    }161162    @Test163    fun castingStreamsThatNeedHeadersIsRefused() = runTest {164        val vm = viewModel(backgroundScope) { _, _ -> listOf(sd.copy(headers = mapOf("Referer" to "x"))) }165        val effects = backgroundScope.effectsOf(vm)166        vm.state.first { !it.loading }167168        vm.onEvent(PlayerEvent.StartCasting(device = null, startPositionMs = 0, subtitleFile = null))169170        assertTrue(cast.calls.isEmpty())171        assertEquals(172            listOf(PlayerEffect.ShowNotice("This episode's streams need request headers or are local, so they cannot be cast")),173            effects,174        )175    }176177    private class RecordingCast : CastController {178        val calls = mutableListOf<String>()179        val loaded = mutableListOf<CastMedia>()180        val appended = mutableListOf<CastMedia>()181        var loadedAtMs = -1L182        override val isSupported = MutableStateFlow(true)183        override val usesSystemPicker = false184        override val devices = MutableStateFlow(emptyList<CastDevice>())185        override val status = MutableStateFlow<CastStatus?>(null)186        override fun startDiscovery() { calls += "discover" }187        override fun stopDiscovery() { calls += "stop-discovery" }188        override suspend fun connect(device: CastDevice?) { calls += "connect" }189        override suspend fun loadQueue(190            items: List<CastMedia>,191            startIndex: Int,192            startPositionMs: Long,193            style: CastTextStyle,194            activeSubtitleIndex: Int?,195        ) {196            loaded += items197            loadedAtMs = startPositionMs198        }199        override suspend fun append(items: List<CastMedia>) { appended += items }200        override fun play() = Unit201        override fun pause() = Unit202        override fun seekTo(positionMs: Long) = Unit203        override fun next() = Unit204        override fun previous() = Unit205        override fun jumpTo(index: Int) = Unit206        override suspend fun disconnect() { calls += "disconnect" }207        override fun close() = Unit208    }209}210

Search chapters, reference and source filenames.