ProfileImageHttpClientTest.kt
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/image/ProfileImageHttpClientTest.kt
1@file:OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class, io.ktor.utils.io.InternalAPI::class)23package eu.friedcutlet.yokan.ui.image45import eu.friedcutlet.yokan.domain.ProfileId6import eu.friedcutlet.yokan.database.InMemoryYokanDatabase7import eu.friedcutlet.yokan.database.emptySnapshot8import eu.friedcutlet.yokan.services.http.ProfileTestEngine9import eu.friedcutlet.yokan.services.http.cookies.CookieJar10import io.ktor.client.engine.callContext11import io.ktor.client.request.HttpResponseData12import io.ktor.client.request.get13import io.ktor.client.request.header14import io.ktor.client.statement.bodyAsText15import io.ktor.http.Headers16import io.ktor.http.HttpProtocolVersion17import io.ktor.http.HttpStatusCode18import io.ktor.util.date.GMTDate19import io.ktor.utils.io.ByteReadChannel20import kotlinx.coroutines.CancellationException21import kotlinx.coroutines.CompletableDeferred22import kotlinx.coroutines.CoroutineScope23import kotlinx.coroutines.Job24import kotlinx.coroutines.NonCancellable25import kotlinx.coroutines.SupervisorJob26import kotlinx.coroutines.awaitCancellation27import kotlinx.coroutines.cancelAndJoin28import kotlinx.coroutines.launch29import kotlinx.coroutines.test.StandardTestDispatcher30import kotlinx.coroutines.test.runTest31import kotlinx.coroutines.withContext32import kotlin.test.Test33import kotlin.test.assertEquals34import kotlin.test.assertFailsWith35import kotlin.test.assertFalse36import kotlin.test.assertTrue3738class ProfileImageHttpClientTest {39 @Test fun proxyProgressHeaderNeverLeavesTheApp() = runTest {40 val parent = SupervisorJob(); val db = InMemoryYokanDatabase(emptySnapshot())41 val engine = ProfileTestEngine(StandardTestDispatcher(testScheduler)) { response() }42 val transport = ProfileImageHttpClient(CookieJar(db), db, CoroutineScope(parent + StandardTestDispatcher(testScheduler))) { engine }43 transport.client.get("https://wsrv.nl/image") { header(OriginalImageProgressHeader, "https://source.example.org/page.png") }44 assertEquals(null, engine.requests.receive().headers[OriginalImageProgressHeader])45 transport.closeAndJoin(); parent.cancelAndJoin()46 }47 @Test fun capturesJarAndSettingsWhileRetainingSourceHeadersAndSolvedUserAgent() = runTest {48 val parent = SupervisorJob(); val db = InMemoryYokanDatabase(emptySnapshot())49 db.updateSettings(db.settings().copy(userAgent = "profile-agent"))50 val jar = CookieJar(db, ProfileId.Default) { parent.isActive }51 jar.put("source.test", "session=profile")52 val engine = ProfileTestEngine(StandardTestDispatcher(testScheduler)) { response() }53 val transport = ProfileImageHttpClient(jar, db, CoroutineScope(parent + StandardTestDispatcher(testScheduler))) { engine }54 assertEquals("image", transport.client.get("https://source.test/page").bodyAsText())55 val first = engine.requests.receive()56 assertEquals("session=profile", first.headers["Cookie"]); assertEquals("profile-agent", first.headers["User-Agent"])57 transport.client.get("https://source.test/page") { header("Cookie", "source=explicit"); header("User-Agent", "source-agent") }58 val second = engine.requests.receive()59 assertEquals("source=explicit", second.headers["Cookie"]); assertEquals("source-agent", second.headers["User-Agent"])60 jar.rememberUserAgent("https://source.test/page", "solved-agent")61 transport.client.get("https://source.test/page") { header("User-Agent", "source-agent") }62 assertEquals("solved-agent", engine.requests.receive().headers["User-Agent"])63 transport.closeAndJoin(); parent.cancelAndJoin(); assertEquals(1, engine.closeCalls)64 }6566 @Test fun retirementCancelsAndJoinsEngineFinalizersBeforeDatabaseRelease() = runTest {67 val parent = SupervisorJob(); val db = InMemoryYokanDatabase(emptySnapshot())68 val release = CompletableDeferred<Unit>(); var finalized = false69 val engine = ProfileTestEngine(StandardTestDispatcher(testScheduler)) {70 try { awaitCancellation() } finally { withContext(NonCancellable) { release.await(); finalized = true } }71 }72 val transport = ProfileImageHttpClient(CookieJar(db, ProfileId.Default) { parent.isActive }, db, CoroutineScope(parent + StandardTestDispatcher(testScheduler))) { engine }73 val caller = launch { transport.client.get("https://source.test/page").bodyAsText() }74 engine.requests.receive()75 val retiring = launch { parent.cancelAndJoin() }76 testScheduler.runCurrent(); assertFalse(retiring.isCompleted)77 release.complete(Unit); retiring.join(); caller.join()78 assertTrue(finalized); assertTrue(engine.coroutineContext[Job]?.isCompleted == true)79 transport.closeAndJoin(); assertEquals(1, engine.closeCalls)80 assertFailsWith<CancellationException> { transport.client.get("https://source.test/page") }81 assertTrue(engine.requests.tryReceive().isFailure)82 }8384 @Test fun explicitTransportClosePreservesOwnerAndRejectsFurtherRequests() = runTest {85 val parent = SupervisorJob(); val db = InMemoryYokanDatabase(emptySnapshot())86 val engine = ProfileTestEngine(StandardTestDispatcher(testScheduler)) { response() }87 val transport = ProfileImageHttpClient(CookieJar(db), db, CoroutineScope(parent + StandardTestDispatcher(testScheduler))) { engine }88 transport.closeAndJoin(); transport.closeAndJoin()89 assertTrue(parent.isActive); assertEquals(1, engine.closeCalls)90 assertFailsWith<CancellationException> { transport.client.get("https://source.test/page") }91 assertTrue(engine.requests.tryReceive().isFailure); parent.cancelAndJoin()92 }9394 @Test fun expiredOwnerCannotAllocateImageTransport() = runTest {95 val parent = SupervisorJob(); val db = InMemoryYokanDatabase(emptySnapshot())96 parent.cancelAndJoin()97 assertFailsWith<CancellationException> {98 ProfileImageHttpClient(CookieJar(db), db, CoroutineScope(parent + StandardTestDispatcher(testScheduler))) { error("Expired allocation") }99 }100 }101102 @Test fun replacementClientsWithSameUrlUseTheirOwnCredentialsAndCleanup() = runTest {103 val a = SupervisorJob(); val b = SupervisorJob()104 val dbA = InMemoryYokanDatabase(emptySnapshot()); val dbB = InMemoryYokanDatabase(emptySnapshot())105 val jarA = CookieJar(dbA, ProfileId.Default) { a.isActive }; val jarB = CookieJar(dbB, ProfileId.Default) { b.isActive }106 jarA.put("source.test", "session=A"); jarB.put("source.test", "session=B")107 val engineA = ProfileTestEngine(StandardTestDispatcher(testScheduler)) { response() }108 val engineB = ProfileTestEngine(StandardTestDispatcher(testScheduler)) { response() }109 val first = ProfileImageHttpClient(jarA, dbA, CoroutineScope(a + StandardTestDispatcher(testScheduler))) { engineA }110 val second = ProfileImageHttpClient(jarB, dbB, CoroutineScope(b + StandardTestDispatcher(testScheduler))) { engineB }111 first.client.get("https://source.test/page"); second.client.get("https://source.test/page")112 assertEquals("session=A", engineA.requests.receive().headers["Cookie"])113 assertEquals("session=B", engineB.requests.receive().headers["Cookie"])114 a.cancelAndJoin(); first.closeAndJoin()115 second.client.get("https://source.test/page")116 assertEquals("session=B", engineB.requests.receive().headers["Cookie"])117 assertEquals(0, engineB.closeCalls); b.cancelAndJoin(); second.closeAndJoin()118 }119120 private suspend fun response() = HttpResponseData(HttpStatusCode.OK, GMTDate(), Headers.Empty,121 HttpProtocolVersion.HTTP_1_1, ByteReadChannel("image"), callContext())122}123