SplitPageStoreTest.kt
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/download/SplitPageStoreTest.kt
1package eu.friedcutlet.yokan.services.download23import eu.friedcutlet.yokan.services.files.LocalEntry4import eu.friedcutlet.yokan.services.files.LocalFileEntry5import eu.friedcutlet.yokan.services.files.LocalFileService6import kotlinx.coroutines.CancellationException7import kotlinx.coroutines.test.runTest8import kotlin.test.*910class SplitPageStoreTest {11 @Test fun regionsCoverEveryPixelInOrderWithoutExceedingLimits() {12 assertEquals(listOf(TallImageRegion(0, 4096), TallImageRegion(4096, 4096), TallImageRegion(8192, 809)), tallImageRegions(800, 9001, 4096))13 assertTrue(tallImageRegions(800, 1024, 4096).isEmpty())14 assertTrue(tallImageRegions(4000, 7000, 4096).isEmpty())15 assertTrue(tallImageRegions(Int.MAX_VALUE, Int.MAX_VALUE, 4096).isEmpty())16 assertTrue(tallImageRegions(1000, 24001, 4096).isEmpty())17 assertEquals(1024, tallImageRegions(400, 3000, -1).first().height)18 }1920 @Test fun committedTilesResumeWithoutFetchingOrDecodingOriginal() = runTest {21 val files = Files().withOriginal()22 var decodes = 023 val store = SplitPageStore(files) { _, _, tile ->24 decodes++25 tile(0, byteArrayOf(1, 2))26 tile(1, byteArrayOf(3, 4, 5))27 true28 }29 assertEquals(5L, store.process("/chapter/0001.jpg", 4096))30 assertFalse(files.exists("/chapter/0001.jpg"))31 assertFalse(files.exists("/chapter/0001.jpg.complete"))32 assertEquals(listOf("0001.split.json", "0001_s0001.jpg", "0001_s0002.jpg"), files.listFiles("/chapter").map { it.name }.sorted())33 assertEquals(5L, SplitPageStore(files).savedSize("/chapter", "0001"))34 assertEquals(1, decodes)35 }3637 @Test fun failedDecodeCleansTilesAndKeepsOriginal() = runTest {38 val files = Files().withOriginal()39 val store = SplitPageStore(files) { _, _, tile ->40 tile(0, byteArrayOf(1))41 error("bad codec")42 }43 assertEquals(3L, store.process("/chapter/0001.jpg", 4096))44 assertEquals(setOf("/chapter/0001.jpg", "/chapter/0001.jpg.complete"), files.data.keys)45 assertContentEquals(byteArrayOf(9, 8, 7), files.readBytes("/chapter/0001.jpg"))46 }4748 @Test fun cancelledSplitRetainsOriginalAndOrphansAreReplacedOnRetry() = runTest {49 val files = Files().withOriginal()50 val cancelled = SplitPageStore(files) { _, _, tile ->51 tile(0, byteArrayOf(1))52 throw CancellationException("pause")53 }54 assertFailsWith<CancellationException> { cancelled.process("/chapter/0001.jpg", 4096) }55 assertTrue(files.exists("/chapter/0001.jpg.complete"))56 val retry = SplitPageStore(files) { _, _, tile ->57 tile(0, byteArrayOf(4, 5))58 tile(1, byteArrayOf(6))59 true60 }61 assertEquals(3L, retry.process("/chapter/0001.jpg", 4096))62 assertContentEquals(byteArrayOf(4, 5), files.readBytes("/chapter/0001_s0001.jpg"))63 }6465 @Test fun promotionFailureKeepsOriginalAndNeverCommitsPartialManifest() = runTest {66 val files = Files().withOriginal().apply { failedPromotionSuffix = "_s0002.jpg" }67 val store = SplitPageStore(files) { _, _, tile -> tile(0, byteArrayOf(1)); tile(1, byteArrayOf(2)); true }68 assertEquals(3L, store.process("/chapter/0001.jpg", 4096))69 assertFalse(files.exists("/chapter/0001.split.json"))70 assertEquals(2, files.data.size)71 }7273 @Test fun manifestCommitFailureCanBeRetriedWithoutLosingOriginal() = runTest {74 val files = Files().withOriginal().apply { failedPromotionSuffix = ".split.json" }75 val store = SplitPageStore(files) { _, _, tile -> tile(0, byteArrayOf(1)); tile(1, byteArrayOf(2)); true }76 assertFailsWith<IllegalStateException> { store.process("/chapter/0001.jpg", 4096) }77 assertNull(store.savedSize("/chapter", "0001"))78 assertTrue(files.exists("/chapter/0001.jpg"))79 files.failedPromotionSuffix = null80 assertEquals(2L, store.process("/chapter/0001.jpg", 4096))81 }8283 @Test fun committedManifestFinishesOriginalDeletionAfterCrash() = runTest {84 val files = Files().withOriginal().apply { refuseOriginalDeletion = true }85 val store = SplitPageStore(files) { _, _, tile -> tile(0, byteArrayOf(1)); tile(1, byteArrayOf(2)); true }86 assertFailsWith<IllegalStateException> { store.process("/chapter/0001.jpg", 4096) }87 assertTrue(files.exists("/chapter/0001.split.json"))88 files.refuseOriginalDeletion = false89 assertEquals(2L, SplitPageStore(files).savedSize("/chapter", "0001"))90 assertFalse(files.exists("/chapter/0001.jpg"))91 }9293 @Test fun corruptMissingOrTruncatedTilesNeverCountAsSaved() = runTest {94 val files = Files().withOriginal()95 val store = SplitPageStore(files) { _, _, tile -> tile(0, byteArrayOf(1)); tile(1, byteArrayOf(2, 3)); true }96 store.process("/chapter/0001.jpg", 4096)97 files.writeBytes("/chapter/0001_s0002.jpg", byteArrayOf(2))98 assertNull(store.savedSize("/chapter", "0001"))99 files.writeBytes("/chapter/0001.split.json", "{\"version\":1,\"original\":\"../other.jpg\",\"sizes\":[1,1]}".encodeToByteArray())100 assertNull(store.savedSize("/chapter", "0001"))101 }102103 @Test fun animationsAndOversizedEncodedImagesBypassDecoder() = runTest {104 val files = Files()105 val store = SplitPageStore(files) { _, _, _ -> error("must not decode") }106 files.writeBytes("/chapter/0001.gif", "GIF89a".encodeToByteArray())107 assertEquals(6L, store.process("/chapter/0001.gif", 4096))108 files.reportedSize = MaxSplitImageBytes + 1109 assertEquals(MaxSplitImageBytes + 1, store.process("/chapter/0001.gif", 4096))110 }111112 @Test fun webpAndPngAnimationHeadersAreDetected() {113 val webp = ByteArray(21)114 "RIFF".encodeToByteArray().copyInto(webp)115 "WEBPVP8X".encodeToByteArray().copyInto(webp, 8)116 webp[20] = 2117 assertTrue(webp.mayBeAnimatedImage())118 webp[20] = 0119 assertFalse(webp.mayBeAnimatedImage())120 val apng = byteArrayOf(0x89.toByte(), 80, 78, 71, 13, 10, 26, 10) + ByteArray(4) + "acTL".encodeToByteArray() + ByteArray(4)121 assertTrue(apng.mayBeAnimatedImage())122 }123124 private class Files : LocalFileService {125 val data = linkedMapOf<String, ByteArray>()126 var failedPromotionSuffix: String? = null127 var refuseOriginalDeletion = false128 var reportedSize: Long? = null129 override val downloadRoot = "/downloads"130 override val backupRoot = "/backups"131 override val cacheRoot = "/cache"132 fun withOriginal() = apply { writeBytes("/chapter/0001.jpg", byteArrayOf(9, 8, 7)); writeBytes("/chapter/0001.jpg.complete", ByteArray(0)) }133 override fun writeBytes(path: String, bytes: ByteArray) { data[path] = bytes.copyOf() }134 override fun readBytes(path: String) = requireNotNull(data[path]).copyOf()135 override fun exists(path: String) = path in data136 override fun promote(sourcePath: String, targetPath: String): Boolean {137 if (failedPromotionSuffix?.let(targetPath::endsWith) == true) return false138 data[targetPath] = data.remove(sourcePath) ?: return false139 return true140 }141 override fun deleteRecursively(path: String): Boolean {142 if (refuseOriginalDeletion && path.endsWith("/0001.jpg")) return false143 data.remove(path)144 return true145 }146 override fun directorySize(path: String) = reportedSize ?: data[path]?.size?.toLong() ?: 0L147 override fun canonicalPath(path: String) = path148 override fun openLocation(path: String) = false149 override fun listLocalEntries(root: String) = emptyList<LocalEntry>()150 override fun listFiles(root: String) = data.entries.filter { it.key.substringBeforeLast('/') == root }151 .map { LocalFileEntry(it.key, it.key.substringAfterLast('/'), it.value.size.toLong(), 0L) }152 }153}154