mirror of
https://github.com/apple/swift-nio
synced 2026-11-25 04:47:49 +00:00
Remove XCTAsyncTest usage (#2461)
# Motivation We introduced `XCTAsyncTest` to bridge the gap where some Swift versions did not have `async` test support. # Modification This PR removes `XCTAsyncTest` and migrates all the places where we used it to native `async` tests. # Result Less custom code.
This commit is contained in:
1 parent
3a88bf6dc0
commit
7e6dc1e982
9 files changed
+1571
-1803
No files matched your search
@@ -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<Never>
|
||||
|
||||
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<Never>
|
||||
|
||||
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<Never>
|
||||
|
||||
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<Never>
|
||||
|
||||
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<Never>
|
||||
|
||||
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<Sentinel, Sentinel, Sentinel>.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<Sentinel, Sentinel, Sentinel>.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()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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<T>(
|
||||
_ expression: @autoclosure () async throws -> T,
|
||||
|
||||
@@ -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<ByteBuffer>(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<ByteBuffer>(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: Sendable, Actual>(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<ByteBuffer>.self)
|
||||
await check(expected: AddressedEnvelope<ByteBuffer>.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<ByteBuffer>(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<ByteBuffer>(remoteAddress: SocketAddress(ipAddress: "1.2.3.4", port: 5678),
|
||||
data: buffer)).isFull)
|
||||
try await XCTAsyncAssertTrue(await channel.writeInbound(buffer).isFull)
|
||||
|
||||
func check<Expected: Sendable, Actual>(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<ByteBuffer>.self)
|
||||
await check(expected: AddressedEnvelope<ByteBuffer>.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<Void, Error>) 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<Void, Error>) in
|
||||
XCTAssertFalse(channel.isActive)
|
||||
let connectPromise = channel.eventLoop.makePromise(of: Void.self)
|
||||
connectPromise.futureResult.whenComplete { (_: Result<Void, Error>) 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<Void, Error>) 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())
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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<T>(
|
||||
_ expression: @autoclosure () async throws -> T,
|
||||
|
||||
@@ -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<StringOrByte>.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<StringOrByte>.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<NegotiationResult, Never> = 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<StringOrByte>.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<NegotiationResult, Never> = 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<NegotiationResult, Never> = 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<StringOrByte>.makeStream()
|
||||
var serverIterator = stream.makeAsyncIterator()
|
||||
|
||||
try await withThrowingTaskGroup(of: Void.self) { group in
|
||||
let (stream, continuation) = AsyncStream<StringOrByte>.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<NegotiationResult, Never> = 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<StringOrByte>.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<NegotiationResult, Never> = 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<NegotiationResult, Never> = 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<StringOrByte>.makeStream()
|
||||
var serverIterator = stream.makeAsyncIterator()
|
||||
try await withThrowingTaskGroup(of: Void.self) { group in
|
||||
let (stream, continuation) = AsyncStream<StringOrByte>.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<Channel> 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<Channel> 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()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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())
|
||||
}
|
||||
}
|
||||
@@ -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<T>(
|
||||
_ expression: @autoclosure () async throws -> T,
|
||||
|
||||
Reference in new issue
Block a user