/
OpenAPITransportTests.swift
160 lines (144 loc) Β· 5.88 KB
/
OpenAPITransportTests.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
//===----------------------------------------------------------------------===//
//
// This source file is part of the Hummingbird server framework project
//
// Copyright (c) 2023 the Hummingbird authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Hummingbird authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import HTTPTypes
import Hummingbird
import HummingbirdCore
import HummingbirdTesting
import NIOCore
import NIOHTTP1
import OpenAPIRuntime
import NIOHTTPTypes
import XCTest
@testable import OpenAPIHummingbird
extension HTTPField.Name {
static let xMumble = Self("X-Mumble")!
static let host = Self("host")!
}
final class HBOpenAPITransportTests: XCTestCase {
func test_requestConversion() async throws {
let router = Router()
router.post("/hello/:name") { hbRequest, context -> Response in
// Hijack the request handler to test the request-conversion functions.
let expectedRequest = HTTPRequest(
method: .post,
scheme: "http",
authority: "localhost",
path: "/hello/Maria?greeting=Howdy",
headerFields: [
.xMumble: "mumble",
.connection: "keep-alive",
.contentLength: "4",
]
)
let expectedRequestMetadata = ServerRequestMetadata(
pathParameters: ["name": "Maria"]
)
let (request, body) = try hbRequest.makeOpenAPIRequest(context: context)
let collectedBody: [UInt8]
if let body = body {
collectedBody = try await .init(collecting: body, upTo: .max)
} else {
collectedBody = []
}
XCTAssertEqual(request, expectedRequest)
XCTAssertEqual(collectedBody, [UInt8]("π".utf8))
XCTAssertEqual(context.makeOpenAPIRequestMetadata(), expectedRequestMetadata)
// Use the response-conversion to create the Request for returning.
let response = HTTPResponse(status: .created, headerFields: [.xMumble: "mumble"])
return Response(response, body: .init([UInt8]("π".utf8)))
}
let app = Application(responder: router.buildResponder())
try await app.test(.live) { client in
try await client.execute(
uri: "/hello/Maria?greeting=Howdy",
method: .post,
headers: [
.xMumble: "mumble",
],
body: ByteBuffer(string: "π")
) { hbResponse in
// Check the HBResponse (created from the Response) is what meets expectations.
XCTAssertEqual(hbResponse.status, .created)
XCTAssertEqual(hbResponse.headers[.xMumble], "mumble")
XCTAssertEqual(hbResponse.headers[.contentLength], "π".utf8.count.description)
XCTAssertEqual(try String(buffer: XCTUnwrap(hbResponse.body)), "π")
}
}
}
func test_largeBody() async throws {
let router = Router()
let bytes = (0..<1_000_000).map { _ in UInt8.random(in: 0...255)}
let byteBuffer = ByteBuffer(bytes: bytes)
router.post("/hello/:name") { hbRequest, context -> Response in
// Hijack the request handler to test the request-conversion functions.
let expectedRequest = HTTPRequest(
method: .post,
scheme: "http",
authority: "localhost",
path: "/hello/Maria?greeting=Howdy",
headerFields: [
.connection: "keep-alive",
.contentLength: "1000000",
]
)
let expectedRequestMetadata = ServerRequestMetadata(
pathParameters: ["name": "Maria"]
)
let (request, body) = try hbRequest.makeOpenAPIRequest(context: context)
XCTAssertEqual(request, expectedRequest)
XCTAssertEqual(context.makeOpenAPIRequestMetadata(), expectedRequestMetadata)
// Use the response-conversion to create the Request for returning.
let response = HTTPResponse(status: .ok)
return Response(response, body: body)
}
let app = Application(
router: router,
server: .http1(
additionalChannelHandlers: [
BreakupHTTPBodyChannelHandler()
]
)
)
try await app.test(.live) { client in
try await client.execute(
uri: "/hello/Maria?greeting=Howdy",
method: .post,
body: byteBuffer
) { hbResponse in
// Check the Response (created from the Response) is what meets expectations.
XCTAssertEqual(hbResponse.status, .ok)
XCTAssertEqual(byteBuffer, hbResponse.body)
}
}
}
}
/// To test streaming we need to break up the HTTP body into multiple chunks. This channel handler
/// breaks up the incoming HTTP body into multiple chunks
class BreakupHTTPBodyChannelHandler: ChannelInboundHandler, RemovableChannelHandler {
typealias InboundIn = HTTPRequestPart
typealias InboundOut = HTTPRequestPart
func channelRead(context: ChannelHandlerContext, data: NIOAny) {
let part = unwrapInboundIn(data)
switch part {
case .head, .end:
context.fireChannelRead(data)
case .body(var buffer):
while buffer.readableBytes > 0 {
let size = min(32768, buffer.readableBytes)
let slice = buffer.readSlice(length: size)!
context.fireChannelRead(self.wrapInboundOut(.body(slice)))
}
}
}
}