-
-
Notifications
You must be signed in to change notification settings - Fork 41
/
LiveTestFramework.swift
86 lines (80 loc) · 2.97 KB
/
LiveTestFramework.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
//===----------------------------------------------------------------------===//
//
// 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 HTTPTypes
import Hummingbird
import HummingbirdCore
import Logging
import NIOCore
import NIOPosix
import NIOTransportServices
import ServiceLifecycle
import XCTest
/// Test using a live server
final class HBLiveTestFramework<App: HBApplicationProtocol>: HBApplicationTestFramework {
struct Client: HBTestClientProtocol {
let client: HBTestClient
/// 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 {
var headers = headers
headers[.connection] = "keep-alive"
let request = HBTestClient.Request(uri, method: method, authority: "localhost", headers: headers, body: body)
let response = try await client.execute(request)
return .init(head: response.head, body: response.body ?? ByteBuffer(), trailerHeaders: response.trailerHeaders)
}
}
init(app: App) {
self.timeout = .seconds(20)
self.application = TestApplication(base: app)
}
/// 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()
let client = HBTestClient(
host: "localhost",
port: port,
configuration: .init(timeout: self.timeout),
eventLoopGroupProvider: .createNew
)
client.connect()
do {
let value = try await test(Client(client: client))
await serviceGroup.triggerGracefulShutdown()
try await client.shutdown()
return value
} catch {
await serviceGroup.triggerGracefulShutdown()
try await client.shutdown()
throw error
}
}
}
let application: TestApplication<App>
let timeout: Duration
}