Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add channel initializer closure to NIOAsyncTestingChannel.init #3053

Merged
merged 1 commit into from
Jan 13, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 20 additions & 5 deletions Sources/NIOEmbedded/AsyncTestingChannel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -307,12 +307,27 @@ public final class NIOAsyncTestingChannel: Channel {
handlers: [ChannelHandler & Sendable],
loop: NIOAsyncTestingEventLoop = NIOAsyncTestingEventLoop()
) async {
self.init(loop: loop)

try! await self._pipeline.addHandlers(handlers)
try! await self.init(loop: loop) { channel in
try channel.pipeline.syncOperations.addHandlers(handlers)
}
}

// This will never throw...
try! await self.register()
/// Create a new instance.
///
/// During creation it will automatically also register itself on the ``NIOAsyncTestingEventLoop``.
///
/// - Parameters:
/// - loop: The ``NIOAsyncTestingEventLoop`` to use.
/// - channelInitializer: The initialization closure which will be run on the `EventLoop` before registration. This could be used to add handlers using `syncOperations`.
public convenience init(
loop: NIOAsyncTestingEventLoop = NIOAsyncTestingEventLoop(),
channelInitializer: @escaping @Sendable (NIOAsyncTestingChannel) throws -> Void
) async throws {
self.init(loop: loop)
try await loop.submit {
try channelInitializer(self)
}.get()
try await self.register()
}

/// Asynchronously closes the ``NIOAsyncTestingChannel``.
Expand Down
11 changes: 11 additions & 0 deletions Tests/NIOEmbeddedTests/AsyncTestingChannelTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,17 @@ class AsyncTestingChannelTests: XCTestCase {
XCTAssertNoThrow(try channel.pipeline.removeHandler(name: "handler2").wait())
}

func testClosureInit() async throws {
final class Handler: ChannelInboundHandler, Sendable {
typealias InboundIn = Never
}

let channel = try await NIOAsyncTestingChannel {
try $0.pipeline.syncOperations.addHandler(Handler())
}
XCTAssertNoThrow(try channel.pipeline.handler(type: Handler.self).wait())
}

func testWaitForInboundWrite() async throws {
let channel = NIOAsyncTestingChannel()
let task = Task {
Expand Down
Loading