NovelContentOwnershipTest.kt
composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/ui/screens/novel/NovelContentOwnershipTest.kt
1@file:OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class, androidx.compose.ui.ExperimentalComposeUiApi::class)23package eu.friedcutlet.yokan.ui.screens.novel45import androidx.compose.runtime.CompositionLocalProvider6import androidx.compose.runtime.SideEffect7import androidx.compose.runtime.mutableStateOf8import androidx.compose.ui.ImageComposeScene9import androidx.compose.ui.text.LinkAnnotation10import androidx.lifecycle.Lifecycle11import androidx.lifecycle.LifecycleOwner12import androidx.lifecycle.LifecycleRegistry13import androidx.lifecycle.compose.LocalLifecycleOwner14import eu.friedcutlet.yokan.domain.Chapter15import eu.friedcutlet.yokan.services.extensions.ProfileReaderContentTest16import java.util.concurrent.CountDownLatch17import java.util.concurrent.FutureTask18import java.util.concurrent.TimeUnit19import javax.swing.SwingUtilities20import kotlin.test.Test21import kotlin.test.assertEquals22import kotlin.test.assertFailsWith23import kotlin.test.assertFalse24import kotlin.test.assertIs25import kotlin.test.assertNotSame26import kotlin.test.assertTrue27import kotlinx.coroutines.CancellationException28import kotlinx.coroutines.CompletableDeferred29import kotlinx.coroutines.Dispatchers30import kotlinx.coroutines.async31import kotlinx.coroutines.cancelAndJoin32import kotlinx.coroutines.test.TestScope33import kotlinx.coroutines.test.UnconfinedTestDispatcher34import kotlinx.coroutines.test.runCurrent35import kotlinx.coroutines.test.runTest3637class NovelContentOwnershipTest {38 @Test fun disposedParsedLinkCannotNavigateAndRemountGetsANewLink() = runTest {39 val f = UiFixture(this)40 try {41 f.click(f.link)42 assertEquals(listOf("A"), f.opened)43 val old = f.link44 f.show(false)45 f.click(old)46 assertEquals(listOf("A"), f.opened)47 assertTrue(f.a.owner.isActive)48 f.show(true)49 assertNotSame(old, f.link)50 f.click(old); f.click(f.link)51 assertEquals(listOf("A", "A"), f.opened)52 } finally { f.finish() }53 }5455 @Test fun chapterReplacementRejectsThePreviousChaptersLink() = runTest {56 val f = UiFixture(this)57 try {58 val old = f.link59 f.ui { f.chapter.value = 11 }; f.pump()60 f.click(old); f.click(f.link)61 assertEquals(listOf("A"), f.opened)62 } finally { f.finish() }63 }6465 @Test fun ownerReplacementWithTheSameChapterCannotRetargetARetainedLink() = runTest {66 val f = UiFixture(this)67 try {68 val old = f.link69 f.ui { f.content.value = f.b.content; f.target.value = "B" }; f.pump()70 f.click(old); f.click(f.link)71 assertEquals(listOf("B"), f.opened)72 assertTrue(f.a.owner.isActive)73 assertTrue(f.b.owner.isActive)74 } finally { f.finish() }75 }7677 @Test fun backgroundLifecycleRejectsLinksImmediatelyAndResumePreservesCurrentContent() = runTest {78 val f = UiFixture(this)79 try {80 val current = f.link81 f.ui { f.registry.currentState = Lifecycle.State.CREATED }82 // No recomposition frame: the click checks the actual lifecycle.83 f.click(current); assertTrue(f.opened.isEmpty())84 f.ui { f.registry.currentState = Lifecycle.State.RESUMED }85 f.click(current); assertEquals(listOf("A"), f.opened)86 } finally { f.finish() }87 }8889 @Test fun replacingTheLifecycleOwnerExpiresPreviousLinksAndPublishesCurrentLinks() = runTest {90 val f = UiFixture(this)91 try {92 val old = f.link93 val replacement = object : LifecycleOwner {94 override val lifecycle = LifecycleRegistry.createUnsafe(this)95 }96 f.ui {97 replacement.lifecycle.currentState = Lifecycle.State.RESUMED98 f.currentLifecycle.value = replacement99 }100 f.pump()101 f.click(old); f.click(f.link)102 assertEquals(listOf("A"), f.opened)103 } finally { f.finish() }104 }105106 @Test fun retirementAdmissionRejectsLinksBeforeJobCancellationAndSameScreenUsesLatestAction() = runTest {107 val f = UiFixture(this)108 try {109 val current = f.link110 f.ui { f.target.value = "latest" }; f.pump()111 f.click(current)112 assertEquals(listOf("latest"), f.opened)113 f.a.open = false114 f.click(current)115 assertEquals(listOf("latest"), f.opened)116 assertTrue(f.a.owner.isActive)117 } finally { f.finish() }118 }119120 @Test fun callerCancellationJoinsABlockedLocalReadWithoutDeliveringParsedContent() = runTest {121 blockedReadIsJoined(retireOwner = false)122 }123124 @Test fun ownerRetirementJoinsABlockedLocalReadWithoutDeliveringParsedContent() = runTest {125 blockedReadIsJoined(retireOwner = true)126 }127128 private suspend fun TestScope.blockedReadIsJoined(retireOwner: Boolean) {129 val f = ProfileReaderContentTest.Fixture(this, fileDispatcher = Dispatchers.Default)130 val entered = CompletableDeferred<Unit>()131 val release = CountDownLatch(1)132 var parsed = false133 f.beforeEpubChapterRead = {134 entered.complete(Unit)135 check(release.await(10, TimeUnit.SECONDS)) { "Blocked archive read was not released" }136 }137 val chapter = Chapter(10, 1, "Local", "/chapter", archivePath = "/A/book.epub#0")138 val request = async { f.content.novelContent(f.source, "Book", chapter) { parsed = true } }139 try {140 entered.await()141 val retiring = if (retireOwner) async { f.owner.cancelAndJoin() } else null142 if (!retireOwner) request.cancel()143 runCurrent()144 assertFalse(request.isCompleted, "extraction is still reading the captured archive")145 if (retiring != null) assertFalse(retiring.isCompleted, "retirement joins the blocking file read")146 release.countDown()147 if (retireOwner) {148 retiring?.await()149 assertFailsWith<CancellationException> { request.await() }150 } else request.join()151 assertFalse(parsed)152 assertTrue(f.epubResourceReads.isEmpty())153 assertEquals(!retireOwner, f.owner.isActive)154 } finally { release.countDown(); request.cancelAndJoin(); f.close() }155 }156157 private class UiFixture(val test: TestScope) {158 val a = ProfileReaderContentTest.Fixture(test, "A")159 val b = ProfileReaderContentTest.Fixture(test, "B")160 val content = mutableStateOf(a.content)161 val chapter = mutableStateOf(10L)162 val visible = mutableStateOf(true)163 val target = mutableStateOf("A")164 val opened = mutableListOf<String>()165 lateinit var link: LinkAnnotation.Url166 val lifecycleOwner = object : LifecycleOwner {167 override val lifecycle = LifecycleRegistry.createUnsafe(this)168 }169 val registry = lifecycleOwner.lifecycle as LifecycleRegistry170 val currentLifecycle = mutableStateOf<LifecycleOwner>(lifecycleOwner)171 val scene = ui {172 registry.currentState = Lifecycle.State.RESUMED173 ImageComposeScene(100, 100, coroutineContext = UnconfinedTestDispatcher(test.testScheduler)) {174 CompositionLocalProvider(LocalLifecycleOwner provides currentLifecycle.value) {175 if (visible.value) {176 val currentTarget = target.value177 val open = rememberNovelOpenLink(content.value, chapter.value) { opened += currentTarget }178 val parsed = parseNovelRichContent("<p><a href='https://book.test/next'>Next</a></p>", onOpenLink = open)179 val text = assertIs<NovelContentBlock.Text>(parsed.blocks.single()).text180 val annotation = assertIs<LinkAnnotation.Url>(text.getLinkAnnotations(0, text.length).single().item)181 SideEffect { link = annotation }182 }183 }184 }185 }186 init { pump() }187 fun click(annotation: LinkAnnotation.Url) = ui { annotation.linkInteractionListener?.onClick(annotation) }188 fun show(value: Boolean) { ui { visible.value = value }; pump() }189 fun pump() = ui { repeat(3) {190 test.testScheduler.runCurrent()191 scene.render(test.testScheduler.currentTime * 1_000_000).close()192 test.testScheduler.runCurrent()193 } }194 fun <T> ui(block: () -> T): T = onUi(block)195 suspend fun finish() { ui { scene.close() }; a.close(); b.close() }196 }197198 private companion object {199 fun <T> onUi(block: () -> T): T {200 if (SwingUtilities.isEventDispatchThread()) return block()201 val task = FutureTask(block)202 SwingUtilities.invokeAndWait(task)203 return task.get()204 }205 }206}207