Description
Motivation
Here's a situation where running tests with an asynchronous expectation causes confirmation
to conclude that the expectation never ran, but prematurely.
@Test func cancelViaAbandon() async throws {
try await confirmation { terminatedExpectation in
_ = Task {
let input = [0, 1, 2, 3, 4, 5, 6]
let (stream, continuation) = AsyncThrowingStream<Int, Error>.makeStream()
continuation.onTermination = { reason in
terminatedExpectation()
print("Terminated: \(reason)")
}
for num in input {
try await Task.sleep(for: .milliseconds(20))
guard num < 4 else { return }
continuation.yield(num)
print(num)
}
}
// If we don't wait a bit for the `onTermination` to complete, then `confirmation` will conclude that the
// expectation is never called.
// try await Task.sleep(for: .milliseconds(500))
}
}
If you run this as is, confirmation
concludes that terminatedExpectation
will never get called, therefore the test fails. However, if we uncomment the last line and add a short delay to give what I assume is ARC and stack unwinding to cleanup the Task contents, causing onTermination
's closure to trigger prior to confirmation
finishing, we are all good.
Proposed solution
Add a timeout to Testing.Confirmation
. This would replicate my simple fix that was commented out in the sample code above.
Now, I realize this is a bit fuzzy and potentially indeterminate... What if the system is running slow enough that the cleanup doesn't happen in time for the timeout? However, I don't see any other way to refactor this test that wouldn't be susceptible to this. And the default could be set to zero so it's identical to what it does now unless deliberately overridden.
Alternatives considered
Refactor the test in some way that would alleviate this issue, but I'm not seeing a way to do so.
Additional information
No response
Activity