AndroidSafLocalArchiveServiceTest.kt
composeApp/src/androidHostTest/kotlin/eu/friedcutlet/yokan/services/files/AndroidSafLocalArchiveServiceTest.kt
1package eu.friedcutlet.yokan.services.files23import java.io.ByteArrayInputStream4import java.io.ByteArrayOutputStream5import java.io.File6import java.net.URI7import java.util.zip.ZipEntry8import java.util.zip.ZipOutputStream9import kotlin.test.Test10import kotlin.test.assertEquals11import kotlin.test.assertFalse12import kotlin.test.assertTrue1314class AndroidSafLocalArchiveServiceTest {15 @Test16 fun fullRescanRefreshesStagedBooksWithoutProviderTimestamps() {17 val root = testDirectory()18 var title = "before"19 var opens = 020 val book = "content://test/document/book.epub"21 try {22 val service = AndroidSafLocalArchiveService(root.absolutePath, contentStreamOpener = {23 opens++24 ByteArrayInputStream(epub(title))25 })26 assertEquals("before", service.listEpubChapters(book).single().title)27 title = "after"28 assertEquals("before", service.listEpubChapters(book).single().title)29 assertEquals(1, opens)30 service.invalidateIndexCache()31 assertEquals("after", service.listEpubChapters(book).single().title)32 assertEquals(2, opens)33 } finally {34 root.deleteRecursively()35 }36 }3738 @Test39 fun stagesEachDocumentOnceAndReusesTheCopy() {40 val root = testDirectory()41 val book = "content://test/document/book.epub"42 var opens = 043 try {44 val service = AndroidSafLocalArchiveService(45 cacheRoot = root.absolutePath,46 contentStreamOpener = { uri ->47 opens++48 ByteArrayInputStream(epub(uri.substringAfterLast('/')))49 },50 )5152 assertEquals("book.epub", service.listEpubChapters(book).single().title)53 assertTrue(service.readEpubChapter(book, 0).contains("book.epub"))54 assertTrue(service.readEpubResource(book, "chapter.xhtml") != null)5556 assertEquals(1, opens)57 assertEquals(1, stagedCopies(root).size)58 } finally {59 root.deleteRecursively()60 }61 }6263 @Test64 fun keepsOnlyTheMostRecentlyUsedStagedCopies() {65 val root = testDirectory()66 val books = listOf("a", "b", "c", "d").associateWith { epub(it) }67 val opens = mutableListOf<String>()68 fun uri(book: String) = "content://test/document/$book"69 try {70 val service = AndroidSafLocalArchiveService(71 cacheRoot = root.absolutePath,72 contentStreamOpener = { uri ->73 val book = uri.substringAfterLast('/')74 opens += book75 books[book]?.let(::ByteArrayInputStream)76 },77 )78 listOf("a", "b", "c").forEach { assertTrue(service.readEpubResource(uri(it), "chapter.xhtml") != null) }79 // Pin the LRU order explicitly: filesystem mtimes can tie within one test.80 stagedCopies(root).forEach { copy ->81 val book = books.entries.first { it.value.contentEquals(copy.readBytes()) }.key82 copy.setLastModified(1_000L * (1 + "abc".indexOf(book)))83 }8485 assertTrue(service.readEpubResource(uri("a"), "chapter.xhtml") != null) // reuse marks a as used86 assertTrue(service.readEpubResource(uri("d"), "chapter.xhtml") != null) // evicts b, the oldest87 val remaining = stagedCopies(root).map { copy -> books.entries.first { it.value.contentEquals(copy.readBytes()) }.key }88 assertEquals(setOf("a", "c", "d"), remaining.toSet())8990 assertTrue(service.readEpubResource(uri("b"), "chapter.xhtml") != null)91 assertEquals(listOf("a", "b", "c", "d", "b"), opens)92 } finally {93 root.deleteRecursively()94 }95 }9697 @Test98 fun providerFailureReturnsNullAndDoesNotLeaveAStagedFile() {99 val root = testDirectory()100 try {101 val service = AndroidSafLocalArchiveService(102 cacheRoot = root.absolutePath,103 contentStreamOpener = { error("provider unavailable") },104 )105106 assertEquals(null, service.readEpubResource("content://test/document/book.epub", "chapter.xhtml"))107 assertTrue(stagedCopies(root).isEmpty())108 } finally {109 root.deleteRecursively()110 }111 }112113 @Test114 fun treeChildUrisStageTheChildArchiveInsteadOfTheTreeRoot() {115 val root = testDirectory()116 val requestedUris = mutableListOf<String>()117 // The Android SDK's DocumentsContract builders are not implemented in JVM tests.118 // Keep the SAF-shaped fixture literal; the service still receives document URIs.119 val rootEpub = "content://test/tree/root/document/root.epub"120 val childEpub = "content://test/tree/root/document/child.epub"121 val rootCbz = "content://test/tree/root/document/root.cbz"122 val childCbz = "content://test/tree/root/document/child.cbz"123 val streams = mapOf(124 rootEpub to epub("root"),125 childEpub to epub("child"),126 rootCbz to cbz("root"),127 childCbz to cbz("child"),128 )129 try {130 val service = AndroidSafLocalArchiveService(131 cacheRoot = root.absolutePath,132 contentStreamOpener = { uri ->133 requestedUris += uri134 streams[uri]?.let(::ByteArrayInputStream)135 },136 )137138 assertEquals("child", service.listEpubChapters(childEpub).single().title)139 val pages = service.listPages(childCbz)140 assertEquals(1, pages.size)141 assertEquals("child", File(URI(pages.single().url)).readText())142 assertTrue(childEpub in requestedUris)143 assertTrue(childCbz in requestedUris)144 assertTrue(rootEpub !in requestedUris)145 assertTrue(rootCbz !in requestedUris)146 } finally {147 root.deleteRecursively()148 }149 }150151 private fun epub(title: String): ByteArray = zipOf(152 "META-INF/container.xml" to """153 <?xml version="1.0"?>154 <container><rootfiles><rootfile full-path="content.opf"/></rootfiles></container>155 """.trimIndent(),156 "content.opf" to """157 <package><manifest><item id="chapter" href="chapter.xhtml"/></manifest>158 <spine><itemref idref="chapter"/></spine></package>159 """.trimIndent(),160 "chapter.xhtml" to "<html><head><title>$title</title></head><body>$title</body></html>",161 )162163 private fun cbz(page: String): ByteArray = zipOf("$page.jpg" to page)164165 private fun zipOf(vararg entries: Pair<String, String>): ByteArray =166 ByteArrayOutputStream().also { bytes ->167 ZipOutputStream(bytes).use { zip ->168 entries.forEach { (name, content) ->169 zip.putNextEntry(ZipEntry(name))170 zip.write(content.encodeToByteArray())171 zip.closeEntry()172 }173 }174 }.toByteArray()175176 private fun stagedCopies(root: File): List<File> = File(root, "archive-staging").listFiles().orEmpty().toList()177178 private fun testDirectory(): File =179 File(System.getProperty("java.io.tmpdir"), "yokan-archive-test-${System.nanoTime()}").also { it.mkdirs() }180}181