Define AsyncEmbeddedEventLoop (#2083)

Motivation

The rise of Swift concurrency has meant that a number of our APIs need
to be recontextualised as async/await capable. While generally this is a
straightforward task, any time those APIs were tested using
EmbeddedChannel we have a testing issue. Swift Concurrency requires the
use of its own cooperative thread pool, which is completely incapable of
safely interoperating with EmbeddedChannel and EmbeddedEventLoop. This
is becuase those two types "embed" into the current thread and are not
thread-safe, but our concurrency-focused APIs want to enable users to
use them from any Task.

To that end we need to develop new types that serve the needs of
EmbeddedChannel and EmbeddedEventLoop (control over I/O and task
scheduling) while remaining fully thread-safe. This is the first of a
series of patches that adds this functionality, starting with the
AsyncEmbeddedEventLoop.

Modifications

- Define AsyncEmbeddedEventLoop

Result

A required building block for AsyncEmbeddedChannel exists.

Co-authored-by: Franz Busch <privat@franz-busch.de>
This commit is contained in:
Cory Benfield 2022-05-04 17:03:03 +01:00 committed by GitHub
parent cd11cf8202
commit ad8500b3d0
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
9 changed files with 1293 additions and 4 deletions

View File

@ -19,7 +19,10 @@ var targets: [PackageDescription.Target] = [
.target(name: "NIOCore",
dependencies: ["NIOConcurrencyHelpers", "CNIOLinux"]),
.target(name: "_NIODataStructures"),
.target(name: "NIOEmbedded", dependencies: ["NIOCore", "_NIODataStructures"]),
.target(name: "NIOEmbedded",
dependencies: ["NIOCore",
"NIOConcurrencyHelpers",
"_NIODataStructures"]),
.target(name: "NIOPosix",
dependencies: ["CNIOLinux",
"CNIODarwin",

View File

@ -334,7 +334,7 @@ extension EventLoopGroup {
/// Represents a time _interval_.
///
/// - note: `TimeAmount` should not be used to represent a point in time.
public struct TimeAmount: Hashable {
public struct TimeAmount: Hashable, NIOSendable {
@available(*, deprecated, message: "This typealias doesn't serve any purpose. Please use Int64 directly.")
public typealias Value = Int64
@ -454,7 +454,7 @@ extension TimeAmount: AdditiveArithmetic {
/// ```
///
/// - note: `NIODeadline` should not be used to represent a time interval
public struct NIODeadline: Equatable, Hashable {
public struct NIODeadline: Equatable, Hashable, NIOSendable {
@available(*, deprecated, message: "This typealias doesn't serve any purpose, please use UInt64 directly.")
public typealias Value = UInt64

View File

@ -0,0 +1,422 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2022 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if compiler(>=5.5.2) && canImport(_Concurrency)
import Dispatch
import _NIODataStructures
import NIOCore
import NIOConcurrencyHelpers
/// An `EventLoop` that is thread safe and whose execution is fully controlled
/// by the user.
///
/// Unlike more complex `EventLoop`s, such as `SelectableEventLoop`, the `NIOAsyncEmbeddedEventLoop`
/// has no proper eventing mechanism. Instead, reads and writes are fully controlled by the
/// entity that instantiates the `NIOAsyncEmbeddedEventLoop`. This property makes `NIOAsyncEmbeddedEventLoop`
/// of limited use for many application purposes, but highly valuable for testing and other
/// kinds of mocking. Unlike `EmbeddedEventLoop`, `NIOAsyncEmbeddedEventLoop` is fully thread-safe and
/// safe to use from within a Swift concurrency context.
///
/// Unlike `EmbeddedEventLoop`, `NIOAsyncEmbeddedEventLoop` does require that user tests appropriately
/// enforce thread safety. Used carefully it is possible to safely operate the event loop without
/// explicit synchronization, but it is recommended to use `executeInContext` in any case where it's
/// necessary to ensure that the event loop is not making progress.
///
/// Time is controllable on an `NIOAsyncEmbeddedEventLoop`. It begins at `NIODeadline.uptimeNanoseconds(0)`
/// and may be advanced by a fixed amount by using `advanceTime(by:)`, or advanced to a point in
/// time with `advanceTime(to:)`.
///
/// If users wish to perform multiple tasks at once on an `NIOAsyncEmbeddedEventLoop`, it is recommended that they
/// use `executeInContext` to perform the operations. For example:
///
/// ```
/// await loop.executeInContext {
/// // All three of these will be queued up simultaneously, and no other code can
/// // get between them.
/// loop.execute { firstTask() }
/// loop.execute { secondTask() }
/// loop.execute { thirdTask() }
/// }
/// ```
///
/// There is a tricky requirement around waiting for `EventLoopFuture`s when working with this
/// event loop. Simply calling `.wait()` from the test thread will never complete. This is because
/// `wait` calls `loop.execute` under the hood, and that callback cannot execute without calling
/// `loop.run()`. As a result, if you need to await an `EventLoopFuture` created on this loop you
/// should use `awaitFuture`.
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
public final class NIOAsyncEmbeddedEventLoop: EventLoop, @unchecked Sendable {
// This type is `@unchecked Sendable` because of the use of `taskNumber`. This
// variable is only used from within `queue`, but the compiler cannot see that.
/// The current "time" for this event loop. This is an amount in nanoseconds.
/// As we need to access this from any thread, we store this as an atomic.
private let _now = NIOAtomic<UInt64>.makeAtomic(value: 0)
internal var now: NIODeadline {
return NIODeadline.uptimeNanoseconds(self._now.load())
}
/// This is used to derive an identifier for this loop.
private var thisLoopID: ObjectIdentifier {
return ObjectIdentifier(self)
}
/// A dispatch specific that we use to determine whether we are on the queue for this
/// "event loop".
private static let inQueueKey = DispatchSpecificKey<ObjectIdentifier>()
// Our scheduledTaskCounter needs to be an atomic because we're going to access it from
// arbitrary threads. This is required by the EventLoop protocol and cannot be avoided.
// Specifically, Scheduled<T> creation requires us to be able to define the cancellation
// operation, so the task ID has to be created early.
private let scheduledTaskCounter = NIOAtomic<UInt64>.makeAtomic(value: 0)
private var scheduledTasks = PriorityQueue<EmbeddedScheduledTask>()
/// Keep track of where promises are allocated to ensure we can identify their source if they leak.
private let _promiseCreationStore = PromiseCreationStore()
// The number of the next task to be created. We track the order so that when we execute tasks
// scheduled at the same time, we may do so in the order in which they were submitted for
// execution.
//
// This can only be accessed from `queue`
private var taskNumber = UInt64(0)
/// The queue on which we run all our operations.
private let queue = DispatchQueue(label: "io.swiftnio.AsyncEmbeddedEventLoop")
// This function must only be called on queue.
private func nextTaskNumber() -> UInt64 {
dispatchPrecondition(condition: .onQueue(self.queue))
defer {
self.taskNumber += 1
}
return self.taskNumber
}
/// - see: `EventLoop.inEventLoop`
public var inEventLoop: Bool {
return DispatchQueue.getSpecific(key: Self.inQueueKey) == self.thisLoopID
}
/// Initialize a new `NIOAsyncEmbeddedEventLoop`.
public init() {
self.queue.setSpecific(key: Self.inQueueKey, value: self.thisLoopID)
}
private func removeTask(taskID: UInt64) {
dispatchPrecondition(condition: .onQueue(self.queue))
self.scheduledTasks.removeFirst { $0.id == taskID }
}
private func insertTask<ReturnType>(
taskID: UInt64,
deadline: NIODeadline,
promise: EventLoopPromise<ReturnType>,
task: @escaping () throws -> ReturnType
) {
dispatchPrecondition(condition: .onQueue(self.queue))
let task = EmbeddedScheduledTask(id: taskID, readyTime: deadline, insertOrder: self.nextTaskNumber(), task: {
do {
promise.succeed(try task())
} catch let err {
promise.fail(err)
}
}, promise.fail)
self.scheduledTasks.push(task)
}
/// - see: `EventLoop.scheduleTask(deadline:_:)`
@discardableResult
public func scheduleTask<T>(deadline: NIODeadline, _ task: @escaping () throws -> T) -> Scheduled<T> {
let promise: EventLoopPromise<T> = self.makePromise()
let taskID = self.scheduledTaskCounter.add(1)
let scheduled = Scheduled(promise: promise, cancellationTask: {
if self.inEventLoop {
self.removeTask(taskID: taskID)
} else {
self.queue.async {
self.removeTask(taskID: taskID)
}
}
})
if self.inEventLoop {
self.insertTask(taskID: taskID, deadline: deadline, promise: promise, task: task)
} else {
self.queue.async {
self.insertTask(taskID: taskID, deadline: deadline, promise: promise, task: task)
}
}
return scheduled
}
/// - see: `EventLoop.scheduleTask(in:_:)`
@discardableResult
public func scheduleTask<T>(in: TimeAmount, _ task: @escaping () throws -> T) -> Scheduled<T> {
return self.scheduleTask(deadline: self.now + `in`, task)
}
/// On an `NIOAsyncEmbeddedEventLoop`, `execute` will simply use `scheduleTask` with a deadline of _now_. This means that
/// `task` will be run the next time you call `AsyncEmbeddedEventLoop.run`.
public func execute(_ task: @escaping () -> Void) {
self.scheduleTask(deadline: self.now, task)
}
/// Run all tasks that have previously been submitted to this `NIOAsyncEmbeddedEventLoop`, either by calling `execute` or
/// events that have been enqueued using `scheduleTask`/`scheduleRepeatedTask`/`scheduleRepeatedAsyncTask` and whose
/// deadlines have expired.
///
/// - seealso: `NIOAsyncEmbeddedEventLoop.advanceTime`.
public func run() async {
// Execute all tasks that are currently enqueued to be executed *now*.
await self.advanceTime(to: self.now)
}
/// Runs the event loop and moves "time" forward by the given amount, running any scheduled
/// tasks that need to be run.
public func advanceTime(by increment: TimeAmount) async {
await self.advanceTime(to: self.now + increment)
}
/// Unwrap a future result from this event loop.
///
/// This replaces `EventLoopFuture.get()` for use with `NIOAsyncEmbeddedEventLoop`. This is necessary because attaching
/// a callback to an `EventLoopFuture` (which is what `EventLoopFuture.get` does) requires scheduling a work item onto
/// the event loop, and running that work item requires spinning the loop. This is a non-trivial dance to get right due
/// to timing issues, so this function provides a helper to ensure that this will work.
public func awaitFuture<ResultType: Sendable>(_ future: EventLoopFuture<ResultType>, timeout: TimeAmount) async throws -> ResultType {
// We need a task group to wait for the scheduled future result, because the future result callback
// can only complete when we actually run the loop, which we need to do in another Task.
return try await withThrowingTaskGroup(of: ResultType.self, returning: ResultType.self) { group in
// We need an innner promise to allow cancellation of the wait.
let promise = self.makePromise(of: ResultType.self)
future.cascade(to: promise)
group.addTask {
try await promise.futureResult.get()
}
group.addTask {
while true {
await self.run()
try Task.checkCancellation()
await Task.yield()
}
}
group.addTask {
try await Task.sleep(nanoseconds: UInt64(timeout.nanoseconds))
promise.fail(NIOAsyncEmbeddedEventLoopError.timeoutAwaitingFuture)
// This self.run() is _very important_. We're about to throw out of this function, which will
// cancel the entire TaskGroup. Depending on how things get scheduled it is possible for that
// cancellation to cancel the runner task above _before_ it spins again, meaning that the
// promise failure never actually happens (as it has to establish event loop context). So
// before we cancel this we make sure that we get a chance to spin the loop.
await self.run()
throw NIOAsyncEmbeddedEventLoopError.timeoutAwaitingFuture
}
do {
// This force-unwrap is safe: there are only three tasks and only one of them can ever return a value,
// the rest will error. The one that does return a value can never return `nil`. In essence, this is an
// `AsyncSequenceOfOneOrError`.
let result = try await group.next()!
group.cancelAll()
return result
} catch {
group.cancelAll()
throw error
}
}
}
/// Runs the event loop and moves "time" forward to the given point in time, running any scheduled
/// tasks that need to be run.
///
/// - Note: If `deadline` is before the current time, the current time will not be advanced.
public func advanceTime(to deadline: NIODeadline) async {
await withCheckedContinuation { (continuation: CheckedContinuation<Void, Never>) in
self.queue.async {
let newTime = max(deadline, self.now)
var tasks = CircularBuffer<EmbeddedScheduledTask>()
while let nextTask = self.scheduledTasks.peek() {
guard nextTask.readyTime <= newTime else {
break
}
// Now we want to grab all tasks that are ready to execute at the same
// time as the first.
while let candidateTask = self.scheduledTasks.peek(), candidateTask.readyTime == nextTask.readyTime {
tasks.append(candidateTask)
self.scheduledTasks.pop()
}
// Set the time correctly before we call into user code, then
// call in for all tasks.
self._now.store(nextTask.readyTime.uptimeNanoseconds)
for task in tasks {
task.task()
}
tasks.removeAll(keepingCapacity: true)
}
// Finally ensure we got the time right.
self._now.store(newTime.uptimeNanoseconds)
continuation.resume()
}
}
}
/// Executes the given function in the context of this event loop. This is useful when it's necessary to be confident that an operation
/// is "blocking" the event loop. As long as you are executing, nothing else can execute in this loop.
///
/// While this call is running, no action can take place on the loop. This function can therefore be a good place to schedule a bunch
/// of tasks "at once", with a guarantee that none of them can progress. It's also useful if you have types that can only be safely
/// accessed from the event loop thread and want to be 100% sure of the thread-safety of accessing them.
///
/// Be careful not to try to spin the event loop again from within this callback, however. As long as this function is on the call
/// stack the `NIOAsyncEmbeddedEventLoop` cannot progress, and so any attempt to progress it will block until this function returns.
public func executeInContext<ReturnType: Sendable>(_ task: @escaping @Sendable () throws -> ReturnType) async throws -> ReturnType {
try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<ReturnType, Error>) in
self.queue.async {
do {
continuation.resume(returning: try task())
} catch {
continuation.resume(throwing: error)
}
}
}
}
internal func drainScheduledTasksByRunningAllCurrentlyScheduledTasks() {
var currentlyScheduledTasks = self.scheduledTasks
while let nextTask = currentlyScheduledTasks.pop() {
self._now.store(nextTask.readyTime.uptimeNanoseconds)
nextTask.task()
}
// Just fail all the remaining scheduled tasks. Despite having run all the tasks that were
// scheduled when we entered the method this may still contain tasks as running the tasks
// may have enqueued more tasks.
while let task = self.scheduledTasks.pop() {
task.fail(EventLoopError.shutdown)
}
}
private func _shutdownGracefully() {
dispatchPrecondition(condition: .onQueue(self.queue))
self.drainScheduledTasksByRunningAllCurrentlyScheduledTasks()
}
/// - see: `EventLoop.shutdownGracefully`
public func shutdownGracefully(queue: DispatchQueue, _ callback: @escaping (Error?) -> Void) {
self.queue.async {
self._shutdownGracefully()
queue.async {
callback(nil)
}
}
}
/// The concurrency-aware equivalent of `shutdownGracefully(queue:_:)`.
public func shutdownGracefully() async {
await withCheckedContinuation { (continuation: CheckedContinuation<Void, Never>) in
self.queue.async {
self._shutdownGracefully()
continuation.resume()
}
}
}
public func _preconditionSafeToWait(file: StaticString, line: UInt) {
dispatchPrecondition(condition: .notOnQueue(self.queue))
}
public func _promiseCreated(futureIdentifier: _NIOEventLoopFutureIdentifier, file: StaticString, line: UInt) {
self._promiseCreationStore.promiseCreated(futureIdentifier: futureIdentifier, file: file, line: line)
}
public func _promiseCompleted(futureIdentifier: _NIOEventLoopFutureIdentifier) -> (file: StaticString, line: UInt)? {
return self._promiseCreationStore.promiseCompleted(futureIdentifier: futureIdentifier)
}
public func _preconditionSafeToSyncShutdown(file: StaticString, line: UInt) {
dispatchPrecondition(condition: .notOnQueue(self.queue))
}
public func preconditionInEventLoop(file: StaticString, line: UInt) {
dispatchPrecondition(condition: .onQueue(self.queue))
}
public func preconditionNotInEventLoop(file: StaticString, line: UInt) {
dispatchPrecondition(condition: .notOnQueue(self.queue))
}
deinit {
precondition(scheduledTasks.isEmpty, "NIOAsyncEmbeddedEventLoop freed with unexecuted scheduled tasks!")
}
}
/// This is a thread-safe promise creation store.
///
/// We use this to keep track of where promises come from in the `NIOAsyncEmbeddedEventLoop`.
private class PromiseCreationStore {
private let lock = Lock()
private var promiseCreationStore: [_NIOEventLoopFutureIdentifier: (file: StaticString, line: UInt)] = [:]
func promiseCreated(futureIdentifier: _NIOEventLoopFutureIdentifier, file: StaticString, line: UInt) {
precondition(_isDebugAssertConfiguration())
self.lock.withLockVoid {
self.promiseCreationStore[futureIdentifier] = (file: file, line: line)
}
}
func promiseCompleted(futureIdentifier: _NIOEventLoopFutureIdentifier) -> (file: StaticString, line: UInt)? {
precondition(_isDebugAssertConfiguration())
return self.lock.withLock {
self.promiseCreationStore.removeValue(forKey: futureIdentifier)
}
}
deinit {
// We no longer need the lock here.
precondition(self.promiseCreationStore.isEmpty, "NIOAsyncEmbeddedEventLoop freed with uncompleted promises!")
}
}
/// Errors that can happen on a `NIOAsyncEmbeddedEventLoop`.
public struct NIOAsyncEmbeddedEventLoopError: Error, Hashable {
private enum Backing {
case timeoutAwaitingFuture
}
private var backing: Backing
private init(_ backing: Backing) {
self.backing = backing
}
/// A timeout occurred while waiting for a future to complete.
public static let timeoutAwaitingFuture = Self(.timeoutAwaitingFuture)
}
#endif

View File

@ -17,7 +17,7 @@ import _NIODataStructures
import NIOCore
private struct EmbeddedScheduledTask {
internal struct EmbeddedScheduledTask {
let id: UInt64
let task: () -> Void
let failFn: (Error) -> ()

View File

@ -104,6 +104,7 @@ class LinuxMainRunnerImpl: LinuxMainRunner {
testCase(MessageToByteHandlerTest.allTests),
testCase(MulticastTest.allTests),
testCase(NIOAnyDebugTest.allTests),
testCase(NIOAsyncEmbeddedEventLoopTests.allTests),
testCase(NIOCloseOnErrorHandlerTest.allTests),
testCase(NIOConcurrencyHelpersTests.allTests),
testCase(NIOHTTP1TestServerTest.allTests),

View File

@ -0,0 +1,56 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2022 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
//
// AsyncEmbeddedEventLoopTests+XCTest.swift
//
import XCTest
///
/// NOTE: This file was generated by generate_linux_tests.rb
///
/// Do NOT edit this file directly as it will be regenerated automatically when needed.
///
extension NIOAsyncEmbeddedEventLoopTests {
@available(*, deprecated, message: "not actually deprecated. Just deprecated to allow deprecated tests (which test deprecated functionality) without warnings")
static var allTests : [(String, (NIOAsyncEmbeddedEventLoopTests) -> () throws -> Void)] {
return [
("testExecuteDoesNotImmediatelyRunTasks", testExecuteDoesNotImmediatelyRunTasks),
("testExecuteWillRunAllTasks", testExecuteWillRunAllTasks),
("testExecuteWillRunTasksAddedRecursively", testExecuteWillRunTasksAddedRecursively),
("testTasksSubmittedAfterRunDontRun", testTasksSubmittedAfterRunDontRun),
("testSyncShutdownGracefullyRunsTasks", testSyncShutdownGracefullyRunsTasks),
("testShutdownGracefullyRunsTasks", testShutdownGracefullyRunsTasks),
("testCanControlTime", testCanControlTime),
("testCanScheduleMultipleTasks", testCanScheduleMultipleTasks),
("testExecutedTasksFromScheduledOnesAreRun", testExecutedTasksFromScheduledOnesAreRun),
("testScheduledTasksFromScheduledTasksProperlySchedule", testScheduledTasksFromScheduledTasksProperlySchedule),
("testScheduledTasksFromExecutedTasks", testScheduledTasksFromExecutedTasks),
("testCancellingScheduledTasks", testCancellingScheduledTasks),
("testScheduledTasksFuturesFire", testScheduledTasksFuturesFire),
("testScheduledTasksFuturesError", testScheduledTasksFuturesError),
("testTaskOrdering", testTaskOrdering),
("testCancelledScheduledTasksDoNotHoldOnToRunClosure", testCancelledScheduledTasksDoNotHoldOnToRunClosure),
("testWaitingForFutureCanTimeOut", testWaitingForFutureCanTimeOut),
("testDrainScheduledTasks", testDrainScheduledTasks),
("testDrainScheduledTasksDoesNotRunNewlyScheduledTasks", testDrainScheduledTasksDoesNotRunNewlyScheduledTasks),
("testAdvanceTimeToDeadline", testAdvanceTimeToDeadline),
("testWeCantTimeTravelByAdvancingTimeToThePast", testWeCantTimeTravelByAdvancingTimeToThePast),
("testExecuteInOrder", testExecuteInOrder),
("testScheduledTasksInOrder", testScheduledTasksInOrder),
]
}
}

View File

@ -0,0 +1,690 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2022 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import NIOCore
import NIOConcurrencyHelpers
@testable import NIOEmbedded
import XCTest
private class EmbeddedTestError: Error { }
final class NIOAsyncEmbeddedEventLoopTests: XCTestCase {
func testExecuteDoesNotImmediatelyRunTasks() throws {
#if compiler(>=5.5.2) && canImport(_Concurrency)
guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { throw XCTSkip() }
XCTAsyncTest {
let callbackRan = NIOAtomic<Bool>.makeAtomic(value: false)
let loop = NIOAsyncEmbeddedEventLoop()
try await loop.executeInContext {
loop.execute { callbackRan.store(true) }
XCTAssertFalse(callbackRan.load())
}
await loop.run()
XCTAssertTrue(callbackRan.load())
}
#else
throw XCTSkip()
#endif
}
func testExecuteWillRunAllTasks() throws {
#if compiler(>=5.5.2) && canImport(_Concurrency)
guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { throw XCTSkip() }
XCTAsyncTest {
let runCount = NIOAtomic<Int>.makeAtomic(value: 0)
let loop = NIOAsyncEmbeddedEventLoop()
loop.execute { runCount.add(1) }
loop.execute { runCount.add(1) }
loop.execute { runCount.add(1) }
try await loop.executeInContext {
XCTAssertEqual(runCount.load(), 0)
}
await loop.run()
try await loop.executeInContext {
XCTAssertEqual(runCount.load(), 3)
}
}
#else
throw XCTSkip()
#endif
}
func testExecuteWillRunTasksAddedRecursively() throws {
#if compiler(>=5.5.2) && canImport(_Concurrency)
guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { throw XCTSkip() }
XCTAsyncTest {
let sentinel = NIOAtomic<Int>.makeAtomic(value: 0)
let loop = NIOAsyncEmbeddedEventLoop()
loop.execute {
// This should execute first.
XCTAssertEqual(sentinel.load(), 0)
sentinel.store(1)
loop.execute {
// This should execute third.
XCTAssertEqual(sentinel.load(), 2)
sentinel.store(3)
}
}
loop.execute {
// This should execute second.
XCTAssertEqual(sentinel.load(), 1)
sentinel.store(2)
}
try await loop.executeInContext {
XCTAssertEqual(sentinel.load(), 0)
}
await loop.run()
try await loop.executeInContext {
XCTAssertEqual(sentinel.load(), 3)
}
}
#else
throw XCTSkip()
#endif
}
func testTasksSubmittedAfterRunDontRun() throws {
#if compiler(>=5.5.2) && canImport(_Concurrency)
guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { throw XCTSkip() }
XCTAsyncTest {
let callbackRan = NIOAtomic<Bool>.makeAtomic(value: false)
let loop = NIOAsyncEmbeddedEventLoop()
loop.execute { callbackRan.store(true) }
try await loop.executeInContext {
XCTAssertFalse(callbackRan.load())
}
await loop.run()
loop.execute { callbackRan.store(false) }
try await loop.executeInContext {
XCTAssertTrue(callbackRan.load())
}
await loop.run()
try await loop.executeInContext {
XCTAssertFalse(callbackRan.load())
}
}
#else
throw XCTSkip()
#endif
}
func testSyncShutdownGracefullyRunsTasks() throws {
#if compiler(>=5.5.2) && canImport(_Concurrency)
guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { throw XCTSkip() }
XCTAsyncTest {
let callbackRan = NIOAtomic<Bool>.makeAtomic(value: false)
let loop = NIOAsyncEmbeddedEventLoop()
loop.execute { callbackRan.store(true) }
try await loop.executeInContext {
XCTAssertFalse(callbackRan.load())
}
XCTAssertNoThrow(try loop.syncShutdownGracefully())
try await loop.executeInContext {
XCTAssertTrue(callbackRan.load())
}
}
#else
throw XCTSkip()
#endif
}
func testShutdownGracefullyRunsTasks() throws {
#if compiler(>=5.5.2) && canImport(_Concurrency)
guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { throw XCTSkip() }
XCTAsyncTest {
let callbackRan = NIOAtomic<Bool>.makeAtomic(value: false)
let loop = NIOAsyncEmbeddedEventLoop()
loop.execute { callbackRan.store(true) }
try await loop.executeInContext {
XCTAssertFalse(callbackRan.load())
}
await loop.shutdownGracefully()
try await loop.executeInContext {
XCTAssertTrue(callbackRan.load())
}
}
#else
throw XCTSkip()
#endif
}
func testCanControlTime() throws {
#if compiler(>=5.5.2) && canImport(_Concurrency)
guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { throw XCTSkip() }
XCTAsyncTest {
let callbackCount = NIOAtomic<Int>.makeAtomic(value: 0)
let loop = NIOAsyncEmbeddedEventLoop()
_ = loop.scheduleTask(in: .nanoseconds(5)) {
callbackCount.add(1)
}
try await loop.executeInContext {
XCTAssertEqual(callbackCount.load(), 0)
}
await loop.advanceTime(by: .nanoseconds(4))
try await loop.executeInContext {
XCTAssertEqual(callbackCount.load(), 0)
}
await loop.advanceTime(by: .nanoseconds(1))
try await loop.executeInContext {
XCTAssertEqual(callbackCount.load(), 1)
}
await loop.advanceTime(by: .nanoseconds(1))
try await loop.executeInContext {
XCTAssertEqual(callbackCount.load(), 1)
}
await loop.advanceTime(by: .hours(1))
try await loop.executeInContext {
XCTAssertEqual(callbackCount.load(), 1)
}
}
#else
throw XCTSkip()
#endif
}
func testCanScheduleMultipleTasks() throws {
#if compiler(>=5.5.2) && canImport(_Concurrency)
guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { throw XCTSkip() }
XCTAsyncTest {
let sentinel = NIOAtomic.makeAtomic(value: 0)
let loop = NIOAsyncEmbeddedEventLoop()
for index in 1...10 {
_ = loop.scheduleTask(in: .nanoseconds(Int64(index))) {
sentinel.store(index)
}
}
for val in 1...10 {
try await loop.executeInContext {
XCTAssertEqual(sentinel.load(), val - 1)
}
await loop.advanceTime(by: .nanoseconds(1))
try await loop.executeInContext {
XCTAssertEqual(sentinel.load(), val)
}
}
}
#else
throw XCTSkip()
#endif
}
func testExecutedTasksFromScheduledOnesAreRun() throws {
#if compiler(>=5.5.2) && canImport(_Concurrency)
guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { throw XCTSkip() }
XCTAsyncTest {
let sentinel = NIOAtomic.makeAtomic(value: 0)
let loop = NIOAsyncEmbeddedEventLoop()
_ = loop.scheduleTask(in: .nanoseconds(5)) {
sentinel.store(1)
loop.execute {
sentinel.store(2)
}
}
await loop.advanceTime(by: .nanoseconds(4))
try await loop.executeInContext {
XCTAssertEqual(sentinel.load(), 0)
}
await loop.advanceTime(by: .nanoseconds(1))
try await loop.executeInContext {
XCTAssertEqual(sentinel.load(), 2)
}
}
#else
throw XCTSkip()
#endif
}
func testScheduledTasksFromScheduledTasksProperlySchedule() throws {
#if compiler(>=5.5.2) && canImport(_Concurrency)
guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { throw XCTSkip() }
XCTAsyncTest {
let sentinel = NIOAtomic.makeAtomic(value: 0)
let loop = NIOAsyncEmbeddedEventLoop()
_ = loop.scheduleTask(in: .nanoseconds(5)) {
sentinel.store(1)
_ = loop.scheduleTask(in: .nanoseconds(3)) {
sentinel.store(2)
}
_ = loop.scheduleTask(in: .nanoseconds(5)) {
sentinel.store(3)
}
}
await loop.advanceTime(by: .nanoseconds(4))
try await loop.executeInContext {
XCTAssertEqual(sentinel.load(), 0)
}
await loop.advanceTime(by: .nanoseconds(1))
try await loop.executeInContext {
XCTAssertEqual(sentinel.load(), 1)
}
await loop.advanceTime(by: .nanoseconds(2))
try await loop.executeInContext {
XCTAssertEqual(sentinel.load(), 1)
}
await loop.advanceTime(by: .nanoseconds(1))
try await loop.executeInContext {
XCTAssertEqual(sentinel.load(), 2)
}
await loop.advanceTime(by: .nanoseconds(1))
try await loop.executeInContext {
XCTAssertEqual(sentinel.load(), 2)
}
await loop.advanceTime(by: .nanoseconds(1))
try await loop.executeInContext {
XCTAssertEqual(sentinel.load(), 3)
}
}
#else
throw XCTSkip()
#endif
}
func testScheduledTasksFromExecutedTasks() throws {
#if compiler(>=5.5.2) && canImport(_Concurrency)
guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { throw XCTSkip() }
XCTAsyncTest {
let sentinel = NIOAtomic.makeAtomic(value: 0)
let loop = NIOAsyncEmbeddedEventLoop()
loop.execute {
XCTAssertEqual(sentinel.load(), 0)
_ = loop.scheduleTask(in: .nanoseconds(5)) {
XCTAssertEqual(sentinel.load(), 1)
sentinel.store(2)
}
loop.execute { sentinel.store(1) }
}
await loop.advanceTime(by: .nanoseconds(5))
try await loop.executeInContext {
XCTAssertEqual(sentinel.load(), 2)
}
}
#else
throw XCTSkip()
#endif
}
func testCancellingScheduledTasks() throws {
#if compiler(>=5.5.2) && canImport(_Concurrency)
guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { throw XCTSkip() }
XCTAsyncTest {
let loop = NIOAsyncEmbeddedEventLoop()
let task = loop.scheduleTask(in: .nanoseconds(10), { XCTFail("Cancelled task ran") })
_ = loop.scheduleTask(in: .nanoseconds(5)) {
task.cancel()
}
await loop.advanceTime(by: .nanoseconds(20))
}
#else
throw XCTSkip()
#endif
}
func testScheduledTasksFuturesFire() throws {
#if compiler(>=5.5.2) && canImport(_Concurrency)
guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { throw XCTSkip() }
XCTAsyncTest {
let fired = NIOAtomic.makeAtomic(value: false)
let loop = NIOAsyncEmbeddedEventLoop()
let task = loop.scheduleTask(in: .nanoseconds(5)) { true }
task.futureResult.whenSuccess { fired.store($0) }
await loop.advanceTime(by: .nanoseconds(4))
XCTAssertFalse(fired.load())
await loop.advanceTime(by: .nanoseconds(1))
XCTAssertTrue(fired.load())
}
#else
throw XCTSkip()
#endif
}
func testScheduledTasksFuturesError() throws {
#if compiler(>=5.5.2) && canImport(_Concurrency)
guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { throw XCTSkip() }
XCTAsyncTest {
let err = EmbeddedTestError()
let fired = NIOAtomic.makeAtomic(value: false)
let loop = NIOAsyncEmbeddedEventLoop()
let task = loop.scheduleTask(in: .nanoseconds(5)) {
throw err
}
task.futureResult.map {
XCTFail("Scheduled future completed")
}.recover { caughtErr in
XCTAssertTrue(err === caughtErr as? EmbeddedTestError)
}.whenComplete { (_: Result<Void, Error>) in
fired.store(true)
}
await loop.advanceTime(by: .nanoseconds(4))
XCTAssertFalse(fired.load())
await loop.advanceTime(by: .nanoseconds(1))
XCTAssertTrue(fired.load())
}
#else
throw XCTSkip()
#endif
}
func testTaskOrdering() throws {
#if compiler(>=5.5.2) && canImport(_Concurrency)
guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { throw XCTSkip() }
XCTAsyncTest {
// This test validates that the ordering of task firing on NIOAsyncEmbeddedEventLoop via
// advanceTime(by:) is the same as on MultiThreadedEventLoopGroup: specifically, that tasks run via
// schedule that expire "now" all run at the same time, and that any work they schedule is run
// after all such tasks expire.
let loop = NIOAsyncEmbeddedEventLoop()
let lock = Lock()
var firstScheduled: Scheduled<Void>? = nil
var secondScheduled: Scheduled<Void>? = nil
let orderingCounter = NIOAtomic.makeAtomic(value: 0)
// Here's the setup. First, we'll set up two scheduled tasks to fire in 5 nanoseconds. Each of these
// will attempt to cancel the other, but the first one scheduled will fire first. Additionally, each will execute{} a single
// callback. Then we'll execute {} one other callback. Finally we'll schedule a task for 10ns, before
// we advance time. The ordering should be as follows:
//
// 1. The task executed by execute {} from this function.
// 2. The first scheduled task.
// 3. The second scheduled task (note that the cancellation will fail).
// 4. The execute {} callback from the first scheduled task.
// 5. The execute {} callbacks from the second scheduled task.
// 6. The 10ns task.
//
// To validate the ordering, we'll use a counter.
lock.withLockVoid {
firstScheduled = loop.scheduleTask(in: .nanoseconds(5)) {
let second = lock.withLock { () -> Scheduled<Void>? in
XCTAssertNotNil(firstScheduled)
firstScheduled = nil
XCTAssertNotNil(secondScheduled)
return secondScheduled
}
if let partner = second {
// Ok, this callback fired first. Cancel the other.
partner.cancel()
} else {
XCTFail("First callback executed second")
}
XCTAssertCompareAndSwapSucceeds(storage: orderingCounter, expected: 1, desired: 2)
loop.execute {
XCTAssertCompareAndSwapSucceeds(storage: orderingCounter, expected: 3, desired: 4)
}
}
secondScheduled = loop.scheduleTask(in: .nanoseconds(5)) {
lock.withLockVoid {
secondScheduled = nil
XCTAssertNil(firstScheduled)
XCTAssertNil(secondScheduled)
}
XCTAssertCompareAndSwapSucceeds(storage: orderingCounter, expected: 2, desired: 3)
loop.execute {
XCTAssertCompareAndSwapSucceeds(storage: orderingCounter, expected: 4, desired: 5)
}
}
}
// Ok, now we set one more task to execute.
loop.execute {
XCTAssertCompareAndSwapSucceeds(storage: orderingCounter, expected: 0, desired: 1)
}
// Finally schedule a task for 10ns.
_ = loop.scheduleTask(in: .nanoseconds(10)) {
XCTAssertCompareAndSwapSucceeds(storage: orderingCounter, expected: 5, desired: 6)
}
// Now we advance time by 10ns.
await loop.advanceTime(by: .nanoseconds(10))
// Now the final value should be 6.
XCTAssertEqual(orderingCounter.load(), 6)
}
#else
throw XCTSkip()
#endif
}
func testCancelledScheduledTasksDoNotHoldOnToRunClosure() throws {
#if compiler(>=5.5.2) && canImport(_Concurrency)
guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { throw XCTSkip() }
XCTAsyncTest {
let eventLoop = NIOAsyncEmbeddedEventLoop()
defer {
XCTAssertNoThrow(try eventLoop.syncShutdownGracefully())
}
class Thing {}
weak var weakThing: Thing? = nil
func make() -> Scheduled<Never> {
let aThing = Thing()
weakThing = aThing
return eventLoop.scheduleTask(in: .hours(1)) {
preconditionFailure("this should definitely not run: \(aThing)")
}
}
let scheduled = make()
scheduled.cancel()
XCTAssertNotNil(weakThing)
await eventLoop.run()
XCTAssertNil(weakThing)
await XCTAssertThrowsError(try await eventLoop.awaitFuture(scheduled.futureResult, timeout: .seconds(1))) { error in
XCTAssertEqual(EventLoopError.cancelled, error as? EventLoopError)
}
}
#else
throw XCTSkip()
#endif
}
func testWaitingForFutureCanTimeOut() throws {
#if compiler(>=5.5.2) && canImport(_Concurrency)
guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { throw XCTSkip() }
XCTAsyncTest {
let eventLoop = NIOAsyncEmbeddedEventLoop()
defer {
XCTAssertNoThrow(try eventLoop.syncShutdownGracefully())
}
let promise = eventLoop.makePromise(of: Void.self)
await XCTAssertThrowsError(try await eventLoop.awaitFuture(promise.futureResult, timeout: .milliseconds(1))) { error in
XCTAssertEqual(NIOAsyncEmbeddedEventLoopError.timeoutAwaitingFuture, error as? NIOAsyncEmbeddedEventLoopError)
}
}
#else
throw XCTSkip()
#endif
}
func testDrainScheduledTasks() throws {
#if compiler(>=5.5.2) && canImport(_Concurrency)
guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { throw XCTSkip() }
XCTAsyncTest {
let eventLoop = NIOAsyncEmbeddedEventLoop()
let tasksRun = NIOAtomic.makeAtomic(value: 0)
let startTime = eventLoop.now
eventLoop.scheduleTask(in: .nanoseconds(3141592)) {
XCTAssertEqual(eventLoop.now, startTime + .nanoseconds(3141592))
tasksRun.add(1)
}
eventLoop.scheduleTask(in: .seconds(3141592)) {
XCTAssertEqual(eventLoop.now, startTime + .seconds(3141592))
tasksRun.add(1)
}
await eventLoop.shutdownGracefully()
XCTAssertEqual(tasksRun.load(), 2)
}
#else
throw XCTSkip()
#endif
}
func testDrainScheduledTasksDoesNotRunNewlyScheduledTasks() throws {
#if compiler(>=5.5.2) && canImport(_Concurrency)
guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { throw XCTSkip() }
XCTAsyncTest {
let eventLoop = NIOAsyncEmbeddedEventLoop()
let tasksRun = NIOAtomic.makeAtomic(value: 0)
func scheduleNowAndIncrement() {
eventLoop.scheduleTask(in: .nanoseconds(0)) {
tasksRun.add(1)
scheduleNowAndIncrement()
}
}
scheduleNowAndIncrement()
await eventLoop.shutdownGracefully()
XCTAssertEqual(tasksRun.load(), 1)
}
#else
throw XCTSkip()
#endif
}
func testAdvanceTimeToDeadline() throws {
#if compiler(>=5.5.2) && canImport(_Concurrency)
guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { throw XCTSkip() }
XCTAsyncTest {
let eventLoop = NIOAsyncEmbeddedEventLoop()
let deadline = NIODeadline.uptimeNanoseconds(0) + .seconds(42)
let tasksRun = NIOAtomic.makeAtomic(value: 0)
eventLoop.scheduleTask(deadline: deadline) {
tasksRun.add(1)
}
await eventLoop.advanceTime(to: deadline)
XCTAssertEqual(tasksRun.load(), 1)
}
#else
throw XCTSkip()
#endif
}
func testWeCantTimeTravelByAdvancingTimeToThePast() throws {
#if compiler(>=5.5.2) && canImport(_Concurrency)
guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { throw XCTSkip() }
XCTAsyncTest {
let eventLoop = NIOAsyncEmbeddedEventLoop()
let tasksRun = NIOAtomic.makeAtomic(value: 0)
eventLoop.scheduleTask(deadline: .uptimeNanoseconds(0) + .seconds(42)) {
tasksRun.add(1)
}
// t=40s
await eventLoop.advanceTime(to: .uptimeNanoseconds(0) + .seconds(40))
XCTAssertEqual(tasksRun.load(), 0)
// t=40s (still)
await eventLoop.advanceTime(to: .distantPast)
XCTAssertEqual(tasksRun.load(), 0)
// t=42s
await eventLoop.advanceTime(by: .seconds(2))
XCTAssertEqual(tasksRun.load(), 1)
}
#else
throw XCTSkip()
#endif
}
func testExecuteInOrder() throws {
#if compiler(>=5.5.2) && canImport(_Concurrency)
guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { throw XCTSkip() }
XCTAsyncTest {
let eventLoop = NIOAsyncEmbeddedEventLoop()
let counter = NIOAtomic.makeAtomic(value: 0)
eventLoop.execute {
let original = counter.add(1)
XCTAssertEqual(original, 0)
}
eventLoop.execute {
let original = counter.add(1)
XCTAssertEqual(original, 1)
}
eventLoop.execute {
let original = counter.add(1)
XCTAssertEqual(original, 2)
}
await eventLoop.run()
XCTAssertEqual(counter.load(), 3)
}
#else
throw XCTSkip()
#endif
}
func testScheduledTasksInOrder() throws {
#if compiler(>=5.5.2) && canImport(_Concurrency)
guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else { throw XCTSkip() }
XCTAsyncTest {
let eventLoop = NIOAsyncEmbeddedEventLoop()
let counter = NIOAtomic.makeAtomic(value: 0)
eventLoop.scheduleTask(in: .seconds(1)) {
let original = counter.add(1)
XCTAssertEqual(original, 1)
}
eventLoop.scheduleTask(in: .milliseconds(1)) {
let original = counter.add(1)
XCTAssertEqual(original, 0)
}
eventLoop.scheduleTask(in: .seconds(1)) {
let original = counter.add(1)
XCTAssertEqual(original, 2)
}
await eventLoop.advanceTime(by: .seconds(1))
XCTAssertEqual(counter.load(), 3)
}
#else
throw XCTSkip()
#endif
}
}

View File

@ -59,3 +59,14 @@ extension EventLoopFuture {
}
}
}
internal func XCTAssertCompareAndSwapSucceeds<Type: NIOAtomicPrimitive>(
storage: NIOAtomic<Type>,
expected: Type,
desired: Type,
file: StaticString = #file,
line: UInt = #line
) {
let swapped = storage.compareAndExchange(expected: expected, desired: desired)
XCTAssertTrue(swapped, file: file, line: line)
}

View File

@ -0,0 +1,106 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2022 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
//===----------------------------------------------------------------------===//
//
// This source file is part of the AsyncHTTPClient open source project
//
// Copyright (c) 2021 Apple Inc. and the AsyncHTTPClient project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of AsyncHTTPClient project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
/*
* Copyright 2021, gRPC Authors All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#if compiler(>=5.5.2) && canImport(_Concurrency)
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,
file: StaticString = #file,
line: UInt = #line,
verify: (Error) -> Void = { _ in }
) async {
do {
_ = try await expression()
XCTFail("Expression did not throw error", file: file, line: line)
} catch {
verify(error)
}
}
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
internal func XCTAssertNoThrowWithResult<Result>(
_ expression: @autoclosure () async throws -> Result,
file: StaticString = #file,
line: UInt = #line
) async -> Result? {
do {
return try await expression()
} catch {
XCTFail("Expression did throw: \(error)", file: file, line: line)
}
return nil
}
#endif