Skip to content

Commit d0d4598

Browse files
authored
Replace tests that depend on task handler (#444)
1 parent 88d47f1 commit d0d4598

8 files changed

+130
-112
lines changed

Tests/AsyncHTTPClientTests/HTTP1ConnectionTests+XCTest.swift

+2
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,8 @@ extension HTTP1ConnectionTests {
3434
("testConnectionClosesAfterTheRequestWithoutHavingSentAnCloseHeader", testConnectionClosesAfterTheRequestWithoutHavingSentAnCloseHeader),
3535
("testConnectionIsClosedAfterSwitchingProtocols", testConnectionIsClosedAfterSwitchingProtocols),
3636
("testConnectionDoesntCrashAfterConnectionCloseAndEarlyHints", testConnectionDoesntCrashAfterConnectionCloseAndEarlyHints),
37+
("testConnectionIsClosedIfResponseIsReceivedBeforeRequest", testConnectionIsClosedIfResponseIsReceivedBeforeRequest),
38+
("testDoubleHTTPResponseLine", testDoubleHTTPResponseLine),
3739
("testDownloadStreamingBackpressure", testDownloadStreamingBackpressure),
3840
]
3941
}

Tests/AsyncHTTPClientTests/HTTP1ConnectionTests.swift

+87
Original file line numberDiff line numberDiff line change
@@ -490,6 +490,93 @@ class HTTP1ConnectionTests: XCTestCase {
490490
}
491491
}
492492

493+
func testConnectionIsClosedIfResponseIsReceivedBeforeRequest() {
494+
let embedded = EmbeddedChannel()
495+
let logger = Logger(label: "test.http1.connection")
496+
497+
XCTAssertNoThrow(try embedded.connect(to: SocketAddress(ipAddress: "127.0.0.1", port: 0)).wait())
498+
499+
let connectionDelegate = MockConnectionDelegate()
500+
XCTAssertNoThrow(try HTTP1Connection.start(
501+
channel: embedded,
502+
connectionID: 0,
503+
delegate: connectionDelegate,
504+
configuration: .init(decompression: .enabled(limit: .ratio(4))),
505+
logger: logger
506+
))
507+
508+
let responseString = """
509+
HTTP/1.1 200 OK\r\n\
510+
date: Mon, 27 Sep 2021 17:53:14 GMT\r\n\
511+
\r\n\
512+
\r\n
513+
"""
514+
515+
XCTAssertEqual(connectionDelegate.hitConnectionClosed, 0)
516+
XCTAssertEqual(connectionDelegate.hitConnectionReleased, 0)
517+
518+
XCTAssertThrowsError(try embedded.writeInbound(ByteBuffer(string: responseString))) {
519+
XCTAssertEqual($0 as? NIOHTTPDecoderError, .unsolicitedResponse)
520+
}
521+
XCTAssertFalse(embedded.isActive)
522+
(embedded.eventLoop as! EmbeddedEventLoop).run() // tick once to run futures.
523+
XCTAssertEqual(connectionDelegate.hitConnectionClosed, 1)
524+
XCTAssertEqual(connectionDelegate.hitConnectionReleased, 0)
525+
}
526+
527+
func testDoubleHTTPResponseLine() {
528+
let embedded = EmbeddedChannel()
529+
let logger = Logger(label: "test.http1.connection")
530+
531+
XCTAssertNoThrow(try embedded.connect(to: SocketAddress(ipAddress: "127.0.0.1", port: 0)).wait())
532+
533+
var maybeConnection: HTTP1Connection?
534+
let connectionDelegate = MockConnectionDelegate()
535+
XCTAssertNoThrow(maybeConnection = try HTTP1Connection.start(
536+
channel: embedded,
537+
connectionID: 0,
538+
delegate: connectionDelegate,
539+
configuration: .init(decompression: .enabled(limit: .ratio(4))),
540+
logger: logger
541+
))
542+
guard let connection = maybeConnection else { return XCTFail("Expected to have a connection at this point.") }
543+
544+
var maybeRequest: HTTPClient.Request?
545+
XCTAssertNoThrow(maybeRequest = try HTTPClient.Request(url: "http://swift.org/"))
546+
guard let request = maybeRequest else { return XCTFail("Expected to be able to create a request") }
547+
548+
let delegate = ResponseAccumulator(request: request)
549+
var maybeRequestBag: RequestBag<ResponseAccumulator>?
550+
XCTAssertNoThrow(maybeRequestBag = try RequestBag(
551+
request: request,
552+
eventLoopPreference: .delegate(on: embedded.eventLoop),
553+
task: .init(eventLoop: embedded.eventLoop, logger: logger),
554+
redirectHandler: nil,
555+
connectionDeadline: .now() + .seconds(30),
556+
requestOptions: .forTests(),
557+
delegate: delegate
558+
))
559+
guard let requestBag = maybeRequestBag else { return XCTFail("Expected to be able to create a request bag") }
560+
561+
connection.executeRequest(requestBag)
562+
563+
let responseString = """
564+
HTTP/1.0 200 OK\r\n\
565+
HTTP/1.0 200 OK\r\n\r\n
566+
"""
567+
568+
XCTAssertNoThrow(try embedded.readOutbound(as: ByteBuffer.self)) // head
569+
XCTAssertNoThrow(try embedded.readOutbound(as: ByteBuffer.self)) // end
570+
571+
XCTAssertEqual(connectionDelegate.hitConnectionClosed, 0)
572+
XCTAssertEqual(connectionDelegate.hitConnectionReleased, 0)
573+
XCTAssertNoThrow(try embedded.writeInbound(ByteBuffer(string: responseString)))
574+
XCTAssertFalse(embedded.isActive)
575+
(embedded.eventLoop as! EmbeddedEventLoop).run() // tick once to run futures.
576+
XCTAssertEqual(connectionDelegate.hitConnectionClosed, 1)
577+
XCTAssertEqual(connectionDelegate.hitConnectionReleased, 0)
578+
}
579+
493580
// In order to test backpressure we need to make sure that reads will not happen
494581
// until the backpressure promise is succeeded. Since we cannot guarantee when
495582
// messages will be delivered to a client pipeline and we need this test to be

