ktor icon indicating copy to clipboard operation
ktor copied to clipboard

HttpTimeout plugin does not work with test dispatchers

Open schielek opened this issue 9 months ago • 1 comments

I want to test my clients timeout behavior. To have a deterministic test which also runs as fast as possible I decided to use the kotlinx.coroutines test dispatcher which comes with a virtual clock. It seems that the ktor's HttpTimeoutPlugin does not respect the virtual clock of kotlinx coroutines. Is there an alternative way to test this or should the HttpTimeoutPlugin respect the timing behavior of kotlinx.coroutines?

runTest {
    val mutex = Mutex(locked = true)

    val mockEngine = MockEngine {
        mutex.withLock {
            respond("OK")
        }
    }

    val client = HttpClient(mockEngine) {
        install(HttpTimeout) {
            requestTimeoutMillis = 100
        }
    }

    launch {
        delay(200)
        mutex.unlock()
    }
    
    // Assertion error since no exception is thrown
    // Test is green when no coroutine test scope is used
    assertThrows<HttpRequestTimeoutException> {
        client.get("/")
    }
}

schielek avatar Mar 03 '25 20:03 schielek

Thank you for the report. I've reproduced the issue (https://youtrack.jetbrains.com/issue/KTOR-8271).

Stexxe avatar Mar 04 '25 12:03 Stexxe