Yokan / rebuild
Course 1 8624561

NovelReaderViewModelTest.kt

composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/novel/NovelReaderViewModelTest.kt

test / fixture168 lines
1package eu.friedcutlet.yokan.ui.screens.novel23import androidx.lifecycle.ViewModelStore4import eu.friedcutlet.yokan.data.DefaultYokanRepository5import eu.friedcutlet.yokan.data.LibraryIndexStore6import eu.friedcutlet.yokan.data.SettingsStore7import eu.friedcutlet.yokan.database.DbChapter8import eu.friedcutlet.yokan.database.DbItemType9import eu.friedcutlet.yokan.database.DbManga10import eu.friedcutlet.yokan.database.DbSource11import eu.friedcutlet.yokan.database.InMemoryYokanDatabase12import eu.friedcutlet.yokan.database.seedDatabaseSnapshot13import eu.friedcutlet.yokan.domain.Chapter14import eu.friedcutlet.yokan.domain.Source15import eu.friedcutlet.yokan.services.tts.ProfileSpeechService16import eu.friedcutlet.yokan.services.tts.TextToSpeechRequest17import eu.friedcutlet.yokan.services.tts.TextToSpeechService18import eu.friedcutlet.yokan.ui.ViewModelTestHost19import eu.friedcutlet.yokan.ui.screens.reader.autoScrollSettings20import kotlin.test.AfterTest21import kotlin.test.Test22import kotlin.test.assertEquals23import kotlin.test.assertNull24import kotlin.test.assertTrue25import kotlinx.coroutines.CoroutineScope26import kotlinx.coroutines.ExperimentalCoroutinesApi27import kotlinx.coroutines.SupervisorJob28import kotlinx.coroutines.awaitCancellation29import kotlinx.coroutines.cancelAndJoin30import kotlinx.coroutines.test.TestScope31import kotlinx.coroutines.test.runCurrent32import kotlinx.coroutines.test.runTest3334@OptIn(ExperimentalCoroutinesApi::class)35class NovelReaderViewModelTest {36    private val database = InMemoryYokanDatabase(37        seedDatabaseSnapshot().copy(38            sources = listOf(DbSource(id = 1, name = "Web", lang = "en", itemType = DbItemType.Novel, isAdded = true)),39            mangas = listOf(40                DbManga(id = 1, name = "Book", link = "/book", description = "Blurb", source = "Web", sourceId = 1, itemType = DbItemType.Novel, favorite = true),41            ),42            chapters = listOf(DbChapter(id = 10, mangaId = 1, name = "Ch 1", url = "/1")),43        ),44    )45    private val repository = DefaultYokanRepository(database)46    private val host = ViewModelTestHost()47    private val dispatcher = host.dispatcher48    private val native = Native()49    private val speechJob = SupervisorJob()50    private val speech = ProfileSpeechService(native, CoroutineScope(speechJob + dispatcher))5152    @AfterTest53    fun tearDown() = host.close()5455    private fun TestScope.viewModel(56        store: ViewModelStore? = null,57        loadHeaders: suspend (Source) -> Map<String, String> = { emptyMap() },58        loadDocument: suspend (Source?, Chapter) -> NovelDocument = { _, _ -> NovelDocument("<p>One</p><p>Two</p>") },59    ): Pair<NovelReaderViewModel, SettingsStore> {60        val settings = SettingsStore(repository, backgroundScope, onSchedulingChanged = {})61        val manga = requireNotNull(repository.manga(1))62        val chapter = repository.chapters(1).single()63        val create = {64            NovelReaderViewModel(65                manga, chapter, repository, settings, LibraryIndexStore(repository, backgroundScope, dispatcher), speech,66                loadHeaders, loadDocument, workDispatcher = dispatcher,67            )68        }69        val vm = if (store == null) host.create(create) else create().also { store.put("novel", it) }70        return vm to settings71    }7273    @Test74    fun loadsDocumentAndAddsTheWebViewUserAgentToImageHeaders() = runTest {75        repository.updateDbSettings { it.copy(userAgent = "Agent") }76        val (vm, _) = viewModel(loadHeaders = { mapOf("Referer" to "https://web.test") })77        runCurrent()7879        val state = vm.state.value80        assertEquals(false, state.loading)81        assertNull(state.error)82        assertEquals("<p>One</p><p>Two</p>", state.document?.html)83        assertEquals(mapOf("Referer" to "https://web.test", "User-Agent" to "Agent"), state.imageHeaders)84    }8586    @Test87    fun failedExtractionShowsTheErrorOverTheTitleDescription() = runTest {88        val (vm, _) = viewModel(loadDocument = { _, _ -> error("Source offline") })89        runCurrent()9091        assertEquals("Source offline", vm.state.value.error)92        assertEquals("Blurb", vm.state.value.document?.html)93    }9495    @Test96    fun savingProgressMarksTheChapterReadPastNinetyPercent() = runTest {97        val (vm, _) = viewModel()9899        vm.onEvent(NovelReaderEvent.SaveProgress(0.95))100101        val chapter = repository.chapters(1).single()102        assertTrue(chapter.isRead)103        assertEquals("0.95", chapter.lastPageRead)104    }105106    @Test107    fun autoScrollTogglePersistsPerTitle() = runTest {108        val (vm, settings) = viewModel()109110        vm.onEvent(NovelReaderEvent.SetAutoScrollOffset(12f))111        vm.onEvent(NovelReaderEvent.SetAutoScrollEnabled(false))112113        assertEquals(false, vm.state.value.autoScrollPlaying)114        val stored = settings.db.value.autoScrollSettings(1)115        assertEquals(false, stored.autoScroll)116        assertEquals(12.0, stored.pageOffset)117    }118119    @Test120    fun speechFollowsEventsAndRestartsWithChangedVoiceSettings() = runTest {121        val (vm, settings) = viewModel()122        runCurrent()123124        vm.onEvent(NovelReaderEvent.StartTts(listOf("One", "Two")))125        runCurrent()126        assertEquals(NovelTtsPlaybackState.Playing, vm.state.value.tts.playback)127        settings.updateDb { it.copy(ttsPitch = 1.5) }128        runCurrent()129        vm.onEvent(NovelReaderEvent.SkipNextTts)130        runCurrent()131132        assertEquals(listOf("One" to 1.0, "One" to 1.5, "Two" to 1.5), native.spoken)133        assertEquals(1, vm.state.value.tts.paragraphIndex)134        vm.onEvent(NovelReaderEvent.StopTts)135        runCurrent()136        assertEquals(NovelTtsPlaybackState.Stopped, vm.state.value.tts.playback)137    }138139    @Test140    fun clearingTheViewModelSilencesSpeechAndRejectsLaterCommands() = runTest {141        val store = ViewModelStore()142        val (vm, _) = viewModel(store)143        vm.onEvent(NovelReaderEvent.StartTts(listOf("One")))144        runCurrent()145        val stopsBefore = native.stops146147        store.clear()148        runCurrent()149        vm.onEvent(NovelReaderEvent.StartTts(listOf("Late")))150        runCurrent()151152        assertTrue(native.stops > stopsBefore)153        assertEquals(listOf("One" to 1.0), native.spoken)154        speech.closeAndJoin()155        speechJob.cancelAndJoin()156    }157158    private class Native : TextToSpeechService {159        val spoken = mutableListOf<Pair<String, Double>>()160        var stops = 0161        override suspend fun voices(language: String?): List<String> = emptyList()162        override suspend fun speak(text: String, request: TextToSpeechRequest, onProgress: (Int, Int) -> Unit) {163            spoken += text to request.pitch164            awaitCancellation()165        }166        override suspend fun stop() { stops++ }167    }168}169

Search chapters, reference and source filenames.