Tests/AsyncHTTPClientTests/HTTPClientInternalTests+XCTest.swift

-4
Original file line numberDiff line numberDiff line change
@@ -26,11 +26,7 @@ extension HTTPClientInternalTests {
2626
static var allTests: [(String, (HTTPClientInternalTests) -> () throws -> Void)] {
2727
return [
2828
("testHTTPPartsHandler", testHTTPPartsHandler),
29-
("testBadHTTPRequest", testBadHTTPRequest),
30-
("testHostPort", testHostPort),
3129
("testHTTPPartsHandlerMultiBody", testHTTPPartsHandlerMultiBody),
32-
("testHTTPResponseHeadBeforeRequestHead", testHTTPResponseHeadBeforeRequestHead),
33-
("testHTTPResponseDoubleHead", testHTTPResponseDoubleHead),
3430
("testRequestFinishesAfterRedirectIfServerRespondsBeforeClientFinishes", testRequestFinishesAfterRedirectIfServerRespondsBeforeClientFinishes),
3531
("testProxyStreaming", testProxyStreaming),
3632
("testProxyStreamingFailure", testProxyStreamingFailure),

Tests/AsyncHTTPClientTests/HTTPClientInternalTests.swift

-108
Original file line numberDiff line numberDiff line change
@@ -75,65 +75,6 @@ class HTTPClientInternalTests: XCTestCase {
7575
XCTAssertNoThrow(try channel.writeInbound(HTTPClientResponsePart.end(nil)))
7676
}
7777

78-
func testBadHTTPRequest() throws {
79-
let channel = EmbeddedChannel()
80-
let recorder = RecordingHandler<HTTPClientResponsePart, HTTPClientRequestPart>()
81-
let task = Task<Void>(eventLoop: channel.eventLoop, logger: HTTPClient.loggingDisabled)
82-
83-
XCTAssertNoThrow(try channel.pipeline.addHandler(recorder).wait())
84-
XCTAssertNoThrow(try channel.pipeline.addHandler(TaskHandler(task: task,
85-
kind: .host,
86-
delegate: TestHTTPDelegate(),
87-
redirectHandler: nil,
88-
ignoreUncleanSSLShutdown: false,
89-
logger: HTTPClient.loggingDisabled)).wait())
90-
91-
var request = try Request(url: "http://localhost/get")
92-
request.headers.add(name: "X-Test-Header", value: "X-Test-Value")
93-
request.headers.add(name: "Transfer-Encoding", value: "identity")
94-
request.body = .string("1234")
95-
96-
XCTAssertThrowsError(try channel.writeOutbound(request)) { error in
97-
XCTAssertEqual(HTTPClientError.identityCodingIncorrectlyPresent, error as? HTTPClientError)
98-
}
99-
}
100-
101-
func testHostPort() throws {
102-
let channel = EmbeddedChannel()
103-
let recorder = RecordingHandler<HTTPClientResponsePart, HTTPClientRequestPart>()
104-
let task = Task<Void>(eventLoop: channel.eventLoop, logger: HTTPClient.loggingDisabled)
105-
106-
try channel.pipeline.addHandler(recorder).wait()
107-
try channel.pipeline.addHandler(TaskHandler(task: task,
108-
kind: .host,
109-
delegate: TestHTTPDelegate(),
110-
redirectHandler: nil,
111-
ignoreUncleanSSLShutdown: false,
112-
logger: HTTPClient.loggingDisabled)).wait()
113-
114-
let request1 = try Request(url: "http://localhost:80/get")
115-
XCTAssertNoThrow(try channel.writeOutbound(request1))
116-
let request2 = try Request(url: "https://localhost/get")
117-
XCTAssertNoThrow(try channel.writeOutbound(request2))
118-
let request3 = try Request(url: "http://localhost:8080/get")
119-
XCTAssertNoThrow(try channel.writeOutbound(request3))
120-
let request4 = try Request(url: "http://localhost:443/get")
121-
XCTAssertNoThrow(try channel.writeOutbound(request4))
122-
let request5 = try Request(url: "https://localhost:80/get")
123-
XCTAssertNoThrow(try channel.writeOutbound(request5))
124-
125-
let head1 = HTTPRequestHead(version: HTTPVersion(major: 1, minor: 1), method: .GET, uri: "/get", headers: ["host": "localhost"])
126-
XCTAssertEqual(HTTPClientRequestPart.head(head1), recorder.writes[0])
127-
let head2 = HTTPRequestHead(version: HTTPVersion(major: 1, minor: 1), method: .GET, uri: "/get", headers: ["host": "localhost"])
128-
XCTAssertEqual(HTTPClientRequestPart.head(head2), recorder.writes[2])
129-
let head3 = HTTPRequestHead(version: HTTPVersion(major: 1, minor: 1), method: .GET, uri: "/get", headers: ["host": "localhost:8080"])
130-
XCTAssertEqual(HTTPClientRequestPart.head(head3), recorder.writes[4])
131-
let head4 = HTTPRequestHead(version: HTTPVersion(major: 1, minor: 1), method: .GET, uri: "/get", headers: ["host": "localhost:443"])
132-
XCTAssertEqual(HTTPClientRequestPart.head(head4), recorder.writes[6])
133-
let head5 = HTTPRequestHead(version: HTTPVersion(major: 1, minor: 1), method: .GET, uri: "/get", headers: ["host": "localhost:80"])
134-
XCTAssertEqual(HTTPClientRequestPart.head(head5), recorder.writes[8])
135-
}
136-
13778
func testHTTPPartsHandlerMultiBody() throws {
13879
let channel = EmbeddedChannel()
13980
let delegate = TestHTTPDelegate()
@@ -163,55 +104,6 @@ class HTTPClientInternalTests: XCTestCase {
163104
}
164105
}
165106

166-
func testHTTPResponseHeadBeforeRequestHead() throws {
167-
let channel = EmbeddedChannel()
168-
XCTAssertNoThrow(try channel.connect(to: try SocketAddress(unixDomainSocketPath: "/fake")).wait())
169-
170-
let delegate = TestHTTPDelegate()
171-
let task = Task<Void>(eventLoop: channel.eventLoop, logger: HTTPClient.loggingDisabled)
172-
let handler = TaskHandler(task: task,
173-
kind: .host,
174-
delegate: delegate,
175-
redirectHandler: nil,
176-
ignoreUncleanSSLShutdown: false,
177-
logger: HTTPClient.loggingDisabled)
178-
179-
XCTAssertNoThrow(try channel.pipeline.addHTTPClientHandlers().wait())
180-
XCTAssertNoThrow(try channel.pipeline.addHandler(handler).wait())
181-
182-
XCTAssertNoThrow(try channel.writeInbound(ByteBuffer(string: "HTTP/1.0 200 OK\r\n\r\n")))
183-
184-
XCTAssertThrowsError(try task.futureResult.wait()) { error in
185-
XCTAssertEqual(error as? NIOHTTPDecoderError, NIOHTTPDecoderError.unsolicitedResponse)
186-
}
187-
}
188-
189-
func testHTTPResponseDoubleHead() throws {
190-
let channel = EmbeddedChannel()
191-
XCTAssertNoThrow(try channel.connect(to: try SocketAddress(unixDomainSocketPath: "/fake")).wait())
192-
193-
let delegate = TestHTTPDelegate()
194-
let task = Task<Void>(eventLoop: channel.eventLoop, logger: HTTPClient.loggingDisabled)
195-
let handler = TaskHandler(task: task,
196-
kind: .host,
197-
delegate: delegate,
198-
redirectHandler: nil,
199-
ignoreUncleanSSLShutdown: false,
200-
logger: HTTPClient.loggingDisabled)
201-
202-
XCTAssertNoThrow(try channel.pipeline.addHTTPClientHandlers().wait())
203-
XCTAssertNoThrow(try channel.pipeline.addHandler(handler).wait())
204-
205-
let request = try HTTPClient.Request(url: "http://localhost/get")
206-
XCTAssertNoThrow(try channel.writeOutbound(request))
207-
208-
XCTAssertNoThrow(try channel.writeInbound(ByteBuffer(string: "HTTP/1.0 200 OK\r\nHTTP/1.0 200 OK\r\n\r\n")))
209-
210-
XCTAssertThrowsError(try task.futureResult.wait()) { error in
211-
XCTAssertEqual((error as? HTTPParserError)?.debugDescription, "invalid character in header")
212-
}
213-
}
214-
215107
func testRequestFinishesAfterRedirectIfServerRespondsBeforeClientFinishes() throws {
216108
let channel = EmbeddedChannel()
217109

Tests/AsyncHTTPClientTests/HTTPClientTests+XCTest.swift

+1
Original file line numberDiff line numberDiff line change
@@ -136,6 +136,7 @@ extension HTTPClientTests {
136136
("testErrorAfterCloseWhileBackpressureExerted", testErrorAfterCloseWhileBackpressureExerted),
137137
("testRequestSpecificTLS", testRequestSpecificTLS),
138138
("testConnectionPoolSizeConfigValueIsRespected", testConnectionPoolSizeConfigValueIsRespected),
139+
("testRequestWithHeaderTransferEncodingIdentityFails", testRequestWithHeaderTransferEncodingIdentityFails),
139140
]
140141
}
141142
}

Tests/AsyncHTTPClientTests/HTTPClientTests.swift

+19
Original file line numberDiff line numberDiff line change
@@ -3103,4 +3103,23 @@ class HTTPClientTests: XCTestCase {
31033103

31043104
XCTAssertEqual(httpBin.createdConnections, poolSize)
31053105
}
3106+
3107+
func testRequestWithHeaderTransferEncodingIdentityFails() {
3108+
let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
3109+
defer { XCTAssertNoThrow(try group.syncShutdownGracefully()) }
3110+
3111+
let client = HTTPClient(eventLoopGroupProvider: .shared(group))
3112+
defer { XCTAssertNoThrow(try client.syncShutdown()) }
3113+
3114+
guard var request = try? Request(url: "http://localhost/get") else {
3115+
return XCTFail("Expected to have a request here.")
3116+
}
3117+
request.headers.add(name: "X-Test-Header", value: "X-Test-Value")
3118+
request.headers.add(name: "Transfer-Encoding", value: "identity")
3119+
request.body = .string("1234")
3120+
3121+
XCTAssertThrowsError(try client.execute(request: request).wait()) {
3122+
XCTAssertEqual($0 as? HTTPClientError, .identityCodingIncorrectlyPresent)
3123+
}
3124+
}
31063125
}

Tests/AsyncHTTPClientTests/RequestValidationTests+XCTest.swift

+1
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@ extension RequestValidationTests {
4242
("testTransferEncodingHeaderHasBody", testTransferEncodingHeaderHasBody),
4343
("testBothHeadersNoBody", testBothHeadersNoBody),
4444
("testBothHeadersHasBody", testBothHeadersHasBody),
45+
("testHostHeaderIsSetCorrectlyInCreateRequestHead", testHostHeaderIsSetCorrectlyInCreateRequestHead),
4546
]
4647
}
4748
}

