Yokan / rebuild
Course 1 8624561

SeasonRecordsTest.kt

composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/data/SeasonRecordsTest.kt

test / fixture130 lines
1package eu.friedcutlet.yokan.data23import eu.friedcutlet.yokan.database.*4import eu.friedcutlet.yokan.database.sync.SyncPaths5import eu.friedcutlet.yokan.domain.ItemType6import eu.friedcutlet.yokan.domain.Source7import eu.friedcutlet.yokan.services.backup.BackupJson8import eu.friedcutlet.yokan.services.backup.BackupMerge9import eu.friedcutlet.yokan.services.backup.BackupSection10import eu.friedcutlet.yokan.services.backup.BackupSnapshot11import eu.friedcutlet.yokan.services.backup.MangayomiBackupCodec12import eu.friedcutlet.yokan.services.extensions.*13import eu.friedcutlet.yokan.services.extensions.js.remoteDetailFromJson14import eu.friedcutlet.yokan.services.extensions.js.seasonListFromJson15import eu.friedcutlet.yokan.services.library.DefaultLibraryUpdaterService16import kotlinx.coroutines.test.runTest17import kotlinx.serialization.json.*18import kotlin.test.*1920class SeasonRecordsTest {21    private val source = Source(id = 5, name = "Source", baseUrl = "https://example.com", lang = "en", itemType = ItemType.Anime, typeSource = "single")22    private val dbSource = DbSource(id = 5, name = "Source", baseUrl = "https://example.com", lang = "en", itemType = DbItemType.Anime,23        isActive = true, isAdded = true, sourceCodeLanguage = DbSourceCodeLanguage.JavaScript)2425    @Test fun decoderReadsAnimetailFetchTypeAndBoundsSeasonLists() {26        val detail = remoteDetailFromJson(Json.parseToJsonElement("""{"title":"Show","url":"/show","fetch_type":"Seasons",27            "episodes":[{"name":"Ignored","url":"/e"}],28            "seasons":[{"title":"S1","url":"/s1","season_number":1},{"title":"Dup","url":"/s1"},{"title":"Movies","url":"/m","fetch_type":0,"season_number":-1}]}"""))29        assertEquals(listOf("/s1", "/m"), detail.seasons?.map { it.url })30        assertEquals(listOf(1.0, null), detail.seasons?.map { it.seasonNumber })31        assertEquals(listOf(false, true), detail.seasons?.map { it.fetchesSeasons })32        assertTrue(detail.chapters.isEmpty())33        // Older extensions omit fetch_type: an ordinary episode list, inline seasons ignored.34        val episodes = remoteDetailFromJson(Json.parseToJsonElement("""{"title":"Show","url":"/show","episodes":[{"name":"E1","url":"/e1"}],"seasons":[]}"""))35        assertNull(episodes.seasons)36        assertEquals(1, episodes.chapters.size)37        assertEquals(emptyList(), remoteDetailFromJson(Json.parseToJsonElement("""{"title":"Show","fetchType":"seasons"}""")).seasons)38        assertFailsWith<IllegalStateException> { seasonListFromJson(JsonObject(emptyMap())) }39        assertFailsWith<IllegalArgumentException> { seasonListFromJson(JsonArray(List(501) { buildJsonObject { put("title", "S$it") } })) }40    }4142    @Test fun seasonRecordsKeepProgressFavoritesAndStayOutOfTheLibraryAndCleanup() {43        val db = InMemoryYokanDatabase(seedDatabaseSnapshot().copy(44            sources = listOf(dbSource),45            // A season browsed earlier from the source becomes the season record, keeping its progress.46            mangas = listOf(DbManga(id = 7, name = "Browsed", link = "/s2", itemType = DbItemType.Anime, source = "Source", sourceId = 5)),47            chapters = listOf(DbChapter(id = 70, mangaId = 7, name = "E1", url = "/s2/e1", isRead = true)),48        ))49        val repository = DefaultYokanRepository(db)50        val detail = RemoteDetail("Show", "/show", seasons = listOf(RemoteManga("Season 1", "/s1", seasonNumber = 1.0), RemoteManga("Season 2", "/s2", seasonNumber = 2.0)))51        val show = repository.upsertRemoteDetail(source, detail, favorite = true)52        assertTrue(show.fetchesSeasons)53        val seasons = db.mangas().filter { it.parentId == show.id }.associateBy { it.link }54        assertEquals(setOf("/s1", "/s2"), seasons.keys)55        assertEquals(7L, seasons.getValue("/s2").id)56        assertTrue(seasons.values.none { it.favorite })57        assertTrue(db.chapter(70)!!.isRead)58        assertEquals(listOf(show.id), repository.library(ItemType.Anime).map { it.id })5960        // A refresh keeps records stable and does not rewrite unchanged seasons.61        val stamped = db.mangas().filter { it.parentId == show.id }.associate { it.id to it.updatedAt }62        repository.upsertRemoteDetail(source, detail.copy(seasons = detail.seasons!!.take(1)), favorite = true)63        assertEquals(stamped, db.mangas().filter { it.parentId == show.id }.associate { it.id to it.updatedAt })6465        // Cache cleanup keeps seasons of a library show but not unrelated browsed titles.66        db.upsertManga(DbManga(id = 99, name = "Stray", link = "/stray", itemType = DbItemType.Anime, sourceId = 5, source = "Source"))67        repository.cleanDatabase()68        assertNull(db.manga(99))69        assertEquals(setOf("/s1", "/s2"), db.mangas().filter { it.parentId == show.id }.map { it.link }.toSet())70        assertTrue(db.chapter(70)!!.isRead)71        // Once the show leaves the library its seasons are ordinary cache entries again.72        db.upsertManga(db.manga(show.id)!!.copy(favorite = false))73        repository.pruneBrowsedTitles()74        assertTrue(db.mangas().none { it.parentId == show.id })75    }7677    @Test fun updaterRefreshesEachSeasonAndRecordsItsNewEpisodes() = runTest {78        val episodes = mutableMapOf("/s1" to listOf("/s1/e1"), "/s2" to listOf("/s2/e1"))79        val db = InMemoryYokanDatabase(seedDatabaseSnapshot().copy(80            sources = listOf(dbSource),81            mangas = listOf(DbManga(id = 1, name = "Show", link = "/show", itemType = DbItemType.Anime, source = "Source", sourceId = 5, favorite = true)),82        ))83        val updater = DefaultLibraryUpdaterService(db, FakeRuntimes { url ->84            if (url == "/show") RemoteDetail("Show", url, seasons = listOf(RemoteManga("S1", "/s1", seasonNumber = 1.0), RemoteManga("S2", "/s2", seasonNumber = 2.0)))85            else RemoteDetail(url, url, chapters = episodes.getValue(url).map { RemoteChapter(it, it) })86        })87        assertEquals(1, updater.updateLibrary(DbItemType.Anime).updated)88        assertEquals(DbFetchType.Seasons, db.manga(1)!!.fetchType)89        val seasons = db.mangas().filter { it.parentId == 1L }.associateBy { it.link }90        assertTrue(db.chapters(1).isEmpty())91        assertEquals(listOf("/s2/e1"), db.chapters(seasons.getValue("/s2").id).map { it.url })92        val firstRun = db.updates().size93        episodes["/s2"] = listOf("/s2/e1", "/s2/e2")94        updater.updateLibrary(DbItemType.Anime)95        val added = db.updates().drop(firstRun).single()96        assertEquals(seasons.getValue("/s2").id, added.mangaId)97        assertEquals("/s2/e2", db.chapter(added.chapterId!!)!!.url)98        assertEquals(2, db.mangas().count { it.parentId == 1L })99    }100101    @Test fun backupsRemapSeasonParentsAndOlderPayloadsDefaultToEpisodeTitles() {102        val show = DbManga(id = 100, name = "Show", link = "/show", itemType = DbItemType.Anime, favorite = true, fetchType = DbFetchType.Seasons)103        val season = DbManga(id = 101, name = "S1", link = "/s1", itemType = DbItemType.Anime, parentId = 100, seasonNumber = 1.0)104        val payload = BackupJson.decodeFromString(BackupSnapshot.serializer(),105            BackupJson.encodeToString(BackupSnapshot.serializer(), BackupSnapshot(createdAtMillis = 1, mangas = listOf(show, season))))106        val current = emptySnapshot().copy(mangas = listOf(DbManga(id = 100, name = "Other", link = "/other", itemType = DbItemType.Anime)))107        val merged = BackupMerge.merge(current, payload, setOf(BackupSection.Anime)).mangas108        val mergedShow = merged.single { it.link == "/show" }109        val mergedSeason = merged.single { it.link == "/s1" }110        assertNotEquals(100L, mergedShow.id)111        assertEquals(mergedShow.id, mergedSeason.parentId)112        assertEquals(DbFetchType.Seasons, mergedShow.fetchType)113        assertFalse(mergedSeason.favorite)114        assertEquals(1.0, mergedSeason.seasonNumber)115        val restored = SyncPaths.json.decodeFromJsonElement(DbManga.serializer(),116            SyncPaths.fromDoc(SyncPaths.KIND_MANGA, SyncPaths.doc(SyncPaths.KIND_MANGA, DbManga.serializer(), season)))117        assertEquals(Triple(100L, DbFetchType.Episodes, 1.0), Triple(restored.parentId, restored.fetchType, restored.seasonNumber))118        val legacy = BackupJson.decodeFromString(DbManga.serializer(), """{"id":3,"name":"Old","itemType":"Anime"}""")119        assertEquals(DbFetchType.Episodes, legacy.fetchType)120        assertNull(legacy.parentId)121        val exported = BackupJson.parseToJsonElement(MangayomiBackupCodec.encode(payload)).jsonObject.getValue("manga").jsonArray122        assertTrue(exported.none { "parentId" in it.jsonObject || "fetchType" in it.jsonObject || "seasonNumber" in it.jsonObject })123    }124125    private class FakeRuntimes(private val detail: (String) -> RemoteDetail) : ExtensionRuntimeFactory {126        override fun create(source: DbSource): ExtensionRuntimeService = object : ExtensionRuntimeService by DatabaseFallbackRuntimeService(source, InMemoryYokanDatabase()) {127            override suspend fun detail(url: String) = detail.invoke(url)128        }129    }130}131

Search chapters, reference and source filenames.