ProfileHttpServiceTest.kt
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/http/ProfileHttpServiceTest.kt
1@file:OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)23package eu.friedcutlet.yokan.services.http45import eu.friedcutlet.yokan.domain.ProfileId6import kotlinx.coroutines.CancellationException7import kotlinx.coroutines.CompletableDeferred8import kotlinx.coroutines.CoroutineScope9import kotlinx.coroutines.Job10import kotlinx.coroutines.NonCancellable11import kotlinx.coroutines.SupervisorJob12import kotlinx.coroutines.awaitCancellation13import kotlinx.coroutines.cancel14import kotlinx.coroutines.cancelAndJoin15import kotlinx.coroutines.currentCoroutineContext16import kotlinx.coroutines.launch17import kotlinx.coroutines.test.StandardTestDispatcher18import kotlinx.coroutines.test.UnconfinedTestDispatcher19import kotlinx.coroutines.test.runTest20import kotlinx.coroutines.withContext21import kotlin.test.Test22import kotlin.test.assertContentEquals23import kotlin.test.assertEquals24import kotlin.test.assertFailsWith25import kotlin.test.assertFalse26import kotlin.test.assertSame27import kotlin.test.assertTrue2829class ProfileHttpServiceTest {30 @Test fun preservesRequestAndResponseIncludingCredentialsAndBinaryBodies() = runTest {31 val parent = SupervisorJob()32 val request = HttpRequest("https://source.test/upload", "POST", mapOf("Authorization" to "Bearer owner"), bodyBytes = byteArrayOf(0, -1))33 val response = HttpResponse(401, headers = mapOf("WWW-Authenticate" to "Bearer"), bodyBytes = byteArrayOf(1, -1), setCookies = listOf("id=owner"))34 val delegate = FakeHttp().apply { requestAction = { assertSame(request, it); response } }35 val service = ProfileHttpService(A, delegate, CoroutineScope(parent + StandardTestDispatcher(testScheduler)))36 assertEquals(A, service.profileId); assertSame(response, service.request(request))37 parent.cancelAndJoin()38 }3940 @Test fun streamsChunksInOrderAndPreservesBufferedErrorResponses() = runTest {41 val parent = SupervisorJob()42 val delegate = FakeHttp().apply { streamAction = { request, chunk ->43 assertSame(Request, request); chunk(byteArrayOf(1, 2)); chunk(byteArrayOf(-1))44 HttpStreamResponse(200, setCookies = listOf("id=owner"))45 } }46 val service = ProfileHttpService(A, delegate, CoroutineScope(parent + StandardTestDispatcher(testScheduler)))47 val received = mutableListOf<Byte>()48 assertEquals(listOf("id=owner"), service.stream(Request) { received.addAll(it.toList()) }.setCookies)49 assertContentEquals(byteArrayOf(1, 2, -1), received.toByteArray())50 val error = HttpStreamResponse(403, body = "challenge".encodeToByteArray())51 delegate.streamAction = { _, _ -> error }52 assertSame(error, service.stream(Request) { error("Error body streamed") })53 parent.cancelAndJoin()54 }5556 @Test fun retiredOwnerRejectsBothEntryPointsBeforeDelegateAccess() = runTest {57 val parent = SupervisorJob()58 val delegate = FakeHttp()59 val service = ProfileHttpService(A, delegate, CoroutineScope(parent + StandardTestDispatcher(testScheduler)))60 parent.cancelAndJoin()61 assertFailsWith<CancellationException> { service.request(Request) }62 assertFailsWith<CancellationException> { service.stream(Request) { error("Expired chunk") } }63 assertEquals(0, delegate.calls)64 }6566 @Test fun retirementJoinsExternalRequestFinalizersBeforeRelease() = runTest {67 val parent = SupervisorJob()68 val entered = CompletableDeferred<Unit>(); val release = CompletableDeferred<Unit>()69 var finalized = false70 val delegate = FakeHttp().apply { requestAction = {71 try { entered.complete(Unit); awaitCancellation() }72 finally { withContext(NonCancellable) { release.await(); finalized = true } }73 } }74 val service = ProfileHttpService(A, delegate, CoroutineScope(parent + StandardTestDispatcher(testScheduler)))75 val caller = launch { service.request(Request) }76 entered.await()77 val retiring = launch { parent.cancelAndJoin() }78 testScheduler.runCurrent(); assertFalse(retiring.isCompleted); assertFalse(caller.isCompleted)79 release.complete(Unit); retiring.join(); caller.join(); assertTrue(finalized)80 }8182 @Test fun callerExpiryJoinsStreamFinalizersAndPreservesSiblingWork() = runTest {83 val parent = SupervisorJob()84 val scope = CoroutineScope(parent + StandardTestDispatcher(testScheduler))85 val entered = CompletableDeferred<Unit>(); val release = CompletableDeferred<Unit>()86 val delegate = FakeHttp().apply { streamAction = { _, _ ->87 try { entered.complete(Unit); awaitCancellation() }88 finally { withContext(NonCancellable) { release.await() } }89 } }90 val service = ProfileHttpService(A, delegate, scope)91 val sibling = scope.launch { awaitCancellation() }92 val caller = launch { service.stream(Request) {} }93 entered.await(); caller.cancel(); testScheduler.runCurrent()94 assertFalse(caller.isCompleted); assertTrue(parent.isActive); assertTrue(sibling.isActive)95 release.complete(Unit); caller.join()96 assertEquals(200, service.request(Request).statusCode)97 parent.cancelAndJoin()98 }99100 @Test fun streamCleanupCannotDeliverLateBytesEvenFromNonCancellableContext() = runTest {101 val parent = SupervisorJob()102 val entered = CompletableDeferred<Unit>()103 var lateRejected = false; var delivered = 0104 val delegate = FakeHttp().apply { streamAction = { _, chunk ->105 try { chunk(byteArrayOf(1)); entered.complete(Unit); awaitCancellation() }106 finally { withContext(NonCancellable) {107 assertFailsWith<CancellationException> { chunk(byteArrayOf(2)) }; lateRejected = true108 } }109 } }110 val service = ProfileHttpService(A, delegate, CoroutineScope(parent + StandardTestDispatcher(testScheduler)))111 val caller = launch { service.stream(Request) { delivered++ } }112 entered.await(); caller.cancelAndJoin()113 assertEquals(1, delivered); assertTrue(lateRejected); assertTrue(parent.isActive)114 parent.cancelAndJoin()115 }116117 @Test fun retainedStreamCallbackCannotWriteAfterSuccessfulCompletion() = runTest {118 val parent = SupervisorJob()119 var retained: (suspend (ByteArray) -> Unit)? = null120 val delegate = FakeHttp().apply { streamAction = { _, chunk -> retained = chunk; HttpStreamResponse(200) } }121 val service = ProfileHttpService(A, delegate, CoroutineScope(parent + StandardTestDispatcher(testScheduler)))122 service.stream(Request) { error("Detached callback wrote bytes") }123 assertFailsWith<CancellationException> { requireNotNull(retained).invoke(byteArrayOf(1)) }124 parent.cancelAndJoin()125 }126127 @Test fun responseHeadersCannotWriteAfterCancellationOrCompletion() = runTest {128 val parent = SupervisorJob()129 val entered = CompletableDeferred<Unit>()130 var retained: (suspend (HttpStreamResponse) -> Unit)? = null131 var delivered = 0132 val response = HttpStreamResponse(200)133 val delegate = FakeHttp().apply { streamAction = { request, _ ->134 retained = request.onStreamResponse135 try {136 requireNotNull(retained).invoke(response)137 entered.complete(Unit)138 awaitCancellation()139 } finally {140 withContext(NonCancellable) {141 assertFailsWith<CancellationException> { requireNotNull(retained).invoke(response) }142 }143 }144 } }145 val service = ProfileHttpService(A, delegate, CoroutineScope(parent + StandardTestDispatcher(testScheduler)))146 val request = Request.copy(onStreamResponse = { delivered++ })147 val caller = launch { service.stream(request) {} }148 entered.await()149 caller.cancelAndJoin()150 assertEquals(1, delivered)151 delegate.streamAction = { current, _ -> retained = current.onStreamResponse; response }152 service.stream(request) {}153 assertFailsWith<CancellationException> { requireNotNull(retained).invoke(response) }154 assertEquals(1, delivered)155 parent.cancelAndJoin()156 }157158 @Test fun alreadyExpiredCallerCannotDispatchWithImmediateOwnerDispatcher() = runTest {159 val parent = SupervisorJob(); val delegate = FakeHttp()160 val service = ProfileHttpService(A, delegate, CoroutineScope(parent + UnconfinedTestDispatcher(testScheduler)))161 val caller = launch {162 currentCoroutineContext().cancel()163 assertFailsWith<CancellationException> { service.request(Request) }164 assertFailsWith<CancellationException> { service.stream(Request) {} }165 }166 caller.join(); assertEquals(0, delegate.calls); assertTrue(parent.isActive)167 parent.cancelAndJoin()168 }169170 @Test fun queuedRequestCannotReachTransportAfterOwnerRetires() = runTest {171 val parent = SupervisorJob(); val delegate = FakeHttp()172 val service = ProfileHttpService(A, delegate, CoroutineScope(parent + StandardTestDispatcher(testScheduler)))173 val caller = launch(UnconfinedTestDispatcher(testScheduler)) { service.request(Request) }174 parent.cancel(); testScheduler.runCurrent(); caller.join(); parent.join()175 assertEquals(0, delegate.calls)176 }177178 @Test fun transportOrChunkFailureDoesNotRetireAnOrdinaryParentOrSiblings() = runTest {179 val parent = Job(); val scope = CoroutineScope(parent + StandardTestDispatcher(testScheduler))180 val delegate = FakeHttp().apply { requestAction = { error("Transport failed") } }181 val service = ProfileHttpService(A, delegate, scope)182 val sibling = scope.launch { awaitCancellation() }183 assertFailsWith<IllegalStateException> { service.request(Request) }184 delegate.streamAction = { _, chunk -> chunk(byteArrayOf(1)); HttpStreamResponse(200) }185 assertFailsWith<IllegalArgumentException> { service.stream(Request) { throw IllegalArgumentException("Disk failed") } }186 assertTrue(parent.isActive); assertTrue(sibling.isActive)187 delegate.requestAction = { HttpResponse(200) }188 assertEquals(200, service.request(Request).statusCode)189 parent.cancelAndJoin()190 }191192 @Test fun retiringOneOwnerDoesNotRetargetOrCancelAnotherOwnersTransport() = runTest {193 val parentA = SupervisorJob(); val parentB = SupervisorJob()194 val a = FakeHttp().apply { requestAction = { HttpResponse(200, "A") } }195 val b = FakeHttp().apply { requestAction = { HttpResponse(200, "B") } }196 val serviceA = ProfileHttpService(A, a, CoroutineScope(parentA + StandardTestDispatcher(testScheduler)))197 val serviceB = ProfileHttpService(B, b, CoroutineScope(parentB + StandardTestDispatcher(testScheduler)))198 assertEquals("A", serviceA.request(Request).body); parentA.cancelAndJoin()199 assertFailsWith<CancellationException> { serviceA.request(Request) }200 assertEquals("B", serviceB.request(Request).body); assertTrue(parentB.isActive)201 assertEquals(1, a.calls); assertEquals(1, b.calls); parentB.cancelAndJoin()202 }203204 @Test fun extraPlatformEnginesHaveIndependentLifetimes() = runTest {205 val first = createPlatformHttpClientEngine(A)206 val second = createPlatformHttpClientEngine(B)207 try {208 kotlin.test.assertNotSame(first, second)209 ProfileHttpEngine(first).closeAndJoin()210 assertTrue(second.coroutineContext[Job]?.isActive == true)211 } finally {212 ProfileHttpEngine(first).closeAndJoin()213 ProfileHttpEngine(second).closeAndJoin()214 }215 }216217 private class FakeHttp : HttpService {218 var calls = 0219 var requestAction: suspend (HttpRequest) -> HttpResponse = { HttpResponse(200) }220 var streamAction: suspend (HttpRequest, suspend (ByteArray) -> Unit) -> HttpStreamResponse = { _, _ -> HttpStreamResponse(200) }221 override suspend fun request(request: HttpRequest): HttpResponse { calls++; return requestAction(request) }222 override suspend fun stream(request: HttpRequest, onChunk: suspend (ByteArray) -> Unit): HttpStreamResponse {223 calls++; return streamAction(request, onChunk)224 }225 }226227 private companion object {228 val A = ProfileId("p_11111111111111111111111111111111")229 val B = ProfileId("p_22222222222222222222222222222222")230 val Request = HttpRequest("https://source.test/chapter")231 }232}233