-
Notifications
You must be signed in to change notification settings - Fork 1k
/
Utils.kt
83 lines (72 loc) · 2.19 KB
/
Utils.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
83
/*
* 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.server.testing
import io.ktor.client.plugins.*
import io.ktor.client.request.*
import io.ktor.http.*
import io.ktor.util.*
import io.ktor.utils.io.*
import kotlinx.coroutines.*
/**
* [on] function receiver object
*/
public object On
/**
* [it] function receiver object
*/
public object It
/**
* DSL for creating a test case
*/
@Suppress("UNUSED_PARAMETER")
public fun on(comment: String, body: On.() -> Unit): Unit = On.body()
/**
* DSL function for a test case assertions
*/
@Suppress("UNUSED_PARAMETER")
public inline fun On.it(description: String, body: It.() -> Unit): Unit = It.body()
/**
* Returns a parsed content type from a test response.
*/
public fun TestApplicationResponse.contentType(): ContentType {
val contentTypeHeader = requireNotNull(headers[HttpHeaders.ContentType])
return ContentType.parse(contentTypeHeader)
}
internal fun CoroutineScope.configureSocketTimeoutIfNeeded(
timeoutAttributes: HttpTimeoutConfig?,
job: Job,
extract: () -> Long
) {
val socketTimeoutMillis = timeoutAttributes?.socketTimeoutMillis
if (socketTimeoutMillis != null) {
socketTimeoutKiller(socketTimeoutMillis, job, extract)
}
}
internal fun CoroutineScope.socketTimeoutKiller(socketTimeoutMillis: Long, job: Job, extract: () -> Long) {
val killJob = launch {
var cur = extract()
while (job.isActive) {
delay(socketTimeoutMillis)
val next = extract()
if (cur == next) {
throw io.ktor.network.sockets.SocketTimeoutException("Socket timeout elapsed")
}
cur = next
}
}
job.invokeOnCompletion {
killJob.cancel()
}
}
@OptIn(InternalAPI::class)
internal fun Throwable.mapToKtor(data: HttpRequestData): Throwable {
return when {
this is io.ktor.network.sockets.SocketTimeoutException -> SocketTimeoutException(data, this)
cause?.rootCause is io.ktor.network.sockets.SocketTimeoutException -> SocketTimeoutException(
data,
cause?.rootCause
)
else -> this
}
}