Tests/AsyncHTTPClientTests/RequestValidationTests.swift

+20
Original file line numberDiff line numberDiff line change
@@ -316,4 +316,24 @@ class RequestValidationTests: XCTestCase {
316316
XCTAssertThrowsError(try headers.validate(method: method, body: .byteBuffer(ByteBuffer(bytes: [0]))))
317317
}
318318
}
319+
320+
func testHostHeaderIsSetCorrectlyInCreateRequestHead() {
321+
let req1 = try! HTTPClient.Request(url: "http://localhost:80/get")
322+
XCTAssertEqual(try req1.createRequestHead().0.headers["host"].first, "localhost")
323+
324+
let req2 = try! HTTPClient.Request(url: "https://localhost/get")
325+
XCTAssertEqual(try req2.createRequestHead().0.headers["host"].first, "localhost")
326+
327+
let req3 = try! HTTPClient.Request(url: "http://localhost:8080/get")
328+
XCTAssertEqual(try req3.createRequestHead().0.headers["host"].first, "localhost:8080")
329+
330+
let req4 = try! HTTPClient.Request(url: "http://localhost:443/get")
331+
XCTAssertEqual(try req4.createRequestHead().0.headers["host"].first, "localhost:443")
332+
333+
let req5 = try! HTTPClient.Request(url: "https://localhost:80/get")
334+
XCTAssertEqual(try req5.createRequestHead().0.headers["host"].first, "localhost:80")
335+
336+
let req6 = try! HTTPClient.Request(url: "https://localhost/get", headers: ["host": "foo"])
337+
XCTAssertEqual(try req6.createRequestHead().0.headers["host"].first, "foo")
338+
}
319339
}

0 commit comments

Comments
 (0)