Yokan / rebuild
Course 1 8624561

LocalAnimeDetailsTest.kt

composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/library/LocalAnimeDetailsTest.kt

test / fixture163 lines
1package eu.friedcutlet.yokan.services.library23import eu.friedcutlet.yokan.database.*4import eu.friedcutlet.yokan.services.files.*5import kotlinx.coroutines.CancellationException6import kotlinx.coroutines.CompletableDeferred7import kotlinx.coroutines.async8import kotlinx.coroutines.test.runTest9import kotlin.test.*1011class LocalAnimeDetailsTest {12    @Test fun castImagesStayWithinTheTitleAndMissingOrInvalidCastPreservesExistingCredits() = runTest {13        val files = AnimeDetailsFiles().apply {14            details = """{"cast":[{"name":"Actor","role":"Voice actor","character":"Hero","image_url":"actor.png"},{"name":"Other","image_url":"../private.png"}]}"""15            extraFiles["/anime/Show/actor.png"] = byteArrayOf(1, 2)16        }17        val db = files.database()18        val scanner = DefaultLocalLibraryService(db, files, NoArchives)19        scanner.scan()20        val title = db.mangas().single()21        assertEquals("file:///anime/Show/actor.png", title.cast[0].imageUrl)22        assertNull(title.cast[1].imageUrl)23        assertNull(title.customCoverImage, "A referenced portrait must not become the title cover")24        assertFalse(files.reads.any { it.endsWith("actor.png") || "private.png" in it })25        val original = db.chapters(title.id).single()26        for (text in listOf("{}", """{"cast":{}}""", """{"cast":[{"name":3}]}""")) {27            files.details = text; files.version++; scanner.scan()28            assertEquals(title.cast, db.manga(title.id)?.cast)29        }30        files.details = """{"cast":[{"name":"Changed actor"}]}"""; files.version++31        val entered = CompletableDeferred<Unit>()32        val release = CompletableDeferred<Unit>()33        files.beforeDetails = { entered.complete(Unit); release.await() }34        val work = async { scanner.scan() }35        entered.await()36        db.upsertManga(title.copy(privateNote = "Concurrent note", favorite = true))37        db.upsertChapter(original.copy(isRead = true, isBookmarked = true, lastPageRead = "1234"))38        release.complete(Unit); work.await()39        assertEquals("Changed actor", db.manga(title.id)?.cast?.single()?.name)40        assertEquals("Concurrent note", db.manga(title.id)?.privateNote)41        assertEquals("1234", db.chapter(original.id)?.lastPageRead)42        files.beforeDetails = {}; files.details = """{"cast":[]}"""; files.version++43        scanner.scan()44        assertEquals(emptyList(), db.manga(title.id)?.cast)45    }4647    @Test fun detailsOverrideDeclaredFieldsAndKeepLegacyArtworkLanguageAndProgress() = runTest {48        val files = AnimeDetailsFiles()49        val db = files.database()50        val scanner = DefaultLocalLibraryService(db, files, NoArchives)51        scanner.scan()52        val initial = db.mangas().single()53        val chapter = db.chapters(initial.id).single()54        assertEquals("File title", initial.name)55        assertEquals("File description", initial.description)56        assertEquals("Author", initial.author)57        assertEquals("Artist", initial.artist)58        assertEquals(listOf("Action"), initial.genre)59        assertEquals(DbStatus.Completed, initial.status)60        assertEquals("https://cover.test/image", initial.imageUrl)61        assertEquals("ja", initial.lang)62        db.upsertManga(initial.copy(favorite = true, categories = listOf(8), privateNote = "Private"))63        db.upsertChapter(chapter.copy(isRead = true, isBookmarked = true, lastPageRead = "1200"))64        val count = files.reads.size65        scanner.scan()66        assertEquals(count, files.reads.size)67        files.details = """{"title":"Renamed","genre":[],"status":4}"""68        files.version++69        scanner.scan()70        val updated = assertNotNull(db.manga(initial.id))71        assertEquals("Renamed", updated.name)72        assertEquals(emptyList(), updated.genre)73        assertEquals(DbStatus.PublishingFinished, updated.status)74        assertTrue(updated.favorite)75        assertEquals(listOf(8L), updated.categories)76        assertEquals("Private", updated.privateNote)77        val current = assertNotNull(db.chapter(chapter.id))78        assertTrue(current.isRead && current.isBookmarked)79        assertEquals("1200", current.lastPageRead)80        assertTrue(files.bounds.all { it == 65536L })81    }8283    @Test fun animetailNumericStatusesDoNotUseLegacyEnumOrdinals() = runTest {84        val files = AnimeDetailsFiles()85        val db = files.database()86        val scanner = DefaultLocalLibraryService(db, files, NoArchives)87        val expected = listOf(DbStatus.Unknown, DbStatus.Ongoing, DbStatus.Completed, DbStatus.Licensed,88            DbStatus.PublishingFinished, DbStatus.Canceled, DbStatus.OnHiatus, DbStatus.Upcoming)89        expected.forEachIndexed { value, status ->90            files.details = "{\"status\":$value}"; files.version++91            scanner.scan()92            assertEquals(status, db.mangas().single().status, "Animetail status $value")93        }94    }9596    @Test fun malformedDetailsFallBackAndSuspendingReadsPreserveConcurrentUserEdits() = runTest {97        val files = AnimeDetailsFiles().apply { details = "not JSON" }98        val db = files.database()99        val scanner = DefaultLocalLibraryService(db, files, NoArchives)100        scanner.scan()101        val title = db.mangas().single()102        assertEquals("Legacy", title.name)103        assertEquals(DbStatus.Ongoing, title.status)104        files.details = """{"title":"Updated"}"""; files.version++105        val entered = CompletableDeferred<Unit>()106        val release = CompletableDeferred<Unit>()107        files.beforeDetails = { entered.complete(Unit); release.await() }108        val scan = async { scanner.scan() }109        entered.await()110        db.upsertManga(title.copy(privateNote = "Edited during read", favorite = true))111        release.complete(Unit); scan.await()112        assertEquals("Edited during read", db.manga(title.id)?.privateNote)113        assertEquals(true, db.manga(title.id)?.favorite)114        files.version++115        files.beforeDetails = { throw CancellationException("Retired") }116        assertFailsWith<CancellationException> { scanner.scan() }117        assertEquals(1, db.mangas().size)118    }119}120121internal class AnimeDetailsFiles : LocalFileService {122    override val downloadRoot = "/downloads"123    override val backupRoot = "/backups"124    override val cacheRoot = "/cache"125    var version = 1L126    var details = """{"title":"File title","description":"File description","author":"Author","artist":"Artist","genre":["Action"],"status":2}"""127    var beforeDetails: suspend () -> Unit = {}128    var episodes: String? = null129    var beforeEpisodes: suspend () -> Unit = {}130    val extraFiles = mutableMapOf<String, ByteArray>()131    val reads = mutableListOf<String>()132    val bounds = mutableListOf<Long>()133    fun database() = InMemoryYokanDatabase(emptySnapshot().copy(settings = DbSettings(namedLocalFolders = listOf(DbLocalFolder("Anime", "/anime")))))134    override fun writeBytes(path: String, bytes: ByteArray) = error("Read-only")135    override fun readBytes(path: String): ByteArray = error("Use async reads")136    override suspend fun readBytesAsync(path: String, maxBytes: Long): ByteArray {137        reads += path; bounds += maxBytes138        if (path.endsWith("details.json")) beforeDetails()139        if (path.endsWith("episodes.json")) beforeEpisodes()140        extraFiles[path]?.let { return it.also { require(it.size <= maxBytes) } }141        val text = if (path.endsWith("details.json")) details else if (path.endsWith("episodes.json")) requireNotNull(episodes)142            else """{"name":"Legacy","status":0,"imageUrl":"https://cover.test/image","language":"ja"}"""143        return text.encodeToByteArray().also { require(it.size <= maxBytes) }144    }145    override fun canonicalPath(path: String) = path146    override fun exists(path: String) = path in extraFiles || (path == "/anime/Show/episodes.json" && episodes != null) ||147        path in setOf("/anime", "/anime/Show", "/anime/Show/metadata.json", "/anime/Show/details.json")148    override fun deleteRecursively(path: String) = false149    override fun directorySize(path: String) = 0L150    override fun openLocation(path: String) = false151    override fun listFiles(root: String) = if (root == "/anime/Show") listOf(152        LocalFileEntry("$root/metadata.json", "metadata.json", 100, version),153        LocalFileEntry("$root/details.json", "details.json", details.length.toLong(), version),154    ) + listOfNotNull(episodes?.let { LocalFileEntry("$root/episodes.json", "episodes.json", it.length.toLong(), version) }) +155        extraFiles.map { (path, bytes) -> LocalFileEntry(path, path.substringAfterLast('/'), bytes.size.toLong(), version) }156        else emptyList()157    override fun listLocalEntries(root: String): List<LocalEntry>? = when (root) {158        "/anime" -> listOf(LocalEntry("/anime/Show", "Show", false))159        "/anime/Show" -> listOf(LocalEntry("/anime/Show/Episode 1.mp4", "Episode 1", true)) +160            extraFiles.keys.map { LocalEntry(it, it.substringAfterLast('/').substringBeforeLast('.'), true) }161        else -> emptyList()162    }163}164

Search chapters, reference and source filenames.