### CocoaPods Installation Source: https://context7.com/dfed/swift-testing-expectation/llms.txt Integrate the TestingExpectation pod into your test target using CocoaPods. ```ruby # Podfile target 'MyAppTests' do pod 'TestingExpectation', '~> 0.1.0' end ``` -------------------------------- ### Swift Package Manager Installation Source: https://context7.com/dfed/swift-testing-expectation/llms.txt Add the TestingExpectation package to your project's dependencies for use in test targets. ```swift // Package.swift dependencies: [ .package(url: "https://github.com/dfed/swift-testing-expectation", from: "0.1.0"), ] // In your test target: .testTarget( name: "MyAppTests", dependencies: [ "MyApp", .product(name: "TestingExpectation", package: "swift-testing-expectation"), ] ) ``` -------------------------------- ### Add swift-testing-expectation via Swift Package Manager Source: https://github.com/dfed/swift-testing-expectation/blob/main/README.md Integrate the library into your project by adding this dependency to your `Package.swift` file. ```swift dependencies: [ .package(url: "https://github.com/dfed/swift-testing-expectation", from: "0.1.0"), ] ``` -------------------------------- ### Add swift-testing-expectation via CocoaPods Source: https://github.com/dfed/swift-testing-expectation/blob/main/README.md Integrate the library into your project by adding this pod dependency to your `Podfile`. ```ruby pod 'TestingExpectation', '~> 0.1.0' ``` -------------------------------- ### Expectation - Opting Out of Awaiting Fulfillment Precondition Source: https://context7.com/dfed/swift-testing-expectation/llms.txt Demonstrates how to disable the `deinit` precondition that requires `fulfillment(within:)` to be awaited. Setting `requireAwaitingFulfillment` to `false` allows the `Expectation` to be discarded without awaiting its fulfillment, preventing potential crashes at deinitialization if fulfillment is not explicitly awaited. ```APIDOC ## Expectation - Opting Out of Awaiting Fulfillment Precondition ### Description This example shows how to disable the default behavior where the `Expectation` actor enforces that `fulfillment(within:)` must be awaited before the actor is deinitialized. By setting `requireAwaitingFulfillment` to `false` during initialization, you can opt out of this precondition, making it safe to discard an `Expectation` without explicitly awaiting its fulfillment, which can prevent test setup bugs from causing crashes. ### Method `Expectation(expectedCount: Int, requireAwaitingFulfillment: Bool)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```swift import Testing import TestingExpectation @Test func optionalExpectation() async { let expectation = Expectation(expectedCount: 1, requireAwaitingFulfillment: false) // Safe to discard without awaiting fulfillment; no precondition crash at deinit } ``` ### Response #### Success Response (200) This is a constructor example and does not have a direct response in the traditional sense. It initializes an `Expectation` actor with the specified parameters. #### Response Example None ``` -------------------------------- ### Expectation - Basic Usage Source: https://context7.com/dfed/swift-testing-expectation/llms.txt Demonstrates the basic usage of `Expectation` for a single asynchronous event. An `Expectation` is created, its `fulfill()` method is called within an asynchronous callback, and then `fulfillment(within:)` is used to await its completion with a timeout. ```APIDOC ## Expectation - Basic Usage ### Description This example shows how to use the `Expectation` actor to wait for a single asynchronous event, such as a network callback. The `Expectation` is initialized with its default `expectedCount` of 1. The `fulfill()` method is called when the asynchronous operation completes, and `await expectation.fulfillment(within:)` is used to wait for this fulfillment with a specified timeout. ### Method `await expectation.fulfillment(within: TimeInterval)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```swift import Testing import TestingExpectation @Test func networkCallbackIsInvoked() async { let expectation = Expectation() // expectedCount defaults to 1 let client = NetworkClient() client.onDataReceived = { data in // Called asynchronously at some indeterminate point in the future expectation.fulfill() } client.startFetch(url: URL(string: "https://example.com/api")!) // Waits up to 5 seconds; fails the test if not fulfilled in time await expectation.fulfillment(within: .seconds(5)) } ``` ### Response #### Success Response (200) This method does not return a value directly but either fulfills the expectation or throws a timeout error if the fulfillment does not occur within the specified duration. #### Response Example None (throws on timeout) ``` -------------------------------- ### Wait for Multiple Asynchronous Expectations in Swift Testing Source: https://github.com/dfed/swift-testing-expectation/blob/main/README.md Use this to test scenarios where multiple asynchronous events need to occur before proceeding. It simplifies waiting for several `Expectation` instances to be fulfilled simultaneously. ```swift let expectation1 = Expectation() let expectation2 = Expectation() let expectation3 = Expectation() systemUnderTest.closure1 = { expectation1.fulfill() } systemUnderTest.closure2 = { expectation2.fulfill() } systemUnderTest.closure3 = { expectation3.fulfill() } systemUnderTest.method() await Expectations(expectation1, expectation2, expectation3).fulfillment(within: .seconds(5)) ``` -------------------------------- ### Wait for Multiple Expectations Concurrently (Array) Source: https://context7.com/dfed/swift-testing-expectation/llms.txt Use the array initializer to wait for a dynamically built list of expectations to be fulfilled concurrently. This is useful when the number of expectations is determined at runtime. ```swift import Testing import TestingExpectation // --- Array initializer: dynamically built expectation list --- @Test func allItemsAreProcessed() async { let items = ["a", "b", "c", "d"] var expectations: [Expectation] = items.map { _ in Expectation() } let processor = ItemProcessor() for (index, item) in items.enumerated() { processor.onProcessed[item] = { expectations[index].fulfill() } } processor.processAll(items) await Expectations(expectations).fulfillment(within: .seconds(10)) } ``` -------------------------------- ### Expectation - Zero Expected Count Source: https://context7.com/dfed/swift-testing-expectation/llms.txt Shows the behavior of `Expectation` when initialized with an `expectedCount` of 0. In this case, the expectation is considered immediately fulfilled, and awaiting it returns without waiting. ```APIDOC ## Expectation - Zero Expected Count ### Description This example illustrates the scenario where an `Expectation` is created with an `expectedCount` of 0. When the expected count is zero, the expectation is considered immediately fulfilled, and any subsequent call to `await expectation.fulfillment(within:)` will return without any delay, as no fulfillments are required. ### Method `await expectation.fulfillment(within: TimeInterval)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```swift import Testing import TestingExpectation @Test func noCallbackExpected() async { let expectation = Expectation(expectedCount: 0) // fulfill() is never called; fulfillment(within:) returns immediately await expectation.fulfillment(within: .seconds(10)) } ``` ### Response #### Success Response (200) This method does not return a value directly but fulfills the expectation immediately because the expected count is zero. #### Response Example None ``` -------------------------------- ### Wait for Multiple Expectations Concurrently (Variadic) Source: https://context7.com/dfed/swift-testing-expectation/llms.txt Use the variadic initializer to wait for multiple independent callbacks to be fulfilled concurrently. Fails if any expectation is not fulfilled within the specified timeout. ```swift import Testing import TestingExpectation // --- Variadic initializer: wait for 3 independent callbacks --- @Test func allThreeCallbacksAreCalled() async { let expectation1 = Expectation() let expectation2 = Expectation() let expectation3 = Expectation() let system = SystemUnderTest() system.onStepOne = { expectation1.fulfill() } system.onStepTwo = { expectation2.fulfill() } system.onStepThree = { expectation3.fulfill() } system.runPipeline() // Waits for ALL three concurrently; fails if any is not fulfilled within 5s await Expectations(expectation1, expectation2, expectation3).fulfillment(within: .seconds(5)) } ``` -------------------------------- ### Expectation - Multiple Fulfillments Source: https://context7.com/dfed/swift-testing-expectation/llms.txt Illustrates how to use `Expectation` when multiple asynchronous events are expected. The `expectedCount` parameter is set to a value greater than 1, and `fulfill()` must be called that many times before the expectation is met. ```APIDOC ## Expectation - Multiple Fulfillments ### Description This example demonstrates using `Expectation` when you need to wait for multiple asynchronous events to occur. By initializing `Expectation` with an `expectedCount` greater than 1, you specify how many times the `fulfill()` method must be called before the expectation is considered met. This is useful for scenarios like tracking progress updates. ### Method `await expectation.fulfillment(within: TimeInterval)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```swift import Testing import TestingExpectation @Test func delegateReceivesThreeProgressUpdates() async { let expectation = Expectation(expectedCount: 3) let downloader = FileDownloader() downloader.onProgress = { _ in expectation.fulfill() // Must be called 3 times total } downloader.start() await expectation.fulfillment(within: .seconds(10)) } ``` ### Response #### Success Response (200) This method does not return a value directly but either fulfills the expectation or throws a timeout error if the fulfillment does not occur within the specified duration. #### Response Example None (throws on timeout) ``` -------------------------------- ### Create and Fulfill a Single Asynchronous Expectation in Swift Testing Source: https://github.com/dfed/swift-testing-expectation/blob/main/README.md Use this when you need to test asynchronous code where a closure is expected to be called at some point in the future. It requires creating an `Expectation` instance and fulfilling it within the asynchronous operation. ```swift let expectation = Expectation() systemUnderTest.closure = { expectation.fulfill() } systemUnderTest.method() await expectation.fulfillment(within: .seconds(5)) ``` -------------------------------- ### Handle Partial Fulfillment of Expectations Source: https://context7.com/dfed/swift-testing-expectation/llms.txt When using `Expectations`, partial fulfillment is reported correctly. Unfulfilled expectations will cause the test to fail, while pre-fulfilled ones pass immediately. Use `.zero` timeout for immediate checking. ```swift import Testing import TestingExpectation // --- Mixed fulfilled/unfulfilled: partial failure is reported per expectation --- @Test func partialFulfillmentReportsCorrectly() async { let fulfilled = Expectation(expectedCount: 1) let unfulfilled = Expectation(expectedCount: 1) await fulfilled.fulfill().value // Pre-fulfill one // Only `unfulfilled` will fail; `fulfilled` passes immediately await Expectations(fulfilled, unfulfilled).fulfillment(within: .zero) } ``` -------------------------------- ### Basic Expectation Usage Source: https://context7.com/dfed/swift-testing-expectation/llms.txt Assert that a callback is invoked exactly once. The `Expectation` is fulfilled when the callback is triggered, and `fulfillment(within:)` waits for this to happen within a specified timeout. ```swift import Testing import TestingExpectation // --- Basic usage: closure fires exactly once --- @Test func networkCallbackIsInvoked() async { let expectation = Expectation() // expectedCount defaults to 1 let client = NetworkClient() client.onDataReceived = { data in // Called asynchronously at some indeterminate point in the future expectation.fulfill() } client.startFetch(url: URL(string: "https://example.com/api")!) // Waits up to 5 seconds; fails the test if not fulfilled in time await expectation.fulfillment(within: .seconds(5)) } ``` -------------------------------- ### Expectation with Zero Expected Fulfillments Source: https://context7.com/dfed/swift-testing-expectation/llms.txt When `expectedCount` is 0, the `Expectation` is considered already complete. `fulfillment(within:)` will return immediately without waiting. ```swift // --- expectedCount: 0 — already complete, fulfillment returns immediately --- @Test func noCallbackExpected() async { let expectation = Expectation(expectedCount: 0) // fulfill() is never called; fulfillment(within:) returns immediately await expectation.fulfillment(within: .seconds(10)) } ``` -------------------------------- ### Expectation Opting Out of Awaiting Fulfillment Source: https://context7.com/dfed/swift-testing-expectation/llms.txt Set `requireAwaitingFulfillment` to `false` to disable the precondition check at deinitialization. This is useful for expectations that are intentionally not awaited, preventing potential crashes if they are discarded without fulfillment. ```swift // --- requireAwaitingFulfillment: false — opt out of deinit precondition --- @Test func optionalExpectation() async { let expectation = Expectation(expectedCount: 1, requireAwaitingFulfillment: false) // Safe to discard without awaiting fulfillment; no precondition crash at deinit } ``` -------------------------------- ### Fulfill Expectation from Synchronous Delegate Source: https://context7.com/dfed/swift-testing-expectation/llms.txt Use `nonisolated fulfill()` from any thread or actor context, including synchronous callbacks. Await the returned Task if actor state synchronization is needed before proceeding. ```swift import Testing import TestingExpectation // --- Called from a synchronous delegate method --- final class MyDelegate: SomeProtocolDelegate { let expectation: Expectation init(expectation: Expectation) { self.expectation = expectation } // Synchronous callback — nonisolated fulfill() is safe here func didComplete() { expectation.fulfill() } } @Test func delegateCompletionIsCalled() async { let expectation = Expectation() let delegate = MyDelegate(expectation: expectation) let system = SystemUnderTest(delegate: delegate) system.performWork() await expectation.fulfillment(within: .seconds(5)) } ``` ```swift import Testing import TestingExpectation // --- Awaiting fulfill()'s Task to synchronize actor state in tests --- @Test func fulfillAndVerifyImmediately() async { let expectation = Expectation(expectedCount: 1, requireAwaitingFulfillment: false) // Await the returned Task to ensure actor state is updated before proceeding await expectation.fulfill().value // Safe to call fulfillment now knowing the count has already been incremented await expectation.fulfillment(within: .seconds(0)) } ``` -------------------------------- ### `Expectation.fulfill()` Source: https://context7.com/dfed/swift-testing-expectation/llms.txt Marks an Expectation as fulfilled. This method is nonisolated and can be called from any thread or actor context. It returns a `Task` that can be awaited to ensure internal actor state has updated. ```APIDOC ## `Expectation.fulfill()` — Mark an Expectation as Fulfilled `fulfill()` is a `nonisolated` method that can be called from any thread or actor context, including non-async synchronous callbacks. It returns a `Task` which can be `await`ed if you need to ensure the internal actor state has updated before proceeding. ```swift import Testing import TestingExpectation // --- Called from a synchronous delegate method --- final class MyDelegate: SomeProtocolDelegate { let expectation: Expectation init(expectation: Expectation) { self.expectation = expectation } // Synchronous callback — nonisolated fulfill() is safe here func didComplete() { expectation.fulfill() } } @Test func delegateCompletionIsCalled() async { let expectation = Expectation() let delegate = MyDelegate(expectation: expectation) let system = SystemUnderTest(delegate: delegate) system.performWork() await expectation.fulfillment(within: .seconds(5)) } // --- Awaiting fulfill()'s Task to synchronize actor state in tests --- @Test func fulfillAndVerifyImmediately() async { let expectation = Expectation(expectedCount: 1, requireAwaitingFulfillment: false) // Await the returned Task to ensure actor state is updated before proceeding await expectation.fulfill().value // Safe to call fulfillment now knowing the count has already been incremented await expectation.fulfillment(within: .seconds(0)) } ``` ``` -------------------------------- ### `Expectation.fulfillment(within:)` Source: https://context7.com/dfed/swift-testing-expectation/llms.txt Suspends the current async task until the expectation is fulfilled or a specified `Duration` elapses. If the timeout expires, a test failure is recorded. If the expectation is already fulfilled, it returns immediately. ```APIDOC ## `Expectation.fulfillment(within:)` — Await Completion with Timeout `fulfillment(within:)` suspends the current async task until the expectation is fulfilled or the given `Duration` elapses. If the timeout expires before fulfillment, a test failure is recorded via Swift Testing's `#expect` at the call site. If the expectation is already fulfilled when called, it returns immediately without sleeping. ```swift import Testing import TestingExpectation // --- Immediate return when already fulfilled --- @Test func alreadyFulfilledExpectationReturnsImmediately() async { let expectation = Expectation(expectedCount: 0) // starts fulfilled // Returns immediately, no sleeping await expectation.fulfillment(within: .seconds(10)) } // --- Timeout failure: test fails with a descriptive message --- @Test func timeoutIsReportedAsTestFailure() async { let expectation = Expectation(expectedCount: 1) // fulfill() is never called; after .zero elapses, #expect fails with: // "Expectation not fulfilled within 0 seconds" await expectation.fulfillment(within: .zero) } // --- Typical pattern: set up → trigger → await --- @Test func buttonTapFiresAnalyticsEvent() async { let expectation = Expectation() let tracker = AnalyticsTracker() tracker.onEvent = { if event.name == "button_tapped" { expectation.fulfill() } } let viewModel = ButtonViewModel(tracker: tracker) viewModel.handleButtonTap() // Test suspends here; resumes when fulfill() cancels the sleep Task await expectation.fulfillment(within: .seconds(2)) } ``` ``` -------------------------------- ### Await Expectation Fulfillment with Timeout Source: https://context7.com/dfed/swift-testing-expectation/llms.txt Suspends the current async task until the expectation is fulfilled or the timeout elapses. If the timeout expires, a test failure is recorded. Returns immediately if already fulfilled. ```swift import Testing import TestingExpectation // --- Immediate return when already fulfilled --- @Test func alreadyFulfilledExpectationReturnsImmediately() async { let expectation = Expectation(expectedCount: 0) // starts fulfilled // Returns immediately, no sleeping await expectation.fulfillment(within: .seconds(10)) } ``` ```swift import Testing import TestingExpectation // --- Timeout failure: test fails with a descriptive message --- @Test func timeoutIsReportedAsTestFailure() async { let expectation = Expectation(expectedCount: 1) // fulfill() is never called; after .zero elapses, #expect fails with: // "Expectation not fulfilled within 0 seconds" await expectation.fulfillment(within: .zero) } ``` ```swift import Testing import TestingExpectation // --- Typical pattern: set up → trigger → await --- @Test func buttonTapFiresAnalyticsEvent() async { let expectation = Expectation() let tracker = AnalyticsTracker() tracker.onEvent = { event in if event.name == "button_tapped" { expectation.fulfill() } } let viewModel = ButtonViewModel(tracker: tracker) viewModel.handleButtonTap() // Test suspends here; resumes when fulfill() cancels the sleep Task await expectation.fulfillment(within: .seconds(2)) } ``` -------------------------------- ### Expectation with Multiple Fulfillments Source: https://context7.com/dfed/swift-testing-expectation/llms.txt Use `expectedCount` greater than 1 to assert that a callback is invoked multiple times. The expectation is only considered met after `fulfill()` has been called the specified number of times. ```swift // --- expectedCount > 1: fulfill() must be called N times --- @Test func delegateReceivesThreeProgressUpdates() async { let expectation = Expectation(expectedCount: 3) let downloader = FileDownloader() downloader.onProgress = { _ in expectation.fulfill() // Must be called 3 times total } downloader.start() await expectation.fulfillment(within: .seconds(10)) } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.