@file:OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class, io.ktor.utils.io.InternalAPI::class) package eu.friedcutlet.yokan.ui.image import eu.friedcutlet.yokan.domain.ProfileId import eu.friedcutlet.yokan.database.InMemoryYokanDatabase import eu.friedcutlet.yokan.database.emptySnapshot import eu.friedcutlet.yokan.services.http.ProfileTestEngine import eu.friedcutlet.yokan.services.http.cookies.CookieJar import io.ktor.client.engine.callContext import io.ktor.client.request.HttpResponseData import io.ktor.client.request.get import io.ktor.client.request.header import io.ktor.client.statement.bodyAsText import io.ktor.http.Headers import io.ktor.http.HttpProtocolVersion import io.ktor.http.HttpStatusCode import io.ktor.util.date.GMTDate import io.ktor.utils.io.ByteReadChannel import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Job import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.awaitCancellation import kotlinx.coroutines.cancelAndJoin import kotlinx.coroutines.launch import kotlinx.coroutines.test.StandardTestDispatcher import kotlinx.coroutines.test.runTest import kotlinx.coroutines.withContext import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFailsWith import kotlin.test.assertFalse import kotlin.test.assertTrue class ProfileImageHttpClientTest { @Test fun proxyProgressHeaderNeverLeavesTheApp() = runTest { val parent = SupervisorJob(); val db = InMemoryYokanDatabase(emptySnapshot()) val engine = ProfileTestEngine(StandardTestDispatcher(testScheduler)) { response() } val transport = ProfileImageHttpClient(CookieJar(db), db, CoroutineScope(parent + StandardTestDispatcher(testScheduler))) { engine } transport.client.get("https://wsrv.nl/image") { header(OriginalImageProgressHeader, "https://source.example.org/page.png") } assertEquals(null, engine.requests.receive().headers[OriginalImageProgressHeader]) transport.closeAndJoin(); parent.cancelAndJoin() } @Test fun capturesJarAndSettingsWhileRetainingSourceHeadersAndSolvedUserAgent() = runTest { val parent = SupervisorJob(); val db = InMemoryYokanDatabase(emptySnapshot()) db.updateSettings(db.settings().copy(userAgent = "profile-agent")) val jar = CookieJar(db, ProfileId.Default) { parent.isActive } jar.put("source.test", "session=profile") val engine = ProfileTestEngine(StandardTestDispatcher(testScheduler)) { response() } val transport = ProfileImageHttpClient(jar, db, CoroutineScope(parent + StandardTestDispatcher(testScheduler))) { engine } assertEquals("image", transport.client.get("https://source.test/page").bodyAsText()) val first = engine.requests.receive() assertEquals("session=profile", first.headers["Cookie"]); assertEquals("profile-agent", first.headers["User-Agent"]) transport.client.get("https://source.test/page") { header("Cookie", "source=explicit"); header("User-Agent", "source-agent") } val second = engine.requests.receive() assertEquals("source=explicit", second.headers["Cookie"]); assertEquals("source-agent", second.headers["User-Agent"]) jar.rememberUserAgent("https://source.test/page", "solved-agent") transport.client.get("https://source.test/page") { header("User-Agent", "source-agent") } assertEquals("solved-agent", engine.requests.receive().headers["User-Agent"]) transport.closeAndJoin(); parent.cancelAndJoin(); assertEquals(1, engine.closeCalls) } @Test fun retirementCancelsAndJoinsEngineFinalizersBeforeDatabaseRelease() = runTest { val parent = SupervisorJob(); val db = InMemoryYokanDatabase(emptySnapshot()) val release = CompletableDeferred(); var finalized = false val engine = ProfileTestEngine(StandardTestDispatcher(testScheduler)) { try { awaitCancellation() } finally { withContext(NonCancellable) { release.await(); finalized = true } } } val transport = ProfileImageHttpClient(CookieJar(db, ProfileId.Default) { parent.isActive }, db, CoroutineScope(parent + StandardTestDispatcher(testScheduler))) { engine } val caller = launch { transport.client.get("https://source.test/page").bodyAsText() } engine.requests.receive() val retiring = launch { parent.cancelAndJoin() } testScheduler.runCurrent(); assertFalse(retiring.isCompleted) release.complete(Unit); retiring.join(); caller.join() assertTrue(finalized); assertTrue(engine.coroutineContext[Job]?.isCompleted == true) transport.closeAndJoin(); assertEquals(1, engine.closeCalls) assertFailsWith { transport.client.get("https://source.test/page") } assertTrue(engine.requests.tryReceive().isFailure) } @Test fun explicitTransportClosePreservesOwnerAndRejectsFurtherRequests() = runTest { val parent = SupervisorJob(); val db = InMemoryYokanDatabase(emptySnapshot()) val engine = ProfileTestEngine(StandardTestDispatcher(testScheduler)) { response() } val transport = ProfileImageHttpClient(CookieJar(db), db, CoroutineScope(parent + StandardTestDispatcher(testScheduler))) { engine } transport.closeAndJoin(); transport.closeAndJoin() assertTrue(parent.isActive); assertEquals(1, engine.closeCalls) assertFailsWith { transport.client.get("https://source.test/page") } assertTrue(engine.requests.tryReceive().isFailure); parent.cancelAndJoin() } @Test fun expiredOwnerCannotAllocateImageTransport() = runTest { val parent = SupervisorJob(); val db = InMemoryYokanDatabase(emptySnapshot()) parent.cancelAndJoin() assertFailsWith { ProfileImageHttpClient(CookieJar(db), db, CoroutineScope(parent + StandardTestDispatcher(testScheduler))) { error("Expired allocation") } } } @Test fun replacementClientsWithSameUrlUseTheirOwnCredentialsAndCleanup() = runTest { val a = SupervisorJob(); val b = SupervisorJob() val dbA = InMemoryYokanDatabase(emptySnapshot()); val dbB = InMemoryYokanDatabase(emptySnapshot()) val jarA = CookieJar(dbA, ProfileId.Default) { a.isActive }; val jarB = CookieJar(dbB, ProfileId.Default) { b.isActive } jarA.put("source.test", "session=A"); jarB.put("source.test", "session=B") val engineA = ProfileTestEngine(StandardTestDispatcher(testScheduler)) { response() } val engineB = ProfileTestEngine(StandardTestDispatcher(testScheduler)) { response() } val first = ProfileImageHttpClient(jarA, dbA, CoroutineScope(a + StandardTestDispatcher(testScheduler))) { engineA } val second = ProfileImageHttpClient(jarB, dbB, CoroutineScope(b + StandardTestDispatcher(testScheduler))) { engineB } first.client.get("https://source.test/page"); second.client.get("https://source.test/page") assertEquals("session=A", engineA.requests.receive().headers["Cookie"]) assertEquals("session=B", engineB.requests.receive().headers["Cookie"]) a.cancelAndJoin(); first.closeAndJoin() second.client.get("https://source.test/page") assertEquals("session=B", engineB.requests.receive().headers["Cookie"]) assertEquals(0, engineB.closeCalls); b.cancelAndJoin(); second.closeAndJoin() } private suspend fun response() = HttpResponseData(HttpStatusCode.OK, GMTDate(), Headers.Empty, HttpProtocolVersion.HTTP_1_1, ByteReadChannel("image"), callContext()) }