-
-
Notifications
You must be signed in to change notification settings - Fork 41
/
AsyncHTTPClientTestFramework.swift
247 lines (234 loc) · 8.96 KB
/
AsyncHTTPClientTestFramework.swift
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
//===----------------------------------------------------------------------===//
//
// This source file is part of the Hummingbird server framework project
//
// Copyright (c) 2021-2023 the Hummingbird authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See hummingbird/CONTRIBUTORS.txt for the list of Hummingbird authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import AsyncHTTPClient
import HTTPTypes
import Hummingbird
import HummingbirdCore
import Logging
import NIOCore
import NIOHTTP1
import NIOPosix
import NIOSSL
import ServiceLifecycle
import XCTest
/// Test using a live server and AsyncHTTPClient as a client
final class HBAsyncHTTPClientTestFramework<App: HBApplicationProtocol>: HBApplicationTestFramework {
struct Client: HBTestClientProtocol {
let client: HTTPClient
let urlPrefix: String
let timeout: TimeAmount
/// Send request and call test callback on the response returned
func executeRequest(
uri: String,
method: HTTPRequest.Method,
headers: HTTPFields = [:],
body: ByteBuffer? = nil
) async throws -> HBTestResponse {
let url = "\(self.urlPrefix)\(uri.first == "/" ? "" : "/")\(uri)"
var request = HTTPClientRequest(url: url)
request.method = .init(method)
request.headers = .init(headers)
request.body = body.map { .bytes($0) }
let response = try await client.execute(request, deadline: .now() + self.timeout)
let responseHead = HTTPResponseHead(version: response.version, status: response.status, headers: response.headers)
return try await .init(head: .init(responseHead), body: response.body.collect(upTo: .max), trailerHeaders: nil)
}
}
init(app: App, scheme: HBTestHTTPScheme) {
self.timeout = .seconds(15)
self.application = TestApplication(base: app)
self.scheme = scheme
}
/// Start tests
func run<Value>(_ test: @escaping @Sendable (HBTestClientProtocol) async throws -> Value) async throws -> Value {
try await withThrowingTaskGroup(of: Void.self) { group in
let serviceGroup = ServiceGroup(
configuration: .init(
services: [self.application],
gracefulShutdownSignals: [.sigterm, .sigint],
logger: self.application.logger
)
)
group.addTask {
try await serviceGroup.run()
}
let port = await self.application.portPromise.wait()
var tlsConfiguration = TLSConfiguration.makeClientConfiguration()
tlsConfiguration.certificateVerification = .none
let httpClient = HTTPClient(
eventLoopGroupProvider: .singleton,
configuration: .init(tlsConfiguration: tlsConfiguration)
)
let client = Client(client: httpClient, urlPrefix: "\(self.scheme)://localhost:\(port)", timeout: self.timeout)
do {
let value = try await test(client)
await serviceGroup.triggerGracefulShutdown()
try await httpClient.shutdown()
return value
} catch {
await serviceGroup.triggerGracefulShutdown()
try await httpClient.shutdown()
throw error
}
}
}
let application: TestApplication<App>
let scheme: HBTestHTTPScheme
let timeout: TimeAmount
}
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2023 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
private enum HTTP1TypeConversionError: Error {
case invalidMethod
case missingPath
case invalidStatusCode
}
extension HTTPMethod {
init(_ newMethod: HTTPRequest.Method) {
switch newMethod {
case .get: self = .GET
case .head: self = .HEAD
case .post: self = .POST
case .put: self = .PUT
case .delete: self = .DELETE
case .connect: self = .CONNECT
case .options: self = .OPTIONS
case .trace: self = .TRACE
case .patch: self = .PATCH
default:
let rawValue = newMethod.rawValue
switch rawValue {
case "ACL": self = .ACL
case "COPY": self = .COPY
case "LOCK": self = .LOCK
case "MOVE": self = .MOVE
case "BIND": self = .BIND
case "LINK": self = .LINK
case "MKCOL": self = .MKCOL
case "MERGE": self = .MERGE
case "PURGE": self = .PURGE
case "NOTIFY": self = .NOTIFY
case "SEARCH": self = .SEARCH
case "UNLOCK": self = .UNLOCK
case "REBIND": self = .REBIND
case "UNBIND": self = .UNBIND
case "REPORT": self = .REPORT
case "UNLINK": self = .UNLINK
case "MSEARCH": self = .MSEARCH
case "PROPFIND": self = .PROPFIND
case "CHECKOUT": self = .CHECKOUT
case "PROPPATCH": self = .PROPPATCH
case "SUBSCRIBE": self = .SUBSCRIBE
case "MKCALENDAR": self = .MKCALENDAR
case "MKACTIVITY": self = .MKACTIVITY
case "UNSUBSCRIBE": self = .UNSUBSCRIBE
case "SOURCE": self = .SOURCE
default: self = .RAW(value: rawValue)
}
}
}
}
extension HTTPRequest.Method {
init(_ oldMethod: HTTPMethod) throws {
switch oldMethod {
case .GET: self = .get
case .PUT: self = .put
case .ACL: self = .init("ACL")!
case .HEAD: self = .head
case .POST: self = .post
case .COPY: self = .init("COPY")!
case .LOCK: self = .init("LOCK")!
case .MOVE: self = .init("MOVE")!
case .BIND: self = .init("BIND")!
case .LINK: self = .init("LINK")!
case .PATCH: self = .patch
case .TRACE: self = .trace
case .MKCOL: self = .init("MKCOL")!
case .MERGE: self = .init("MERGE")!
case .PURGE: self = .init("PURGE")!
case .NOTIFY: self = .init("NOTIFY")!
case .SEARCH: self = .init("SEARCH")!
case .UNLOCK: self = .init("UNLOCK")!
case .REBIND: self = .init("REBIND")!
case .UNBIND: self = .init("UNBIND")!
case .REPORT: self = .init("REPORT")!
case .DELETE: self = .delete
case .UNLINK: self = .init("UNLINK")!
case .CONNECT: self = .connect
case .MSEARCH: self = .init("MSEARCH")!
case .OPTIONS: self = .options
case .PROPFIND: self = .init("PROPFIND")!
case .CHECKOUT: self = .init("CHECKOUT")!
case .PROPPATCH: self = .init("PROPPATCH")!
case .SUBSCRIBE: self = .init("SUBSCRIBE")!
case .MKCALENDAR: self = .init("MKCALENDAR")!
case .MKACTIVITY: self = .init("MKACTIVITY")!
case .UNSUBSCRIBE: self = .init("UNSUBSCRIBE")!
case .SOURCE: self = .init("SOURCE")!
case .RAW(value: let value):
guard let method = HTTPRequest.Method(value) else {
throw HTTP1TypeConversionError.invalidMethod
}
self = method
}
}
}
extension HTTPHeaders {
init(_ newFields: HTTPFields) {
let fields = newFields.map { ($0.name.rawName, $0.value) }
self.init(fields)
}
}
extension HTTPFields {
init(_ oldHeaders: HTTPHeaders, splitCookie: Bool) {
self.init()
self.reserveCapacity(count)
var firstHost = true
for field in oldHeaders {
if firstHost, field.name.lowercased() == "host" {
firstHost = false
continue
}
if let name = HTTPField.Name(field.name) {
if splitCookie, name == .cookie, #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) {
self.append(contentsOf: field.value.split(separator: "; ", omittingEmptySubsequences: false).map {
HTTPField(name: name, value: String($0))
})
} else {
self.append(HTTPField(name: name, value: field.value))
}
}
}
}
}
extension HTTPResponse {
init(_ oldResponse: HTTPResponseHead) throws {
guard oldResponse.status.code <= 999 else {
throw HTTP1TypeConversionError.invalidStatusCode
}
let status = HTTPResponse.Status(code: Int(oldResponse.status.code), reasonPhrase: oldResponse.status.reasonPhrase)
self.init(status: status, headerFields: HTTPFields(oldResponse.headers, splitCookie: false))
}
}