tests: improve tests that are supposed to throw (#1430)

Motivation:

The

    do {
        try someOperation()
	XCTFail("should throw") // easy to forget
    } catch error as SomethingError {
        XCTAssertEqual(.something, error as? SomethingError)
    } catch {
        XCTFail("wrong error")
    }

pattern is not only very long, it's also very error prone. If you forget
any of the XCTFails, you might not tests what it looks like

    XCTAssertThrowsError(try someOperation) { error in
        XCTAssertEqual(.something, error as? SomethingError)
    }

is much safer and shorter.

Modifcations:

Do many of the above replaces.

Result:

Cleaner, shorter, and safer tests.
This commit is contained in:
Johannes Weiss authored and GitHub committed 2020-03-03 18:14:49 +00:00
1 parent 2512b8e277
commit 8912d1a48b
19 files changed
+282 -736

No files matched your search

+16 -37
View File
@@ -443,13 +443,9 @@ class HTTPDecoderLengthTest: XCTestCase {
XCTAssertNoThrow(try channel.pipeline.addHandler(ByteToMessageHandler(HTTPRequestDecoder())).wait())
// Send a GET with the invalid headers.
do {
try channel.writeInbound(ByteBuffer(string: "POST / HTTP/1.1\r\nTransfer-Encoding: chunked\r\nContent-Length: 4\r\n\r\n"))
XCTFail("Did not throw")
} catch HTTPParserError.unexpectedContentLength {
// ok
} catch {
XCTFail("Unexpected error: \(error)")
let request = ByteBuffer(string: "POST / HTTP/1.1\r\nTransfer-Encoding: chunked\r\nContent-Length: 4\r\n\r\n")
XCTAssertThrowsError(try channel.writeInbound(request)) { error in
XCTAssertEqual(HTTPParserError.unexpectedContentLength, error as? HTTPParserError)
}
// Must spin the loop.
@@ -467,13 +463,9 @@ class HTTPDecoderLengthTest: XCTestCase {
uri: "/"))).isFull)
// Send a 200 OK with the invalid headers.
do {
try channel.writeInbound(ByteBuffer(string: "HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\nContent-Length: 4\r\n\r\n"))
XCTFail("Did not throw")
} catch HTTPParserError.unexpectedContentLength {
// ok
} catch {
XCTFail("Unexpected error: \(error)")
let response = "HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\nContent-Length: 4\r\n\r\n"
XCTAssertThrowsError(try channel.writeInbound(ByteBuffer(string: response))) { error in
XCTAssertEqual(HTTPParserError.unexpectedContentLength, error as? HTTPParserError)
}
// Must spin the loop.
@@ -485,15 +477,10 @@ class HTTPDecoderLengthTest: XCTestCase {
XCTAssertNoThrow(try channel.pipeline.addHandler(ByteToMessageHandler(HTTPRequestDecoder())).wait())
// Send a GET with the invalid headers.
do {
try channel.writeInbound(ByteBuffer(string: "POST / HTTP/1.1\r\nContent-Length: \(contentLengthField)\r\n\r\n"))
XCTFail("Did not throw")
} catch HTTPParserError.invalidContentLength {
// ok
} catch HTTPParserError.unexpectedContentLength {
// also ok
} catch {
XCTFail("Unexpected error: \(error)")
let request = "POST / HTTP/1.1\r\nContent-Length: \(contentLengthField)\r\n\r\n"
XCTAssertThrowsError(try channel.writeInbound(ByteBuffer(string: request))) { error in
XCTAssert(HTTPParserError.unexpectedContentLength == error as? HTTPParserError ||
HTTPParserError.invalidContentLength == error as? HTTPParserError)
}
// Must spin the loop.
@@ -520,13 +507,9 @@ class HTTPDecoderLengthTest: XCTestCase {
// Send two POSTs with repeated content length, one with one field and one with two.
// Both should error.
do {
try channel.writeInbound(ByteBuffer(string: "POST / HTTP/1.1\r\nContent-Length: 4, 4\r\n\r\n"))
XCTFail("Did not throw")
} catch HTTPParserError.invalidContentLength {
// ok
} catch {
XCTFail("Unexpected error \(error)")
let request = "POST / HTTP/1.1\r\nContent-Length: 4, 4\r\n\r\n"
XCTAssertThrowsError(try channel.writeInbound(ByteBuffer(string: request))) { error in
XCTAssertEqual(HTTPParserError.invalidContentLength, error as? HTTPParserError)
}
// Must spin the loop.
@@ -539,13 +522,9 @@ class HTTPDecoderLengthTest: XCTestCase {
// the spec. Regardless, we match it.
XCTAssertNoThrow(try channel.pipeline.addHandler(ByteToMessageHandler(HTTPRequestDecoder())).wait())
do {
try channel.writeInbound(ByteBuffer(string: "POST / HTTP/1.1\r\nContent-Length: 4\r\nContent-Length: 4\r\n\r\n"))
XCTFail("Did not throw")
} catch HTTPParserError.unexpectedContentLength {
// ok
} catch {
XCTFail("Unexpected error \(error)")
let request = "POST / HTTP/1.1\r\nContent-Length: 4\r\nContent-Length: 4\r\n\r\n"
XCTAssertThrowsError(try channel.writeInbound(ByteBuffer(string: request))) { error in
XCTAssertEqual(HTTPParserError.unexpectedContentLength, error as? HTTPParserError)
}
// Must spin the loop.
+24 -59
View File
@@ -34,23 +34,18 @@ class HTTPDecoderTest: XCTestCase {
func testDoesNotDecodeRealHTTP09Request() throws {
XCTAssertNoThrow(try channel.pipeline.addHandler(ByteToMessageHandler(HTTPRequestDecoder())).wait())
// This is an invalid HTTP/0.9 simple request (too many CRLFs), but we need to
// trigger https://github.com/nodejs/http-parser/issues/386 or http_parser won't
// actually parse this at all.
var buffer = channel.allocator.buffer(capacity: 64)
buffer.writeStaticString("GET /a-file\r\n\r\n")
do {
try channel.writeInbound(buffer)
XCTFail("Did not error")
} catch HTTPParserError.invalidVersion {
// ok
} catch {
XCTFail("Unexpected error: \(error)")
XCTAssertThrowsError(try channel.writeInbound(buffer)) { error in
XCTAssertEqual(.invalidVersion, error as? HTTPParserError)
}
loop.run()
self.loop.run()
}
func testDoesNotDecodeFakeHTTP09Request() throws {
@@ -60,16 +55,11 @@ class HTTPDecoderTest: XCTestCase {
var buffer = channel.allocator.buffer(capacity: 64)
buffer.writeStaticString("GET / HTTP/0.9\r\nHost: whatever\r\n\r\n")
do {
try channel.writeInbound(buffer)
XCTFail("Did not error")
} catch HTTPParserError.invalidVersion {
// ok
} catch {
XCTFail("Unexpected error: \(error)")
XCTAssertThrowsError(try channel.writeInbound(buffer)) { error in
XCTAssertEqual(.invalidVersion, error as? HTTPParserError)
}
loop.run()
self.loop.run()
}
func testDoesNotDecodeHTTP2XRequest() throws {
@@ -80,16 +70,11 @@ class HTTPDecoderTest: XCTestCase {
var buffer = channel.allocator.buffer(capacity: 64)
buffer.writeStaticString("GET / HTTP/2.0\r\nHost: whatever\r\n\r\n")
do {
try channel.writeInbound(buffer)
XCTFail("Did not error")
} catch HTTPParserError.invalidVersion {
// ok
} catch {
XCTFail("Unexpected error: \(error)")
XCTAssertThrowsError(try channel.writeInbound(buffer)) { error in
XCTAssertEqual(.invalidVersion, error as? HTTPParserError)
}
loop.run()
self.loop.run()
}
func testToleratesHTTP13Request() throws {
@@ -116,16 +101,11 @@ class HTTPDecoderTest: XCTestCase {
var buffer = channel.allocator.buffer(capacity: 64)
buffer.writeStaticString("This is file data\n")
do {
try channel.writeInbound(buffer)
XCTFail("Did not error")
} catch HTTPParserError.invalidConstant {
// ok
} catch {
XCTFail("Unexpected error: \(error)")
XCTAssertThrowsError(try channel.writeInbound(buffer)) { error in
XCTAssertEqual(.invalidConstant, error as? HTTPParserError)
}
loop.run()
self.loop.run()
}
func testDoesNotDecodeFakeHTTP09Response() throws {
@@ -139,16 +119,11 @@ class HTTPDecoderTest: XCTestCase {
var buffer = channel.allocator.buffer(capacity: 64)
buffer.writeStaticString("HTTP/0.9 200 OK\r\nServer: whatever\r\n\r\n")
do {
try channel.writeInbound(buffer)
XCTFail("Did not error")
} catch HTTPParserError.invalidVersion {
// ok
} catch {
XCTFail("Unexpected error: \(error)")
XCTAssertThrowsError(try channel.writeInbound(buffer)) { error in
XCTAssertEqual(.invalidVersion, error as? HTTPParserError)
}
loop.run()
self.loop.run()
}
func testDoesNotDecodeHTTP2XResponse() throws {
@@ -163,16 +138,11 @@ class HTTPDecoderTest: XCTestCase {
var buffer = channel.allocator.buffer(capacity: 64)
buffer.writeStaticString("HTTP/2.0 200 OK\r\nServer: whatever\r\n\r\n")
do {
try channel.writeInbound(buffer)
XCTFail("Did not error")
} catch HTTPParserError.invalidVersion {
// ok
} catch {
XCTFail("Unexpected error: \(error)")
XCTAssertThrowsError(try channel.writeInbound(buffer)) { error in
XCTAssertEqual(.invalidVersion, error as? HTTPParserError)
}
loop.run()
self.loop.run()
}
func testToleratesHTTP13Response() throws {
@@ -844,16 +814,11 @@ class HTTPDecoderTest: XCTestCase {
"Transfer-Encoding: gzip, chunked\r\n\r\n" +
"3\r\na=1\r\n0\r\n\r\n")
do {
try channel.writeInbound(buffer)
XCTFail("Did not error")
} catch HTTPParserError.unexpectedContentLength {
// ok
} catch {
XCTFail("Unexpected error: \(error)")
XCTAssertThrowsError(try channel.writeInbound(buffer)) { error in
XCTAssertEqual(.unexpectedContentLength, error as? HTTPParserError)
}
loop.run()
self.loop.run()
}
func testTrimsTrailingOWS() throws {
@@ -141,15 +141,9 @@ class HTTPRequestEncoderTests: XCTestCase {
}
private func assertOutboundContainsOnly(_ channel: EmbeddedChannel, _ expected: String) {
do {
if let buffer = try channel.readOutbound(as: ByteBuffer.self) {
buffer.assertContainsOnly(expected)
} else {
fatalError("Could not read ByteBuffer from channel")
}
} catch {
XCTFail("unexpected error: \(error)")
}
XCTAssertNoThrow(XCTAssertNotNil(try channel.readOutbound(as: ByteBuffer.self).map { buffer in
buffer.assertContainsOnly(expected)
}, "couldn't read ByteBuffer"))
}
}
@@ -66,13 +66,8 @@ class HTTPServerProtocolErrorHandlerTest: XCTestCase {
XCTAssertNoThrow(try channel.pipeline.configureHTTPServerPipeline(withErrorHandling: true).wait())
channel.pipeline.fireErrorCaught(DummyError.error)
do {
try channel.throwIfErrorCaught()
XCTFail("No error caught")
} catch DummyError.error {
// ok
} catch {
XCTFail("Unexpected error: \(error)")
XCTAssertThrowsError(try channel.throwIfErrorCaught()) { error in
XCTAssertEqual(DummyError.error, error as? DummyError)
}
XCTAssertNoThrow(try channel.finish())
@@ -38,11 +38,7 @@ extension ChannelPipeline {
}
func assertContains<Handler: ChannelHandler>(handlerType: Handler.Type) throws {
do {
_ = try self.context(handlerType: handlerType).wait()
} catch ChannelPipelineError.notFound {
XCTFail("Did not find handler")
}
XCTAssertNoThrow(try self.context(handlerType: handlerType).wait(), "did not find handler")
}
fileprivate func removeUpgrader() throws {
@@ -425,11 +421,8 @@ class HTTPServerUpgradeTestCase: XCTestCase {
XCTAssertNoThrow(try channel.pipeline.addHandler(handler).wait())
do {
try channel.writeInbound(data)
XCTFail("Writing of bad data did not error")
} catch HTTPServerUpgradeErrors.invalidHTTPOrdering {
// Nothing to see here.
XCTAssertThrowsError(try channel.writeInbound(data)) { error in
XCTAssertEqual(.invalidHTTPOrdering, error as? HTTPServerUpgradeErrors)
}
// The handler removed itself from the pipeline and passed the unexpected
@@ -924,13 +917,9 @@ class HTTPServerUpgradeTestCase: XCTestCase {
XCTAssertEqual(upgradingProtocol, "myproto")
XCTAssertNoThrow(try channel.pipeline.assertContainsUpgrader())
XCTAssertNoThrow(XCTAssertNil(try channel.readOutbound(as: ByteBuffer.self)))
do {
try channel.throwIfErrorCaught()
XCTFail("Did not throw")
} catch No.no {
// ok
} catch {
XCTFail("Unexpected error: \(error)")
XCTAssertThrowsError(try channel.throwIfErrorCaught()) { error in
XCTAssertEqual(.no, error as? No)
}
// Ok, now we can upgrade. Upgrader should be out of the pipeline, and we should have seen the 101 response.
@@ -985,13 +974,8 @@ class HTTPServerUpgradeTestCase: XCTestCase {
XCTAssertNoThrow(try channel.pipeline.assertDoesNotContainUpgrader())
XCTAssertNoThrow(XCTAssertNil(try channel.readOutbound(as: ByteBuffer.self)))
do {
try channel.throwIfErrorCaught()
XCTFail("Did not throw")
} catch No.no {
// ok
} catch {
XCTFail("Unexpected error: \(error)")
XCTAssertThrowsError(try channel.throwIfErrorCaught()) { error in
XCTAssertEqual(.no, error as? No)
}
switch try channel.readInbound(as: HTTPServerRequestPart.self) {
@@ -1065,13 +1049,8 @@ class HTTPServerUpgradeTestCase: XCTestCase {
XCTAssertNoThrow(try channel.pipeline.assertDoesNotContainUpgrader())
XCTAssertNoThrow(XCTAssertNil(try channel.readOutbound(as: ByteBuffer.self)))
do {
try channel.throwIfErrorCaught()
XCTFail("Did not throw")
} catch No.no {
// ok
} catch {
XCTFail("Unexpected error: \(error)")
XCTAssertThrowsError(try channel.throwIfErrorCaught()) { error in
XCTAssertEqual(.no, error as? No)
}
switch try channel.readInbound(as: HTTPServerRequestPart.self) {
+40 -101
View File
@@ -44,26 +44,20 @@ private final class IndexWritingHandler: ChannelDuplexHandler {
private extension EmbeddedChannel {
func assertReadIndexOrder(_ order: [UInt8]) {
XCTAssertTrue(try self.writeInbound(self.allocator.buffer(capacity: 32)).isFull)
do {
var outBuffer: ByteBuffer = try self.readInbound()!
XCTAssertEqual(outBuffer.readBytes(length: outBuffer.readableBytes)!, order)
} catch {
XCTFail("unexpected error: \(error)")
}
XCTAssertNoThrow(XCTAssertEqual(order,
try self.readInbound(as: ByteBuffer.self).flatMap { buffer in
var buffer = buffer
return buffer.readBytes(length: buffer.readableBytes)
}))
}
func assertWriteIndexOrder(_ order: [UInt8]) {
XCTAssertTrue(try self.writeOutbound(self.allocator.buffer(capacity: 32)).isFull)
do {
guard var outBuffer2 = try self.readOutbound(as: ByteBuffer.self) else {
XCTFail("Could not read byte buffer")
return
}
XCTAssertEqual(outBuffer2.readBytes(length: outBuffer2.readableBytes)!, order)
} catch {
XCTFail("unexpected error: \(error)")
}
XCTAssertNoThrow(XCTAssertEqual(order,
try self.readOutbound(as: ByteBuffer.self).flatMap { buffer in
var buffer = buffer
return buffer.readBytes(length: buffer.readableBytes)
}))
}
}
@@ -154,11 +148,8 @@ class ChannelPipelineTest: XCTestCase {
XCTAssertFalse(handler.handlerAddedCalled.load())
XCTAssertFalse(handler.handlerRemovedCalled.load())
}
do {
try channel.pipeline.addHandler(handler).wait()
XCTFail()
} catch let err as ChannelError {
XCTAssertEqual(err, .ioOnClosedChannel)
XCTAssertThrowsError(try channel.pipeline.addHandler(handler).wait()) { error in
XCTAssertEqual(.ioOnClosedChannel, error as? ChannelError)
}
}
@@ -597,13 +588,8 @@ class ChannelPipelineTest: XCTestCase {
func testAddAfterWhileClosed() {
let channel = EmbeddedChannel()
defer {
do {
_ = try channel.finish()
XCTFail("Did not throw")
} catch ChannelError.alreadyClosed {
// Ok
} catch {
XCTFail("unexpected error \(error)")
XCTAssertThrowsError(try channel.finish()) { error in
XCTAssertEqual(.alreadyClosed, error as? ChannelError)
}
}
@@ -612,13 +598,9 @@ class ChannelPipelineTest: XCTestCase {
XCTAssertNoThrow(try channel.close().wait())
channel.embeddedEventLoop.run()
do {
try channel.pipeline.addHandler(IndexWritingHandler(2), position: .after(handler)).wait()
XCTFail("Did not throw")
} catch ChannelError.ioOnClosedChannel {
// all good
} catch {
XCTFail("Got incorrect error: \(error)")
XCTAssertThrowsError(try channel.pipeline.addHandler(IndexWritingHandler(2),
position: .after(handler)).wait()) { error in
XCTAssertEqual(.ioOnClosedChannel, error as? ChannelError)
}
}
@@ -635,13 +617,9 @@ class ChannelPipelineTest: XCTestCase {
XCTAssertNoThrow(try channel.close().wait())
channel.embeddedEventLoop.run()
do {
try channel.pipeline.addHandler(IndexWritingHandler(2), position: .before(handler)).wait()
XCTFail("Did not throw")
} catch ChannelError.ioOnClosedChannel {
// all good
} catch {
XCTFail("Got incorrect error: \(error)")
XCTAssertThrowsError(try channel.pipeline.addHandler(IndexWritingHandler(2),
position: .before(handler)).wait()) { error in
XCTAssertEqual(.ioOnClosedChannel, error as? ChannelError)
}
}
@@ -674,13 +652,8 @@ class ChannelPipelineTest: XCTestCase {
XCTAssertTrue(try h1 === channel.pipeline.context(handlerType: TypeAHandler.self).wait().handler)
XCTAssertTrue(try h2 === channel.pipeline.context(handlerType: TypeBHandler.self).wait().handler)
do {
_ = try channel.pipeline.context(handlerType: TypeCHandler.self).wait()
XCTFail("Did not throw")
} catch ChannelPipelineError.notFound {
// ok
} catch {
XCTFail("Unexpected error \(error)")
XCTAssertThrowsError(try channel.pipeline.context(handlerType: TypeCHandler.self).wait()) { error in
XCTAssertEqual(.notFound, error as? ChannelPipelineError)
}
}
@@ -711,32 +684,20 @@ class ChannelPipelineTest: XCTestCase {
XCTAssertTrue(try channel.finish().isClean)
}
do {
_ = try channel.pipeline.context(name: HeadChannelHandler.name).wait()
XCTFail()
} catch let err as ChannelPipelineError where err == .notFound {
/// expected
XCTAssertThrowsError(try channel.pipeline.context(name: HeadChannelHandler.name).wait()) { error in
XCTAssertEqual(.notFound, error as? ChannelPipelineError)
}
do {
_ = try channel.pipeline.context(handlerType: HeadChannelHandler.self).wait()
XCTFail()
} catch let err as ChannelPipelineError where err == .notFound {
/// expected
XCTAssertThrowsError(try channel.pipeline.context(handlerType: HeadChannelHandler.self).wait()) { error in
XCTAssertEqual(.notFound, error as? ChannelPipelineError)
}
do {
_ = try channel.pipeline.context(name: TailChannelHandler.name).wait()
XCTFail()
} catch let err as ChannelPipelineError where err == .notFound {
/// expected
XCTAssertThrowsError(try channel.pipeline.context(name: TailChannelHandler.name).wait()) { error in
XCTAssertEqual(.notFound, error as? ChannelPipelineError)
}
do {
_ = try channel.pipeline.context(handlerType: TailChannelHandler.self).wait()
XCTFail()
} catch let err as ChannelPipelineError where err == .notFound {
/// expected
XCTAssertThrowsError(try channel.pipeline.context(handlerType: TailChannelHandler.self).wait()) { error in
XCTAssertEqual(.notFound, error as? ChannelPipelineError)
}
}
@@ -747,18 +708,11 @@ class ChannelPipelineTest: XCTestCase {
XCTAssertTrue(try channel.finish().isClean)
}
do {
_ = try channel.pipeline.removeHandler(name: HeadChannelHandler.name).wait()
XCTFail()
} catch let err as ChannelPipelineError where err == .notFound {
/// expected
XCTAssertThrowsError(try channel.pipeline.removeHandler(name: HeadChannelHandler.name).wait()) { error in
XCTAssertEqual(.notFound, error as? ChannelPipelineError)
}
do {
_ = try channel.pipeline.removeHandler(name: TailChannelHandler.name).wait()
XCTFail()
} catch let err as ChannelPipelineError where err == .notFound {
/// expected
XCTAssertThrowsError(try channel.pipeline.removeHandler(name: TailChannelHandler.name).wait()) { error in
XCTAssertEqual(.notFound, error as? ChannelPipelineError)
}
}
@@ -798,13 +752,8 @@ class ChannelPipelineTest: XCTestCase {
}
XCTAssertEqual(receivedBuffer, buffer)
do {
try channel.throwIfErrorCaught()
XCTFail("Did not throw")
} catch is DummyError {
// expected
} catch {
XCTFail("Unexpected error: \(error)")
XCTAssertThrowsError(try channel.throwIfErrorCaught()) { error in
XCTAssertNotNil(error as? DummyError)
}
}
@@ -870,13 +819,8 @@ class ChannelPipelineTest: XCTestCase {
XCTAssertNoThrow(XCTAssertEqual(try channel.readOutbound(), buffer))
do {
try channel.throwIfErrorCaught()
XCTFail("Did not throw")
} catch is DummyError {
// expected
} catch {
XCTFail("Unexpected error: \(error)")
XCTAssertThrowsError(try channel.throwIfErrorCaught()) { error in
XCTAssertNotNil(error as? DummyError)
}
}
@@ -941,13 +885,8 @@ class ChannelPipelineTest: XCTestCase {
XCTAssertNoThrow(XCTAssertEqual(try channel.readOutbound(), buffer))
do {
try channel.throwIfErrorCaught()
XCTFail("Did not throw")
} catch is DummyError {
// expected
} catch {
XCTFail("Unexpected error: \(error)")
XCTAssertThrowsError(try channel.throwIfErrorCaught()) { error in
XCTAssertNotNil(error as? DummyError)
}
}
+40 -78
View File
@@ -1141,11 +1141,8 @@ public final class ChannelTests: XCTestCase {
try channel.close(mode: .output).wait()
verificationHandler.waitForEvent()
do {
try channel.writeAndFlush(NIOAny(buffer)).wait()
XCTFail()
} catch let err as ChannelError {
XCTAssertEqual(ChannelError.outputClosed, err)
XCTAssertThrowsError(try channel.writeAndFlush(NIOAny(buffer)).wait()) { error in
XCTAssertEqual(.outputClosed, error as? ChannelError)
}
let written = try buffer.withUnsafeReadableBytes { p in
try accepted.write(pointer: UnsafeRawBufferPointer(rebasing: p.prefix(4)))
@@ -1386,16 +1383,11 @@ public final class ChannelTests: XCTestCase {
XCTAssertNoThrow(try serverChannel.closeFuture.wait())
}()
let pipeline = try promise.futureResult.wait()
do {
try pipeline.eventLoop.submit { () -> Channel in
XCTAssertTrue(pipeline.channel is DeadChannel)
return pipeline.channel
}.wait().writeAndFlush(NIOAny(())).wait()
XCTFail("shouldn't have been reached")
} catch let e as ChannelError where e == .ioOnClosedChannel {
// OK
} catch {
XCTFail("wrong error \(error) received")
XCTAssertThrowsError(try pipeline.eventLoop.submit { () -> Channel in
XCTAssertTrue(pipeline.channel is DeadChannel)
return pipeline.channel
}.wait().writeAndFlush(NIOAny(())).wait()) { error in
XCTAssertEqual(.ioOnClosedChannel, error as? ChannelError)
}
// Annoyingly it's totally possible to get to this stage and have the channels
@@ -1843,8 +1835,9 @@ public final class ChannelTests: XCTestCase {
closeFutures.forEach {
do {
try $0.wait()
} catch let e as ChannelError where e == .alreadyClosed {
// ok
// No error is okay,
} catch ChannelError.alreadyClosed {
// as well as already closed.
} catch {
XCTFail("unexpected error \(error) received")
}
@@ -1967,13 +1960,8 @@ public final class ChannelTests: XCTestCase {
func testAppropriateAndInappropriateOperationsForUnregisteredSockets() throws {
func checkThatItThrowsInappropriateOperationForState(file: StaticString = #file, line: UInt = #line, _ body: () throws -> Void) {
do {
try body()
XCTFail("didn't throw", file: file, line: line)
} catch let error as ChannelError where error == .inappropriateOperationForState {
//OK
} catch {
XCTFail("unexpected error \(error)", file: file, line: line)
XCTAssertThrowsError(try body(), file: file, line: line) { error in
XCTAssertEqual(.inappropriateOperationForState, error as? ChannelError)
}
}
let elg = MultiThreadedEventLoopGroup(numberOfThreads: 1)
@@ -2177,13 +2165,8 @@ public final class ChannelTests: XCTestCase {
}
}
}.wait()
do {
try cf.wait()
XCTFail("should've thrown")
} catch DummyError.dummy {
// ok
} catch {
XCTFail("unexpected error \(error)")
XCTAssertThrowsError(try cf.wait()) { error in
XCTAssertEqual(.dummy, error as? DummyError)
}
XCTAssertNoThrow(try allDone.futureResult.wait())
XCTAssertNoThrow(try sc.syncCloseAcceptingAlreadyClosed())
@@ -2251,13 +2234,8 @@ public final class ChannelTests: XCTestCase {
// we're just looping here to get a pretty good chance we're hitting both the synchronous and the asynchronous
// connect path.
for _ in 0..<64 {
do {
_ = try ClientBootstrap(group: group).connect(to: serverSockAddress).wait()
XCTFail("just worked")
} catch let error as IOError where error.errnoCode == ECONNREFUSED {
// OK
} catch {
XCTFail("unexpected error: \(error)")
XCTAssertThrowsError(try ClientBootstrap(group: group).connect(to: serverSockAddress).wait()) { error in
XCTAssertEqual(ECONNREFUSED, (error as? IOError).map { $0.errnoCode })
}
}
}
@@ -2294,26 +2272,20 @@ public final class ChannelTests: XCTestCase {
}
}.wait() as Void)
do {
try sc.eventLoop.flatSubmit { () -> EventLoopFuture<Void> in
let p = sc.eventLoop.makePromise(of: Void.self)
// this callback must be attached before we call the close
let f = p.futureResult.map {
XCTFail("shouldn't be reached")
}.flatMapError { err in
XCTAssertNotNil(err as? DummyError)
return sc.close()
}
sc.close(promise: p)
return f
}.wait()
XCTFail("shouldn't be reached")
} catch ChannelError.alreadyClosed {
// ok
} catch {
XCTFail("wrong error: \(error)")
XCTAssertThrowsError(try sc.eventLoop.flatSubmit { () -> EventLoopFuture<Void> in
let p = sc.eventLoop.makePromise(of: Void.self)
// this callback must be attached before we call the close
let f = p.futureResult.map {
XCTFail("shouldn't be reached")
}.flatMapError { err in
XCTAssertNotNil(err as? DummyError)
return sc.close()
}
sc.close(promise: p)
return f
}.wait()) { error in
XCTAssertEqual(.alreadyClosed, error as? ChannelError)
}
}
func testLazyRegistrationWorksForServerSockets() throws {
@@ -2371,18 +2343,13 @@ public final class ChannelTests: XCTestCase {
defer {
XCTAssertNoThrow(try serverChannel.close().wait())
}
do {
let clientChannel = try ClientBootstrap(group: group)
.channelInitializer { channel in
channel.pipeline.addHandler(FailRegistrationAndDelayCloseHandler())
}
.connect(to: serverChannel.localAddress!)
.wait()
XCTFail("shouldn't have reached this but got \(clientChannel)")
} catch FailRegistrationAndDelayCloseHandler.RegistrationFailedError.error {
// ok
} catch {
XCTFail("unexpected error \(error)")
XCTAssertThrowsError(try ClientBootstrap(group: group)
.channelInitializer { channel in
channel.pipeline.addHandler(FailRegistrationAndDelayCloseHandler())
}
.connect(to: serverChannel.localAddress!)
.wait()) { error in
XCTAssertEqual(.error, error as? FailRegistrationAndDelayCloseHandler.RegistrationFailedError)
}
}
@@ -2410,18 +2377,13 @@ public final class ChannelTests: XCTestCase {
defer {
XCTAssertNoThrow(try group.syncShutdownGracefully())
}
do {
let serverChannel = try ServerBootstrap(group: group)
XCTAssertThrowsError(try ServerBootstrap(group: group)
.serverChannelInitializer { channel in
channel.pipeline.addHandler(FailRegistrationAndDelayCloseHandler())
}
.bind(host: "localhost", port: 0).wait()
XCTFail("shouldn't be reached")
XCTAssertNoThrow(try serverChannel.close().wait())
} catch FailRegistrationAndDelayCloseHandler.RegistrationFailedError.error {
// ok
} catch {
XCTFail("unexpected error \(error)")
.bind(host: "localhost", port: 0)
.wait()) { error in
XCTAssertEqual(.error, error as? FailRegistrationAndDelayCloseHandler.RegistrationFailedError)
}
}
+12 -36
View File
@@ -164,12 +164,8 @@ final class DatagramChannelTests: XCTestCase {
}
func testConnectionFails() throws {
do {
try self.firstChannel.connect(to: self.secondChannel.localAddress!).wait()
} catch ChannelError.operationUnsupported {
// All is well
} catch {
XCTFail("Encountered error: \(error)")
XCTAssertThrowsError(try self.firstChannel.connect(to: self.secondChannel.localAddress!).wait()) { error in
XCTAssertEqual(.operationUnsupported, error as? ChannelError)
}
}
@@ -216,16 +212,11 @@ final class DatagramChannelTests: XCTestCase {
}.wait()
XCTAssertTrue(fulfilled)
promises.forEach {
do {
try $0.wait()
XCTFail("Did not error")
} catch ChannelError.ioOnClosedChannel {
// All good
} catch {
XCTFail("Unexpected error: \(error)")
XCTAssertNoThrow(try promises.forEach {
XCTAssertThrowsError(try $0.wait()) { error in
XCTAssertEqual(.ioOnClosedChannel, error as? ChannelError)
}
}
})
}
func testManyManyDatagramWrites() throws {
@@ -291,13 +282,8 @@ final class DatagramChannelTests: XCTestCase {
let writeFut = self.firstChannel.write(NIOAny(envelope))
self.firstChannel.flush()
do {
try writeFut.wait()
XCTFail("Did not throw")
} catch ChannelError.writeMessageTooLarge {
// All good
} catch {
XCTFail("Got unexpected error \(error)")
XCTAssertThrowsError(try writeFut.wait()) { error in
XCTAssertEqual(.writeMessageTooLarge, error as? ChannelError)
}
}
@@ -324,13 +310,8 @@ final class DatagramChannelTests: XCTestCase {
XCTAssertNoThrow(try thirdWrite.wait())
// The second should have failed.
do {
try secondWrite.wait()
XCTFail("Did not throw")
} catch ChannelError.writeMessageTooLarge {
// All good
} catch {
XCTFail("Got unexpected error \(error)")
XCTAssertThrowsError(try secondWrite.wait()) { error in
XCTAssertEqual(.writeMessageTooLarge, error as? ChannelError)
}
}
@@ -357,13 +338,8 @@ final class DatagramChannelTests: XCTestCase {
XCTAssertNoThrow(try thirdWrite.wait())
// The second should have failed.
do {
try secondWrite.wait()
XCTFail("Did not throw")
} catch ChannelError.writeMessageTooLarge {
// All good
} catch {
XCTFail("Got unexpected error \(error)")
XCTAssertThrowsError(try secondWrite.wait()) { error in
XCTAssertEqual(.writeMessageTooLarge, error as? ChannelError)
}
}
+26 -91
View File
@@ -104,13 +104,8 @@ class EventLoopFutureTest : XCTestCase {
_ = promises.map { $0.succeed(0) }
XCTAssert(fN.isFulfilled)
do {
_ = try fN.wait()
XCTFail("should've thrown an error")
} catch _ as E {
/* good */
} catch let e {
XCTFail("error of wrong type \(e)")
XCTAssertThrowsError(try fN.wait()) { error in
XCTAssertNotNil(error as? E)
}
}
@@ -143,13 +138,8 @@ class EventLoopFutureTest : XCTestCase {
}
XCTAssert(fN.isFulfilled)
do {
_ = try fN.wait()
XCTFail("should've thrown an error")
} catch _ as E {
/* good */
} catch let e {
XCTFail("error of wrong type \(e)")
XCTAssertThrowsError(try fN.wait()) { error in
XCTAssertNotNil(error as? E)
}
}
@@ -169,13 +159,8 @@ class EventLoopFutureTest : XCTestCase {
_ = promises.map { $0.succeed(1) }
XCTAssert(fN.isFulfilled)
do {
_ = try fN.wait()
XCTFail("should've thrown an error")
} catch _ as E {
/* good */
} catch let e {
XCTFail("error of wrong type \(e)")
XCTAssertThrowsError(try fN.wait()) { error in
XCTAssertNotNil(error as? E)
}
}
@@ -194,13 +179,8 @@ class EventLoopFutureTest : XCTestCase {
}
XCTAssert(fN.isFulfilled)
do {
_ = try fN.wait()
XCTFail("should've thrown an error")
} catch _ as E {
/* good */
} catch let e {
XCTFail("error of wrong type \(e)")
XCTAssertThrowsError(try fN.wait()) { error in
XCTAssertNotNil(error as? E)
}
}
@@ -218,13 +198,8 @@ class EventLoopFutureTest : XCTestCase {
}
XCTAssert(fN.isFulfilled)
do {
_ = try fN.wait()
XCTFail("should've thrown an error")
} catch _ as E {
/* good */
} catch let e {
XCTFail("error of wrong type \(e)")
XCTAssertThrowsError(try fN.wait()) { error in
XCTAssertNotNil(error as? E)
}
}
@@ -255,13 +230,8 @@ class EventLoopFutureTest : XCTestCase {
let fN = EventLoopFuture.andAllSucceed(futures, on: eventLoop)
_ = promises.map { $0.fail(E()) }
do {
() = try fN.wait()
XCTFail("should've thrown an error")
} catch _ as E {
/* good */
} catch let e {
XCTFail("error of wrong type \(e)")
XCTAssertThrowsError(try fN.wait()) { error in
XCTAssertNotNil(error as? E)
}
}
@@ -277,13 +247,8 @@ class EventLoopFutureTest : XCTestCase {
let futures = promises.map { $0.futureResult }
let fN = EventLoopFuture.andAllSucceed(futures, on: eventLoop)
do {
() = try fN.wait()
XCTFail("should've thrown an error")
} catch _ as E {
/* good */
} catch let e {
XCTFail("error of wrong type \(e)")
XCTAssertThrowsError(try fN.wait()) { error in
XCTAssertNotNil(error as? E)
}
}
@@ -325,13 +290,8 @@ class EventLoopFutureTest : XCTestCase {
let fN: EventLoopFuture<Int> = EventLoopFuture<Int>.reduce(0, futures, on: eventLoop, +)
_ = promises.map { $0.fail(E()) }
XCTAssert(fN.eventLoop === eventLoop)
do {
_ = try fN.wait()
XCTFail("should've thrown an error")
} catch _ as E {
/* good */
} catch let e {
XCTFail("error of wrong type \(e)")
XCTAssertThrowsError(try fN.wait()) { error in
XCTAssertNotNil(error as? E)
}
}
@@ -348,13 +308,8 @@ class EventLoopFutureTest : XCTestCase {
let fN: EventLoopFuture<Int> = EventLoopFuture<Int>.reduce(0, futures, on: eventLoop, +)
XCTAssert(fN.eventLoop === eventLoop)
do {
_ = try fN.wait()
XCTFail("should've thrown an error")
} catch _ as E {
/* good */
} catch let e {
XCTFail("error of wrong type \(e)")
XCTAssertThrowsError(try fN.wait()) { error in
XCTAssertNotNil(error as? E)
}
}
@@ -373,13 +328,8 @@ class EventLoopFutureTest : XCTestCase {
XCTAssertTrue(fN.isFulfilled)
XCTAssert(fN.eventLoop === eventLoop)
do {
_ = try fN.wait()
XCTFail("should've thrown an error")
} catch _ as E {
/* good */
} catch let e {
XCTFail("error of wrong type \(e)")
XCTAssertThrowsError(try fN.wait()) { error in
XCTAssertNotNil(error as? E)
}
}
@@ -432,13 +382,8 @@ class EventLoopFutureTest : XCTestCase {
XCTAssert(fN.isFulfilled)
XCTAssert(fN.eventLoop === eventLoop)
do {
_ = try fN.wait()
XCTFail("should've thrown an error")
} catch _ as E {
/* good */
} catch let e {
XCTFail("error of wrong type \(e)")
XCTAssertThrowsError(try fN.wait()) { error in
XCTAssertNotNil(error as? E)
}
}
@@ -625,13 +570,8 @@ class EventLoopFutureTest : XCTestCase {
}
prev = p.futureResult
}
do {
_ = try prev.wait()
XCTFail("should have failed")
} catch _ as DummyError {
// OK
} catch {
XCTFail("wrong error \(error)")
XCTAssertThrowsError(try prev.wait()) { error in
XCTAssertNotNil(error as? DummyError)
}
XCTAssertNoThrow(try elg.syncShutdownGracefully())
}
@@ -670,13 +610,8 @@ class EventLoopFutureTest : XCTestCase {
}
}
}
do {
try allOfEm.wait()
XCTFail("unexpected failure")
} catch _ as DummyError {
// ok
} catch {
XCTFail("unexpected error: \(error)")
XCTAssertThrowsError(try allOfEm.wait()) { error in
XCTAssertNotNil(error as? DummyError)
}
XCTAssertNoThrow(try elg.syncShutdownGracefully())
XCTAssertNoThrow(try fireBackEl.syncShutdownGracefully())
+4 -13
View File
@@ -420,12 +420,8 @@ public final class EventLoopTest : XCTestCase {
let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
defer {
do {
try group.syncShutdownGracefully()
} catch EventLoopError.shutdown {
// Fine, that's expected if the test completed.
} catch {
XCTFail("Unexpected error on close: \(error)")
XCTAssertThrowsError(try group.syncShutdownGracefully()) { error in
XCTAssertEqual(.shutdown, error as? EventLoopError)
}
}
let loop = group.next() as! SelectableEventLoop
@@ -477,13 +473,8 @@ public final class EventLoopTest : XCTestCase {
// Now we're going to attempt to register a new channel. This should immediately fail.
let newChannel = try SocketChannel(eventLoop: loop, protocolFamily: AF_INET)
do {
try newChannel.register().wait()
XCTFail("Register did not throw")
} catch EventLoopError.shutdown {
// All good
} catch {
XCTFail("Unexpected error: \(error)")
XCTAssertThrowsError(try newChannel.register().wait()) { error in
XCTAssertEqual(.shutdown, error as? EventLoopError)
}
// Confirm that the loop still hasn't closed.
+10 -15
View File
@@ -152,21 +152,16 @@ class FileRegionTest : XCTestCase {
XCTAssertNoThrow(try fh2.close())
}
try content.write(toFile: filePath, atomically: false, encoding: .ascii)
do {
() = try clientChannel.writeAndFlush(NIOAny(fr1)).flatMap {
let frFuture = clientChannel.write(NIOAny(fr2))
var buffer = clientChannel.allocator.buffer(capacity: bytes.count)
buffer.writeBytes(bytes)
let bbFuture = clientChannel.write(NIOAny(buffer))
clientChannel.close(promise: nil)
clientChannel.flush()
return frFuture.flatMap { bbFuture }
}.wait()
XCTFail("no error happened even though we closed before flush")
} catch let e as ChannelError {
XCTAssertEqual(ChannelError.ioOnClosedChannel, e)
} catch let e {
XCTFail("unexpected error \(e)")
XCTAssertThrowsError(try clientChannel.writeAndFlush(NIOAny(fr1)).flatMap { () -> EventLoopFuture<Void> in
let frFuture = clientChannel.write(NIOAny(fr2))
var buffer = clientChannel.allocator.buffer(capacity: bytes.count)
buffer.writeBytes(bytes)
let bbFuture = clientChannel.write(NIOAny(buffer))
clientChannel.close(promise: nil)
clientChannel.flush()
return frFuture.flatMap { bbFuture }
}.wait()) { error in
XCTAssertEqual(.ioOnClosedChannel, error as? ChannelError)
}
var buffer = clientChannel.allocator.buffer(capacity: bytes.count)
+6 -15
View File
@@ -32,8 +32,9 @@ private extension Array where Element == Channel {
self.forEach {
do {
_ = try($0 as! EmbeddedChannel).finish()
// We're happy with no error
} catch ChannelError.alreadyClosed {
return
return // as well as already closed.
} catch {
XCTFail("Finishing got error \(error)")
}
@@ -1168,13 +1169,8 @@ public final class HappyEyeballsTest : XCTestCase {
// At this time the connection attempt should have failed, as the connect timeout
// fired.
do {
_ = try channelFuture.wait()
XCTFail("connection succeeded")
} catch ChannelError.connectTimeout(.milliseconds(250)) {
// ok
} catch {
XCTFail("Unexpected error: \(error)")
XCTAssertThrowsError(try channelFuture.wait()) { error in
XCTAssertEqual(.connectTimeout(.milliseconds(250)), error as? ChannelError)
}
// There may be one or two channels, depending on ordering, but both
@@ -1217,13 +1213,8 @@ public final class HappyEyeballsTest : XCTestCase {
// At this time the connection attempt should have failed, as the connect timeout
// fired.
do {
_ = try channelFuture.wait()
XCTFail("connection succeeded")
} catch ChannelError.connectTimeout(.milliseconds(50)) {
// ok
} catch {
XCTFail("Unexpected error: \(error)")
XCTAssertThrowsError(try channelFuture.wait()) { error in
XCTAssertEqual(.connectTimeout(.milliseconds(50)), error as? ChannelError)
}
// There may be zero or one channels, depending on ordering, but if there is one it
+23 -43
View File
@@ -134,16 +134,11 @@ class NonBlockingFileIOTest: XCTestCase {
}
try withPipe { readFH, writeFH in
do {
_ = try self.fileIO.read(fileHandle: readFH,
XCTAssertThrowsError(try self.fileIO.read(fileHandle: readFH,
byteCount: 1,
allocator: self.allocator,
eventLoop: self.eventLoop).wait()
XCTFail("should've thrown")
} catch let e as ChannelError {
XCTAssertEqual(ChannelError.ioOnClosedChannel, e)
} catch {
XCTFail("unexpected error \(error)")
eventLoop: self.eventLoop).wait()) { error in
XCTAssertEqual(.ioOnClosedChannel, error as? ChannelError)
}
return [readFH, writeFH]
}
@@ -175,25 +170,20 @@ class NonBlockingFileIOTest: XCTestCase {
let content = "hello"
let contentBytes = Array(content.utf8)
var numCalls = 0
withTemporaryFile(content: content) { (fileHandle, path) -> Void in
try withTemporaryFile(content: content) { (fileHandle, path) -> Void in
let fr = FileRegion(fileHandle: fileHandle, readerIndex: 0, endIndex: 5)
do {
try self.fileIO.readChunked(fileRegion: fr,
chunkSize: 1,
allocator: self.allocator,
eventLoop: self.eventLoop) { buf in
var buf = buf
XCTAssertTrue(self.eventLoop.inEventLoop)
XCTAssertEqual(1, buf.readableBytes)
XCTAssertEqual(contentBytes[numCalls], buf.readBytes(length: 1)?.first!)
numCalls += 1
return self.eventLoop.makeFailedFuture(DummyError.dummy)
}.wait()
XCTFail("call successful but should've failed")
} catch let e as DummyError where e == .dummy {
// ok
} catch {
XCTFail("wrong error \(error) caught")
XCTAssertThrowsError(try self.fileIO.readChunked(fileRegion: fr,
chunkSize: 1,
allocator: self.allocator,
eventLoop: self.eventLoop) { buf in
var buf = buf
XCTAssertTrue(self.eventLoop.inEventLoop)
XCTAssertEqual(1, buf.readableBytes)
XCTAssertEqual(contentBytes[numCalls], buf.readBytes(length: 1)?.first!)
numCalls += 1
return self.eventLoop.makeFailedFuture(DummyError.dummy)
}.wait()) { error in
XCTAssertEqual(.dummy, error as? DummyError)
}
}
XCTAssertEqual(1, numCalls)
@@ -205,24 +195,19 @@ class NonBlockingFileIOTest: XCTestCase {
defer {
XCTAssertNoThrow(try unconnectedSockFH.close())
}
do {
try self.fileIO.readChunked(fileHandle: unconnectedSockFH,
XCTAssertThrowsError(try self.fileIO.readChunked(fileHandle: unconnectedSockFH,
byteCount: 5,
chunkSize: 1,
allocator: self.allocator,
eventLoop: self.eventLoop) { buf in
XCTFail("shouldn't have been called")
return self.eventLoop.makeSucceededFuture(())
}.wait()
XCTFail("call successful but should've failed")
} catch let e as IOError {
}.wait()) { error in
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
XCTAssertEqual(ENOTCONN, e.errnoCode)
XCTAssertEqual(ENOTCONN, (error as? IOError)?.errnoCode)
#else
XCTAssertEqual(EINVAL, e.errnoCode)
XCTAssertEqual(EINVAL, (error as? IOError)?.errnoCode)
#endif
} catch {
XCTFail("wrong error \(error) caught")
}
}
@@ -384,19 +369,14 @@ class NonBlockingFileIOTest: XCTestCase {
_ = try! Posix.write(descriptor: writeFD, pointer: "ABC", size: 3)
}
let fr = FileRegion(fileHandle: readFH, readerIndex: 1, endIndex: 2)
do {
try self.fileIO.readChunked(fileRegion: fr,
XCTAssertThrowsError(try self.fileIO.readChunked(fileRegion: fr,
chunkSize: 10,
allocator: self.allocator,
eventLoop: self.eventLoop) { buf in
XCTFail("this shouldn't have been called")
return self.eventLoop.makeSucceededFuture(())
}.wait()
XCTFail("succeeded and shouldn't have")
} catch let e as IOError where e.errnoCode == ESPIPE {
// OK
} catch {
XCTFail("wrong error \(error) caught")
}.wait()) { error in
XCTAssertEqual(ESPIPE, (error as? IOError)?.errnoCode)
}
return [readFH, writeFH]
}
+10 -30
View File
@@ -261,11 +261,8 @@ public final class SocketChannelTest : XCTestCase {
let serverChannel = try assertNoThrowWithValue(ServerBootstrap(group: group)
.bind(host: "127.0.0.1", port: 0)
.wait())
do {
try serverChannel.writeAndFlush("test").wait()
XCTFail("did not throw")
} catch let err as ChannelError where err == .operationUnsupported {
// expected
XCTAssertThrowsError(try serverChannel.writeAndFlush("test").wait()) { error in
XCTAssertEqual(.operationUnsupported, error as? ChannelError)
}
try serverChannel.close().wait()
}
@@ -278,10 +275,8 @@ public final class SocketChannelTest : XCTestCase {
let serverChannel = try assertNoThrowWithValue(ServerBootstrap(group: group)
.bind(host: "127.0.0.1", port: 0)
.wait())
do {
try serverChannel.writeAndFlush("test").wait()
} catch let err as ChannelError where err == .operationUnsupported {
// expected
XCTAssertThrowsError(try serverChannel.writeAndFlush("test").wait()) { error in
XCTAssertEqual(.operationUnsupported, error as? ChannelError)
}
try serverChannel.close().wait()
}
@@ -294,15 +289,8 @@ public final class SocketChannelTest : XCTestCase {
let serverChannel = try assertNoThrowWithValue(ServerBootstrap(group: group)
.bind(host: "127.0.0.1", port: 0)
.wait())
do {
try serverChannel.connect(to: serverChannel.localAddress!).wait()
XCTFail("Did not throw")
XCTAssertNoThrow(try serverChannel.close().wait())
} catch let err as ChannelError where err == .operationUnsupported {
// expected, no close here as the channel is already closed.
} catch {
XCTFail("Unexpected error \(error)")
XCTAssertNoThrow(try serverChannel.close().wait())
XCTAssertThrowsError(try serverChannel.writeAndFlush("test").wait()) { error in
XCTAssertEqual(.operationUnsupported, error as? ChannelError)
}
}
@@ -330,13 +318,8 @@ public final class SocketChannelTest : XCTestCase {
}
XCTAssertNoThrow(try clientChannel.close().wait())
do {
try writeFut.wait()
XCTFail("Did not throw")
} catch ChannelError.alreadyClosed {
// ok
} catch {
XCTFail("Unexpected error \(error)")
XCTAssertThrowsError(try writeFut.wait()) { error in
XCTAssertEqual(.alreadyClosed, error as? ChannelError)
}
}
@@ -471,11 +454,8 @@ public final class SocketChannelTest : XCTestCase {
}
}.wait() as Void)
do {
try connectPromise.futureResult.wait()
XCTFail("Did not throw")
} catch let err as ChannelError where err == .ioOnClosedChannel {
// expected
XCTAssertThrowsError(try connectPromise.futureResult.wait()) { error in
XCTAssertEqual(.ioOnClosedChannel, error as? ChannelError)
}
XCTAssertNoThrow(try closePromise.futureResult.wait())
XCTAssertNoThrow(try channel.closeFuture.wait())
@@ -142,13 +142,9 @@ final class SocketOptionProviderTest: XCTestCase {
// we just abandon the other tests: this is sufficient to prove that the error path works.
let provider = try assertNoThrowWithValue(self.convertedChannel())
do {
try provider.unsafeSetSocketOption(level: SocketOptionLevel(SOL_SOCKET), name: SO_RCVTIMEO, value: CInt(1)).wait()
XCTFail("Did not throw")
} catch let err as IOError where err.errnoCode == EINVAL {
// Acceptable error
} catch {
XCTFail("Invalid error: \(error)")
XCTAssertThrowsError(try provider.unsafeSetSocketOption(level: SocketOptionLevel(SOL_SOCKET),
name: SO_RCVTIMEO, value: CInt(1)).wait()) { error in
XCTAssertEqual(EINVAL, (error as? IOError)?.errnoCode)
}
}
+4 -2
View File
@@ -231,14 +231,16 @@ func assertSetGetOptionOnOpenAndClosed<Option: ChannelOption>(channel: Channel,
do {
_ = try channel.setOption(option, value: value).wait()
// We're okay with no error
} catch let err as ChannelError where err == .ioOnClosedChannel {
// expected
// as well as already closed channels.
}
do {
_ = try channel.getOption(option).wait()
// We're okay with no error
} catch let err as ChannelError where err == .ioOnClosedChannel {
// expected
// as well as already closed channels.
}
}
@@ -34,11 +34,8 @@ extension ChannelPipeline {
fileprivate func assertDoesNotContain<Handler: ChannelHandler>(handlerType: Handler.Type,
file: StaticString = #file,
line: UInt = #line) throws {
do {
let context = try self.context(handlerType: handlerType).wait()
XCTFail("Found handler: \(context.handler)", file: file, line: line)
} catch ChannelPipelineError.notFound {
// Nothing to see here
XCTAssertThrowsError(try self.context(handlerType: handlerType).wait(), file: file, line: line) { error in
XCTAssertEqual(.notFound, error as? ChannelPipelineError)
}
}
@@ -234,15 +231,10 @@ class WebSocketClientEndToEndTests: XCTestCase {
// Push the successful server response but with a missing accept key.
let response = "HTTP/1.1 101 Switching Protocols\r\nConnection: upgrade\r\nUpgrade: websocket\r\n\r\n"
do {
try clientChannel.writeInbound(ByteBuffer.forString(response))
XCTFail()
} catch {
if (error as? NIOHTTPClientUpgradeError) != .upgraderDeniedUpgrade {
XCTFail()
}
XCTAssertThrowsError(try clientChannel.writeInbound(ByteBuffer.forString(response))) { error in
XCTAssertEqual(.upgraderDeniedUpgrade, error as? NIOHTTPClientUpgradeError)
}
// Close the pipeline.
XCTAssertNoThrow(try clientChannel.close().wait())
}
@@ -265,15 +257,10 @@ class WebSocketClientEndToEndTests: XCTestCase {
// Push the successful server response but with an incorrect response key.
let response = "HTTP/1.1 101 Switching Protocols\r\nConnection: upgrade\r\nUpgrade: websocket\r\nSec-WebSocket-Accept:\(responseKey)\r\n\r\n"
do {
try clientChannel.writeInbound(ByteBuffer.forString(response))
XCTFail()
} catch {
if (error as? NIOHTTPClientUpgradeError) != .upgraderDeniedUpgrade {
XCTFail()
}
XCTAssertThrowsError(try clientChannel.writeInbound(ByteBuffer.forString(response))) { error in
XCTAssertEqual(.upgraderDeniedUpgrade, error as? NIOHTTPClientUpgradeError)
}
// Close the pipeline.
XCTAssertNoThrow(try clientChannel.close().wait())
}
@@ -296,15 +283,10 @@ class WebSocketClientEndToEndTests: XCTestCase {
// Push the successful server response with an incorrect protocol.
let response = "HTTP/1.1 101 Switching Protocols\r\nConnection: upgrade\r\nUpgrade: myProtocol\r\nSec-WebSocket-Accept:\(responseKey)\r\n\r\n"
do {
try clientChannel.writeInbound(ByteBuffer.forString(response))
XCTFail()
} catch {
if (error as? NIOHTTPClientUpgradeError) != .responseProtocolNotFound {
XCTFail()
}
XCTAssertThrowsError(try clientChannel.writeInbound(ByteBuffer.forString(response))) { error in
XCTAssertEqual(.responseProtocolNotFound, error as? NIOHTTPClientUpgradeError)
}
// Close the pipeline.
XCTAssertNoThrow(try clientChannel.close().wait())
}
@@ -247,13 +247,8 @@ public final class WebSocketFrameDecoderTest: XCTestCase {
// larger than the frame max.
self.buffer.writeBytes([0x81, 0xFE, 0x40, 0x01])
do {
try self.decoderChannel.writeInbound(self.buffer)
XCTFail("did not throw")
} catch NIOWebSocketError.invalidFrameLength {
// OK
} catch {
XCTFail("Unexpected error: \(error)")
XCTAssertThrowsError(try self.decoderChannel.writeInbound(self.buffer)) { error in
XCTAssertEqual(.invalidFrameLength, error as? NIOWebSocketError)
}
// We expect that an error frame will have been written out.
@@ -267,13 +262,8 @@ public final class WebSocketFrameDecoderTest: XCTestCase {
// A fake frame header that claims this is a fragmented ping frame.
self.buffer.writeBytes([0x09, 0x00])
do {
try self.decoderChannel.writeInbound(self.buffer)
XCTFail("did not throw")
} catch NIOWebSocketError.fragmentedControlFrame {
// OK
} catch {
XCTFail("Unexpected error: \(error)")
XCTAssertThrowsError(try self.decoderChannel.writeInbound(self.buffer)) { error in
XCTAssertEqual(.fragmentedControlFrame, error as? NIOWebSocketError)
}
// We expect that an error frame will have been written out.
@@ -287,13 +277,8 @@ public final class WebSocketFrameDecoderTest: XCTestCase {
// A fake frame header that claims this is a ping frame with 126 bytes of data.
self.buffer.writeBytes([0x89, 0x7E, 0x00, 0x7E])
do {
try self.decoderChannel.writeInbound(self.buffer)
XCTFail("did not throw")
} catch NIOWebSocketError.multiByteControlFrameLength {
// OK
} catch {
XCTFail("Unexpected error: \(error)")
XCTAssertThrowsError(try self.decoderChannel.writeInbound(self.buffer)) { error in
XCTAssertEqual(.multiByteControlFrameLength, error as? NIOWebSocketError)
}
// We expect that an error frame will have been written out.
@@ -309,13 +294,8 @@ public final class WebSocketFrameDecoderTest: XCTestCase {
// A fake frame header that claims this is a fragmented ping frame.
self.buffer.writeBytes([0x09, 0x00])
do {
try self.decoderChannel.writeInbound(self.buffer)
XCTFail("did not throw")
} catch NIOWebSocketError.fragmentedControlFrame {
// OK
} catch {
XCTFail("Unexpected error: \(error)")
XCTAssertThrowsError(try self.decoderChannel.writeInbound(self.buffer)) { error in
XCTAssertEqual(.fragmentedControlFrame, error as? NIOWebSocketError)
}
// We expect that an error frame will have been written out.
@@ -377,13 +357,8 @@ public final class WebSocketFrameDecoderTest: XCTestCase {
// larger than the frame max.
self.buffer.writeBytes([0x81, 0xFE, 0x40, 0x01])
do {
try self.decoderChannel.writeInbound(self.buffer)
XCTFail("did not throw")
} catch NIOWebSocketError.invalidFrameLength {
// OK
} catch {
XCTFail("Unexpected error: \(error)")
XCTAssertThrowsError(try self.decoderChannel.writeInbound(self.buffer)) { error in
XCTAssertEqual(.invalidFrameLength, error as? NIOWebSocketError)
}
// No error frame should be written.
@@ -399,13 +374,8 @@ public final class WebSocketFrameDecoderTest: XCTestCase {
// A fake frame header that claims this is a fragmented ping frame.
self.buffer.writeBytes([0x09, 0x00])
do {
try self.decoderChannel.writeInbound(self.buffer)
XCTFail("did not throw")
} catch NIOWebSocketError.fragmentedControlFrame {
// OK
} catch {
XCTFail("Unexpected error: \(error)")
XCTAssertThrowsError(try self.decoderChannel.writeInbound(self.buffer)) { error in
XCTAssertEqual(.fragmentedControlFrame, error as? NIOWebSocketError)
}
// No error frame should be written.
@@ -421,13 +391,8 @@ public final class WebSocketFrameDecoderTest: XCTestCase {
// A fake frame header that claims this is a ping frame with 126 bytes of data.
self.buffer.writeBytes([0x89, 0x7E, 0x00, 0x7E])
do {
try self.decoderChannel.writeInbound(self.buffer)
XCTFail("did not throw")
} catch NIOWebSocketError.multiByteControlFrameLength {
// OK
} catch {
XCTFail("Unexpected error: \(error)")
XCTAssertThrowsError(try self.decoderChannel.writeInbound(self.buffer)) { error in
XCTAssertEqual(.multiByteControlFrameLength, error as? NIOWebSocketError)
}
// No error frame should be written.
@@ -443,13 +408,8 @@ public final class WebSocketFrameDecoderTest: XCTestCase {
// A fake frame header that claims this is a fragmented ping frame.
self.buffer.writeBytes([0x09, 0x00])
do {
try self.decoderChannel.writeInbound(self.buffer)
XCTFail("did not throw")
} catch NIOWebSocketError.fragmentedControlFrame {
// OK
} catch {
XCTFail("Unexpected error: \(error)")
XCTAssertThrowsError(try self.decoderChannel.writeInbound(self.buffer)) { error in
XCTAssertEqual(.fragmentedControlFrame, error as? NIOWebSocketError)
}
// No error frame should be written.
@@ -484,13 +444,8 @@ public final class WebSocketFrameDecoderTest: XCTestCase {
// larger than the frame max.
self.buffer.writeBytes([0x81, 0xFE, 0x40, 0x01])
do {
try self.decoderChannel.writeInbound(self.buffer)
XCTFail("did not throw")
} catch NIOWebSocketError.invalidFrameLength {
// OK
} catch {
XCTFail("Unexpected error: \(error)")
XCTAssertThrowsError(try self.decoderChannel.writeInbound(self.buffer)) { error in
XCTAssertEqual(.invalidFrameLength, error as? NIOWebSocketError)
}
// We expect that an error frame will have been written out.
@@ -507,13 +462,8 @@ public final class WebSocketFrameDecoderTest: XCTestCase {
// A fake frame header that claims this is a fragmented ping frame.
self.buffer.writeBytes([0x09, 0x00])
do {
try self.decoderChannel.writeInbound(self.buffer)
XCTFail("did not throw")
} catch NIOWebSocketError.fragmentedControlFrame {
// OK
} catch {
XCTFail("Unexpected error: \(error)")
XCTAssertThrowsError(try self.decoderChannel.writeInbound(self.buffer)) { error in
XCTAssertEqual(.fragmentedControlFrame, error as? NIOWebSocketError)
}
// We expect that an error frame will have been written out.
@@ -530,13 +480,8 @@ public final class WebSocketFrameDecoderTest: XCTestCase {
// A fake frame header that claims this is a ping frame with 126 bytes of data.
self.buffer.writeBytes([0x89, 0x7E, 0x00, 0x7E])
do {
try self.decoderChannel.writeInbound(self.buffer)
XCTFail("did not throw")
} catch NIOWebSocketError.multiByteControlFrameLength {
// OK
} catch {
XCTFail("Unexpected error: \(error)")
XCTAssertThrowsError(try self.decoderChannel.writeInbound(self.buffer)) { error in
XCTAssertEqual(.multiByteControlFrameLength, error as? NIOWebSocketError)
}
// We expect that an error frame will have been written out.
@@ -555,13 +500,8 @@ public final class WebSocketFrameDecoderTest: XCTestCase {
// A fake frame header that claims this is a fragmented ping frame.
self.buffer.writeBytes([0x09, 0x00])
do {
try self.decoderChannel.writeInbound(self.buffer)
XCTFail("did not throw")
} catch NIOWebSocketError.fragmentedControlFrame {
// OK
} catch {
XCTFail("Unexpected error: \(error)")
XCTAssertThrowsError(try self.decoderChannel.writeInbound(self.buffer)) { error in
XCTAssertEqual(.fragmentedControlFrame, error as? NIOWebSocketError)
}
// We expect that an error frame will have been written out.
@@ -606,13 +546,8 @@ public final class WebSocketFrameDecoderTest: XCTestCase {
XCTAssertNotNil(error as? Dummy, "unexpected error: \(error)")
}
do {
try self.decoderChannel.writeInbound(self.buffer)
XCTFail("did not throw")
} catch NIOWebSocketError.invalidFrameLength {
// OK
} catch {
XCTFail("Unexpected error: \(error)")
XCTAssertThrowsError(try self.decoderChannel.writeInbound(self.buffer)) { error in
XCTAssertEqual(.invalidFrameLength, error as? NIOWebSocketError)
}
// We expect that an error frame will have been written out.
@@ -188,13 +188,8 @@ class WebSocketServerEndToEndTests: XCTestCase {
buffer.writeString(upgradeRequest)
// Write this directly to the server.
do {
try server.writeInbound(buffer)
XCTFail("Did not throw")
} catch let error as NIOWebSocketUpgradeError where error == .unsupportedWebSocketTarget {
// ok
} catch {
XCTFail("Unexpected error hit: \(error)")
XCTAssertThrowsError(try server.writeInbound(buffer)) { error in
XCTAssertEqual(.unsupportedWebSocketTarget, error as? NIOWebSocketUpgradeError)
}
// Nothing gets written.
@@ -260,13 +255,8 @@ class WebSocketServerEndToEndTests: XCTestCase {
buffer.writeString(upgradeRequest)
// Write this directly to the server.
do {
try server.writeInbound(buffer)
XCTFail("Did not throw")
} catch let error as NIOWebSocketUpgradeError where error == .invalidUpgradeHeader {
// ok
} catch {
XCTFail("Unexpected error hit: \(error)")
XCTAssertThrowsError(try server.writeInbound(buffer)) { error in
XCTAssertEqual(.invalidUpgradeHeader, error as? NIOWebSocketUpgradeError)
}
// Nothing gets written.
@@ -288,13 +278,8 @@ class WebSocketServerEndToEndTests: XCTestCase {
buffer.writeString(upgradeRequest)
// Write this directly to the server.
do {
try server.writeInbound(buffer)
XCTFail("Did not throw")
} catch let error as NIOWebSocketUpgradeError where error == .invalidUpgradeHeader {
// ok
} catch {
XCTFail("Unexpected error hit: \(error)")
XCTAssertThrowsError(try server.writeInbound(buffer)) { error in
XCTAssertEqual(.invalidUpgradeHeader, error as? NIOWebSocketUpgradeError)
}
// Nothing gets written.
@@ -316,13 +301,8 @@ class WebSocketServerEndToEndTests: XCTestCase {
buffer.writeString(upgradeRequest)
// Write this directly to the server.
do {
try server.writeInbound(buffer)
XCTFail("Did not throw")
} catch let error as NIOWebSocketUpgradeError where error == .invalidUpgradeHeader {
// ok
} catch {
XCTFail("Unexpected error hit: \(error)")
XCTAssertThrowsError(try server.writeInbound(buffer)) { error in
XCTAssertEqual(.invalidUpgradeHeader, error as? NIOWebSocketUpgradeError)
}
// Nothing gets written.
@@ -472,13 +452,8 @@ class WebSocketServerEndToEndTests: XCTestCase {
data.writeBytes([0x89, 0x7E, 0x00, 0x7E])
XCTAssertNoThrow(try client.writeAndFlush(data).wait())
do {
try interactInMemory(client, server, eventLoop: loop)
XCTFail("Did not throw")
} catch NIOWebSocketError.multiByteControlFrameLength {
// ok
} catch {
XCTFail("Unexpected error: \(error)")
XCTAssertThrowsError(try interactInMemory(client, server, eventLoop: loop)) { error in
XCTAssertEqual(NIOWebSocketError.multiByteControlFrameLength, error as? NIOWebSocketError)
}
XCTAssertEqual(recorder.errors.count, 1)
@@ -516,13 +491,8 @@ class WebSocketServerEndToEndTests: XCTestCase {
data.writeBytes([0x89, 0x7E, 0x00, 0x7E])
XCTAssertNoThrow(try client.writeAndFlush(data).wait())
do {
try interactInMemory(client, server, eventLoop: loop)
XCTFail("Did not throw")
} catch NIOWebSocketError.multiByteControlFrameLength {
// ok
} catch {
XCTFail("Unexpected error: \(error)")
XCTAssertThrowsError(try interactInMemory(client, server, eventLoop: loop)) { error in
XCTAssertEqual(NIOWebSocketError.multiByteControlFrameLength, error as? NIOWebSocketError)
}
XCTAssertEqual(recorder.errors.count, 1)