DetailViewModelTest.kt
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/detail/DetailViewModelTest.kt
1package eu.friedcutlet.yokan.ui.screens.detail23import eu.friedcutlet.yokan.ui.ViewModelTestHost4import eu.friedcutlet.yokan.services.notifications.NoNotifications5import eu.friedcutlet.yokan.data.DefaultYokanRepository6import eu.friedcutlet.yokan.data.LibraryIndexStore7import eu.friedcutlet.yokan.data.SettingsStore8import eu.friedcutlet.yokan.database.DbChapter9import eu.friedcutlet.yokan.database.DbChapterReleasePreference10import eu.friedcutlet.yokan.database.chapterReleasePreference11import eu.friedcutlet.yokan.database.DbItemType12import eu.friedcutlet.yokan.database.DbManga13import eu.friedcutlet.yokan.database.DbSource14import eu.friedcutlet.yokan.database.InMemoryYokanDatabase15import eu.friedcutlet.yokan.database.seedDatabaseSnapshot16import eu.friedcutlet.yokan.domain.ProfileId17import eu.friedcutlet.yokan.database.DbSyncPreference18import eu.friedcutlet.yokan.services.http.HttpService19import eu.friedcutlet.yokan.services.http.RecordingHttpService20import eu.friedcutlet.yokan.services.http.HttpResponse21import eu.friedcutlet.yokan.services.http.ProfileTestEngine22import eu.friedcutlet.yokan.services.together.ProfileTogetherSession23import kotlinx.coroutines.awaitCancellation24import eu.friedcutlet.yokan.services.download.ChapterDownloads25import eu.friedcutlet.yokan.services.download.DownloadProgress26import eu.friedcutlet.yokan.services.download.DownloadRequest27import eu.friedcutlet.yokan.services.download.DownloadService28import eu.friedcutlet.yokan.services.extensions.ExtensionRuntimeFactory29import eu.friedcutlet.yokan.services.extensions.ExtensionRuntimeService30import eu.friedcutlet.yokan.services.files.NoFiles31import eu.friedcutlet.yokan.services.metadata.MetadataLibraryEntry32import eu.friedcutlet.yokan.services.metadata.MetadataMedia33import eu.friedcutlet.yokan.services.metadata.MetadataService34import kotlin.test.AfterTest35import kotlin.test.Test36import kotlin.test.assertEquals37import kotlin.test.assertTrue38import kotlinx.coroutines.CoroutineScope39import kotlinx.coroutines.ExperimentalCoroutinesApi40import kotlinx.coroutines.flow.filterNotNull41import kotlinx.coroutines.flow.first42import kotlinx.coroutines.test.runTest43import eu.friedcutlet.yokan.services.library.ChapterFilterKind4445@OptIn(ExperimentalCoroutinesApi::class)46class DetailViewModelTest {47 // No source id: a title without an installed source never triggers the remote refresh.48 private val database = InMemoryYokanDatabase(49 seedDatabaseSnapshot().copy(50 mangas = listOf(DbManga(id = 1, name = "Title", link = "/t", source = "Src", itemType = DbItemType.Manga, favorite = true)),51 chapters = (1L..3L).map { DbChapter(id = it, mangaId = 1, url = "/c$it", name = "Chapter $it", isRead = it == 2L) },52 ),53 )54 private val repository = DefaultYokanRepository(database)55 private val host = ViewModelTestHost()56 private val dispatcher = host.dispatcher5758 @AfterTest59 fun tearDown() = host.close()6061 private fun viewModel(62 scope: CoroutineScope,63 downloader: DownloadService = NoDownloads,64 together: ProfileTogetherSession? = null,65 http: HttpService? = null,66 ): DetailViewModel {67 val settings = SettingsStore(repository, scope, onSchedulingChanged = {})68 val downloads = ChapterDownloads(repository, database, downloader, NoNotifications, settings, NoFiles, scope)69 return host.create {70 DetailViewModel(71 mangaId = 1,72 repository = repository,73 settings = settings,74 libraryIndex = LibraryIndexStore(repository, scope),75 downloads = downloads,76 metadata = NoMetadata,77 runtimeFactory = NoRuntimeFactory,78 database = database,79 allTrackers = emptyList(),80 files = NoFiles,81 workDispatcher = dispatcher,82 together = together,83 togetherHttp = http,84 )85 }86 }8788 @Test89 fun castOnlyUpdatesReachTheObservedDetailWithoutChangingChapters() = runTest {90 val vm = viewModel(backgroundScope)91 vm.state.filterNotNull().first { it.content.loaded }92 val ids = database.chapters(1).map { it.id }93 val credit = eu.friedcutlet.yokan.domain.TitleCredit("Actor", "Voice actor", "Hero")94 database.upsertManga(requireNotNull(database.manga(1)).copy(cast = listOf(credit)))95 val changed = vm.state.filterNotNull().first { it.content.manga.cast == listOf(credit) }96 assertEquals(ids.toSet(), changed.content.chapters.map { it.id }.toSet())97 database.upsertManga(requireNotNull(database.manga(1)).copy(cast = emptyList()))98 vm.state.filterNotNull().first { it.content.manga.cast.isEmpty() }99 }100101 @Test102 fun seasonSelectionScopesEpisodesContinuationAndActionsAndRecoversAfterRemoval() = runTest {103 database.upsertManga(requireNotNull(database.manga(1)).copy(itemType = DbItemType.Anime))104 database.upsertChapter(DbChapter(id = 1, mangaId = 1, url = "/special", name = "Special", number = 1.0, season = 0))105 database.upsertChapter(DbChapter(id = 2, mangaId = 1, url = "/premiere", name = "Premiere", number = 1.0, season = 2))106 database.upsertChapter(DbChapter(id = 3, mangaId = 1, url = "/second", name = "S02E02"))107 database.upsertChapter(DbChapter(id = 4, mangaId = 1, url = "/ova", name = "Unnumbered OVA"))108 val requests = mutableListOf<Long>()109 val downloader = object : DownloadService by NoDownloads {110 override fun enqueue(request: DownloadRequest, onProgress: (DownloadProgress) -> Unit) { requests += request.chapterId }111 }112 val vm = viewModel(backgroundScope, downloader)113 val all = vm.state.filterNotNull().first { it.content.loaded && it.content.chapters.size == 4 }114 assertEquals(listOf(0, 2), all.content.seasons)115 assertEquals(null, all.content.selectedSeason)116 vm.onEvent(DetailEvent.ToggleSelection(1))117 vm.onEvent(DetailEvent.SelectSeason(2))118 val second = vm.state.filterNotNull().first { it.content.selectedSeason == 2 }119 assertEquals(setOf(2L, 3L), second.content.chapters.map { it.id }.toSet())120 assertTrue(second.selection.ids.isEmpty())121 assertTrue(second.content.continueChapter?.id in setOf(2L, 3L))122 vm.onEvent(DetailEvent.DownloadAll(repository.chapters(1), DetailDownloadOption.All, null))123 assertEquals(setOf(2L, 3L), requests.toSet())124 vm.onEvent(DetailEvent.SetRead(setOf(2), true))125 assertEquals(false, database.chapter(1)?.isRead)126 assertEquals(true, database.chapter(2)?.isRead)127 vm.onEvent(DetailEvent.SelectSeason(99))128 assertEquals(2, vm.state.value?.selectedSeason)129 vm.onEvent(DetailEvent.SelectSeason(0))130 val specials = vm.state.filterNotNull().first { it.content.selectedSeason == 0 }131 assertEquals(listOf(1L), specials.content.chapters.map { it.id })132 assertEquals(1L, specials.content.continueChapter?.id)133 vm.onEvent(DetailEvent.SelectSeason(null))134 vm.state.filterNotNull().first { it.content.selectedSeason == null && it.content.chapters.size == 4 }135 vm.onEvent(DetailEvent.SelectSeason(2))136 vm.state.filterNotNull().first { it.content.selectedSeason == 2 }137 database.batch { database.removeChapter(2); database.removeChapter(3) }138 val removed = vm.state.filterNotNull().first { it.selectedSeason == null && it.content.chapters.size == 2 }139 assertEquals(listOf(0), removed.content.seasons)140 assertEquals(setOf(1L, 4L), removed.content.chapters.map { it.id }.toSet())141 }142143 @Test144 fun seasonsTitleListsItsSeasonRecordsWithTheirOwnProgressAndContinuation() = runTest {145 database.upsertManga(requireNotNull(database.manga(1)).copy(itemType = DbItemType.Anime, fetchType = eu.friedcutlet.yokan.database.DbFetchType.Seasons))146 database.chapters(1).forEach { database.removeChapter(it.id) }147 database.upsertManga(DbManga(id = 21, name = "Second", link = "/s2", itemType = DbItemType.Anime, parentId = 1, seasonNumber = 2.0))148 database.upsertManga(DbManga(id = 20, name = "First", link = "/s1", itemType = DbItemType.Anime, parentId = 1, seasonNumber = 1.0))149 database.upsertManga(DbManga(id = 22, name = "Unrelated", link = "/x", itemType = DbItemType.Anime))150 database.upsertChapter(DbChapter(id = 30, mangaId = 20, url = "/s1/e1", name = "Episode 1", isRead = true))151 database.upsertChapter(DbChapter(id = 31, mangaId = 20, url = "/s1/e2", name = "Episode 2"))152 database.upsertChapter(DbChapter(id = 32, mangaId = 21, url = "/s2/e1", name = "Episode 1", isRead = true))153 val vm = viewModel(backgroundScope)154 val state = vm.state.filterNotNull().first { it.content.loaded && it.content.seasonTitles.size == 2 }155 assertEquals(listOf(20L, 21L), state.content.seasonTitles.map { it.title.id })156 assertEquals(listOf(2 to 1, 1 to 1), state.content.seasonTitles.map { it.episodeCount to it.watchedCount })157 assertEquals(listOf(31L, null), state.content.seasonTitles.map { it.continueChapter?.id })158 assertTrue(state.content.chapters.isEmpty())159 database.upsertChapter(DbChapter(id = 33, mangaId = 21, url = "/s2/e2", name = "Episode 2"))160 val updated = vm.state.filterNotNull().first { it.content.seasonTitles.getOrNull(1)?.continueChapter?.id == 33L }161 assertEquals(2, updated.content.seasonTitles[1].episodeCount)162 }163164 @Test165 fun explicitUncategorizedSelectionOverridesDefaultButOrdinaryAddUsesIt() = runTest {166 val category = repository.createCategory(eu.friedcutlet.yokan.domain.ItemType.Manga, "Default")167 repository.updateDbSettings { db -> db.copy(features = db.features.copy(168 library = db.features.library.withDefaultCategory(DbItemType.Manga, category.id),169 )) }170 repository.setMangaFavorite(1, false)171 val vm = viewModel(backgroundScope)172 vm.state.filterNotNull().first { it.content.loaded && !it.content.manga.favorite }173 vm.onEvent(DetailEvent.SetFavorite(true))174 assertEquals(listOf(category.id), repository.manga(1)?.categories)175 vm.onEvent(DetailEvent.SetFavorite(false))176 vm.onEvent(DetailEvent.SetCategories(emptyList(), favorite = true))177 assertEquals(true, repository.manga(1)?.favorite)178 assertEquals(emptyList(), repository.manga(1)?.categories)179 vm.state.filterNotNull().first { it.content.manga.favorite && it.content.manga.categories.isEmpty() }180 }181182 @Test183 fun togetherEventAndRoomObservationUseTheInjectedControllerAndTransport() = runTest {184 database.upsertSyncPreference(DbSyncPreference(syncId = 1, server = "https://captured-hub.test", authToken = "captured-token", deviceId = "captured-device"))185 val engine = ProfileTestEngine(dispatcher) { awaitCancellation() }186 val together = ProfileTogetherSession(ProfileId.Default, database, backgroundScope) { engine }187 val http = RecordingHttpService { HttpResponse(201, "{\"code\":\"ABCDEF\",\"join_url\":\"join\"}") }188 val vm = viewModel(backgroundScope, together = together, http = http)189 vm.state.filterNotNull().first { it.content.loaded }190 vm.onEvent(DetailEvent.Together)191 assertEquals(DetailEffect.OpenTogetherSettings, vm.effects.first())192 assertTrue((vm.effects.first() as DetailEffect.ShowMessage).text.startsWith("Room ABCDEF"))193 val state = vm.state.filterNotNull().first { it.togetherRoom?.code == "ABCDEF" }194 assertEquals("ABCDEF", state.togetherRoom?.code)195 assertEquals("https://captured-hub.test/api/v1/rooms", http.requests.single().url)196 assertEquals("Bearer captured-token", http.requests.single().headers["Authorization"])197 together.leave()198 vm.state.filterNotNull().first { it.togetherRoom == null }199 together.closeAndJoin()200 }201202 @Test203 fun selectionTogglesSplitByCurrentFlagAndClearTheSelection() = runTest {204 val vm = viewModel(backgroundScope)205 vm.state.filterNotNull().first { it.content.loaded }206 vm.onEvent(DetailEvent.Select(ChapterSelectionOption.All))207 vm.onEvent(DetailEvent.ToggleSelectedRead)208 assertEquals(listOf(true, false, true), (1L..3L).map { database.chapter(it)?.isRead })209 assertTrue(checkNotNull(vm.state.value).selection.ids.isEmpty())210 vm.state.filterNotNull().first { it.content.chapters.count { chapter -> chapter.isRead } == 2 }211 vm.onEvent(DetailEvent.ToggleSelection(1))212 vm.onEvent(DetailEvent.ToggleSelectedBookmarks)213 vm.state.filterNotNull().first { it.content.chapters.single { chapter -> chapter.id == 1L }.isBookmarked }214 vm.onEvent(DetailEvent.ToggleSelection(1))215 vm.onEvent(DetailEvent.ToggleSelection(2))216 vm.onEvent(DetailEvent.ToggleSelectedBookmarks)217 assertEquals(listOf(false, true, false), (1L..3L).map { database.chapter(it)?.isBookmarked })218 assertTrue(checkNotNull(vm.state.value).selection.ids.isEmpty())219 }220221 @Test222 fun releasePreferencesChooseOneWinnerPreserveFilesAndSupportGroupActionsAndAlternates() = runTest {223 database.upsertChapter(checkNotNull(database.chapter(1)).copy(scanlator = "Fallback", isRead = true, archivePath = "/kept"))224 database.upsertChapter(DbChapter(id = 4, mangaId = 1, name = "Chapter 1", url = "/preferred", scanlator = "Preferred"))225 database.updateSettings(database.settings().copy(chapterReleasePreferences = listOf(DbChapterReleasePreference(226 scanlatorPriority = listOf("Fallback", "Preferred"), skipDuplicateReleases = true))))227 val requests = mutableListOf<Long>()228 val downloader = object : DownloadService by NoDownloads {229 override fun enqueue(request: DownloadRequest, onProgress: (DownloadProgress) -> Unit) { requests += request.chapterId }230 }231 val vm = viewModel(backgroundScope, downloader)232 vm.state.filterNotNull().first { it.content.loaded && it.content.chapters.size == 3 }233 vm.onEvent(DetailEvent.MoveScanlator("Preferred", -1))234 val preferred = vm.state.filterNotNull().first { it.content.chapters.any { chapter -> chapter.id == 4L } }235 assertTrue(preferred.content.chapters.single { it.id == 4L }.isRead)236 assertEquals("/kept", database.chapter(1)?.archivePath)237 vm.onEvent(DetailEvent.SetRead(setOf(4), false))238 vm.state.filterNotNull().first { !it.content.chapters.single { chapter -> chapter.id == 4L }.isRead }239 assertEquals(false, database.chapter(1)?.isRead)240 assertEquals(false, database.chapter(4)?.isRead)241 vm.onEvent(DetailEvent.SetBookmarked(setOf(4), true))242 vm.state.filterNotNull().first { it.content.chapters.single { chapter -> chapter.id == 4L }.isBookmarked }243 assertTrue(checkNotNull(database.chapter(1)).isBookmarked)244 assertTrue(checkNotNull(database.chapter(4)).isBookmarked)245 vm.onEvent(DetailEvent.DownloadAll(checkNotNull(vm.state.value).content.chapters, DetailDownloadOption.All, null))246 assertEquals(setOf(2L, 3L, 4L), requests.toSet())247 vm.onEvent(DetailEvent.ShowAllReleases(true))248 vm.state.filterNotNull().first { it.content.chapters.size == 4 }249 vm.onEvent(DetailEvent.ShowAllReleases(false))250 vm.state.filterNotNull().first { it.content.chapters.size == 3 }251 vm.onEvent(DetailEvent.ResetReleaseOverride)252 vm.state.filterNotNull().first { it.content.chapters.any { chapter -> chapter.id == 1L } }253 assertEquals(listOf("Fallback", "Preferred"), database.settings().chapterReleasePreference(1).scanlatorPriority)254 assertEquals(4, database.chapters(1).size)255 assertEquals("/kept", database.chapter(1)?.archivePath)256 }257258 @Test259 fun noteSaveCancelAndClearOnlyCommitSavedDrafts() = runTest {260 val vm = viewModel(backgroundScope)261 vm.state.filterNotNull().first { it.content.loaded }262 val note = "日本語 🌙\nSecond line"263 vm.onEvent(DetailEvent.EditNote)264 vm.onEvent(DetailEvent.ChangeNote(note))265 assertEquals("", repository.manga(1)?.privateNote)266 vm.onEvent(DetailEvent.SaveNote)267 assertEquals(note, repository.manga(1)?.privateNote)268 assertEquals(null, vm.state.value?.noteDraft)269 vm.onEvent(DetailEvent.EditNote)270 vm.onEvent(DetailEvent.ChangeNote("discard me"))271 vm.onEvent(DetailEvent.CancelNote)272 assertEquals(note, repository.manga(1)?.privateNote)273 vm.onEvent(DetailEvent.EditNote)274 vm.onEvent(DetailEvent.ChangeNote(""))275 vm.onEvent(DetailEvent.CancelNote)276 assertEquals(note, repository.manga(1)?.privateNote)277 vm.onEvent(DetailEvent.EditNote)278 vm.onEvent(DetailEvent.ChangeNote(""))279 vm.onEvent(DetailEvent.SaveNote)280 assertEquals("", repository.manga(1)?.privateNote)281 vm.onEvent(DetailEvent.SetFavorite(false))282 vm.state.filterNotNull().first { !it.content.manga.favorite }283 vm.onEvent(DetailEvent.EditNote)284 assertEquals(null, vm.state.value?.noteDraft)285 }286287 @Test288 fun chapterFilterHidesChaptersAndDropsThemFromTheSelection() = runTest {289 val vm = viewModel(backgroundScope)290 val loaded = vm.state.filterNotNull().first { it.content.loaded }291 assertEquals(listOf(3L, 2L, 1L), loaded.content.chapters.map { it.id })292293 vm.onEvent(DetailEvent.Select(ChapterSelectionOption.All))294 vm.onEvent(DetailEvent.CycleFilter(ChapterFilterKind.Unread))295296 val filtered = vm.state.filterNotNull().first { it.content.chapters.size == 2 }297 assertEquals(listOf(3L, 1L), filtered.content.chapters.map { it.id })298 assertEquals(setOf(3L, 1L), filtered.selection.ids)299 }300}301302private object NoDownloads : DownloadService {303 override suspend fun initialize(poolSize: Int) = Unit304 override fun enqueue(request: DownloadRequest, onProgress: (DownloadProgress) -> Unit) = Unit305 override fun cancel(taskId: String) = Unit306 override fun pause(taskId: String) = Unit307 override fun resume(taskId: String) = Unit308 override fun retry(taskId: String): Boolean = false309 override fun storageLocation(taskId: String): String? = null310 override fun deleteArtifacts(taskId: String) = Unit311 override fun activeDownloads(): List<DownloadProgress> = emptyList()312}313314private object NoRuntimeFactory : ExtensionRuntimeFactory {315 override fun create(source: DbSource): ExtensionRuntimeService = error("No extension runtime in tests")316}317318private object NoMetadata : MetadataService {319 override suspend fun health(baseUrl: String) = false320 override suspend fun search(baseUrl: String, query: String, itemType: DbItemType, limit: Int): List<MetadataMedia> = emptyList()321 override suspend fun library(baseUrl: String, token: String, itemType: DbItemType): List<Pair<MetadataLibraryEntry, MetadataMedia>> = emptyList()322 override suspend fun upsertLibraryEntry(323 baseUrl: String,324 token: String,325 mediaId: String,326 status: String,327 progress: Int,328 score: Int?,329 isFavorite: Boolean,330 ) = false331}332