Yokan / rebuild
Course 1 8624561

JavaScriptHostCancellationTest.kt

composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/services/extensions/js/JavaScriptHostCancellationTest.kt

test / fixture50 lines
1package eu.friedcutlet.yokan.services.extensions.js23import eu.friedcutlet.yokan.database.DbSource4import eu.friedcutlet.yokan.services.http.HttpService5import kotlinx.coroutines.CompletableDeferred6import kotlinx.coroutines.Dispatchers7import kotlinx.coroutines.awaitCancellation8import kotlinx.coroutines.launch9import kotlinx.coroutines.runBlocking10import kotlinx.coroutines.withTimeout11import kotlin.test.Test12import kotlin.test.assertEquals13import kotlin.time.Duration.Companion.seconds1415class JavaScriptHostCancellationTest {16    @Test17    fun cancellingRunawayScriptReleasesHostForNextCall() = assertCancelledCallReleasesHost(18        script = "__bridge.sendMessage('entered', ''); while (true) {}",19    )2021    @Test22    fun cancellingCallBlockedOnBridgeHttpReleasesHostForNextCall() = assertCancelledCallReleasesHost(23        script = "__bridge.sendMessage('entered', ''); __bridge.sendMessage('http_get', JSON.stringify([null, null, 'https://example.org', {}, null]));",24    )2526    private fun assertCancelledCallReleasesHost(script: String) = runBlocking {27        val entered = CompletableDeferred<Unit>()28        val host = JavaScriptHost(29            source = DbSource(id = 1L, name = "Runaway", sourceCode = "var ready = true;"),30            http = HttpService { awaitCancellation() },31            database = null,32            engineFactory = { bridge -> QuickJsJavaScriptEngine(bridge) },33            boot = { engine -> engine.evaluate("var ready = true;") },34            channels = { channel, _ -> if (channel == "entered") "null".also { entered.complete(Unit) } else null },35        )3637        try {38            val blocked = launch(Dispatchers.Default) { host.call { it.evaluate(script) } }39            entered.await()40            blocked.cancel()4142            // Without cancellation support the first call holds the host for the 30 s evaluation timeout.43            val next = withTimeout(5.seconds) { host.call { it.evaluate("1 + 1") } }4445            assertEquals("2", next)46        } finally {47            host.close()48        }49    }50}51

Search chapters, reference and source filenames.