Created
September 20, 2026 19:51
-
-
Save michalraska/11ecbb834e173935b3d7ee6b296994e2 to your computer and use it in GitHub Desktop.
Deterministic Swift concurrency testing: values, timeouts, errors, and cancellation.
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 Testing | |
| @Suite("Deterministic timeout testing") | |
| struct ConcurrentCodeTestingExamples { | |
| @Test("A value returned before the deadline wins", .timeLimit(.minutes(1))) | |
| func valueBeforeTimeout() async throws { | |
| // Given: a provider and a timeout that both wait for input from the test. | |
| let provider = AsyncValueProviderSpy() | |
| let sleep = SleepSpy() | |
| let sut = TimedValueLoader(provider: provider, sleep: sleep) | |
| // When: loading starts and both child tasks report their calls. | |
| async let loadedValue = sut.load(within: .seconds(3)) | |
| // These awaits confirm that both the value provider and sleep were called. | |
| let valueCall = try #require(await provider.nextCall()) | |
| let sleepCall = try #require(await sleep.nextCall()) | |
| #expect(valueCall == .value) | |
| #expect(sleepCall == .seconds(3)) | |
| // Provide a value while the timeout continues to wait. | |
| provider.respond(with: .success("loaded value")) | |
| // Then: the loader returns the provided value. | |
| let value = try await loadedValue | |
| #expect(value == "loaded value") | |
| } | |
| @Test("The timeout finishes before a value arrives", .timeLimit(.minutes(1))) | |
| func timeoutBeforeValue() async throws { | |
| // Given: a provider and a timeout controlled by the test. | |
| let provider = AsyncValueProviderSpy() | |
| let sleep = SleepSpy() | |
| let sut = TimedValueLoader(provider: provider, sleep: sleep) | |
| // When: both child tasks start. | |
| async let loadedValue = sut.load(within: .seconds(3)) | |
| let valueCall = try #require(await provider.nextCall()) | |
| let sleepCall = try #require(await sleep.nextCall()) | |
| #expect(valueCall == .value) | |
| #expect(sleepCall == .seconds(3)) | |
| // Trigger the timeout while the provider continues to wait. | |
| sleep.resume() | |
| // Then: the loader throws the expected error. | |
| do { | |
| _ = try await loadedValue | |
| Issue.record("Expected the timeout to win") | |
| } catch { | |
| #expect(error as? TimedValueLoader.Error == .timedOut) | |
| } | |
| } | |
| @Test("The loader propagates the provider error", .timeLimit(.minutes(1))) | |
| func providerError() async throws { | |
| enum ExampleError: Error { | |
| case valueFailed | |
| } | |
| // Given: a provider and a timeout controlled by the test. | |
| let provider = AsyncValueProviderSpy() | |
| let sleep = SleepSpy() | |
| let sut = TimedValueLoader(provider: provider, sleep: sleep) | |
| // When: both child tasks start. | |
| async let loadedValue = sut.load(within: .seconds(3)) | |
| let valueCall = try #require(await provider.nextCall()) | |
| let sleepCall = try #require(await sleep.nextCall()) | |
| #expect(valueCall == .value) | |
| #expect(sleepCall == .seconds(3)) | |
| // Respond to the pending request with the expected error. | |
| provider.respond(with: .failure(ExampleError.valueFailed)) | |
| // Then: the loader throws the expected error. | |
| do { | |
| _ = try await loadedValue | |
| Issue.record("Expected the provider error") | |
| } catch { | |
| #expect(error as? ExampleError == .valueFailed) | |
| } | |
| } | |
| @Test("Caller cancellation stops both child tasks", .timeLimit(.minutes(1))) | |
| func callerCancellation() async throws { | |
| // Given: a provider and a timeout controlled by the test. | |
| let provider = AsyncValueProviderSpy() | |
| let sleep = SleepSpy() | |
| let sut = TimedValueLoader(provider: provider, sleep: sleep) | |
| // When: loading starts in a task that can be cancelled. | |
| let loadingTask = Task { | |
| try await sut.load(within: .seconds(3)) | |
| } | |
| // A #require can throw before we reach loadingTask.cancel(). | |
| // Without do/catch, the test would exit while loadingTask keeps waiting. | |
| // The catch block cancels that task and waits for it to finish. | |
| do { | |
| try await withTaskCancellationHandler { | |
| let valueCall = try #require(await provider.nextCall()) | |
| let sleepCall = try #require(await sleep.nextCall()) | |
| #expect(valueCall == .value) | |
| #expect(sleepCall == .seconds(3)) | |
| // Cancel after both child tasks have started. | |
| loadingTask.cancel() | |
| // Then: loading ends with cancellation. | |
| await #expect(throws: CancellationError.self) { | |
| try await loadingTask.value | |
| } | |
| } onCancel: { | |
| loadingTask.cancel() | |
| } | |
| } catch { | |
| loadingTask.cancel() | |
| _ = await loadingTask.result | |
| throw error | |
| } | |
| } | |
| @Test("The loader returns the prepared value", .timeLimit(.minutes(1))) | |
| func preparedResponse() async throws { | |
| // Given: a provider with a successful response already prepared. | |
| let provider = AsyncValueProviderSpy() | |
| provider.respond(with: .success("loaded value")) | |
| let sut = TimedValueLoader(provider: provider, sleep: SleepSpy()) | |
| // When: the loader requests a value. | |
| let value = try await sut.load(within: .seconds(3)) | |
| // Then: the loader returns the prepared value. | |
| #expect(value == "loaded value") | |
| } | |
| } | |
| // Provides an asynchronous value so tests can control its result and delivery. | |
| private protocol AsyncValueProviding: Sendable { | |
| func value() async throws -> String | |
| } | |
| // Replaces direct Task.sleep calls so tests can control when the wait ends. | |
| private protocol Sleeping: Sendable { | |
| func callAsFunction(for duration: Duration) async throws | |
| } | |
| // Races the value against a timeout and cancels the remaining work. | |
| private struct TimedValueLoader: Sendable { | |
| enum Error: Swift.Error, Equatable { | |
| case timedOut | |
| } | |
| let provider: any AsyncValueProviding | |
| let sleep: any Sleeping | |
| func load(within timeout: Duration) async throws -> String { | |
| try await withThrowingTaskGroup(of: String.self) { group in | |
| group.addTask { | |
| try await provider.value() | |
| } | |
| group.addTask { | |
| try await sleep(for: timeout) | |
| throw Error.timedOut | |
| } | |
| defer { | |
| // Cancel whichever child loses the race. | |
| group.cancelAll() | |
| } | |
| guard let firstResult = try await group.next() else { | |
| throw CancellationError() | |
| } | |
| return firstResult | |
| } | |
| } | |
| } | |
| private actor AsyncValueProviderSpy: AsyncValueProviding { | |
| enum Call: Equatable, Sendable { | |
| case value | |
| } | |
| enum Error: Swift.Error, Equatable { | |
| case finishedWithoutResponse | |
| } | |
| private var callIterator: AsyncStream<Call>.Iterator? | |
| private let responsesContinuation: AsyncStream<Result<String, any Swift.Error>>.Continuation | |
| private let responses: AsyncStream<Result<String, any Swift.Error>> | |
| private let callEventsContinuation: AsyncStream<Call>.Continuation | |
| init() { | |
| (responses, responsesContinuation) = AsyncStream<Result<String, any Swift.Error>>.makeStream() | |
| let (callEvents, continuation) = AsyncStream<Call>.makeStream() | |
| callEventsContinuation = continuation | |
| callIterator = callEvents.makeAsyncIterator() | |
| } | |
| // Read call events sequentially; overlapping reads are a test error. | |
| func nextCall() async -> Call? { | |
| guard var iterator = callIterator else { | |
| preconditionFailure("Only one nextCall() may be active at a time") | |
| } | |
| callIterator = nil | |
| defer { callIterator = iterator } | |
| return await iterator.next(isolation: self) | |
| } | |
| nonisolated func respond(with response: Result<String, any Swift.Error>) { | |
| responsesContinuation.yield(response) | |
| } | |
| func value() async throws -> String { | |
| callEventsContinuation.yield(.value) | |
| var iterator = responses.makeAsyncIterator() | |
| guard let response = await iterator.next() else { | |
| try Task.checkCancellation() | |
| throw Error.finishedWithoutResponse | |
| } | |
| return try response.get() | |
| } | |
| } | |
| private actor SleepSpy: Sleeping { | |
| private var callIterator: AsyncStream<Duration>.Iterator? | |
| private let progressContinuation: AsyncStream<Void>.Continuation | |
| private let progress: AsyncStream<Void> | |
| private let callEventsContinuation: AsyncStream<Duration>.Continuation | |
| init() { | |
| (progress, progressContinuation) = AsyncStream<Void>.makeStream() | |
| let (callEvents, continuation) = AsyncStream<Duration>.makeStream() | |
| callEventsContinuation = continuation | |
| callIterator = callEvents.makeAsyncIterator() | |
| } | |
| // Read call events sequentially; overlapping reads are a test error. | |
| func nextCall() async -> Duration? { | |
| guard var iterator = callIterator else { | |
| preconditionFailure("Only one nextCall() may be active at a time") | |
| } | |
| callIterator = nil | |
| defer { callIterator = iterator } | |
| return await iterator.next(isolation: self) | |
| } | |
| nonisolated func resume() { | |
| progressContinuation.yield(()) | |
| } | |
| func callAsFunction(for duration: Duration) async throws { | |
| callEventsContinuation.yield(duration) | |
| // One consumer at a time: each token releases one sequential call. | |
| for await _ in progress { | |
| try Task.checkCancellation() | |
| return | |
| } | |
| // Normal completion releases current and later waits in this test double. | |
| try Task.checkCancellation() | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment