Created
September 27, 2024 21:12
-
-
Save loganblevins/541ab4c3ec1f3ec5ddb255c4ab88169b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
import Combine | |
import XCTest | |
@testable import Stock | |
extension XCTestCase { | |
func awaitPublisher<T: Publisher>( | |
_ publisher: T, | |
timeout: TimeInterval = 1.0, | |
file: StaticString = #filePath, | |
line: UInt = #line | |
) throws -> T.Output where T.Failure == Error { | |
var result: Result<T.Output, Error>? | |
let expectation = self.expectation(description: "Awaiting publisher") | |
let cancellable = publisher.sink( | |
receiveCompletion: { completion in | |
switch completion { | |
case .failure(let error): | |
result = .failure(error) | |
case .finished: | |
break | |
} | |
expectation.fulfill() | |
}, | |
receiveValue: { value in | |
result = .success(value) | |
} | |
) | |
waitForExpectations(timeout: timeout) | |
cancellable.cancel() | |
let unwrappedResult = try XCTUnwrap( | |
result, | |
"Awaited publisher did not produce any output", | |
file: file, | |
line: line | |
) | |
return try unwrappedResult.get() | |
} | |
func awaitPublisher<T: Publisher>( | |
_ publisher: T, | |
dropFirst count: Int = 1, | |
timeout: TimeInterval = 1.0, | |
file: StaticString = #filePath, | |
line: UInt = #line | |
) throws -> T.Output where T.Failure == Never { | |
var result: Result<T.Output, Error>? | |
let expectation = self.expectation(description: "Awaiting publisher") | |
let cancellable = publisher | |
.dropFirst(count) | |
.sink { value in | |
result = .success(value) | |
expectation.fulfill() | |
} | |
waitForExpectations(timeout: timeout) | |
cancellable.cancel() | |
let unwrappedResult = try XCTUnwrap( | |
result, | |
"Awaited publisher did not produce any output", | |
file: file, | |
line: line | |
) | |
return try unwrappedResult.get() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment