-
Notifications
You must be signed in to change notification settings - Fork 1k
/
CommonClientTestUtils.kt
82 lines (70 loc) · 2.23 KB
/
CommonClientTestUtils.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/*
* Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.client.tests.utils
import io.ktor.client.*
import io.ktor.client.engine.*
import io.ktor.test.dispatcher.*
import io.ktor.util.*
import kotlinx.coroutines.*
import io.ktor.utils.io.core.*
/**
* Local test server url.
*/
const val TEST_SERVER: String = "http://127.0.0.1:8080"
const val HTTP_PROXY_SERVER: String = "http://127.0.0.1:8082"
/**
* Perform test with selected client [engine].
*/
fun clientTest(
engine: HttpClientEngine,
block: suspend TestClientBuilder<*>.() -> Unit
) = clientTest(HttpClient(engine), block)
/**
* Perform test with selected [client] or client loaded by service loader.
*/
fun clientTest(
client: HttpClient = HttpClient(),
block: suspend TestClientBuilder<HttpClientEngineConfig>.() -> Unit
) = testSuspend {
val builder = TestClientBuilder<HttpClientEngineConfig>().also { it.block() }
@Suppress("UNCHECKED_CAST")
client.config { builder.config(this as HttpClientConfig<HttpClientEngineConfig>) }
.use { client -> builder.test(client) }
}
/**
* Perform test with selected client engine [factory].
*/
fun <T : HttpClientEngineConfig> clientTest(
factory: HttpClientEngineFactory<T>,
block: suspend TestClientBuilder<T>.() -> Unit
) = testSuspend {
val builder = TestClientBuilder<T>().apply { block() }
val client = HttpClient(factory, block = builder.config)
client.use {
builder.test(it)
}
try {
val job = client.coroutineContext[Job]!!
job.join()
} catch (cause: Throwable) {
client.cancel("Test failed", cause)
throw cause
}
}
@InternalAPI
@Suppress("KDocMissingDocumentation")
class TestClientBuilder<T : HttpClientEngineConfig>(
var config: HttpClientConfig<T>.() -> Unit = {},
var test: suspend (client: HttpClient) -> Unit = {}
)
@InternalAPI
@Suppress("KDocMissingDocumentation")
fun <T : HttpClientEngineConfig> TestClientBuilder<T>.config(block: HttpClientConfig<T>.() -> Unit): Unit {
config = block
}
@InternalAPI
@Suppress("KDocMissingDocumentation")
fun TestClientBuilder<*>.test(block: suspend (client: HttpClient) -> Unit): Unit {
test = block
}