diff --git a/Tests/NIOCoreTests/AsyncChannel/AsyncChannelTests.swift b/Tests/NIOCoreTests/AsyncChannel/AsyncChannelTests.swift index e9fa71fb1..0a632f98b 100644 --- a/Tests/NIOCoreTests/AsyncChannel/AsyncChannelTests.swift +++ b/Tests/NIOCoreTests/AsyncChannel/AsyncChannelTests.swift @@ -18,62 +18,120 @@ import NIOEmbedded import XCTest final class AsyncChannelTests: XCTestCase { - func testAsyncChannelBasicFunctionality() { + func testAsyncChannelBasicFunctionality() async throws { guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { return } - XCTAsyncTest(timeout: 5) { - let channel = NIOAsyncTestingChannel() + let channel = NIOAsyncTestingChannel() + let wrapped = try await channel.testingEventLoop.executeInContext { + try NIOAsyncChannel(synchronouslyWrapping: channel, inboundType: String.self, outboundType: Never.self) + } + + var iterator = wrapped.inboundStream.makeAsyncIterator() + try await channel.writeInbound("hello") + let firstRead = try await iterator.next() + XCTAssertEqual(firstRead, "hello") + + try await channel.writeInbound("world") + let secondRead = try await iterator.next() + XCTAssertEqual(secondRead, "world") + + try await channel.testingEventLoop.executeInContext { + channel.pipeline.fireUserInboundEventTriggered(ChannelEvent.inputClosed) + } + + let thirdRead = try await iterator.next() + XCTAssertNil(thirdRead) + + try await channel.close() + } + + func testAsyncChannelBasicWrites() async throws { + guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { return } + let channel = NIOAsyncTestingChannel() + let wrapped = try await channel.testingEventLoop.executeInContext { + try NIOAsyncChannel(synchronouslyWrapping: channel, inboundType: Never.self, outboundType: String.self) + } + + try await wrapped.outboundWriter.write("hello") + try await wrapped.outboundWriter.write("world") + + let firstRead = try await channel.waitForOutboundWrite(as: String.self) + let secondRead = try await channel.waitForOutboundWrite(as: String.self) + + XCTAssertEqual(firstRead, "hello") + XCTAssertEqual(secondRead, "world") + + try await channel.close() + } + + func testDroppingTheWriterClosesTheWriteSideOfTheChannel() async throws { + guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { return } + let channel = NIOAsyncTestingChannel() + let closeRecorder = CloseRecorder() + try await channel.pipeline.addHandler(closeRecorder) + + let inboundReader: NIOAsyncChannelInboundStream + + do { let wrapped = try await channel.testingEventLoop.executeInContext { - try NIOAsyncChannel(synchronouslyWrapping: channel, inboundType: String.self, outboundType: Never.self) + try NIOAsyncChannel( + synchronouslyWrapping: channel, + isOutboundHalfClosureEnabled: true, + inboundType: Never.self, + outboundType: Never.self + ) } - - var iterator = wrapped.inboundStream.makeAsyncIterator() - try await channel.writeInbound("hello") - let firstRead = try await iterator.next() - XCTAssertEqual(firstRead, "hello") - - try await channel.writeInbound("world") - let secondRead = try await iterator.next() - XCTAssertEqual(secondRead, "world") + inboundReader = wrapped.inboundStream try await channel.testingEventLoop.executeInContext { - channel.pipeline.fireUserInboundEventTriggered(ChannelEvent.inputClosed) + XCTAssertEqual(0, closeRecorder.outboundCloses) } - - let thirdRead = try await iterator.next() - XCTAssertNil(thirdRead) - - try await channel.close() } + + try await channel.testingEventLoop.executeInContext { + XCTAssertEqual(1, closeRecorder.outboundCloses) + } + + // Just use this to keep the inbound reader alive. + withExtendedLifetime(inboundReader) {} + channel.close(promise: nil) } - func testAsyncChannelBasicWrites() { + func testDroppingTheWriterDoesntCloseTheWriteSideOfTheChannelIfHalfClosureIsDisabled() async throws { guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { return } - XCTAsyncTest(timeout: 5) { - let channel = NIOAsyncTestingChannel() + let channel = NIOAsyncTestingChannel() + let closeRecorder = CloseRecorder() + try await channel.pipeline.addHandler(closeRecorder) + + let inboundReader: NIOAsyncChannelInboundStream + + do { let wrapped = try await channel.testingEventLoop.executeInContext { - try NIOAsyncChannel(synchronouslyWrapping: channel, inboundType: Never.self, outboundType: String.self) + try NIOAsyncChannel(synchronouslyWrapping: channel, isOutboundHalfClosureEnabled: false, inboundType: Never.self, outboundType: Never.self) } + inboundReader = wrapped.inboundStream - try await wrapped.outboundWriter.write("hello") - try await wrapped.outboundWriter.write("world") - - let firstRead = try await channel.waitForOutboundWrite(as: String.self) - let secondRead = try await channel.waitForOutboundWrite(as: String.self) - - XCTAssertEqual(firstRead, "hello") - XCTAssertEqual(secondRead, "world") - - try await channel.close() + try await channel.testingEventLoop.executeInContext { + XCTAssertEqual(0, closeRecorder.outboundCloses) + } } + + try await channel.testingEventLoop.executeInContext { + XCTAssertEqual(0, closeRecorder.outboundCloses) + } + + // Just use this to keep the inbound reader alive. + withExtendedLifetime(inboundReader) {} + channel.close(promise: nil) } - func testDroppingTheWriterClosesTheWriteSideOfTheChannel() { + func testDroppingTheWriterFirstLeadsToChannelClosureWhenReaderIsAlsoDropped() async throws { guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { return } - XCTAsyncTest(timeout: 5) { - let channel = NIOAsyncTestingChannel() - let closeRecorder = CloseRecorder() - try await channel.pipeline.addHandler(closeRecorder) + let channel = NIOAsyncTestingChannel() + let closeRecorder = CloseRecorder() + try await channel.pipeline.addHandler(CloseSuppressor()) + try await channel.pipeline.addHandler(closeRecorder) + do { let inboundReader: NIOAsyncChannelInboundStream do { @@ -87,368 +145,286 @@ final class AsyncChannelTests: XCTestCase { } inboundReader = wrapped.inboundStream - try await channel.testingEventLoop.executeInContext { - XCTAssertEqual(0, closeRecorder.outboundCloses) - } - } - - try await channel.testingEventLoop.executeInContext { - XCTAssertEqual(1, closeRecorder.outboundCloses) - } - - // Just use this to keep the inbound reader alive. - withExtendedLifetime(inboundReader) {} - channel.close(promise: nil) - } - } - - func testDroppingTheWriterDoesntCloseTheWriteSideOfTheChannelIfHalfClosureIsDisabled() { - guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { return } - XCTAsyncTest(timeout: 5) { - let channel = NIOAsyncTestingChannel() - let closeRecorder = CloseRecorder() - try await channel.pipeline.addHandler(closeRecorder) - - let inboundReader: NIOAsyncChannelInboundStream - - do { - let wrapped = try await channel.testingEventLoop.executeInContext { - try NIOAsyncChannel(synchronouslyWrapping: channel, isOutboundHalfClosureEnabled: false, inboundType: Never.self, outboundType: Never.self) - } - inboundReader = wrapped.inboundStream - - try await channel.testingEventLoop.executeInContext { - XCTAssertEqual(0, closeRecorder.outboundCloses) - } - } - - try await channel.testingEventLoop.executeInContext { - XCTAssertEqual(0, closeRecorder.outboundCloses) - } - - // Just use this to keep the inbound reader alive. - withExtendedLifetime(inboundReader) {} - channel.close(promise: nil) - } - } - - func testDroppingTheWriterFirstLeadsToChannelClosureWhenReaderIsAlsoDropped() { - guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { return } - XCTAsyncTest(timeout: 5) { - let channel = NIOAsyncTestingChannel() - let closeRecorder = CloseRecorder() - try await channel.pipeline.addHandler(CloseSuppressor()) - try await channel.pipeline.addHandler(closeRecorder) - - do { - let inboundReader: NIOAsyncChannelInboundStream - - do { - let wrapped = try await channel.testingEventLoop.executeInContext { - try NIOAsyncChannel( - synchronouslyWrapping: channel, - isOutboundHalfClosureEnabled: true, - inboundType: Never.self, - outboundType: Never.self - ) - } - inboundReader = wrapped.inboundStream - - try await channel.testingEventLoop.executeInContext { - XCTAssertEqual(0, closeRecorder.allCloses) - } - } - - // First we see half-closure. - try await channel.testingEventLoop.executeInContext { - XCTAssertEqual(1, closeRecorder.allCloses) - } - - // Just use this to keep the inbound reader alive. - withExtendedLifetime(inboundReader) {} - } - - // Now the inbound reader is dead, we see full closure. - try await channel.testingEventLoop.executeInContext { - XCTAssertEqual(2, closeRecorder.allCloses) - } - - try await channel.closeIgnoringSuppression() - } - } - - func testDroppingEverythingClosesTheChannel() { - guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { return } - XCTAsyncTest(timeout: 5) { - let channel = NIOAsyncTestingChannel() - let closeRecorder = CloseRecorder() - try await channel.pipeline.addHandler(CloseSuppressor()) - try await channel.pipeline.addHandler(closeRecorder) - - do { - let wrapped = try await channel.testingEventLoop.executeInContext { - try NIOAsyncChannel(synchronouslyWrapping: channel, isOutboundHalfClosureEnabled: false, inboundType: Never.self, outboundType: Never.self) - } - try await channel.testingEventLoop.executeInContext { XCTAssertEqual(0, closeRecorder.allCloses) } - - // Just use this to keep the wrapper alive until here. - withExtendedLifetime(wrapped) {} } - // Now that everything is dead, we see full closure. + // First we see half-closure. try await channel.testingEventLoop.executeInContext { XCTAssertEqual(1, closeRecorder.allCloses) } - try await channel.closeIgnoringSuppression() + // Just use this to keep the inbound reader alive. + withExtendedLifetime(inboundReader) {} } + + // Now the inbound reader is dead, we see full closure. + try await channel.testingEventLoop.executeInContext { + XCTAssertEqual(2, closeRecorder.allCloses) + } + + try await channel.closeIgnoringSuppression() } - func testReadsArePropagated() { + func testDroppingEverythingClosesTheChannel() async throws { guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { return } - XCTAsyncTest(timeout: 5) { - let channel = NIOAsyncTestingChannel() + let channel = NIOAsyncTestingChannel() + let closeRecorder = CloseRecorder() + try await channel.pipeline.addHandler(CloseSuppressor()) + try await channel.pipeline.addHandler(closeRecorder) + + do { let wrapped = try await channel.testingEventLoop.executeInContext { - try NIOAsyncChannel(synchronouslyWrapping: channel, inboundType: String.self, outboundType: Never.self) - } - - try await channel.writeInbound("hello") - let propagated = try await channel.readInbound(as: String.self) - XCTAssertEqual(propagated, "hello") - - try await channel.close().get() - - let reads = try await Array(wrapped.inboundStream) - XCTAssertEqual(reads, ["hello"]) - } - } - - func testErrorsArePropagatedButAfterReads() { - guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { return } - XCTAsyncTest(timeout: 5) { - let channel = NIOAsyncTestingChannel() - let wrapped = try await channel.testingEventLoop.executeInContext { - try NIOAsyncChannel(synchronouslyWrapping: channel, inboundType: String.self, outboundType: Never.self) - } - - try await channel.writeInbound("hello") - try await channel.testingEventLoop.executeInContext { - channel.pipeline.fireErrorCaught(TestError.bang) - } - - var iterator = wrapped.inboundStream.makeAsyncIterator() - let first = try await iterator.next() - XCTAssertEqual(first, "hello") - - try await XCTAssertThrowsError(await iterator.next()) { error in - XCTAssertEqual(error as? TestError, .bang) - } - } - } - - func testChannelBecomingNonWritableDelaysWriters() { - guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { return } - XCTAsyncTest(timeout: 5) { - let channel = NIOAsyncTestingChannel() - let wrapped = try await channel.testingEventLoop.executeInContext { - try NIOAsyncChannel(synchronouslyWrapping: channel, inboundType: Never.self, outboundType: String.self) + try NIOAsyncChannel(synchronouslyWrapping: channel, isOutboundHalfClosureEnabled: false, inboundType: Never.self, outboundType: Never.self) } try await channel.testingEventLoop.executeInContext { - channel.isWritable = false - channel.pipeline.fireChannelWritabilityChanged() + XCTAssertEqual(0, closeRecorder.allCloses) } - let lock = NIOLockedValueBox(false) + // Just use this to keep the wrapper alive until here. + withExtendedLifetime(wrapped) {} + } - await withThrowingTaskGroup(of: Void.self) { group in - group.addTask { - try await wrapped.outboundWriter.write("hello") - lock.withLockedValue { - XCTAssertTrue($0) - } - } + // Now that everything is dead, we see full closure. + try await channel.testingEventLoop.executeInContext { + XCTAssertEqual(1, closeRecorder.allCloses) + } - group.addTask { - // 10ms sleep before we wake the thing up - try await Task.sleep(nanoseconds: 10_000_000) + try await channel.closeIgnoringSuppression() + } - try await channel.testingEventLoop.executeInContext { - channel.isWritable = true - lock.withLockedValue { $0 = true } - channel.pipeline.fireChannelWritabilityChanged() - } + func testReadsArePropagated() async throws { + guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { return } + let channel = NIOAsyncTestingChannel() + let wrapped = try await channel.testingEventLoop.executeInContext { + try NIOAsyncChannel(synchronouslyWrapping: channel, inboundType: String.self, outboundType: Never.self) + } + + try await channel.writeInbound("hello") + let propagated = try await channel.readInbound(as: String.self) + XCTAssertEqual(propagated, "hello") + + try await channel.close().get() + + let reads = try await Array(wrapped.inboundStream) + XCTAssertEqual(reads, ["hello"]) + } + + func testErrorsArePropagatedButAfterReads() async throws { + guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { return } + let channel = NIOAsyncTestingChannel() + let wrapped = try await channel.testingEventLoop.executeInContext { + try NIOAsyncChannel(synchronouslyWrapping: channel, inboundType: String.self, outboundType: Never.self) + } + + try await channel.writeInbound("hello") + try await channel.testingEventLoop.executeInContext { + channel.pipeline.fireErrorCaught(TestError.bang) + } + + var iterator = wrapped.inboundStream.makeAsyncIterator() + let first = try await iterator.next() + XCTAssertEqual(first, "hello") + + try await XCTAssertThrowsError(await iterator.next()) { error in + XCTAssertEqual(error as? TestError, .bang) + } + } + + func testChannelBecomingNonWritableDelaysWriters() async throws { + guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { return } + let channel = NIOAsyncTestingChannel() + let wrapped = try await channel.testingEventLoop.executeInContext { + try NIOAsyncChannel(synchronouslyWrapping: channel, inboundType: Never.self, outboundType: String.self) + } + + try await channel.testingEventLoop.executeInContext { + channel.isWritable = false + channel.pipeline.fireChannelWritabilityChanged() + } + + let lock = NIOLockedValueBox(false) + + await withThrowingTaskGroup(of: Void.self) { group in + group.addTask { + try await wrapped.outboundWriter.write("hello") + lock.withLockedValue { + XCTAssertTrue($0) } } - try await channel.close().get() - } - } + group.addTask { + // 10ms sleep before we wake the thing up + try await Task.sleep(nanoseconds: 10_000_000) - func testBufferDropsReadsIfTheReaderIsGone() { - guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { return } - XCTAsyncTest(timeout: 5) { - let channel = NIOAsyncTestingChannel() - try await channel.pipeline.addHandler(CloseSuppressor()).get() - do { - // Create the NIOAsyncChannel, then drop it. The handler will still be in the pipeline. - _ = try await channel.testingEventLoop.executeInContext { - _ = try NIOAsyncChannel(synchronouslyWrapping: channel, inboundType: Sentinel.self, outboundType: Never.self) + try await channel.testingEventLoop.executeInContext { + channel.isWritable = true + lock.withLockedValue { $0 = true } + channel.pipeline.fireChannelWritabilityChanged() } } - - weak var sentinel: Sentinel? - do { - let strongSentinel: Sentinel? = Sentinel() - sentinel = strongSentinel! - try await XCTAsyncAssertNotNil(await channel.pipeline.handler(type: NIOAsyncChannelInboundStreamChannelHandler.self).get()) - try await channel.writeInbound(strongSentinel!) - _ = try await channel.readInbound(as: Sentinel.self) - } - - XCTAssertNil(sentinel) - - try await channel.closeIgnoringSuppression() } + + try await channel.close().get() } - func testManagingBackpressure() { + func testBufferDropsReadsIfTheReaderIsGone() async throws { guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { return } - XCTAsyncTest(timeout: 5) { - let channel = NIOAsyncTestingChannel() - let readCounter = ReadCounter() - try await channel.pipeline.addHandler(readCounter) - let wrapped = try await channel.testingEventLoop.executeInContext { - try NIOAsyncChannel(synchronouslyWrapping: channel, backpressureStrategy: .init(lowWatermark: 2, highWatermark: 4), inboundType: Void.self, outboundType: Never.self) + let channel = NIOAsyncTestingChannel() + try await channel.pipeline.addHandler(CloseSuppressor()).get() + do { + // Create the NIOAsyncChannel, then drop it. The handler will still be in the pipeline. + _ = try await channel.testingEventLoop.executeInContext { + _ = try NIOAsyncChannel(synchronouslyWrapping: channel, inboundType: Sentinel.self, outboundType: Never.self) } + } - // Attempt to read. This should succeed an arbitrary number of times. - XCTAssertEqual(readCounter.readCount, 0) - try await channel.testingEventLoop.executeInContext { - channel.pipeline.read() - channel.pipeline.read() - channel.pipeline.read() - } - XCTAssertEqual(readCounter.readCount, 3) + weak var sentinel: Sentinel? + do { + let strongSentinel: Sentinel? = Sentinel() + sentinel = strongSentinel! + try await XCTAsyncAssertNotNil(await channel.pipeline.handler(type: NIOAsyncChannelInboundStreamChannelHandler.self).get()) + try await channel.writeInbound(strongSentinel!) + _ = try await channel.readInbound(as: Sentinel.self) + } - // Push 3 elements into the buffer. Reads continue to work. - try await channel.testingEventLoop.executeInContext { - channel.pipeline.fireChannelRead(NIOAny(())) - channel.pipeline.fireChannelRead(NIOAny(())) - channel.pipeline.fireChannelRead(NIOAny(())) - channel.pipeline.fireChannelReadComplete() + XCTAssertNil(sentinel) - channel.pipeline.read() - channel.pipeline.read() - channel.pipeline.read() - } - XCTAssertEqual(readCounter.readCount, 6) + try await channel.closeIgnoringSuppression() + } - // Add one more element into the buffer. This should flip our backpressure mode, and the reads should now be delayed. - try await channel.testingEventLoop.executeInContext { - channel.pipeline.fireChannelRead(NIOAny(())) - channel.pipeline.fireChannelReadComplete() + func testManagingBackpressure() async throws { + guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { return } + let channel = NIOAsyncTestingChannel() + let readCounter = ReadCounter() + try await channel.pipeline.addHandler(readCounter) + let wrapped = try await channel.testingEventLoop.executeInContext { + try NIOAsyncChannel(synchronouslyWrapping: channel, backpressureStrategy: .init(lowWatermark: 2, highWatermark: 4), inboundType: Void.self, outboundType: Never.self) + } - channel.pipeline.read() - channel.pipeline.read() - channel.pipeline.read() - } - XCTAssertEqual(readCounter.readCount, 6) + // Attempt to read. This should succeed an arbitrary number of times. + XCTAssertEqual(readCounter.readCount, 0) + try await channel.testingEventLoop.executeInContext { + channel.pipeline.read() + channel.pipeline.read() + channel.pipeline.read() + } + XCTAssertEqual(readCounter.readCount, 3) - // More elements don't help. - try await channel.testingEventLoop.executeInContext { - channel.pipeline.fireChannelRead(NIOAny(())) - channel.pipeline.fireChannelReadComplete() + // Push 3 elements into the buffer. Reads continue to work. + try await channel.testingEventLoop.executeInContext { + channel.pipeline.fireChannelRead(NIOAny(())) + channel.pipeline.fireChannelRead(NIOAny(())) + channel.pipeline.fireChannelRead(NIOAny(())) + channel.pipeline.fireChannelReadComplete() - channel.pipeline.read() - channel.pipeline.read() - channel.pipeline.read() - } - XCTAssertEqual(readCounter.readCount, 6) + channel.pipeline.read() + channel.pipeline.read() + channel.pipeline.read() + } + XCTAssertEqual(readCounter.readCount, 6) - // Now consume three elements from the pipeline. This should not unbuffer the read, as 3 elements remain. - var reader = wrapped.inboundStream.makeAsyncIterator() - for _ in 0..<3 { - try await XCTAsyncAssertNotNil(await reader.next()) - } - await channel.testingEventLoop.run() - XCTAssertEqual(readCounter.readCount, 6) + // Add one more element into the buffer. This should flip our backpressure mode, and the reads should now be delayed. + try await channel.testingEventLoop.executeInContext { + channel.pipeline.fireChannelRead(NIOAny(())) + channel.pipeline.fireChannelReadComplete() - // Removing the next element should trigger an automatic read. + channel.pipeline.read() + channel.pipeline.read() + channel.pipeline.read() + } + XCTAssertEqual(readCounter.readCount, 6) + + // More elements don't help. + try await channel.testingEventLoop.executeInContext { + channel.pipeline.fireChannelRead(NIOAny(())) + channel.pipeline.fireChannelReadComplete() + + channel.pipeline.read() + channel.pipeline.read() + channel.pipeline.read() + } + XCTAssertEqual(readCounter.readCount, 6) + + // Now consume three elements from the pipeline. This should not unbuffer the read, as 3 elements remain. + var reader = wrapped.inboundStream.makeAsyncIterator() + for _ in 0..<3 { try await XCTAsyncAssertNotNil(await reader.next()) - await channel.testingEventLoop.run() - XCTAssertEqual(readCounter.readCount, 7) - - // Reads now work again, even if more data arrives. - try await channel.testingEventLoop.executeInContext { - channel.pipeline.read() - channel.pipeline.read() - channel.pipeline.read() - - channel.pipeline.fireChannelRead(NIOAny(())) - channel.pipeline.fireChannelReadComplete() - - channel.pipeline.read() - channel.pipeline.read() - channel.pipeline.read() - } - XCTAssertEqual(readCounter.readCount, 13) - - // The next reads arriving pushes us past the limit again. - // This time we won't read. - try await channel.testingEventLoop.executeInContext { - channel.pipeline.fireChannelRead(NIOAny(())) - channel.pipeline.fireChannelRead(NIOAny(())) - channel.pipeline.fireChannelReadComplete() - } - XCTAssertEqual(readCounter.readCount, 13) - - // This time we'll consume 4 more elements, and we won't find a read at all. - for _ in 0..<4 { - try await XCTAsyncAssertNotNil(await reader.next()) - } - await channel.testingEventLoop.run() - XCTAssertEqual(readCounter.readCount, 13) - - // But the next reads work fine. - try await channel.testingEventLoop.executeInContext { - channel.pipeline.read() - channel.pipeline.read() - channel.pipeline.read() - } - XCTAssertEqual(readCounter.readCount, 16) } + await channel.testingEventLoop.run() + XCTAssertEqual(readCounter.readCount, 6) + + // Removing the next element should trigger an automatic read. + try await XCTAsyncAssertNotNil(await reader.next()) + await channel.testingEventLoop.run() + XCTAssertEqual(readCounter.readCount, 7) + + // Reads now work again, even if more data arrives. + try await channel.testingEventLoop.executeInContext { + channel.pipeline.read() + channel.pipeline.read() + channel.pipeline.read() + + channel.pipeline.fireChannelRead(NIOAny(())) + channel.pipeline.fireChannelReadComplete() + + channel.pipeline.read() + channel.pipeline.read() + channel.pipeline.read() + } + XCTAssertEqual(readCounter.readCount, 13) + + // The next reads arriving pushes us past the limit again. + // This time we won't read. + try await channel.testingEventLoop.executeInContext { + channel.pipeline.fireChannelRead(NIOAny(())) + channel.pipeline.fireChannelRead(NIOAny(())) + channel.pipeline.fireChannelReadComplete() + } + XCTAssertEqual(readCounter.readCount, 13) + + // This time we'll consume 4 more elements, and we won't find a read at all. + for _ in 0..<4 { + try await XCTAsyncAssertNotNil(await reader.next()) + } + await channel.testingEventLoop.run() + XCTAssertEqual(readCounter.readCount, 13) + + // But the next reads work fine. + try await channel.testingEventLoop.executeInContext { + channel.pipeline.read() + channel.pipeline.read() + channel.pipeline.read() + } + XCTAssertEqual(readCounter.readCount, 16) } - func testCanWrapAChannelSynchronously() throws { + func testCanWrapAChannelSynchronously() async throws { guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { return } - XCTAsyncTest(timeout: 5) { - let channel = NIOAsyncTestingChannel() - let wrapped = try await channel.testingEventLoop.executeInContext { - try NIOAsyncChannel(synchronouslyWrapping: channel, inboundType: String.self, outboundType: String.self) - } - - var iterator = wrapped.inboundStream.makeAsyncIterator() - try await channel.writeInbound("hello") - let firstRead = try await iterator.next() - XCTAssertEqual(firstRead, "hello") - - try await wrapped.outboundWriter.write("world") - let write = try await channel.waitForOutboundWrite(as: String.self) - XCTAssertEqual(write, "world") - - try await channel.testingEventLoop.executeInContext { - channel.pipeline.fireUserInboundEventTriggered(ChannelEvent.inputClosed) - } - - let secondRead = try await iterator.next() - XCTAssertNil(secondRead) - - try await channel.close() + let channel = NIOAsyncTestingChannel() + let wrapped = try await channel.testingEventLoop.executeInContext { + try NIOAsyncChannel(synchronouslyWrapping: channel, inboundType: String.self, outboundType: String.self) } + + var iterator = wrapped.inboundStream.makeAsyncIterator() + try await channel.writeInbound("hello") + let firstRead = try await iterator.next() + XCTAssertEqual(firstRead, "hello") + + try await wrapped.outboundWriter.write("world") + let write = try await channel.waitForOutboundWrite(as: String.self) + XCTAssertEqual(write, "world") + + try await channel.testingEventLoop.executeInContext { + channel.pipeline.fireUserInboundEventTriggered(ChannelEvent.inputClosed) + } + + let secondRead = try await iterator.next() + XCTAssertNil(secondRead) + + try await channel.close() } } diff --git a/Tests/NIOCoreTests/AsyncSequenceTests.swift b/Tests/NIOCoreTests/AsyncSequenceTests.swift index c570ee4f4..07c51b34d 100644 --- a/Tests/NIOCoreTests/AsyncSequenceTests.swift +++ b/Tests/NIOCoreTests/AsyncSequenceTests.swift @@ -26,136 +26,134 @@ fileprivate struct TestCase { } final class AsyncSequenceCollectTests: XCTestCase { - func testAsyncSequenceCollect() { + func testAsyncSequenceCollect() async throws { guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { return } - XCTAsyncTest(timeout: 5) { - let testCases = [ - TestCase([ - [], - ]), - TestCase([ - [], - [], - ]), - TestCase([ - [0], - [], - ]), - TestCase([ - [], - [0], - ]), - TestCase([ - [0], - [1], - ]), - TestCase([ - [0], - [1], - ]), - TestCase([ - [0], - [1], - [2], - ]), - TestCase([ - [], - [0], - [], - [1], - [], - [2], - [], - ]), - TestCase([ - [0], - [1], - [2], - [], - [], - ]), - TestCase([ - Array(0..<10), - ]), - TestCase([ - Array(0..<10), - Array(10..<20), - ]), - TestCase([ - Array(0..<10), - Array(10..<20), - Array(20..<30), - ]), - TestCase([ - Array(0..<10), - Array(10..<20), - Array(20..<30), - Array(repeating: 99, count: 1000), - ]), - ] - for testCase in testCases { - let expectedBytes = testCase.buffers.flatMap({ $0 }) - - // happy case where maxBytes is exactly the same as number of buffers received - - // test for the generic version - let accumulatedBytes1 = try await testCase.buffers + let testCases = [ + TestCase([ + [], + ]), + TestCase([ + [], + [], + ]), + TestCase([ + [0], + [], + ]), + TestCase([ + [], + [0], + ]), + TestCase([ + [0], + [1], + ]), + TestCase([ + [0], + [1], + ]), + TestCase([ + [0], + [1], + [2], + ]), + TestCase([ + [], + [0], + [], + [1], + [], + [2], + [], + ]), + TestCase([ + [0], + [1], + [2], + [], + [], + ]), + TestCase([ + Array(0..<10), + ]), + TestCase([ + Array(0..<10), + Array(10..<20), + ]), + TestCase([ + Array(0..<10), + Array(10..<20), + Array(20..<30), + ]), + TestCase([ + Array(0..<10), + Array(10..<20), + Array(20..<30), + Array(repeating: 99, count: 1000), + ]), + ] + for testCase in testCases { + let expectedBytes = testCase.buffers.flatMap({ $0 }) + + // happy case where maxBytes is exactly the same as number of buffers received + + // test for the generic version + let accumulatedBytes1 = try await testCase.buffers + .asAsyncSequence() + .collect(upTo: expectedBytes.count, using: .init()) + XCTAssertEqual( + accumulatedBytes1, + ByteBuffer(bytes: expectedBytes), + file: testCase.file, + line: testCase.line + ) + + // test for the `ByteBuffer` optimised version + let accumulatedBytes2 = try await testCase.buffers + .map(ByteBuffer.init(bytes:)) + .asAsyncSequence() + .collect(upTo: expectedBytes.count) + XCTAssertEqual( + accumulatedBytes2, + ByteBuffer(bytes: expectedBytes), + file: testCase.file, + line: testCase.line + ) + + // unhappy case where maxBytes is one byte less than actually received + guard expectedBytes.count >= 1 else { + continue + } + + // test for the generic version + await XCTAssertThrowsError( + try await testCase.buffers .asAsyncSequence() - .collect(upTo: expectedBytes.count, using: .init()) - XCTAssertEqual( - accumulatedBytes1, - ByteBuffer(bytes: expectedBytes), + .collect(upTo: max(expectedBytes.count - 1, 0), using: .init()), + file: testCase.file, + line: testCase.line + ) { error in + XCTAssertTrue( + error is NIOTooManyBytesError, file: testCase.file, line: testCase.line ) - - // test for the `ByteBuffer` optimised version - let accumulatedBytes2 = try await testCase.buffers + } + + // test for the `ByteBuffer` optimised version + await XCTAssertThrowsError( + try await testCase.buffers .map(ByteBuffer.init(bytes:)) .asAsyncSequence() - .collect(upTo: expectedBytes.count) - XCTAssertEqual( - accumulatedBytes2, - ByteBuffer(bytes: expectedBytes), + .collect(upTo: max(expectedBytes.count - 1, 0)), + file: testCase.file, + line: testCase.line + ) { error in + XCTAssertTrue( + error is NIOTooManyBytesError, file: testCase.file, line: testCase.line ) - - // unhappy case where maxBytes is one byte less than actually received - guard expectedBytes.count >= 1 else { - continue - } - - // test for the generic version - await XCTAssertThrowsError( - try await testCase.buffers - .asAsyncSequence() - .collect(upTo: max(expectedBytes.count - 1, 0), using: .init()), - file: testCase.file, - line: testCase.line - ) { error in - XCTAssertTrue( - error is NIOTooManyBytesError, - file: testCase.file, - line: testCase.line - ) - } - - // test for the `ByteBuffer` optimised version - await XCTAssertThrowsError( - try await testCase.buffers - .map(ByteBuffer.init(bytes:)) - .asAsyncSequence() - .collect(upTo: max(expectedBytes.count - 1, 0)), - file: testCase.file, - line: testCase.line - ) { error in - XCTAssertTrue( - error is NIOTooManyBytesError, - file: testCase.file, - line: testCase.line - ) - } } } } diff --git a/Tests/NIOCoreTests/XCTest+AsyncAwait.swift b/Tests/NIOCoreTests/XCTest+AsyncAwait.swift index 222952fa9..b60221889 100644 --- a/Tests/NIOCoreTests/XCTest+AsyncAwait.swift +++ b/Tests/NIOCoreTests/XCTest+AsyncAwait.swift @@ -41,39 +41,6 @@ */ import XCTest - -extension XCTestCase { - @available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) - /// Cross-platform XCTest support for async-await tests. - /// - /// Currently the Linux implementation of XCTest doesn't have async-await support. - /// Until it does, we make use of this shim which uses a detached `Task` along with - /// `XCTest.wait(for:timeout:)` to wrap the operation. - /// - /// - NOTE: Support for Linux is tracked by https://bugs.swift.org/browse/SR-14403. - /// - NOTE: Implementation currently in progress: https://github.com/apple/swift-corelibs-xctest/pull/326 - func XCTAsyncTest( - expectationDescription: String = "Async operation", - timeout: TimeInterval = 30, - file: StaticString = #filePath, - line: UInt = #line, - function: StaticString = #function, - operation: @escaping @Sendable () async throws -> Void - ) { - let expectation = self.expectation(description: expectationDescription) - Task { - do { - try await operation() - } catch { - XCTFail("Error thrown while executing \(function): \(error)", file: file, line: line) - Thread.callStackSymbols.forEach { print($0) } - } - expectation.fulfill() - } - self.wait(for: [expectation], timeout: timeout) - } -} - @available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) internal func XCTAssertThrowsError( _ expression: @autoclosure () async throws -> T, diff --git a/Tests/NIOEmbeddedTests/AsyncTestingChannelTests.swift b/Tests/NIOEmbeddedTests/AsyncTestingChannelTests.swift index ddd0b9d13..c3122e9b8 100644 --- a/Tests/NIOEmbeddedTests/AsyncTestingChannelTests.swift +++ b/Tests/NIOEmbeddedTests/AsyncTestingChannelTests.swift @@ -18,16 +18,14 @@ import NIOCore @testable import NIOEmbedded class AsyncTestingChannelTests: XCTestCase { - func testSingleHandlerInit() throws { + func testSingleHandlerInit() async throws { guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { throw XCTSkip() } - XCTAsyncTest { - class Handler: ChannelInboundHandler { - typealias InboundIn = Never - } - - let channel = await NIOAsyncTestingChannel(handler: Handler()) - XCTAssertNoThrow(try channel.pipeline.handler(type: Handler.self).wait()) + class Handler: ChannelInboundHandler { + typealias InboundIn = Never } + + let channel = await NIOAsyncTestingChannel(handler: Handler()) + XCTAssertNoThrow(try channel.pipeline.handler(type: Handler.self).wait()) } func testEmptyInit() throws { @@ -44,351 +42,317 @@ class AsyncTestingChannelTests: XCTestCase { } - func testMultipleHandlerInit() throws { + func testMultipleHandlerInit() async throws { guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { throw XCTSkip() } - XCTAsyncTest { - class Handler: ChannelInboundHandler, RemovableChannelHandler { - typealias InboundIn = Never - let identifier: String + class Handler: ChannelInboundHandler, RemovableChannelHandler { + typealias InboundIn = Never + let identifier: String - init(identifier: String) { - self.identifier = identifier - } + init(identifier: String) { + self.identifier = identifier } + } - let channel = await NIOAsyncTestingChannel( - handlers: [Handler(identifier: "0"), Handler(identifier: "1"), Handler(identifier: "2")] - ) - XCTAssertNoThrow(XCTAssertEqual(try channel.pipeline.handler(type: Handler.self).wait().identifier, "0")) - XCTAssertNoThrow(try channel.pipeline.removeHandler(name: "handler0").wait()) + let channel = await NIOAsyncTestingChannel( + handlers: [Handler(identifier: "0"), Handler(identifier: "1"), Handler(identifier: "2")] + ) + XCTAssertNoThrow(XCTAssertEqual(try channel.pipeline.handler(type: Handler.self).wait().identifier, "0")) + XCTAssertNoThrow(try channel.pipeline.removeHandler(name: "handler0").wait()) - XCTAssertNoThrow(XCTAssertEqual(try channel.pipeline.handler(type: Handler.self).wait().identifier, "1")) - XCTAssertNoThrow(try channel.pipeline.removeHandler(name: "handler1").wait()) + XCTAssertNoThrow(XCTAssertEqual(try channel.pipeline.handler(type: Handler.self).wait().identifier, "1")) + XCTAssertNoThrow(try channel.pipeline.removeHandler(name: "handler1").wait()) - XCTAssertNoThrow(XCTAssertEqual(try channel.pipeline.handler(type: Handler.self).wait().identifier, "2")) - XCTAssertNoThrow(try channel.pipeline.removeHandler(name: "handler2").wait()) + XCTAssertNoThrow(XCTAssertEqual(try channel.pipeline.handler(type: Handler.self).wait().identifier, "2")) + XCTAssertNoThrow(try channel.pipeline.removeHandler(name: "handler2").wait()) + } + + func testWaitForInboundWrite() async throws { + guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { throw XCTSkip() } + let channel = NIOAsyncTestingChannel() + let task = Task { + try await XCTAsyncAssertEqual(try await channel.waitForInboundWrite(), 1) + try await XCTAsyncAssertEqual(try await channel.waitForInboundWrite(), 2) + try await XCTAsyncAssertEqual(try await channel.waitForInboundWrite(), 3) + } + + try await channel.writeInbound(1) + try await channel.writeInbound(2) + try await channel.writeInbound(3) + try await task.value + } + + func testWaitForMultipleInboundWritesInParallel() async throws { + guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { throw XCTSkip() } + let channel = NIOAsyncTestingChannel() + let task = Task { + let task1 = Task { try await channel.waitForInboundWrite(as: Int.self) } + let task2 = Task { try await channel.waitForInboundWrite(as: Int.self) } + let task3 = Task { try await channel.waitForInboundWrite(as: Int.self) } + try await XCTAsyncAssertEqual(Set([ + try await task1.value, + try await task2.value, + try await task3.value, + ]), [1, 2, 3]) + } + + try await channel.writeInbound(1) + try await channel.writeInbound(2) + try await channel.writeInbound(3) + try await task.value + } + + func testWaitForOutboundWrite() async throws { + guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { throw XCTSkip() } + let channel = NIOAsyncTestingChannel() + let task = Task { + try await XCTAsyncAssertEqual(try await channel.waitForOutboundWrite(), 1) + try await XCTAsyncAssertEqual(try await channel.waitForOutboundWrite(), 2) + try await XCTAsyncAssertEqual(try await channel.waitForOutboundWrite(), 3) + } + + try await channel.writeOutbound(1) + try await channel.writeOutbound(2) + try await channel.writeOutbound(3) + try await task.value + } + + func testWaitForMultipleOutboundWritesInParallel() async throws { + guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { throw XCTSkip() } + let channel = NIOAsyncTestingChannel() + let task = Task { + let task1 = Task { try await channel.waitForOutboundWrite(as: Int.self) } + let task2 = Task { try await channel.waitForOutboundWrite(as: Int.self) } + let task3 = Task { try await channel.waitForOutboundWrite(as: Int.self) } + try await XCTAsyncAssertEqual(Set([ + try await task1.value, + try await task2.value, + try await task3.value, + ]), [1, 2, 3]) + } + + try await channel.writeOutbound(1) + try await channel.writeOutbound(2) + try await channel.writeOutbound(3) + try await task.value + } + + func testWriteOutboundByteBuffer() async throws { + guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { throw XCTSkip() } + let channel = NIOAsyncTestingChannel() + var buf = channel.allocator.buffer(capacity: 1024) + buf.writeString("hello") + + let isFull = try await channel.writeOutbound(buf).isFull + XCTAssertTrue(isFull) + + let hasLeftovers = try await channel.finish().hasLeftOvers + XCTAssertTrue(hasLeftovers) + + let read = try await channel.readOutbound(as: ByteBuffer.self) + XCTAssertNoThrow(XCTAssertEqual(buf, read)) + + let nextOutboundRead = try await channel.readOutbound(as: ByteBuffer.self) + let nextInboundRead = try await channel.readInbound(as: ByteBuffer.self) + XCTAssertNoThrow(XCTAssertNil(nextOutboundRead)) + XCTAssertNoThrow(XCTAssertNil(nextInboundRead)) + } + + func testWriteOutboundByteBufferMultipleTimes() async throws { + guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { throw XCTSkip() } + let channel = NIOAsyncTestingChannel() + var buf = channel.allocator.buffer(capacity: 1024) + buf.writeString("hello") + + try await XCTAsyncAssertTrue(await channel.writeOutbound(buf).isFull) + try await XCTAsyncAssertEqual(buf, await channel.readOutbound()) + try await XCTAsyncAssertNil(await channel.readOutbound(as: ByteBuffer.self)) + try await XCTAsyncAssertNil(await channel.readInbound(as: ByteBuffer.self)) + + var bufB = channel.allocator.buffer(capacity: 1024) + bufB.writeString("again") + + try await XCTAsyncAssertTrue(await channel.writeOutbound(bufB).isFull) + try await XCTAsyncAssertTrue(await channel.finish().hasLeftOvers) + try await XCTAsyncAssertEqual(bufB, await channel.readOutbound()) + try await XCTAsyncAssertNil(await channel.readOutbound(as: ByteBuffer.self)) + try await XCTAsyncAssertNil(await channel.readInbound(as: ByteBuffer.self)) + } + + func testWriteInboundByteBuffer() async throws { + guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { throw XCTSkip() } + let channel = NIOAsyncTestingChannel() + var buf = channel.allocator.buffer(capacity: 1024) + buf.writeString("hello") + + try await XCTAsyncAssertTrue(await channel.writeInbound(buf).isFull) + try await XCTAsyncAssertTrue(await channel.finish().hasLeftOvers) + try await XCTAsyncAssertEqual(buf, await channel.readInbound()) + try await XCTAsyncAssertNil(await channel.readInbound(as: ByteBuffer.self)) + try await XCTAsyncAssertNil(await channel.readOutbound(as: ByteBuffer.self)) + } + + func testWriteInboundByteBufferMultipleTimes() async throws { + guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { throw XCTSkip() } + let channel = NIOAsyncTestingChannel() + var buf = channel.allocator.buffer(capacity: 1024) + buf.writeString("hello") + + try await XCTAsyncAssertTrue(await channel.writeInbound(buf).isFull) + try await XCTAsyncAssertEqual(buf, await channel.readInbound()) + try await XCTAsyncAssertNil(await channel.readInbound(as: ByteBuffer.self)) + try await XCTAsyncAssertNil(await channel.readOutbound(as: ByteBuffer.self)) + + var bufB = channel.allocator.buffer(capacity: 1024) + bufB.writeString("again") + + try await XCTAsyncAssertTrue(await channel.writeInbound(bufB).isFull) + try await XCTAsyncAssertTrue(await channel.finish().hasLeftOvers) + try await XCTAsyncAssertEqual(bufB, await channel.readInbound()) + try await XCTAsyncAssertNil(await channel.readInbound(as: ByteBuffer.self)) + try await XCTAsyncAssertNil(await channel.readOutbound(as: ByteBuffer.self)) + } + + func testWriteInboundByteBufferReThrow() async throws { + guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { throw XCTSkip() } + let channel = NIOAsyncTestingChannel() + XCTAssertNoThrow(try channel.pipeline.addHandler(ExceptionThrowingInboundHandler()).wait()) + await XCTAsyncAssertThrowsError(try await channel.writeInbound("msg")) { error in + XCTAssertEqual(ChannelError.operationUnsupported, error as? ChannelError) + } + try await XCTAsyncAssertTrue(await channel.finish().isClean) + } + + func testWriteOutboundByteBufferReThrow() async throws { + guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { throw XCTSkip() } + let channel = NIOAsyncTestingChannel() + XCTAssertNoThrow(try channel.pipeline.addHandler(ExceptionThrowingOutboundHandler()).wait()) + await XCTAsyncAssertThrowsError(try await channel.writeOutbound("msg")) { error in + XCTAssertEqual(ChannelError.operationUnsupported, error as? ChannelError) + } + try await XCTAsyncAssertTrue(await channel.finish().isClean) + } + + func testReadOutboundWrongTypeThrows() async throws { + guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { throw XCTSkip() } + let channel = NIOAsyncTestingChannel() + try await XCTAsyncAssertTrue(await channel.writeOutbound("hello").isFull) + do { + _ = try await channel.readOutbound(as: Int.self) + XCTFail() + } catch let error as NIOAsyncTestingChannel.WrongTypeError { + let expectedError = NIOAsyncTestingChannel.WrongTypeError(expected: Int.self, actual: String.self) + XCTAssertEqual(error, expectedError) + } catch { + XCTFail() } } - func testWaitForInboundWrite() throws { + func testReadInboundWrongTypeThrows() async throws { guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { throw XCTSkip() } - XCTAsyncTest { - let channel = NIOAsyncTestingChannel() - let task = Task { - try await XCTAsyncAssertEqual(try await channel.waitForInboundWrite(), 1) - try await XCTAsyncAssertEqual(try await channel.waitForInboundWrite(), 2) - try await XCTAsyncAssertEqual(try await channel.waitForInboundWrite(), 3) - } - - try await channel.writeInbound(1) - try await channel.writeInbound(2) - try await channel.writeInbound(3) - try await task.value + let channel = NIOAsyncTestingChannel() + try await XCTAsyncAssertTrue(await channel.writeInbound("hello").isFull) + do { + _ = try await channel.readInbound(as: Int.self) + XCTFail() + } catch let error as NIOAsyncTestingChannel.WrongTypeError { + let expectedError = NIOAsyncTestingChannel.WrongTypeError(expected: Int.self, actual: String.self) + XCTAssertEqual(error, expectedError) + } catch { + XCTFail() } } - func testWaitForMultipleInboundWritesInParallel() throws { + func testWrongTypesWithFastpathTypes() async throws { guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { throw XCTSkip() } - XCTAsyncTest { - let channel = NIOAsyncTestingChannel() - let task = Task { - let task1 = Task { try await channel.waitForInboundWrite(as: Int.self) } - let task2 = Task { try await channel.waitForInboundWrite(as: Int.self) } - let task3 = Task { try await channel.waitForInboundWrite(as: Int.self) } - try await XCTAsyncAssertEqual(Set([ - try await task1.value, - try await task2.value, - try await task3.value, - ]), [1, 2, 3]) - } + let channel = NIOAsyncTestingChannel() - try await channel.writeInbound(1) - try await channel.writeInbound(2) - try await channel.writeInbound(3) - try await task.value - } - } + let buffer = channel.allocator.buffer(capacity: 0) - func testWaitForOutboundWrite() throws { - guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { throw XCTSkip() } - XCTAsyncTest { - let channel = NIOAsyncTestingChannel() - let task = Task { - try await XCTAsyncAssertEqual(try await channel.waitForOutboundWrite(), 1) - try await XCTAsyncAssertEqual(try await channel.waitForOutboundWrite(), 2) - try await XCTAsyncAssertEqual(try await channel.waitForOutboundWrite(), 3) - } + try await XCTAsyncAssertTrue(await channel.writeOutbound(buffer).isFull) + try await XCTAsyncAssertTrue(await channel.writeOutbound( + AddressedEnvelope(remoteAddress: SocketAddress(ipAddress: "1.2.3.4", port: 5678), + data: buffer)).isFull) + try await XCTAsyncAssertTrue(await channel.writeOutbound(buffer).isFull) - try await channel.writeOutbound(1) - try await channel.writeOutbound(2) - try await channel.writeOutbound(3) - try await task.value - } - } - func testWaitForMultipleOutboundWritesInParallel() throws { - guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { throw XCTSkip() } - XCTAsyncTest { - let channel = NIOAsyncTestingChannel() - let task = Task { - let task1 = Task { try await channel.waitForOutboundWrite(as: Int.self) } - let task2 = Task { try await channel.waitForOutboundWrite(as: Int.self) } - let task3 = Task { try await channel.waitForOutboundWrite(as: Int.self) } - try await XCTAsyncAssertEqual(Set([ - try await task1.value, - try await task2.value, - try await task3.value, - ]), [1, 2, 3]) - } + try await XCTAsyncAssertTrue(await channel.writeInbound(buffer).isFull) + try await XCTAsyncAssertTrue(await channel.writeInbound( + AddressedEnvelope(remoteAddress: SocketAddress(ipAddress: "1.2.3.4", port: 5678), + data: buffer)).isFull) + try await XCTAsyncAssertTrue(await channel.writeInbound(buffer).isFull) - try await channel.writeOutbound(1) - try await channel.writeOutbound(2) - try await channel.writeOutbound(3) - try await task.value - } - } - - func testWriteOutboundByteBuffer() throws { - guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { throw XCTSkip() } - XCTAsyncTest { - let channel = NIOAsyncTestingChannel() - var buf = channel.allocator.buffer(capacity: 1024) - buf.writeString("hello") - - let isFull = try await channel.writeOutbound(buf).isFull - XCTAssertTrue(isFull) - - let hasLeftovers = try await channel.finish().hasLeftOvers - XCTAssertTrue(hasLeftovers) - - let read = try await channel.readOutbound(as: ByteBuffer.self) - XCTAssertNoThrow(XCTAssertEqual(buf, read)) - - let nextOutboundRead = try await channel.readOutbound(as: ByteBuffer.self) - let nextInboundRead = try await channel.readInbound(as: ByteBuffer.self) - XCTAssertNoThrow(XCTAssertNil(nextOutboundRead)) - XCTAssertNoThrow(XCTAssertNil(nextInboundRead)) - } - } - - func testWriteOutboundByteBufferMultipleTimes() throws { - guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { throw XCTSkip() } - XCTAsyncTest { - let channel = NIOAsyncTestingChannel() - var buf = channel.allocator.buffer(capacity: 1024) - buf.writeString("hello") - - try await XCTAsyncAssertTrue(await channel.writeOutbound(buf).isFull) - try await XCTAsyncAssertEqual(buf, await channel.readOutbound()) - try await XCTAsyncAssertNil(await channel.readOutbound(as: ByteBuffer.self)) - try await XCTAsyncAssertNil(await channel.readInbound(as: ByteBuffer.self)) - - var bufB = channel.allocator.buffer(capacity: 1024) - bufB.writeString("again") - - try await XCTAsyncAssertTrue(await channel.writeOutbound(bufB).isFull) - try await XCTAsyncAssertTrue(await channel.finish().hasLeftOvers) - try await XCTAsyncAssertEqual(bufB, await channel.readOutbound()) - try await XCTAsyncAssertNil(await channel.readOutbound(as: ByteBuffer.self)) - try await XCTAsyncAssertNil(await channel.readInbound(as: ByteBuffer.self)) - } - } - - func testWriteInboundByteBuffer() throws { - guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { throw XCTSkip() } - XCTAsyncTest { - let channel = NIOAsyncTestingChannel() - var buf = channel.allocator.buffer(capacity: 1024) - buf.writeString("hello") - - try await XCTAsyncAssertTrue(await channel.writeInbound(buf).isFull) - try await XCTAsyncAssertTrue(await channel.finish().hasLeftOvers) - try await XCTAsyncAssertEqual(buf, await channel.readInbound()) - try await XCTAsyncAssertNil(await channel.readInbound(as: ByteBuffer.self)) - try await XCTAsyncAssertNil(await channel.readOutbound(as: ByteBuffer.self)) - } - } - - func testWriteInboundByteBufferMultipleTimes() throws { - guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { throw XCTSkip() } - XCTAsyncTest { - let channel = NIOAsyncTestingChannel() - var buf = channel.allocator.buffer(capacity: 1024) - buf.writeString("hello") - - try await XCTAsyncAssertTrue(await channel.writeInbound(buf).isFull) - try await XCTAsyncAssertEqual(buf, await channel.readInbound()) - try await XCTAsyncAssertNil(await channel.readInbound(as: ByteBuffer.self)) - try await XCTAsyncAssertNil(await channel.readOutbound(as: ByteBuffer.self)) - - var bufB = channel.allocator.buffer(capacity: 1024) - bufB.writeString("again") - - try await XCTAsyncAssertTrue(await channel.writeInbound(bufB).isFull) - try await XCTAsyncAssertTrue(await channel.finish().hasLeftOvers) - try await XCTAsyncAssertEqual(bufB, await channel.readInbound()) - try await XCTAsyncAssertNil(await channel.readInbound(as: ByteBuffer.self)) - try await XCTAsyncAssertNil(await channel.readOutbound(as: ByteBuffer.self)) - } - } - - func testWriteInboundByteBufferReThrow() throws { - guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { throw XCTSkip() } - XCTAsyncTest { - let channel = NIOAsyncTestingChannel() - XCTAssertNoThrow(try channel.pipeline.addHandler(ExceptionThrowingInboundHandler()).wait()) - await XCTAsyncAssertThrowsError(try await channel.writeInbound("msg")) { error in - XCTAssertEqual(ChannelError.operationUnsupported, error as? ChannelError) - } - try await XCTAsyncAssertTrue(await channel.finish().isClean) - } - } - - func testWriteOutboundByteBufferReThrow() throws { - guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { throw XCTSkip() } - XCTAsyncTest { - let channel = NIOAsyncTestingChannel() - XCTAssertNoThrow(try channel.pipeline.addHandler(ExceptionThrowingOutboundHandler()).wait()) - await XCTAsyncAssertThrowsError(try await channel.writeOutbound("msg")) { error in - XCTAssertEqual(ChannelError.operationUnsupported, error as? ChannelError) - } - try await XCTAsyncAssertTrue(await channel.finish().isClean) - } - } - - func testReadOutboundWrongTypeThrows() throws { - guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { throw XCTSkip() } - XCTAsyncTest { - let channel = NIOAsyncTestingChannel() - try await XCTAsyncAssertTrue(await channel.writeOutbound("hello").isFull) + func check(expected: Expected.Type, + actual: Actual.Type, + file: StaticString = #filePath, + line: UInt = #line) async { do { - _ = try await channel.readOutbound(as: Int.self) - XCTFail() + _ = try await channel.readOutbound(as: Expected.self) + XCTFail("this should have failed", file: (file), line: line) } catch let error as NIOAsyncTestingChannel.WrongTypeError { - let expectedError = NIOAsyncTestingChannel.WrongTypeError(expected: Int.self, actual: String.self) - XCTAssertEqual(error, expectedError) + let expectedError = NIOAsyncTestingChannel.WrongTypeError(expected: Expected.self, actual: Actual.self) + XCTAssertEqual(error, expectedError, file: (file), line: line) } catch { - XCTFail() + XCTFail("unexpected error: \(error)", file: (file), line: line) } - } - } - func testReadInboundWrongTypeThrows() throws { - guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { throw XCTSkip() } - XCTAsyncTest { - let channel = NIOAsyncTestingChannel() - try await XCTAsyncAssertTrue(await channel.writeInbound("hello").isFull) do { - _ = try await channel.readInbound(as: Int.self) - XCTFail() + _ = try await channel.readInbound(as: Expected.self) + XCTFail("this should have failed", file: (file), line: line) } catch let error as NIOAsyncTestingChannel.WrongTypeError { - let expectedError = NIOAsyncTestingChannel.WrongTypeError(expected: Int.self, actual: String.self) - XCTAssertEqual(error, expectedError) + let expectedError = NIOAsyncTestingChannel.WrongTypeError(expected: Expected.self, actual: Actual.self) + XCTAssertEqual(error, expectedError, file: (file), line: line) } catch { - XCTFail() + XCTFail("unexpected error: \(error)", file: (file), line: line) } } + + await check(expected: Never.self, actual: IOData.self) + await check(expected: ByteBuffer.self, actual: AddressedEnvelope.self) + await check(expected: AddressedEnvelope.self, actual: IOData.self) } - func testWrongTypesWithFastpathTypes() throws { + func testCloseMultipleTimesThrows() async throws { guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { throw XCTSkip() } - XCTAsyncTest { - let channel = NIOAsyncTestingChannel() + let channel = NIOAsyncTestingChannel() + try await XCTAsyncAssertTrue(await channel.finish().isClean) - let buffer = channel.allocator.buffer(capacity: 0) - - try await XCTAsyncAssertTrue(await channel.writeOutbound(buffer).isFull) - try await XCTAsyncAssertTrue(await channel.writeOutbound( - AddressedEnvelope(remoteAddress: SocketAddress(ipAddress: "1.2.3.4", port: 5678), - data: buffer)).isFull) - try await XCTAsyncAssertTrue(await channel.writeOutbound(buffer).isFull) - - - try await XCTAsyncAssertTrue(await channel.writeInbound(buffer).isFull) - try await XCTAsyncAssertTrue(await channel.writeInbound( - AddressedEnvelope(remoteAddress: SocketAddress(ipAddress: "1.2.3.4", port: 5678), - data: buffer)).isFull) - try await XCTAsyncAssertTrue(await channel.writeInbound(buffer).isFull) - - func check(expected: Expected.Type, - actual: Actual.Type, - file: StaticString = #filePath, - line: UInt = #line) async { - do { - _ = try await channel.readOutbound(as: Expected.self) - XCTFail("this should have failed", file: (file), line: line) - } catch let error as NIOAsyncTestingChannel.WrongTypeError { - let expectedError = NIOAsyncTestingChannel.WrongTypeError(expected: Expected.self, actual: Actual.self) - XCTAssertEqual(error, expectedError, file: (file), line: line) - } catch { - XCTFail("unexpected error: \(error)", file: (file), line: line) - } - - do { - _ = try await channel.readInbound(as: Expected.self) - XCTFail("this should have failed", file: (file), line: line) - } catch let error as NIOAsyncTestingChannel.WrongTypeError { - let expectedError = NIOAsyncTestingChannel.WrongTypeError(expected: Expected.self, actual: Actual.self) - XCTAssertEqual(error, expectedError, file: (file), line: line) - } catch { - XCTFail("unexpected error: \(error)", file: (file), line: line) - } - } - - await check(expected: Never.self, actual: IOData.self) - await check(expected: ByteBuffer.self, actual: AddressedEnvelope.self) - await check(expected: AddressedEnvelope.self, actual: IOData.self) + // Close a second time. This must fail. + do { + try await channel.close() + XCTFail("Second close succeeded") + } catch ChannelError.alreadyClosed { + // Nothing to do here. } } - func testCloseMultipleTimesThrows() throws { + func testCloseOnInactiveIsOk() async throws { guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { throw XCTSkip() } - XCTAsyncTest { - let channel = NIOAsyncTestingChannel() - try await XCTAsyncAssertTrue(await channel.finish().isClean) + let channel = NIOAsyncTestingChannel() + let inactiveHandler = CloseInChannelInactiveHandler() + XCTAssertNoThrow(try channel.pipeline.addHandler(inactiveHandler).wait()) + try await XCTAsyncAssertTrue(await channel.finish().isClean) - // Close a second time. This must fail. - do { - try await channel.close() - XCTFail("Second close succeeded") - } catch ChannelError.alreadyClosed { - // Nothing to do here. - } - } + // channelInactive should fire only once. + XCTAssertEqual(inactiveHandler.inactiveNotifications, 1) } - func testCloseOnInactiveIsOk() throws { + func testEmbeddedLifecycle() async throws { guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { throw XCTSkip() } - XCTAsyncTest { - let channel = NIOAsyncTestingChannel() - let inactiveHandler = CloseInChannelInactiveHandler() - XCTAssertNoThrow(try channel.pipeline.addHandler(inactiveHandler).wait()) - try await XCTAsyncAssertTrue(await channel.finish().isClean) + let handler = ChannelLifecycleHandler() + XCTAssertEqual(handler.currentState, .unregistered) - // channelInactive should fire only once. - XCTAssertEqual(inactiveHandler.inactiveNotifications, 1) - } - } + let channel = await NIOAsyncTestingChannel(handler: handler) - func testEmbeddedLifecycle() throws { - guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { throw XCTSkip() } - XCTAsyncTest { - let handler = ChannelLifecycleHandler() - XCTAssertEqual(handler.currentState, .unregistered) + XCTAssertEqual(handler.currentState, .registered) + XCTAssertFalse(channel.isActive) - let channel = await NIOAsyncTestingChannel(handler: handler) + XCTAssertNoThrow(try channel.connect(to: try SocketAddress(unixDomainSocketPath: "/fake")).wait()) + XCTAssertEqual(handler.currentState, .active) + XCTAssertTrue(channel.isActive) - XCTAssertEqual(handler.currentState, .registered) - XCTAssertFalse(channel.isActive) - - XCTAssertNoThrow(try channel.connect(to: try SocketAddress(unixDomainSocketPath: "/fake")).wait()) - XCTAssertEqual(handler.currentState, .active) - XCTAssertTrue(channel.isActive) - - try await XCTAsyncAssertTrue(await channel.finish().isClean) - XCTAssertEqual(handler.currentState, .unregistered) - XCTAssertFalse(channel.isActive) - } + try await XCTAsyncAssertTrue(await channel.finish().isClean) + XCTAssertEqual(handler.currentState, .unregistered) + XCTAssertFalse(channel.isActive) } private final class ExceptionThrowingInboundHandler : ChannelInboundHandler { @@ -418,74 +382,66 @@ class AsyncTestingChannelTests: XCTestCase { } } - func testEmbeddedChannelAndPipelineAndChannelCoreShareTheEventLoop() throws { + func testEmbeddedChannelAndPipelineAndChannelCoreShareTheEventLoop() async throws { guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { throw XCTSkip() } - XCTAsyncTest { - let channel = NIOAsyncTestingChannel() - let pipelineEventLoop = channel.pipeline.eventLoop - XCTAssert(pipelineEventLoop === channel.eventLoop) - XCTAssert(pipelineEventLoop === (channel._channelCore as! EmbeddedChannelCore).eventLoop) - try await XCTAsyncAssertTrue(await channel.finish().isClean) - } + let channel = NIOAsyncTestingChannel() + let pipelineEventLoop = channel.pipeline.eventLoop + XCTAssert(pipelineEventLoop === channel.eventLoop) + XCTAssert(pipelineEventLoop === (channel._channelCore as! EmbeddedChannelCore).eventLoop) + try await XCTAsyncAssertTrue(await channel.finish().isClean) } - func testSendingAnythingOnEmbeddedChannel() throws { + func testSendingAnythingOnEmbeddedChannel() async throws { guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { throw XCTSkip() } - XCTAsyncTest { - let channel = NIOAsyncTestingChannel() - let buffer = ByteBufferAllocator().buffer(capacity: 5) - let socketAddress = try SocketAddress(unixDomainSocketPath: "path") - let handle = NIOFileHandle(descriptor: 1) - let fileRegion = FileRegion(fileHandle: handle, readerIndex: 1, endIndex: 2) - defer { - // fake descriptor, so shouldn't be closed. - XCTAssertNoThrow(try handle.takeDescriptorOwnership()) - } - try await channel.writeAndFlush(1) - try await channel.writeAndFlush("1") - try await channel.writeAndFlush(buffer) - try await channel.writeAndFlush(IOData.byteBuffer(buffer)) - try await channel.writeAndFlush(IOData.fileRegion(fileRegion)) - try await channel.writeAndFlush(AddressedEnvelope(remoteAddress: socketAddress, data: buffer)) + let channel = NIOAsyncTestingChannel() + let buffer = ByteBufferAllocator().buffer(capacity: 5) + let socketAddress = try SocketAddress(unixDomainSocketPath: "path") + let handle = NIOFileHandle(descriptor: 1) + let fileRegion = FileRegion(fileHandle: handle, readerIndex: 1, endIndex: 2) + defer { + // fake descriptor, so shouldn't be closed. + XCTAssertNoThrow(try handle.takeDescriptorOwnership()) } + try await channel.writeAndFlush(1) + try await channel.writeAndFlush("1") + try await channel.writeAndFlush(buffer) + try await channel.writeAndFlush(IOData.byteBuffer(buffer)) + try await channel.writeAndFlush(IOData.fileRegion(fileRegion)) + try await channel.writeAndFlush(AddressedEnvelope(remoteAddress: socketAddress, data: buffer)) } - func testActiveWhenConnectPromiseFiresAndInactiveWhenClosePromiseFires() throws { + func testActiveWhenConnectPromiseFiresAndInactiveWhenClosePromiseFires() async throws { guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { throw XCTSkip() } - XCTAsyncTest { - let channel = NIOAsyncTestingChannel() + let channel = NIOAsyncTestingChannel() + XCTAssertFalse(channel.isActive) + let connectPromise = channel.eventLoop.makePromise(of: Void.self) + connectPromise.futureResult.whenComplete { (_: Result) in + XCTAssertTrue(channel.isActive) + } + channel.connect(to: try SocketAddress(ipAddress: "127.0.0.1", port: 0), promise: connectPromise) + try await connectPromise.futureResult.get() + + let closePromise = channel.eventLoop.makePromise(of: Void.self) + closePromise.futureResult.whenComplete { (_: Result) in XCTAssertFalse(channel.isActive) - let connectPromise = channel.eventLoop.makePromise(of: Void.self) - connectPromise.futureResult.whenComplete { (_: Result) in - XCTAssertTrue(channel.isActive) - } - channel.connect(to: try SocketAddress(ipAddress: "127.0.0.1", port: 0), promise: connectPromise) - try await connectPromise.futureResult.get() - - let closePromise = channel.eventLoop.makePromise(of: Void.self) - closePromise.futureResult.whenComplete { (_: Result) in - XCTAssertFalse(channel.isActive) - } - - channel.close(promise: closePromise) - try await closePromise.futureResult.get() } + + channel.close(promise: closePromise) + try await closePromise.futureResult.get() } - func testWriteWithoutFlushDoesNotWrite() throws { + func testWriteWithoutFlushDoesNotWrite() async throws { guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { throw XCTSkip() } - XCTAsyncTest { - let channel = NIOAsyncTestingChannel() + let channel = NIOAsyncTestingChannel() - let buf = ByteBuffer(bytes: [1]) - let writeFuture = channel.write(buf) - try await XCTAsyncAssertNil(await channel.readOutbound(as: ByteBuffer.self)) - XCTAssertFalse(writeFuture.isFulfilled) - channel.flush() - try await XCTAsyncAssertNotNil(await channel.readOutbound(as: ByteBuffer.self)) - XCTAssertTrue(writeFuture.isFulfilled) - try await XCTAsyncAssertTrue(await channel.finish().isClean) - } + let buf = ByteBuffer(bytes: [1]) + let writeFuture = channel.write(buf) + try await XCTAsyncAssertNil(await channel.readOutbound(as: ByteBuffer.self)) + XCTAssertFalse(writeFuture.isFulfilled) + channel.flush() + try await XCTAsyncAssertNotNil(await channel.readOutbound(as: ByteBuffer.self)) + XCTAssertTrue(writeFuture.isFulfilled) + try await XCTAsyncAssertTrue(await channel.finish().isClean) } func testSetLocalAddressAfterSuccessfulBind() throws { @@ -543,9 +499,8 @@ class AsyncTestingChannelTests: XCTestCase { } - func testFinishWithRecursivelyScheduledTasks() throws { + func testFinishWithRecursivelyScheduledTasks() async throws { guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { throw XCTSkip() } - XCTAsyncTest { let channel = NIOAsyncTestingChannel() let invocations = AtomicCounter() @@ -560,7 +515,6 @@ class AsyncTestingChannelTests: XCTestCase { _ = try await channel.finish() XCTAssertEqual(invocations.load(), 1) - } } func testSyncOptionsAreSupported() throws { @@ -604,13 +558,11 @@ class AsyncTestingChannelTests: XCTestCase { }.wait() } - func testSecondFinishThrows() throws { + func testSecondFinishThrows() async throws { guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { throw XCTSkip() } - XCTAsyncTest { - let channel = NIOAsyncTestingChannel() - _ = try await channel.finish() - await XCTAsyncAssertThrowsError(try await channel.finish()) - } + let channel = NIOAsyncTestingChannel() + _ = try await channel.finish() + await XCTAsyncAssertThrowsError(try await channel.finish()) } } diff --git a/Tests/NIOEmbeddedTests/AsyncTestingEventLoopTests.swift b/Tests/NIOEmbeddedTests/AsyncTestingEventLoopTests.swift index c2927db1c..334d1c50e 100644 --- a/Tests/NIOEmbeddedTests/AsyncTestingEventLoopTests.swift +++ b/Tests/NIOEmbeddedTests/AsyncTestingEventLoopTests.swift @@ -20,617 +20,569 @@ import Atomics private class EmbeddedTestError: Error { } final class NIOAsyncTestingEventLoopTests: XCTestCase { - func testExecuteDoesNotImmediatelyRunTasks() throws { + func testExecuteDoesNotImmediatelyRunTasks() async throws { guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { throw XCTSkip() } - XCTAsyncTest { - let callbackRan = ManagedAtomic(false) - let loop = NIOAsyncTestingEventLoop() - try await loop.executeInContext { - loop.execute { callbackRan.store(true, ordering: .relaxed) } - XCTAssertFalse(callbackRan.load(ordering: .relaxed)) + let callbackRan = ManagedAtomic(false) + let loop = NIOAsyncTestingEventLoop() + try await loop.executeInContext { + loop.execute { callbackRan.store(true, ordering: .relaxed) } + XCTAssertFalse(callbackRan.load(ordering: .relaxed)) + } + await loop.run() + XCTAssertTrue(callbackRan.load(ordering: .relaxed)) + } + + func testExecuteWillRunAllTasks() async throws { + guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { throw XCTSkip() } + let runCount = ManagedAtomic(0) + let loop = NIOAsyncTestingEventLoop() + loop.execute { runCount.wrappingIncrement(ordering: .relaxed) } + loop.execute { runCount.wrappingIncrement(ordering: .relaxed) } + loop.execute { runCount.wrappingIncrement(ordering: .relaxed) } + + try await loop.executeInContext { + XCTAssertEqual(runCount.load(ordering: .relaxed), 3) + } + await loop.run() + try await loop.executeInContext { + XCTAssertEqual(runCount.load(ordering: .relaxed), 3) + } + } + + func testExecuteWillRunTasksAddedRecursively() async throws { + guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { throw XCTSkip() } + let sentinel = ManagedAtomic(0) + let loop = NIOAsyncTestingEventLoop() + + loop.execute { + // This should execute first. + XCTAssertEqual(sentinel.load(ordering: .relaxed), 0) + sentinel.store(1, ordering: .relaxed) + loop.execute { + // This should execute second + let loaded = sentinel.loadThenWrappingIncrement(ordering: .relaxed) + XCTAssertEqual(loaded, 1) } - await loop.run() + } + loop.execute { + // This should execute third + let loaded = sentinel.loadThenWrappingIncrement(ordering: .relaxed) + XCTAssertEqual(loaded, 2) + } + + try await loop.executeInContext { + XCTAssertEqual(sentinel.load(ordering: .relaxed), 3) + } + await loop.run() + try await loop.executeInContext { + XCTAssertEqual(sentinel.load(ordering: .relaxed), 3) + } + } + + func testExecuteRunsImmediately() async throws { + guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { throw XCTSkip() } + let callbackRan = ManagedAtomic(false) + let loop = NIOAsyncTestingEventLoop() + loop.execute { callbackRan.store(true, ordering: .relaxed) } + + try await loop.executeInContext { + XCTAssertTrue(callbackRan.load(ordering: .relaxed)) + } + loop.execute { callbackRan.store(false, ordering: .relaxed) } + + try await loop.executeInContext { + XCTAssertFalse(callbackRan.load(ordering: .relaxed)) + } + try await loop.executeInContext { + XCTAssertFalse(callbackRan.load(ordering: .relaxed)) + } + } + + func testTasksScheduledAfterRunDontRun() async throws { + guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { throw XCTSkip() } + let callbackRan = ManagedAtomic(false) + let loop = NIOAsyncTestingEventLoop() + loop.scheduleTask(deadline: loop.now) { callbackRan.store(true, ordering: .relaxed) } + + try await loop.executeInContext { + XCTAssertFalse(callbackRan.load(ordering: .relaxed)) + } + await loop.run() + loop.scheduleTask(deadline: loop.now) { callbackRan.store(false, ordering: .relaxed) } + + try await loop.executeInContext { + XCTAssertTrue(callbackRan.load(ordering: .relaxed)) + } + await loop.run() + try await loop.executeInContext { + XCTAssertFalse(callbackRan.load(ordering: .relaxed)) + } + } + + func testSubmitRunsImmediately() async throws { + guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { throw XCTSkip() } + let callbackRan = ManagedAtomic(false) + let loop = NIOAsyncTestingEventLoop() + _ = loop.submit { callbackRan.store(true, ordering: .relaxed) } + + try await loop.executeInContext { + XCTAssertTrue(callbackRan.load(ordering: .relaxed)) + } + _ = loop.submit { callbackRan.store(false, ordering: .relaxed) } + + try await loop.executeInContext { + XCTAssertFalse(callbackRan.load(ordering: .relaxed)) + } + try await loop.executeInContext { + XCTAssertFalse(callbackRan.load(ordering: .relaxed)) + } + } + + func testSyncShutdownGracefullyRunsTasks() async throws { + guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { throw XCTSkip() } + let callbackRan = ManagedAtomic(false) + let loop = NIOAsyncTestingEventLoop() + loop.scheduleTask(deadline: loop.now) { callbackRan.store(true, ordering: .relaxed) } + + try await loop.executeInContext { + XCTAssertFalse(callbackRan.load(ordering: .relaxed)) + } + XCTAssertNoThrow(try loop.syncShutdownGracefully()) + try await loop.executeInContext { XCTAssertTrue(callbackRan.load(ordering: .relaxed)) } } - func testExecuteWillRunAllTasks() throws { + func testShutdownGracefullyRunsTasks() async throws { guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { throw XCTSkip() } - XCTAsyncTest { - let runCount = ManagedAtomic(0) - let loop = NIOAsyncTestingEventLoop() - loop.execute { runCount.wrappingIncrement(ordering: .relaxed) } - loop.execute { runCount.wrappingIncrement(ordering: .relaxed) } - loop.execute { runCount.wrappingIncrement(ordering: .relaxed) } + let callbackRan = ManagedAtomic(false) + let loop = NIOAsyncTestingEventLoop() + loop.scheduleTask(deadline: loop.now) { callbackRan.store(true, ordering: .relaxed) } - try await loop.executeInContext { - XCTAssertEqual(runCount.load(ordering: .relaxed), 3) + try await loop.executeInContext { + XCTAssertFalse(callbackRan.load(ordering: .relaxed)) + } + await loop.shutdownGracefully() + try await loop.executeInContext { + XCTAssertTrue(callbackRan.load(ordering: .relaxed)) + } + } + + func testCanControlTime() async throws { + guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { throw XCTSkip() } + let callbackCount = ManagedAtomic(0) + let loop = NIOAsyncTestingEventLoop() + _ = loop.scheduleTask(in: .nanoseconds(5)) { + callbackCount.loadThenWrappingIncrement(ordering: .relaxed) + } + + try await loop.executeInContext { + XCTAssertEqual(callbackCount.load(ordering: .relaxed), 0) + } + await loop.advanceTime(by: .nanoseconds(4)) + try await loop.executeInContext { + XCTAssertEqual(callbackCount.load(ordering: .relaxed), 0) + } + await loop.advanceTime(by: .nanoseconds(1)) + try await loop.executeInContext { + XCTAssertEqual(callbackCount.load(ordering: .relaxed), 1) + } + await loop.advanceTime(by: .nanoseconds(1)) + try await loop.executeInContext { + XCTAssertEqual(callbackCount.load(ordering: .relaxed), 1) + } + await loop.advanceTime(by: .hours(1)) + try await loop.executeInContext { + XCTAssertEqual(callbackCount.load(ordering: .relaxed), 1) + } + } + + func testCanScheduleMultipleTasks() async throws { + guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { throw XCTSkip() } + let sentinel = ManagedAtomic(0) + let loop = NIOAsyncTestingEventLoop() + for index in 1...10 { + _ = loop.scheduleTask(in: .nanoseconds(Int64(index))) { + sentinel.store(index, ordering: .relaxed) } - await loop.run() + } + + for val in 1...10 { try await loop.executeInContext { - XCTAssertEqual(runCount.load(ordering: .relaxed), 3) + XCTAssertEqual(sentinel.load(ordering: .relaxed), val - 1) + } + await loop.advanceTime(by: .nanoseconds(1)) + try await loop.executeInContext { + XCTAssertEqual(sentinel.load(ordering: .relaxed), val) } } } - func testExecuteWillRunTasksAddedRecursively() throws { + func testExecutedTasksFromScheduledOnesAreRun() async throws { guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { throw XCTSkip() } - XCTAsyncTest { - let sentinel = ManagedAtomic(0) - let loop = NIOAsyncTestingEventLoop() - + let sentinel = ManagedAtomic(0) + let loop = NIOAsyncTestingEventLoop() + _ = loop.scheduleTask(in: .nanoseconds(5)) { + sentinel.store(1, ordering: .relaxed) loop.execute { - // This should execute first. - XCTAssertEqual(sentinel.load(ordering: .relaxed), 0) - sentinel.store(1, ordering: .relaxed) - loop.execute { - // This should execute second - let loaded = sentinel.loadThenWrappingIncrement(ordering: .relaxed) - XCTAssertEqual(loaded, 1) - } - } - loop.execute { - // This should execute third - let loaded = sentinel.loadThenWrappingIncrement(ordering: .relaxed) - XCTAssertEqual(loaded, 2) + sentinel.store(2, ordering: .relaxed) } + } - try await loop.executeInContext { - XCTAssertEqual(sentinel.load(ordering: .relaxed), 3) - } - await loop.run() - try await loop.executeInContext { - XCTAssertEqual(sentinel.load(ordering: .relaxed), 3) - } + await loop.advanceTime(by: .nanoseconds(4)) + try await loop.executeInContext { + XCTAssertEqual(sentinel.load(ordering: .relaxed), 0) + } + await loop.advanceTime(by: .nanoseconds(1)) + try await loop.executeInContext { + XCTAssertEqual(sentinel.load(ordering: .relaxed), 2) } } - func testExecuteRunsImmediately() throws { + func testScheduledTasksFromScheduledTasksProperlySchedule() async throws { guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { throw XCTSkip() } - XCTAsyncTest { - let callbackRan = ManagedAtomic(false) - let loop = NIOAsyncTestingEventLoop() - loop.execute { callbackRan.store(true, ordering: .relaxed) } - - try await loop.executeInContext { - XCTAssertTrue(callbackRan.load(ordering: .relaxed)) + let sentinel = ManagedAtomic(0) + let loop = NIOAsyncTestingEventLoop() + _ = loop.scheduleTask(in: .nanoseconds(5)) { + sentinel.store(1, ordering: .relaxed) + _ = loop.scheduleTask(in: .nanoseconds(3)) { + sentinel.store(2, ordering: .relaxed) } - loop.execute { callbackRan.store(false, ordering: .relaxed) } - - try await loop.executeInContext { - XCTAssertFalse(callbackRan.load(ordering: .relaxed)) - } - try await loop.executeInContext { - XCTAssertFalse(callbackRan.load(ordering: .relaxed)) - } - } - } - - func testTasksScheduledAfterRunDontRun() throws { - guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { throw XCTSkip() } - XCTAsyncTest { - let callbackRan = ManagedAtomic(false) - let loop = NIOAsyncTestingEventLoop() - loop.scheduleTask(deadline: loop.now) { callbackRan.store(true, ordering: .relaxed) } - - try await loop.executeInContext { - XCTAssertFalse(callbackRan.load(ordering: .relaxed)) - } - await loop.run() - loop.scheduleTask(deadline: loop.now) { callbackRan.store(false, ordering: .relaxed) } - - try await loop.executeInContext { - XCTAssertTrue(callbackRan.load(ordering: .relaxed)) - } - await loop.run() - try await loop.executeInContext { - XCTAssertFalse(callbackRan.load(ordering: .relaxed)) - } - } - } - - func testSubmitRunsImmediately() throws { - guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { throw XCTSkip() } - XCTAsyncTest { - let callbackRan = ManagedAtomic(false) - let loop = NIOAsyncTestingEventLoop() - _ = loop.submit { callbackRan.store(true, ordering: .relaxed) } - - try await loop.executeInContext { - XCTAssertTrue(callbackRan.load(ordering: .relaxed)) - } - _ = loop.submit { callbackRan.store(false, ordering: .relaxed) } - - try await loop.executeInContext { - XCTAssertFalse(callbackRan.load(ordering: .relaxed)) - } - try await loop.executeInContext { - XCTAssertFalse(callbackRan.load(ordering: .relaxed)) - } - } - } - - func testSyncShutdownGracefullyRunsTasks() throws { - guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { throw XCTSkip() } - XCTAsyncTest { - let callbackRan = ManagedAtomic(false) - let loop = NIOAsyncTestingEventLoop() - loop.scheduleTask(deadline: loop.now) { callbackRan.store(true, ordering: .relaxed) } - - try await loop.executeInContext { - XCTAssertFalse(callbackRan.load(ordering: .relaxed)) - } - XCTAssertNoThrow(try loop.syncShutdownGracefully()) - try await loop.executeInContext { - XCTAssertTrue(callbackRan.load(ordering: .relaxed)) - } - } - } - - func testShutdownGracefullyRunsTasks() throws { - guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { throw XCTSkip() } - XCTAsyncTest { - let callbackRan = ManagedAtomic(false) - let loop = NIOAsyncTestingEventLoop() - loop.scheduleTask(deadline: loop.now) { callbackRan.store(true, ordering: .relaxed) } - - try await loop.executeInContext { - XCTAssertFalse(callbackRan.load(ordering: .relaxed)) - } - await loop.shutdownGracefully() - try await loop.executeInContext { - XCTAssertTrue(callbackRan.load(ordering: .relaxed)) - } - } - } - - func testCanControlTime() throws { - guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { throw XCTSkip() } - XCTAsyncTest { - let callbackCount = ManagedAtomic(0) - let loop = NIOAsyncTestingEventLoop() _ = loop.scheduleTask(in: .nanoseconds(5)) { - callbackCount.loadThenWrappingIncrement(ordering: .relaxed) + sentinel.store(3, ordering: .relaxed) } + } - try await loop.executeInContext { - XCTAssertEqual(callbackCount.load(ordering: .relaxed), 0) - } - await loop.advanceTime(by: .nanoseconds(4)) - try await loop.executeInContext { - XCTAssertEqual(callbackCount.load(ordering: .relaxed), 0) - } - await loop.advanceTime(by: .nanoseconds(1)) - try await loop.executeInContext { - XCTAssertEqual(callbackCount.load(ordering: .relaxed), 1) - } - await loop.advanceTime(by: .nanoseconds(1)) - try await loop.executeInContext { - XCTAssertEqual(callbackCount.load(ordering: .relaxed), 1) - } - await loop.advanceTime(by: .hours(1)) - try await loop.executeInContext { - XCTAssertEqual(callbackCount.load(ordering: .relaxed), 1) - } + await loop.advanceTime(by: .nanoseconds(4)) + try await loop.executeInContext { + XCTAssertEqual(sentinel.load(ordering: .relaxed), 0) + } + await loop.advanceTime(by: .nanoseconds(1)) + try await loop.executeInContext { + XCTAssertEqual(sentinel.load(ordering: .relaxed), 1) + } + await loop.advanceTime(by: .nanoseconds(2)) + try await loop.executeInContext { + XCTAssertEqual(sentinel.load(ordering: .relaxed), 1) + } + await loop.advanceTime(by: .nanoseconds(1)) + try await loop.executeInContext { + XCTAssertEqual(sentinel.load(ordering: .relaxed), 2) + } + await loop.advanceTime(by: .nanoseconds(1)) + try await loop.executeInContext { + XCTAssertEqual(sentinel.load(ordering: .relaxed), 2) + } + await loop.advanceTime(by: .nanoseconds(1)) + try await loop.executeInContext { + XCTAssertEqual(sentinel.load(ordering: .relaxed), 3) } } - func testCanScheduleMultipleTasks() throws { + func testScheduledTasksFromExecutedTasks() async throws { guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { throw XCTSkip() } - XCTAsyncTest { - let sentinel = ManagedAtomic(0) - let loop = NIOAsyncTestingEventLoop() - for index in 1...10 { - _ = loop.scheduleTask(in: .nanoseconds(Int64(index))) { - sentinel.store(index, ordering: .relaxed) - } - } - - for val in 1...10 { - try await loop.executeInContext { - XCTAssertEqual(sentinel.load(ordering: .relaxed), val - 1) - } - await loop.advanceTime(by: .nanoseconds(1)) - try await loop.executeInContext { - XCTAssertEqual(sentinel.load(ordering: .relaxed), val) - } - } - } - } - - func testExecutedTasksFromScheduledOnesAreRun() throws { - guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { throw XCTSkip() } - XCTAsyncTest { - let sentinel = ManagedAtomic(0) - let loop = NIOAsyncTestingEventLoop() + let sentinel = ManagedAtomic(0) + let loop = NIOAsyncTestingEventLoop() + loop.execute { + XCTAssertEqual(sentinel.load(ordering: .relaxed), 0) _ = loop.scheduleTask(in: .nanoseconds(5)) { - sentinel.store(1, ordering: .relaxed) - loop.execute { - sentinel.store(2, ordering: .relaxed) - } - } - - await loop.advanceTime(by: .nanoseconds(4)) - try await loop.executeInContext { - XCTAssertEqual(sentinel.load(ordering: .relaxed), 0) - } - await loop.advanceTime(by: .nanoseconds(1)) - try await loop.executeInContext { - XCTAssertEqual(sentinel.load(ordering: .relaxed), 2) - } - } - } - - func testScheduledTasksFromScheduledTasksProperlySchedule() throws { - guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { throw XCTSkip() } - XCTAsyncTest { - let sentinel = ManagedAtomic(0) - let loop = NIOAsyncTestingEventLoop() - _ = loop.scheduleTask(in: .nanoseconds(5)) { - sentinel.store(1, ordering: .relaxed) - _ = loop.scheduleTask(in: .nanoseconds(3)) { - sentinel.store(2, ordering: .relaxed) - } - _ = loop.scheduleTask(in: .nanoseconds(5)) { - sentinel.store(3, ordering: .relaxed) - } - } - - await loop.advanceTime(by: .nanoseconds(4)) - try await loop.executeInContext { - XCTAssertEqual(sentinel.load(ordering: .relaxed), 0) - } - await loop.advanceTime(by: .nanoseconds(1)) - try await loop.executeInContext { XCTAssertEqual(sentinel.load(ordering: .relaxed), 1) + sentinel.store(2, ordering: .relaxed) } - await loop.advanceTime(by: .nanoseconds(2)) - try await loop.executeInContext { - XCTAssertEqual(sentinel.load(ordering: .relaxed), 1) - } - await loop.advanceTime(by: .nanoseconds(1)) - try await loop.executeInContext { - XCTAssertEqual(sentinel.load(ordering: .relaxed), 2) - } - await loop.advanceTime(by: .nanoseconds(1)) - try await loop.executeInContext { - XCTAssertEqual(sentinel.load(ordering: .relaxed), 2) - } - await loop.advanceTime(by: .nanoseconds(1)) - try await loop.executeInContext { - XCTAssertEqual(sentinel.load(ordering: .relaxed), 3) - } + loop.execute { sentinel.store(1, ordering: .relaxed) } + } + + await loop.advanceTime(by: .nanoseconds(5)) + try await loop.executeInContext { + XCTAssertEqual(sentinel.load(ordering: .relaxed), 2) } } - func testScheduledTasksFromExecutedTasks() throws { + func testCancellingScheduledTasks() async throws { guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { throw XCTSkip() } - XCTAsyncTest { - let sentinel = ManagedAtomic(0) - let loop = NIOAsyncTestingEventLoop() - loop.execute { - XCTAssertEqual(sentinel.load(ordering: .relaxed), 0) - _ = loop.scheduleTask(in: .nanoseconds(5)) { - XCTAssertEqual(sentinel.load(ordering: .relaxed), 1) - sentinel.store(2, ordering: .relaxed) - } - loop.execute { sentinel.store(1, ordering: .relaxed) } - } - - await loop.advanceTime(by: .nanoseconds(5)) - try await loop.executeInContext { - XCTAssertEqual(sentinel.load(ordering: .relaxed), 2) - } + let loop = NIOAsyncTestingEventLoop() + let task = loop.scheduleTask(in: .nanoseconds(10), { XCTFail("Cancelled task ran") }) + _ = loop.scheduleTask(in: .nanoseconds(5)) { + task.cancel() } + + await loop.advanceTime(by: .nanoseconds(20)) } - func testCancellingScheduledTasks() throws { + func testScheduledTasksFuturesFire() async throws { guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { throw XCTSkip() } - XCTAsyncTest { - let loop = NIOAsyncTestingEventLoop() - let task = loop.scheduleTask(in: .nanoseconds(10), { XCTFail("Cancelled task ran") }) - _ = loop.scheduleTask(in: .nanoseconds(5)) { - task.cancel() - } + let fired = ManagedAtomic(false) + let loop = NIOAsyncTestingEventLoop() + let task = loop.scheduleTask(in: .nanoseconds(5)) { true } + task.futureResult.whenSuccess { fired.store($0, ordering: .relaxed) } - await loop.advanceTime(by: .nanoseconds(20)) - } + await loop.advanceTime(by: .nanoseconds(4)) + XCTAssertFalse(fired.load(ordering: .relaxed)) + await loop.advanceTime(by: .nanoseconds(1)) + XCTAssertTrue(fired.load(ordering: .relaxed)) } - func testScheduledTasksFuturesFire() throws { + func testScheduledTasksFuturesError() async throws { guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { throw XCTSkip() } - XCTAsyncTest { - let fired = ManagedAtomic(false) - let loop = NIOAsyncTestingEventLoop() - let task = loop.scheduleTask(in: .nanoseconds(5)) { true } - task.futureResult.whenSuccess { fired.store($0, ordering: .relaxed) } - - await loop.advanceTime(by: .nanoseconds(4)) - XCTAssertFalse(fired.load(ordering: .relaxed)) - await loop.advanceTime(by: .nanoseconds(1)) - XCTAssertTrue(fired.load(ordering: .relaxed)) + let err = EmbeddedTestError() + let fired = ManagedAtomic(false) + let loop = NIOAsyncTestingEventLoop() + let task = loop.scheduleTask(in: .nanoseconds(5)) { + throw err } + task.futureResult.map { + XCTFail("Scheduled future completed") + }.recover { caughtErr in + XCTAssertTrue(err === caughtErr as? EmbeddedTestError) + }.whenComplete { (_: Result) in + fired.store(true, ordering: .relaxed) + } + + await loop.advanceTime(by: .nanoseconds(4)) + XCTAssertFalse(fired.load(ordering: .relaxed)) + await loop.advanceTime(by: .nanoseconds(1)) + XCTAssertTrue(fired.load(ordering: .relaxed)) } - func testScheduledTasksFuturesError() throws { + func testTaskOrdering() async throws { guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { throw XCTSkip() } - XCTAsyncTest { - let err = EmbeddedTestError() - let fired = ManagedAtomic(false) - let loop = NIOAsyncTestingEventLoop() - let task = loop.scheduleTask(in: .nanoseconds(5)) { - throw err - } - task.futureResult.map { - XCTFail("Scheduled future completed") - }.recover { caughtErr in - XCTAssertTrue(err === caughtErr as? EmbeddedTestError) - }.whenComplete { (_: Result) in - fired.store(true, ordering: .relaxed) - } + // This test validates that the ordering of task firing on NIOAsyncTestingEventLoop via + // advanceTime(by:) is the same as on MultiThreadedEventLoopGroup: specifically, that tasks run via + // schedule that expire "now" all run at the same time, and that any work they schedule is run + // after all such tasks expire. + let loop = NIOAsyncTestingEventLoop() + let lock = NIOLock() + var firstScheduled: Scheduled? = nil + var secondScheduled: Scheduled? = nil + let orderingCounter = ManagedAtomic(0) - await loop.advanceTime(by: .nanoseconds(4)) - XCTAssertFalse(fired.load(ordering: .relaxed)) - await loop.advanceTime(by: .nanoseconds(1)) - XCTAssertTrue(fired.load(ordering: .relaxed)) - } - } + // Here's the setup. First, we'll set up two scheduled tasks to fire in 5 nanoseconds. Each of these + // will attempt to cancel the other, but the first one scheduled will fire first. Additionally, each will execute{} a single + // callback. Then we'll execute {} one other callback. Finally we'll schedule a task for 10ns, before + // we advance time. The ordering should be as follows: + // + // 1. The task executed by execute {} from this function. + // 2. The first scheduled task. + // 3. The second scheduled task (note that the cancellation will fail). + // 4. The execute {} callback from the first scheduled task. + // 5. The execute {} callbacks from the second scheduled task. + // 6. The 10ns task. + // + // To validate the ordering, we'll use a counter. - func testTaskOrdering() throws { - guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { throw XCTSkip() } - XCTAsyncTest { - // This test validates that the ordering of task firing on NIOAsyncTestingEventLoop via - // advanceTime(by:) is the same as on MultiThreadedEventLoopGroup: specifically, that tasks run via - // schedule that expire "now" all run at the same time, and that any work they schedule is run - // after all such tasks expire. - let loop = NIOAsyncTestingEventLoop() - let lock = NIOLock() - var firstScheduled: Scheduled? = nil - var secondScheduled: Scheduled? = nil - let orderingCounter = ManagedAtomic(0) - - // Here's the setup. First, we'll set up two scheduled tasks to fire in 5 nanoseconds. Each of these - // will attempt to cancel the other, but the first one scheduled will fire first. Additionally, each will execute{} a single - // callback. Then we'll execute {} one other callback. Finally we'll schedule a task for 10ns, before - // we advance time. The ordering should be as follows: - // - // 1. The task executed by execute {} from this function. - // 2. The first scheduled task. - // 3. The second scheduled task (note that the cancellation will fail). - // 4. The execute {} callback from the first scheduled task. - // 5. The execute {} callbacks from the second scheduled task. - // 6. The 10ns task. - // - // To validate the ordering, we'll use a counter. - - lock.withLock { () -> Void in - firstScheduled = loop.scheduleTask(in: .nanoseconds(5)) { - let second = lock.withLock { () -> Scheduled? in - XCTAssertNotNil(firstScheduled) - firstScheduled = nil - XCTAssertNotNil(secondScheduled) - return secondScheduled - } - - if let partner = second { - // Ok, this callback fired first. Cancel the other. - partner.cancel() - } else { - XCTFail("First callback executed second") - } - - XCTAssertCompareAndSwapSucceeds(storage: orderingCounter, expected: 1, desired: 2) - - loop.execute { - XCTAssertCompareAndSwapSucceeds(storage: orderingCounter, expected: 3, desired: 4) - } + lock.withLock { () -> Void in + firstScheduled = loop.scheduleTask(in: .nanoseconds(5)) { + let second = lock.withLock { () -> Scheduled? in + XCTAssertNotNil(firstScheduled) + firstScheduled = nil + XCTAssertNotNil(secondScheduled) + return secondScheduled } - secondScheduled = loop.scheduleTask(in: .nanoseconds(5)) { - lock.withLock { () -> Void in - secondScheduled = nil - XCTAssertNil(firstScheduled) - XCTAssertNil(secondScheduled) - } + if let partner = second { + // Ok, this callback fired first. Cancel the other. + partner.cancel() + } else { + XCTFail("First callback executed second") + } - XCTAssertCompareAndSwapSucceeds(storage: orderingCounter, expected: 2, desired: 3) + XCTAssertCompareAndSwapSucceeds(storage: orderingCounter, expected: 1, desired: 2) - loop.execute { - XCTAssertCompareAndSwapSucceeds(storage: orderingCounter, expected: 4, desired: 5) - } + loop.execute { + XCTAssertCompareAndSwapSucceeds(storage: orderingCounter, expected: 3, desired: 4) } } - // Ok, now we set one more task to execute. - loop.execute { - XCTAssertCompareAndSwapSucceeds(storage: orderingCounter, expected: 0, desired: 1) + secondScheduled = loop.scheduleTask(in: .nanoseconds(5)) { + lock.withLock { () -> Void in + secondScheduled = nil + XCTAssertNil(firstScheduled) + XCTAssertNil(secondScheduled) + } + + XCTAssertCompareAndSwapSucceeds(storage: orderingCounter, expected: 2, desired: 3) + + loop.execute { + XCTAssertCompareAndSwapSucceeds(storage: orderingCounter, expected: 4, desired: 5) + } + } + } + + // Ok, now we set one more task to execute. + loop.execute { + XCTAssertCompareAndSwapSucceeds(storage: orderingCounter, expected: 0, desired: 1) + } + + // Finally schedule a task for 10ns. + _ = loop.scheduleTask(in: .nanoseconds(10)) { + XCTAssertCompareAndSwapSucceeds(storage: orderingCounter, expected: 5, desired: 6) + } + + // Now we advance time by 10ns. + await loop.advanceTime(by: .nanoseconds(10)) + + // Now the final value should be 6. + XCTAssertEqual(orderingCounter.load(ordering: .relaxed), 6) + } + + func testCancelledScheduledTasksDoNotHoldOnToRunClosure() async throws { + guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { throw XCTSkip() } + let eventLoop = NIOAsyncTestingEventLoop() + defer { + XCTAssertNoThrow(try eventLoop.syncShutdownGracefully()) + } + + class Thing: @unchecked Sendable { + private let deallocated: ConditionLock + + init(_ deallocated: ConditionLock) { + self.deallocated = deallocated } - // Finally schedule a task for 10ns. - _ = loop.scheduleTask(in: .nanoseconds(10)) { - XCTAssertCompareAndSwapSucceeds(storage: orderingCounter, expected: 5, desired: 6) + deinit { + self.deallocated.lock() + self.deallocated.unlock(withValue: 1) } + } - // Now we advance time by 10ns. - await loop.advanceTime(by: .nanoseconds(10)) + func make(deallocated: ConditionLock) -> Scheduled { + let aThing = Thing(deallocated) + return eventLoop.next().scheduleTask(in: .hours(1)) { + preconditionFailure("this should definitely not run: \(aThing)") + } + } - // Now the final value should be 6. - XCTAssertEqual(orderingCounter.load(ordering: .relaxed), 6) + let deallocated = ConditionLock(value: 0) + let scheduled = make(deallocated: deallocated) + scheduled.cancel() + if deallocated.lock(whenValue: 1, timeoutSeconds: 60) { + deallocated.unlock() + } else { + XCTFail("Timed out waiting for lock") + } + await XCTAssertThrowsError(try await scheduled.futureResult.get()) { error in + XCTAssertEqual(EventLoopError.cancelled, error as? EventLoopError) } } - func testCancelledScheduledTasksDoNotHoldOnToRunClosure() throws { + func testDrainScheduledTasks() async throws { guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { throw XCTSkip() } - XCTAsyncTest { - let eventLoop = NIOAsyncTestingEventLoop() - defer { - XCTAssertNoThrow(try eventLoop.syncShutdownGracefully()) - } + let eventLoop = NIOAsyncTestingEventLoop() + let tasksRun = ManagedAtomic(0) + let startTime = eventLoop.now - class Thing: @unchecked Sendable { - private let deallocated: ConditionLock - - init(_ deallocated: ConditionLock) { - self.deallocated = deallocated - } - - deinit { - self.deallocated.lock() - self.deallocated.unlock(withValue: 1) - } - } - - func make(deallocated: ConditionLock) -> Scheduled { - let aThing = Thing(deallocated) - return eventLoop.next().scheduleTask(in: .hours(1)) { - preconditionFailure("this should definitely not run: \(aThing)") - } - } - - let deallocated = ConditionLock(value: 0) - let scheduled = make(deallocated: deallocated) - scheduled.cancel() - if deallocated.lock(whenValue: 1, timeoutSeconds: 60) { - deallocated.unlock() - } else { - XCTFail("Timed out waiting for lock") - } - await XCTAssertThrowsError(try await scheduled.futureResult.get()) { error in - XCTAssertEqual(EventLoopError.cancelled, error as? EventLoopError) - } + eventLoop.scheduleTask(in: .nanoseconds(3141592)) { + XCTAssertEqual(eventLoop.now, startTime + .nanoseconds(3141592)) + tasksRun.wrappingIncrement(ordering: .relaxed) } + + eventLoop.scheduleTask(in: .seconds(3141592)) { + XCTAssertEqual(eventLoop.now, startTime + .seconds(3141592)) + tasksRun.wrappingIncrement(ordering: .relaxed) + } + + await eventLoop.shutdownGracefully() + XCTAssertEqual(tasksRun.load(ordering: .relaxed), 2) } - func testDrainScheduledTasks() throws { + func testDrainScheduledTasksDoesNotRunNewlyScheduledTasks() async throws { guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { throw XCTSkip() } - XCTAsyncTest { - let eventLoop = NIOAsyncTestingEventLoop() - let tasksRun = ManagedAtomic(0) - let startTime = eventLoop.now + let eventLoop = NIOAsyncTestingEventLoop() + let tasksRun = ManagedAtomic(0) - eventLoop.scheduleTask(in: .nanoseconds(3141592)) { - XCTAssertEqual(eventLoop.now, startTime + .nanoseconds(3141592)) + func scheduleNowAndIncrement() { + eventLoop.scheduleTask(in: .nanoseconds(0)) { tasksRun.wrappingIncrement(ordering: .relaxed) + scheduleNowAndIncrement() } - - eventLoop.scheduleTask(in: .seconds(3141592)) { - XCTAssertEqual(eventLoop.now, startTime + .seconds(3141592)) - tasksRun.wrappingIncrement(ordering: .relaxed) - } - - await eventLoop.shutdownGracefully() - XCTAssertEqual(tasksRun.load(ordering: .relaxed), 2) } + + scheduleNowAndIncrement() + await eventLoop.shutdownGracefully() + XCTAssertEqual(tasksRun.load(ordering: .relaxed), 1) } - func testDrainScheduledTasksDoesNotRunNewlyScheduledTasks() throws { + func testAdvanceTimeToDeadline() async throws { guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { throw XCTSkip() } - XCTAsyncTest { - let eventLoop = NIOAsyncTestingEventLoop() - let tasksRun = ManagedAtomic(0) + let eventLoop = NIOAsyncTestingEventLoop() + let deadline = NIODeadline.uptimeNanoseconds(0) + .seconds(42) - func scheduleNowAndIncrement() { - eventLoop.scheduleTask(in: .nanoseconds(0)) { - tasksRun.wrappingIncrement(ordering: .relaxed) - scheduleNowAndIncrement() - } - } - - scheduleNowAndIncrement() - await eventLoop.shutdownGracefully() - XCTAssertEqual(tasksRun.load(ordering: .relaxed), 1) + let tasksRun = ManagedAtomic(0) + eventLoop.scheduleTask(deadline: deadline) { + tasksRun.loadThenWrappingIncrement(ordering: .relaxed) } + + await eventLoop.advanceTime(to: deadline) + XCTAssertEqual(tasksRun.load(ordering: .relaxed), 1) } - func testAdvanceTimeToDeadline() throws { + func testWeCantTimeTravelByAdvancingTimeToThePast() async throws { guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { throw XCTSkip() } - XCTAsyncTest { - let eventLoop = NIOAsyncTestingEventLoop() - let deadline = NIODeadline.uptimeNanoseconds(0) + .seconds(42) + let eventLoop = NIOAsyncTestingEventLoop() - let tasksRun = ManagedAtomic(0) - eventLoop.scheduleTask(deadline: deadline) { - tasksRun.loadThenWrappingIncrement(ordering: .relaxed) - } - - await eventLoop.advanceTime(to: deadline) - XCTAssertEqual(tasksRun.load(ordering: .relaxed), 1) + let tasksRun = ManagedAtomic(0) + eventLoop.scheduleTask(deadline: .uptimeNanoseconds(0) + .seconds(42)) { + tasksRun.loadThenWrappingIncrement(ordering: .relaxed) } + + // t=40s + await eventLoop.advanceTime(to: .uptimeNanoseconds(0) + .seconds(40)) + XCTAssertEqual(tasksRun.load(ordering: .relaxed), 0) + + // t=40s (still) + await eventLoop.advanceTime(to: .distantPast) + XCTAssertEqual(tasksRun.load(ordering: .relaxed), 0) + + // t=42s + await eventLoop.advanceTime(by: .seconds(2)) + XCTAssertEqual(tasksRun.load(ordering: .relaxed), 1) } - func testWeCantTimeTravelByAdvancingTimeToThePast() throws { + func testExecuteInOrder() async throws { guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { throw XCTSkip() } - XCTAsyncTest { - let eventLoop = NIOAsyncTestingEventLoop() + let eventLoop = NIOAsyncTestingEventLoop() + let counter = ManagedAtomic(0) - let tasksRun = ManagedAtomic(0) - eventLoop.scheduleTask(deadline: .uptimeNanoseconds(0) + .seconds(42)) { - tasksRun.loadThenWrappingIncrement(ordering: .relaxed) - } - - // t=40s - await eventLoop.advanceTime(to: .uptimeNanoseconds(0) + .seconds(40)) - XCTAssertEqual(tasksRun.load(ordering: .relaxed), 0) - - // t=40s (still) - await eventLoop.advanceTime(to: .distantPast) - XCTAssertEqual(tasksRun.load(ordering: .relaxed), 0) - - // t=42s - await eventLoop.advanceTime(by: .seconds(2)) - XCTAssertEqual(tasksRun.load(ordering: .relaxed), 1) + eventLoop.execute { + let original = counter.loadThenWrappingIncrement(ordering: .relaxed) + XCTAssertEqual(original, 0) } + + eventLoop.execute { + let original = counter.loadThenWrappingIncrement(ordering: .relaxed) + XCTAssertEqual(original, 1) + } + + eventLoop.execute { + let original = counter.loadThenWrappingIncrement(ordering: .relaxed) + XCTAssertEqual(original, 2) + } + + await eventLoop.run() + XCTAssertEqual(counter.load(ordering: .relaxed), 3) } - func testExecuteInOrder() throws { + func testScheduledTasksInOrder() async throws { guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { throw XCTSkip() } - XCTAsyncTest { - let eventLoop = NIOAsyncTestingEventLoop() - let counter = ManagedAtomic(0) + let eventLoop = NIOAsyncTestingEventLoop() + let counter = ManagedAtomic(0) - eventLoop.execute { - let original = counter.loadThenWrappingIncrement(ordering: .relaxed) - XCTAssertEqual(original, 0) - } - - eventLoop.execute { - let original = counter.loadThenWrappingIncrement(ordering: .relaxed) - XCTAssertEqual(original, 1) - } - - eventLoop.execute { - let original = counter.loadThenWrappingIncrement(ordering: .relaxed) - XCTAssertEqual(original, 2) - } - - await eventLoop.run() - XCTAssertEqual(counter.load(ordering: .relaxed), 3) + eventLoop.scheduleTask(in: .seconds(1)) { + let original = counter.loadThenWrappingIncrement(ordering: .relaxed) + XCTAssertEqual(original, 1) } - } - func testScheduledTasksInOrder() throws { - guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { throw XCTSkip() } - XCTAsyncTest { - let eventLoop = NIOAsyncTestingEventLoop() - let counter = ManagedAtomic(0) - - eventLoop.scheduleTask(in: .seconds(1)) { - let original = counter.loadThenWrappingIncrement(ordering: .relaxed) - XCTAssertEqual(original, 1) - } - - eventLoop.scheduleTask(in: .milliseconds(1)) { - let original = counter.loadThenWrappingIncrement(ordering: .relaxed) - XCTAssertEqual(original, 0) - } - - eventLoop.scheduleTask(in: .seconds(1)) { - let original = counter.loadThenWrappingIncrement(ordering: .relaxed) - XCTAssertEqual(original, 2) - } - - await eventLoop.advanceTime(by: .seconds(1)) - XCTAssertEqual(counter.load(ordering: .relaxed), 3) + eventLoop.scheduleTask(in: .milliseconds(1)) { + let original = counter.loadThenWrappingIncrement(ordering: .relaxed) + XCTAssertEqual(original, 0) } + + eventLoop.scheduleTask(in: .seconds(1)) { + let original = counter.loadThenWrappingIncrement(ordering: .relaxed) + XCTAssertEqual(original, 2) + } + + await eventLoop.advanceTime(by: .seconds(1)) + XCTAssertEqual(counter.load(ordering: .relaxed), 3) } } diff --git a/Tests/NIOEmbeddedTests/XCTest+AsyncAwait.swift b/Tests/NIOEmbeddedTests/XCTest+AsyncAwait.swift index 29b8b66d3..59665ad56 100644 --- a/Tests/NIOEmbeddedTests/XCTest+AsyncAwait.swift +++ b/Tests/NIOEmbeddedTests/XCTest+AsyncAwait.swift @@ -42,38 +42,6 @@ import XCTest -extension XCTestCase { - @available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) - /// Cross-platform XCTest support for async-await tests. - /// - /// Currently the Linux implementation of XCTest doesn't have async-await support. - /// Until it does, we make use of this shim which uses a detached `Task` along with - /// `XCTest.wait(for:timeout:)` to wrap the operation. - /// - /// - NOTE: Support for Linux is tracked by https://bugs.swift.org/browse/SR-14403. - /// - NOTE: Implementation currently in progress: https://github.com/apple/swift-corelibs-xctest/pull/326 - func XCTAsyncTest( - expectationDescription: String = "Async operation", - timeout: TimeInterval = 30, - file: StaticString = #filePath, - line: UInt = #line, - function: StaticString = #function, - operation: @escaping @Sendable () async throws -> Void - ) { - let expectation = self.expectation(description: expectationDescription) - Task { - do { - try await operation() - } catch { - XCTFail("Error thrown while executing \(function): \(error)", file: file, line: line) - Thread.callStackSymbols.forEach { print($0) } - } - expectation.fulfill() - } - self.wait(for: [expectation], timeout: timeout) - } -} - @available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) internal func XCTAssertThrowsError( _ expression: @autoclosure () async throws -> T, diff --git a/Tests/NIOPosixTests/AsyncChannelBootstrapTests.swift b/Tests/NIOPosixTests/AsyncChannelBootstrapTests.swift index 31d049f5d..b365ae50a 100644 --- a/Tests/NIOPosixTests/AsyncChannelBootstrapTests.swift +++ b/Tests/NIOPosixTests/AsyncChannelBootstrapTests.swift @@ -206,237 +206,231 @@ final class AsyncChannelBootstrapTests: XCTestCase { // MARK: Server/Client Bootstrap - func testServerClientBootstrap_withAsyncChannel_andHostPort() throws { - XCTAsyncTest { - let eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 3) - defer { - try! eventLoopGroup.syncShutdownGracefully() - } + func testServerClientBootstrap_withAsyncChannel_andHostPort() async throws { + let eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 3) + defer { + try! eventLoopGroup.syncShutdownGracefully() + } - let channel = try await ServerBootstrap(group: eventLoopGroup) - .serverChannelOption(ChannelOptions.socketOption(.so_reuseaddr), value: 1) - .childChannelOption(ChannelOptions.autoRead, value: true) - .childChannelInitializer { channel in - channel.eventLoop.makeCompletedFuture { - try channel.pipeline.syncOperations.addHandler(ByteToMessageHandler(LineDelimiterCoder())) - try channel.pipeline.syncOperations.addHandler(MessageToByteHandler(LineDelimiterCoder())) - try channel.pipeline.syncOperations.addHandler(ByteBufferToStringHandler()) + let channel = try await ServerBootstrap(group: eventLoopGroup) + .serverChannelOption(ChannelOptions.socketOption(.so_reuseaddr), value: 1) + .childChannelOption(ChannelOptions.autoRead, value: true) + .childChannelInitializer { channel in + channel.eventLoop.makeCompletedFuture { + try channel.pipeline.syncOperations.addHandler(ByteToMessageHandler(LineDelimiterCoder())) + try channel.pipeline.syncOperations.addHandler(MessageToByteHandler(LineDelimiterCoder())) + try channel.pipeline.syncOperations.addHandler(ByteBufferToStringHandler()) + } + } + .bind( + host: "127.0.0.1", + port: 0, + childChannelInboundType: String.self, + childChannelOutboundType: String.self + ) + + try await withThrowingTaskGroup(of: Void.self) { group in + let (stream, continuation) = AsyncStream.makeStream() + var iterator = stream.makeAsyncIterator() + + group.addTask { + try await withThrowingTaskGroup(of: Void.self) { _ in + for try await childChannel in channel.inboundStream { + for try await value in childChannel.inboundStream { + continuation.yield(.string(value)) + } } } - .bind( - host: "127.0.0.1", - port: 0, - childChannelInboundType: String.self, - childChannelOutboundType: String.self - ) + } - try await withThrowingTaskGroup(of: Void.self) { group in - let (stream, continuation) = AsyncStream.makeStream() - var iterator = stream.makeAsyncIterator() + let stringChannel = try await self.makeClientChannel(eventLoopGroup: eventLoopGroup, port: channel.channel.localAddress!.port!) + try await stringChannel.outboundWriter.write("hello") - group.addTask { - try await withThrowingTaskGroup(of: Void.self) { _ in - for try await childChannel in channel.inboundStream { - for try await value in childChannel.inboundStream { - continuation.yield(.string(value)) + await XCTAsyncAssertEqual(await iterator.next(), .string("hello")) + + group.cancelAll() + } + } + + func testAsyncChannelProtocolNegotiation() async throws { + let eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 3) + defer { + try! eventLoopGroup.syncShutdownGracefully() + } + + let channel: NIOAsyncChannel = try await ServerBootstrap(group: eventLoopGroup) + .serverChannelOption(ChannelOptions.socketOption(.so_reuseaddr), value: 1) + .childChannelOption(ChannelOptions.autoRead, value: true) + .bind( + host: "127.0.0.1", + port: 0 + ) { channel in + channel.eventLoop.makeCompletedFuture { + try self.configureProtocolNegotiationHandlers(channel: channel) + } + } + + try await withThrowingTaskGroup(of: Void.self) { group in + let (stream, continuation) = AsyncStream.makeStream() + var serverIterator = stream.makeAsyncIterator() + + group.addTask { + try await withThrowingTaskGroup(of: Void.self) { group in + for try await childChannel in channel.inboundStream { + group.addTask { + switch childChannel { + case .string(let channel): + for try await value in channel.inboundStream { + continuation.yield(.string(value)) + } + case .byte(let channel): + for try await value in channel.inboundStream { + continuation.yield(.byte(value)) + } } } } } + } - let stringChannel = try await self.makeClientChannel(eventLoopGroup: eventLoopGroup, port: channel.channel.localAddress!.port!) + let stringNegotiationResult = try await self.makeClientChannelWithProtocolNegotiation( + eventLoopGroup: eventLoopGroup, + port: channel.channel.localAddress!.port!, + proposedALPN: .string + ) + switch stringNegotiationResult { + case .string(let stringChannel): + // This is the actual content try await stringChannel.outboundWriter.write("hello") - - await XCTAsyncAssertEqual(await iterator.next(), .string("hello")) - - group.cancelAll() + await XCTAsyncAssertEqual(await serverIterator.next(), .string("hello")) + case .byte: + preconditionFailure() } + + let byteNegotiationResult = try await self.makeClientChannelWithProtocolNegotiation( + eventLoopGroup: eventLoopGroup, + port: channel.channel.localAddress!.port!, + proposedALPN: .byte + ) + switch byteNegotiationResult { + case .string: + preconditionFailure() + case .byte(let byteChannel): + // This is the actual content + try await byteChannel.outboundWriter.write(UInt8(8)) + await XCTAsyncAssertEqual(await serverIterator.next(), .byte(8)) + } + + group.cancelAll() } } - func testAsyncChannelProtocolNegotiation() throws { - XCTAsyncTest { - let eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 3) - defer { - try! eventLoopGroup.syncShutdownGracefully() + func testAsyncChannelNestedProtocolNegotiation() async throws { + let eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 3) + defer { + try! eventLoopGroup.syncShutdownGracefully() + } + + let channel: NIOAsyncChannel = try await ServerBootstrap(group: eventLoopGroup) + .serverChannelOption(ChannelOptions.socketOption(.so_reuseaddr), value: 1) + .childChannelOption(ChannelOptions.autoRead, value: true) + .bind( + host: "127.0.0.1", + port: 0 + ) { channel in + channel.eventLoop.makeCompletedFuture { + try self.configureNestedProtocolNegotiationHandlers(channel: channel) + } } - let channel: NIOAsyncChannel = try await ServerBootstrap(group: eventLoopGroup) - .serverChannelOption(ChannelOptions.socketOption(.so_reuseaddr), value: 1) - .childChannelOption(ChannelOptions.autoRead, value: true) - .bind( - host: "127.0.0.1", - port: 0 - ) { channel in - channel.eventLoop.makeCompletedFuture { - try self.configureProtocolNegotiationHandlers(channel: channel) - } - } + try await withThrowingTaskGroup(of: Void.self) { group in + let (stream, continuation) = AsyncStream.makeStream() + var serverIterator = stream.makeAsyncIterator() - try await withThrowingTaskGroup(of: Void.self) { group in - let (stream, continuation) = AsyncStream.makeStream() - var serverIterator = stream.makeAsyncIterator() - - group.addTask { - try await withThrowingTaskGroup(of: Void.self) { group in - for try await childChannel in channel.inboundStream { - group.addTask { - switch childChannel { - case .string(let channel): - for try await value in channel.inboundStream { - continuation.yield(.string(value)) - } - case .byte(let channel): - for try await value in channel.inboundStream { - continuation.yield(.byte(value)) - } + group.addTask { + try await withThrowingTaskGroup(of: Void.self) { group in + for try await childChannel in channel.inboundStream { + group.addTask { + switch childChannel { + case .string(let channel): + for try await value in channel.inboundStream { + continuation.yield(.string(value)) + } + case .byte(let channel): + for try await value in channel.inboundStream { + continuation.yield(.byte(value)) } } } } } - - let stringNegotiationResult = try await self.makeClientChannelWithProtocolNegotiation( - eventLoopGroup: eventLoopGroup, - port: channel.channel.localAddress!.port!, - proposedALPN: .string - ) - switch stringNegotiationResult { - case .string(let stringChannel): - // This is the actual content - try await stringChannel.outboundWriter.write("hello") - await XCTAsyncAssertEqual(await serverIterator.next(), .string("hello")) - case .byte: - preconditionFailure() - } - - let byteNegotiationResult = try await self.makeClientChannelWithProtocolNegotiation( - eventLoopGroup: eventLoopGroup, - port: channel.channel.localAddress!.port!, - proposedALPN: .byte - ) - switch byteNegotiationResult { - case .string: - preconditionFailure() - case .byte(let byteChannel): - // This is the actual content - try await byteChannel.outboundWriter.write(UInt8(8)) - await XCTAsyncAssertEqual(await serverIterator.next(), .byte(8)) - } - - group.cancelAll() } + + let stringStringNegotiationResult = try await self.makeClientChannelWithNestedProtocolNegotiation( + eventLoopGroup: eventLoopGroup, + port: channel.channel.localAddress!.port!, + proposedOuterALPN: .string, + proposedInnerALPN: .string + ) + switch stringStringNegotiationResult { + case .string(let stringChannel): + // This is the actual content + try await stringChannel.outboundWriter.write("hello") + await XCTAsyncAssertEqual(await serverIterator.next(), .string("hello")) + case .byte: + preconditionFailure() + } + + let byteStringNegotiationResult = try await self.makeClientChannelWithNestedProtocolNegotiation( + eventLoopGroup: eventLoopGroup, + port: channel.channel.localAddress!.port!, + proposedOuterALPN: .byte, + proposedInnerALPN: .string + ) + switch byteStringNegotiationResult { + case .string(let stringChannel): + // This is the actual content + try await stringChannel.outboundWriter.write("hello") + await XCTAsyncAssertEqual(await serverIterator.next(), .string("hello")) + case .byte: + preconditionFailure() + } + + let byteByteNegotiationResult = try await self.makeClientChannelWithNestedProtocolNegotiation( + eventLoopGroup: eventLoopGroup, + port: channel.channel.localAddress!.port!, + proposedOuterALPN: .byte, + proposedInnerALPN: .byte + ) + switch byteByteNegotiationResult { + case .string: + preconditionFailure() + case .byte(let byteChannel): + // This is the actual content + try await byteChannel.outboundWriter.write(UInt8(8)) + await XCTAsyncAssertEqual(await serverIterator.next(), .byte(8)) + } + + let stringByteNegotiationResult = try await self.makeClientChannelWithNestedProtocolNegotiation( + eventLoopGroup: eventLoopGroup, + port: channel.channel.localAddress!.port!, + proposedOuterALPN: .string, + proposedInnerALPN: .byte + ) + switch stringByteNegotiationResult { + case .string: + preconditionFailure() + case .byte(let byteChannel): + // This is the actual content + try await byteChannel.outboundWriter.write(UInt8(8)) + await XCTAsyncAssertEqual(await serverIterator.next(), .byte(8)) + } + + group.cancelAll() } } - func testAsyncChannelNestedProtocolNegotiation() throws { - XCTAsyncTest { - let eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 3) - defer { - try! eventLoopGroup.syncShutdownGracefully() - } - - let channel: NIOAsyncChannel = try await ServerBootstrap(group: eventLoopGroup) - .serverChannelOption(ChannelOptions.socketOption(.so_reuseaddr), value: 1) - .childChannelOption(ChannelOptions.autoRead, value: true) - .bind( - host: "127.0.0.1", - port: 0 - ) { channel in - channel.eventLoop.makeCompletedFuture { - try self.configureNestedProtocolNegotiationHandlers(channel: channel) - } - } - - try await withThrowingTaskGroup(of: Void.self) { group in - let (stream, continuation) = AsyncStream.makeStream() - var serverIterator = stream.makeAsyncIterator() - - group.addTask { - try await withThrowingTaskGroup(of: Void.self) { group in - for try await childChannel in channel.inboundStream { - group.addTask { - switch childChannel { - case .string(let channel): - for try await value in channel.inboundStream { - continuation.yield(.string(value)) - } - case .byte(let channel): - for try await value in channel.inboundStream { - continuation.yield(.byte(value)) - } - } - } - } - } - } - - let stringStringNegotiationResult = try await self.makeClientChannelWithNestedProtocolNegotiation( - eventLoopGroup: eventLoopGroup, - port: channel.channel.localAddress!.port!, - proposedOuterALPN: .string, - proposedInnerALPN: .string - ) - switch stringStringNegotiationResult { - case .string(let stringChannel): - // This is the actual content - try await stringChannel.outboundWriter.write("hello") - await XCTAsyncAssertEqual(await serverIterator.next(), .string("hello")) - case .byte: - preconditionFailure() - } - - let byteStringNegotiationResult = try await self.makeClientChannelWithNestedProtocolNegotiation( - eventLoopGroup: eventLoopGroup, - port: channel.channel.localAddress!.port!, - proposedOuterALPN: .byte, - proposedInnerALPN: .string - ) - switch byteStringNegotiationResult { - case .string(let stringChannel): - // This is the actual content - try await stringChannel.outboundWriter.write("hello") - await XCTAsyncAssertEqual(await serverIterator.next(), .string("hello")) - case .byte: - preconditionFailure() - } - - let byteByteNegotiationResult = try await self.makeClientChannelWithNestedProtocolNegotiation( - eventLoopGroup: eventLoopGroup, - port: channel.channel.localAddress!.port!, - proposedOuterALPN: .byte, - proposedInnerALPN: .byte - ) - switch byteByteNegotiationResult { - case .string: - preconditionFailure() - case .byte(let byteChannel): - // This is the actual content - try await byteChannel.outboundWriter.write(UInt8(8)) - await XCTAsyncAssertEqual(await serverIterator.next(), .byte(8)) - } - - let stringByteNegotiationResult = try await self.makeClientChannelWithNestedProtocolNegotiation( - eventLoopGroup: eventLoopGroup, - port: channel.channel.localAddress!.port!, - proposedOuterALPN: .string, - proposedInnerALPN: .byte - ) - switch stringByteNegotiationResult { - case .string: - preconditionFailure() - case .byte(let byteChannel): - // This is the actual content - try await byteChannel.outboundWriter.write(UInt8(8)) - await XCTAsyncAssertEqual(await serverIterator.next(), .byte(8)) - } - - group.cancelAll() - } - } - } - - func testAsyncChannelProtocolNegotiation_whenFails() throws { + func testAsyncChannelProtocolNegotiation_whenFails() async throws { final class CollectingHandler: ChannelInboundHandler { typealias InboundIn = Channel @@ -454,171 +448,166 @@ final class AsyncChannelBootstrapTests: XCTestCase { context.fireChannelRead(data) } } - XCTAsyncTest { - let eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 3) - defer { - try! eventLoopGroup.syncShutdownGracefully() + + let eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 3) + defer { + try! eventLoopGroup.syncShutdownGracefully() + } + let channels = NIOLockedValueBox<[Channel]>([Channel]()) + + let channel: NIOAsyncChannel = try await ServerBootstrap(group: eventLoopGroup) + .serverChannelOption(ChannelOptions.socketOption(.so_reuseaddr), value: 1) + .serverChannelInitializer { channel in + channel.eventLoop.makeCompletedFuture { + try channel.pipeline.syncOperations.addHandler(CollectingHandler(channels: channels)) + } } - let channels = NIOLockedValueBox<[Channel]>([Channel]()) - - let channel: NIOAsyncChannel = try await ServerBootstrap(group: eventLoopGroup) - .serverChannelOption(ChannelOptions.socketOption(.so_reuseaddr), value: 1) - .serverChannelInitializer { channel in - channel.eventLoop.makeCompletedFuture { - try channel.pipeline.syncOperations.addHandler(CollectingHandler(channels: channels)) - } - } - .childChannelOption(ChannelOptions.autoRead, value: true) - .bind( - host: "127.0.0.1", - port: 0 - ) { channel in - channel.eventLoop.makeCompletedFuture { - try self.configureProtocolNegotiationHandlers(channel: channel) - } + .childChannelOption(ChannelOptions.autoRead, value: true) + .bind( + host: "127.0.0.1", + port: 0 + ) { channel in + channel.eventLoop.makeCompletedFuture { + try self.configureProtocolNegotiationHandlers(channel: channel) } + } - try await withThrowingTaskGroup(of: Void.self) { group in - let (stream, continuation) = AsyncStream.makeStream() - var serverIterator = stream.makeAsyncIterator() + try await withThrowingTaskGroup(of: Void.self) { group in + let (stream, continuation) = AsyncStream.makeStream() + var serverIterator = stream.makeAsyncIterator() - group.addTask { - try await withThrowingTaskGroup(of: Void.self) { group in - for try await childChannel in channel.inboundStream { - group.addTask { - switch childChannel { - case .string(let channel): - for try await value in channel.inboundStream { - continuation.yield(.string(value)) - } - case .byte(let channel): - for try await value in channel.inboundStream { - continuation.yield(.byte(value)) - } + group.addTask { + try await withThrowingTaskGroup(of: Void.self) { group in + for try await childChannel in channel.inboundStream { + group.addTask { + switch childChannel { + case .string(let channel): + for try await value in channel.inboundStream { + continuation.yield(.string(value)) + } + case .byte(let channel): + for try await value in channel.inboundStream { + continuation.yield(.byte(value)) } } } } } + } - await XCTAssertThrowsError( - try await self.makeClientChannelWithProtocolNegotiation( - eventLoopGroup: eventLoopGroup, - port: channel.channel.localAddress!.port!, - proposedALPN: .unknown - ) - ) { error in - XCTAssertTrue(error is ProtocolNegotiationError) - } - - // Let's check that we can still open a new connection - let stringNegotiationResult = try await self.makeClientChannelWithProtocolNegotiation( + await XCTAssertThrowsError( + try await self.makeClientChannelWithProtocolNegotiation( eventLoopGroup: eventLoopGroup, port: channel.channel.localAddress!.port!, - proposedALPN: .string + proposedALPN: .unknown ) - switch stringNegotiationResult { - case .string(let stringChannel): - // This is the actual content - try await stringChannel.outboundWriter.write("hello") - await XCTAsyncAssertEqual(await serverIterator.next(), .string("hello")) - case .byte: - preconditionFailure() - } - - let failedInboundChannel = channels.withLockedValue { channels -> Channel in - XCTAssertEqual(channels.count, 2) - return channels[0] - } - - // We are waiting here to make sure the channel got closed - try await failedInboundChannel.closeFuture.get() - - group.cancelAll() + ) { error in + XCTAssertTrue(error is ProtocolNegotiationError) } + + // Let's check that we can still open a new connection + let stringNegotiationResult = try await self.makeClientChannelWithProtocolNegotiation( + eventLoopGroup: eventLoopGroup, + port: channel.channel.localAddress!.port!, + proposedALPN: .string + ) + switch stringNegotiationResult { + case .string(let stringChannel): + // This is the actual content + try await stringChannel.outboundWriter.write("hello") + await XCTAsyncAssertEqual(await serverIterator.next(), .string("hello")) + case .byte: + preconditionFailure() + } + + let failedInboundChannel = channels.withLockedValue { channels -> Channel in + XCTAssertEqual(channels.count, 2) + return channels[0] + } + + // We are waiting here to make sure the channel got closed + try await failedInboundChannel.closeFuture.get() + + group.cancelAll() } } // MARK: Datagram Bootstrap - func testDatagramBootstrap_withAsyncChannel_andHostPort() throws { - XCTAsyncTest { - let eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 3) - defer { - try! eventLoopGroup.syncShutdownGracefully() - } - - let serverChannel = try await self.makeUDPServerChannel(eventLoopGroup: eventLoopGroup) - let clientChannel = try await self.makeUDPClientChannel( - eventLoopGroup: eventLoopGroup, - port: serverChannel.channel.localAddress!.port! - ) - var serverInboundIterator = serverChannel.inboundStream.makeAsyncIterator() - var clientInboundIterator = clientChannel.inboundStream.makeAsyncIterator() - - try await clientChannel.outboundWriter.write("request") - try await XCTAsyncAssertEqual(try await serverInboundIterator.next(), "request") - - try await serverChannel.outboundWriter.write("response") - try await XCTAsyncAssertEqual(try await clientInboundIterator.next(), "response") + func testDatagramBootstrap_withAsyncChannel_andHostPort() async throws { + let eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 3) + defer { + try! eventLoopGroup.syncShutdownGracefully() } + + let serverChannel = try await self.makeUDPServerChannel(eventLoopGroup: eventLoopGroup) + let clientChannel = try await self.makeUDPClientChannel( + eventLoopGroup: eventLoopGroup, + port: serverChannel.channel.localAddress!.port! + ) + var serverInboundIterator = serverChannel.inboundStream.makeAsyncIterator() + var clientInboundIterator = clientChannel.inboundStream.makeAsyncIterator() + + try await clientChannel.outboundWriter.write("request") + try await XCTAsyncAssertEqual(try await serverInboundIterator.next(), "request") + + try await serverChannel.outboundWriter.write("response") + try await XCTAsyncAssertEqual(try await clientInboundIterator.next(), "response") } - func testDatagramBootstrap_withProtocolNegotiation_andHostPort() throws { - XCTAsyncTest { - let eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 3) - defer { - try! eventLoopGroup.syncShutdownGracefully() + func testDatagramBootstrap_withProtocolNegotiation_andHostPort() async throws { + let eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 3) + defer { + try! eventLoopGroup.syncShutdownGracefully() + } + + // We are creating a channel here to get a random port from the system + let channel = try await DatagramBootstrap(group: eventLoopGroup) + .bind( + to: .init(ipAddress: "127.0.0.1", port: 0), + channelInitializer: { channel -> EventLoopFuture in channel.eventLoop.makeSucceededFuture(channel) } + ) + + let port = channel.localAddress!.port! + try await channel.close() + + try await withThrowingTaskGroup(of: NegotiationResult.self) { group in + group.addTask { + // We have to use a fixed port here since we only get the channel once protocol negotiation is done + try await self.makeUDPServerChannelWithProtocolNegotiation( + eventLoopGroup: eventLoopGroup, + port: port + ) } - // We are creating a channel here to get a random port from the system - let channel = try await DatagramBootstrap(group: eventLoopGroup) - .bind( - to: .init(ipAddress: "127.0.0.1", port: 0), - channelInitializer: { channel -> EventLoopFuture in channel.eventLoop.makeSucceededFuture(channel) } + // We need to sleep here since we can only connect the client after the server started. + try await Task.sleep(nanoseconds: 100000000) + + group.addTask { + // We have to use a fixed port here since we only get the channel once protocol negotiation is done + try await self.makeUDPClientChannelWithProtocolNegotiation( + eventLoopGroup: eventLoopGroup, + port: port, + proposedALPN: .string ) + } - let port = channel.localAddress!.port! - try await channel.close() + let firstNegotiationResult = try await group.next() + let secondNegotiationResult = try await group.next() - try await withThrowingTaskGroup(of: NegotiationResult.self) { group in - group.addTask { - // We have to use a fixed port here since we only get the channel once protocol negotiation is done - try await self.makeUDPServerChannelWithProtocolNegotiation( - eventLoopGroup: eventLoopGroup, - port: port - ) - } + switch (firstNegotiationResult, secondNegotiationResult) { + case (.string(let firstChannel), .string(let secondChannel)): + var firstInboundIterator = firstChannel.inboundStream.makeAsyncIterator() + var secondInboundIterator = secondChannel.inboundStream.makeAsyncIterator() - // We need to sleep here since we can only connect the client after the server started. - try await Task.sleep(nanoseconds: 100000000) + try await firstChannel.outboundWriter.write("request") + try await XCTAsyncAssertEqual(try await secondInboundIterator.next(), "request") - group.addTask { - // We have to use a fixed port here since we only get the channel once protocol negotiation is done - try await self.makeUDPClientChannelWithProtocolNegotiation( - eventLoopGroup: eventLoopGroup, - port: port, - proposedALPN: .string - ) - } + try await secondChannel.outboundWriter.write("response") + try await XCTAsyncAssertEqual(try await firstInboundIterator.next(), "response") - let firstNegotiationResult = try await group.next() - let secondNegotiationResult = try await group.next() - - switch (firstNegotiationResult, secondNegotiationResult) { - case (.string(let firstChannel), .string(let secondChannel)): - var firstInboundIterator = firstChannel.inboundStream.makeAsyncIterator() - var secondInboundIterator = secondChannel.inboundStream.makeAsyncIterator() - - try await firstChannel.outboundWriter.write("request") - try await XCTAsyncAssertEqual(try await secondInboundIterator.next(), "request") - - try await secondChannel.outboundWriter.write("response") - try await XCTAsyncAssertEqual(try await firstInboundIterator.next(), "response") - - default: - preconditionFailure() - } + default: + preconditionFailure() } } } diff --git a/Tests/NIOPosixTests/NIOThreadPoolTest.swift b/Tests/NIOPosixTests/NIOThreadPoolTest.swift index bf66be8ad..a36e4794a 100644 --- a/Tests/NIOPosixTests/NIOThreadPoolTest.swift +++ b/Tests/NIOPosixTests/NIOThreadPoolTest.swift @@ -110,19 +110,17 @@ class NIOThreadPoolTest: XCTestCase { } } - func testAsyncShutdownWorks() throws { + func testAsyncShutdownWorks() async throws { guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { throw XCTSkip() } - XCTAsyncTest { - let threadPool = NIOThreadPool(numberOfThreads: 17) - let eventLoop = NIOAsyncTestingEventLoop() + let threadPool = NIOThreadPool(numberOfThreads: 17) + let eventLoop = NIOAsyncTestingEventLoop() - threadPool.start() - try await threadPool.shutdownGracefully() + threadPool.start() + try await threadPool.shutdownGracefully() - let future = threadPool.runIfActive(eventLoop: eventLoop) { - XCTFail("This shouldn't run because the pool is shutdown.") - } - await XCTAssertThrowsError(try await future.get()) + let future = threadPool.runIfActive(eventLoop: eventLoop) { + XCTFail("This shouldn't run because the pool is shutdown.") } + await XCTAssertThrowsError(try await future.get()) } } diff --git a/Tests/NIOPosixTests/XCTest+AsyncAwait.swift b/Tests/NIOPosixTests/XCTest+AsyncAwait.swift index 4f7904111..810d9185a 100644 --- a/Tests/NIOPosixTests/XCTest+AsyncAwait.swift +++ b/Tests/NIOPosixTests/XCTest+AsyncAwait.swift @@ -42,38 +42,6 @@ import XCTest -extension XCTestCase { - @available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) - /// Cross-platform XCTest support for async-await tests. - /// - /// Currently the Linux implementation of XCTest doesn't have async-await support. - /// Until it does, we make use of this shim which uses a detached `Task` along with - /// `XCTest.wait(for:timeout:)` to wrap the operation. - /// - /// - NOTE: Support for Linux is tracked by https://bugs.swift.org/browse/SR-14403. - /// - NOTE: Implementation currently in progress: https://github.com/apple/swift-corelibs-xctest/pull/326 - func XCTAsyncTest( - expectationDescription: String = "Async operation", - timeout: TimeInterval = 30, - file: StaticString = #filePath, - line: UInt = #line, - function: StaticString = #function, - operation: @escaping @Sendable () async throws -> Void - ) { - let expectation = self.expectation(description: expectationDescription) - Task { - do { - try await operation() - } catch { - XCTFail("Error thrown while executing \(function): \(error)", file: file, line: line) - Thread.callStackSymbols.forEach { print($0) } - } - expectation.fulfill() - } - self.wait(for: [expectation], timeout: timeout) - } -} - @available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) internal func XCTAssertThrowsError( _ expression: @autoclosure () async throws -> T,