-
Notifications
You must be signed in to change notification settings - Fork 6
/
MockHttpClient.kt
84 lines (76 loc) · 2.83 KB
/
MockHttpClient.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
84
package io.imrekaszab.githubuserfinder
import io.ktor.client.HttpClient
import io.ktor.client.engine.mock.MockEngine
import io.ktor.client.engine.mock.respond
import io.ktor.client.engine.mock.respondError
import io.ktor.client.plugins.contentnegotiation.ContentNegotiation
import io.ktor.client.plugins.defaultRequest
import io.ktor.http.HttpMethod
import io.ktor.http.HttpStatusCode
import io.ktor.http.URLBuilder
import io.ktor.http.Url
import io.ktor.http.encodedPath
import io.ktor.http.fullPath
import io.ktor.http.headersOf
import io.ktor.http.hostWithPort
import io.ktor.http.takeFrom
import io.ktor.serialization.kotlinx.json.json
import kotlinx.serialization.json.Json
private val Url.hostWithPortIfRequired: String
get() = if (port == protocol.defaultPort) {
host
} else {
hostWithPort
}
private val Url.urlWithoutPath: String
get() = "${protocol.name}://$hostWithPortIfRequired"
private val Url.fullUrl: String
get() = "${protocol.name}://$hostWithPortIfRequired$fullPath"
internal val mockHttpClient =
HttpClient(MockEngine) {
defaultRequest {
url.takeFrom(
URLBuilder().takeFrom(MockData.baseUrl).apply {
encodedPath += url.encodedPath
}
)
}
install(ContentNegotiation) {
json(
Json {
ignoreUnknownKeys = true
}
)
}
engine {
addHandler { request ->
if (request.url.urlWithoutPath == MockData.baseUrl) {
if (request.method == HttpMethod.Get) {
when {
request.url.fullUrl.contains("search/users") -> respond(
content = getSearchResponseContentByUrl(request.url.fullUrl),
status = HttpStatusCode.OK,
headers = headersOf("Content-Type", "application/json")
)
request.url.fullUrl.contains("users/") -> respond(
content = MockData.userDetailsResponse,
status = HttpStatusCode.OK,
headers = headersOf("Content-Type", "application/json")
)
else -> respondError(HttpStatusCode.BadRequest)
}
} else {
respondError(HttpStatusCode.Unauthorized)
}
} else {
respondError(HttpStatusCode.NotFound)
}
}
}
}
private fun getSearchResponseContentByUrl(fullUrl: String) =
if (fullUrl.contains("?q=&")) {
MockData.emptyResponse
} else {
MockData.nonEmptyResponse
}