Allow defer in xcAwait. simplify sending state actions from a publisher. Fix tests.

This commit is contained in:
David Langley
2021-09-15 16:09:41 +01:00
parent d189c4d618
commit cda4a354d1
6 changed files with 55 additions and 45 deletions
@@ -34,6 +34,25 @@ extension XCTestCase {
_ publisher: T,
timeout: TimeInterval = 10
) throws -> T.Output {
return try xcAwaitDeferred(publisher, timeout: timeout)()
}
/// XCTest utility that allows for a deferred wait of results from publishers, so that the output can be used for assertions.
///
/// ```
/// let collectedEvents = somePublisher.collect(3).first()
/// let awaitDeferred = xcAwaitDeferred(collectedEvents)
/// // Do some other work that publishes to somePublisher
/// XCTAssertEqual(try awaitDeferred(), [expected, values, here])
/// ```
/// - Parameters:
/// - publisher: The publisher to wait on.
/// - timeout: A timeout after which we give up.
/// - Returns: A closure that starts the waiting of results when called. The closure will return the unwrapped result.
func xcAwaitDeferred<T: Publisher>(
_ publisher: T,
timeout: TimeInterval = 10
) -> (() throws -> (T.Output)) {
var result: Result<T.Output, Error>?
let expectation = self.expectation(description: "Awaiting publisher")
@@ -52,12 +71,14 @@ extension XCTestCase {
result = .success(value)
}
)
waitForExpectations(timeout: timeout)
cancellable.cancel()
let unwrappedResult = try XCTUnwrap(
result,
"Awaited publisher did not produce any output"
)
return try unwrappedResult.get()
return {
self.waitForExpectations(timeout: timeout)
cancellable.cancel()
let unwrappedResult = try XCTUnwrap(
result,
"Awaited publisher did not produce any output"
)
return try unwrappedResult.get()
}
}
}