### Convert XCTest Setup to Swift Init Source: https://developer.apple.com/documentation/testing/migratingfromxctest Replace XCTest's setUp() with Swift's init() for initializing test state. The use of async and throws is optional. ```swift // Before class FoodTruckTests: XCTestCase { var batteryLevel: NSNumber! override func setUp() async throws { batteryLevel = 100 } ... } ``` ```swift // After struct FoodTruckTests { var batteryLevel: NSNumber init() async throws { batteryLevel = 100 } ... } ``` -------------------------------- ### Deprecated Usage Example for require(_:sourceLocation:performing:throws:) Source: https://developer.apple.com/documentation/testing/require%28_%3Asourcelocation%3Aperforming%3Athrows%3A%29 This example shows the deprecated usage of the `require` macro. It captures the thrown error for further inspection. ```swift let error = try #require(throws: FoodTruckError.self) { ... } #expect(error.napkinCount == 0) ``` -------------------------------- ### Example of using withKnownIssue Source: https://developer.apple.com/documentation/testing/withknownissue%28_%3Aisintermittent%3Aisolation%3Asourcelocation%3A_%3A%29 This example demonstrates how to use `withKnownIssue` to handle a potentially flaky asynchronous call within a test. ```swift @Test func example() { await withKnownIssue { try await flakyCall() } } ``` -------------------------------- ### Usage Example for withKnownIssue Source: https://developer.apple.com/documentation/testing/withknownissue%28_%3Aisintermittent%3Asourcelocation%3A_%3Awhen%3Amatching%3A%29 Demonstrates wrapping a potentially flaky call with a precondition and an issue matcher to handle expected errors. ```swift @Test func example() throws { try withKnownIssue { try flakyCall() } when: { callsAreFlakyOnThisPlatform() } matching: { issue in issue.error is FileNotFoundError } } ``` -------------------------------- ### Deprecated Usage Example Source: https://developer.apple.com/documentation/testing/expect%28_%3Asourcelocation%3Aperforming%3Athrows%3A%29 This example shows how to use the deprecated `expect` macro to capture an error and then assert a property of that error. Consider using the alternative `expect(throws:_:sourceLocation:performing:)` or `expect(throws:_:sourceLocation:performing:)` instead. ```swift let error = #expect(throws: FoodTruckError.self) { ... } #expect(error?.napkinCount == 0) ``` -------------------------------- ### Test process termination with fatalError() Source: https://developer.apple.com/documentation/testing/expect%28processexitswith%3Aobserving%3A_%3Asourcelocation%3Aperforming%3A%29 Example demonstrating how to use the `expect` macro to verify that calling `fatalError()` causes the process to terminate with a failure. ```swift await #expect(processExitsWith: .failure) { fatalError() } ``` -------------------------------- ### Test process termination with require Source: https://developer.apple.com/documentation/testing/require%28processexitswith%3Aobserving%3A_%3Asourcelocation%3Aperforming%3A%29 Example usage of the require macro to verify that a fatalError call causes a process failure. ```Swift try await #require(processExitsWith: .failure) { fatalError() } ``` -------------------------------- ### Define Customer and Test Process Exit Source: https://developer.apple.com/documentation/testing/exit-testing Example showing a Customer class method and a test case that validates process failure while observing standard output. ```swift extension Customer { func eat(_ food: consuming some Food) { print("Let's see if I want to eat \(food)...") precondition(food.isDelicious, "Tasty food only!") precondition(food.isNutritious, "Healthy food only!") ... } } @Test func `Customer won't eat food unless it's delicious`() async { let result = await #expect( processExitsWith: .failure, observing: [\.standardOutputContent] ) { var food = ... food.isDelicious = false Customer.current.eat(food) } if let result { #expect(result.standardOutputContent.contains(UInt8(ascii: "L"))) } } ``` -------------------------------- ### Bug identifier trait examples Source: https://developer.apple.com/documentation/testing/bugidentifiers Examples of how different bug trait configurations are interpreted by the testing library. ```Swift .bug(id: 12345) ``` ```Swift .bug(id: "12345") ``` ```Swift .bug("https://www.example.com?id=12345", id: "12345") ``` ```Swift .bug("https://github.com/swiftlang/swift/pull/12345") ``` ```Swift .bug("https://bugs.webkit.org/show_bug.cgi?id=12345") ``` ```Swift .bug(id: "FB12345") ``` -------------------------------- ### Observing Child Process Output with `expect` Source: https://developer.apple.com/documentation/testing/exit-testing This example demonstrates how to use the `expect(processExitsWith:observing:_:sourceLocation:performing:)` macro to capture and assert on the standard output of a child process. ```APIDOC ## POST /api/users ### Description This endpoint allows for the creation of a new user in the system. ### Method POST ### Endpoint /api/users ### Parameters #### Query Parameters - **fields** (string) - Optional - Comma-separated list of fields to include in the response. #### Request Body - **username** (string) - Required - The desired username for the new user. - **email** (string) - Required - The email address of the new user. - **password** (string) - Required - The password for the new user. ### Request Example ```json { "username": "johndoe", "email": "john.doe@example.com", "password": "securepassword123" } ``` ### Response #### Success Response (201) - **id** (string) - The unique identifier for the newly created user. - **username** (string) - The username of the created user. - **email** (string) - The email address of the created user. #### Response Example ```json { "id": "user-12345", "username": "johndoe", "email": "john.doe@example.com" } ``` ``` -------------------------------- ### Use confirmation to verify event occurrences Source: https://developer.apple.com/documentation/testing/confirmation%28_%3Aexpectedcount%3Aisolation%3Asourcelocation%3A_%3A%29-l3il Example demonstrating how to use a confirmation to verify that a specific event occurs a set number of times within a closure. ```swift let minBuns = 5 let maxBuns = 10 await confirmation( "Baked between \(minBuns) and \(maxBuns) buns", expectedCount: minBuns ... maxBuns ) { bunBaked in foodTruck.eventHandler = { event in if event == .baked(.cinnamonBun) { bunBaked() } } await foodTruck.bakeTray(of: .cinnamonBun) } ``` -------------------------------- ### Example usage of withKnownIssue Source: https://developer.apple.com/documentation/testing/withknownissue%28_%3Aisintermittent%3Aisolation%3Asourcelocation%3A_%3Awhen%3Amatching%3A%29 Demonstrates wrapping a potentially failing call with a precondition and an issue matcher to suppress specific errors. ```swift @Test func example() async throws { try await withKnownIssue { try await flakyCall() } when: { callsAreFlakyOnThisPlatform() } matching: { issue in issue.error is FileNotFoundError } } ``` -------------------------------- ### GET testDescription Source: https://developer.apple.com/documentation/testing/customteststringconvertible/testdescription-3ar66 Retrieves the description of an instance for use in test output. ```APIDOC ## Property: testDescription ### Description A description of this instance to use when presenting it in a test’s output. This property is available when the type conforms to StringProtocol. ### Declaration `var testDescription: String { get }` ### Discussion Do not use this property directly. To get the test description of a value, use `Swift/String/init(describingForTest:)`. ``` -------------------------------- ### Example: Handling Nondeterministic Failures Source: https://developer.apple.com/documentation/testing/known-issues Illustrates how to use `withKnownIssue` with a `when` condition or `isIntermittent` flag to manage unpredictable test outcomes. ```APIDOC ## Handle a nondeterministic failure If `withKnownIssue()` sometimes succeeds but other times records an issue indicating there were no known issues, this may indicate a nondeterministic failure or a “flaky” test. ### Using a `when` condition: ```swift @Test func grillHeating() throws { var foodTruck = FoodTruck() try foodTruck.startGrill() withKnownIssue { // Only considered known when hasPropane == false #expect(foodTruck.grill.isHeating) } when: { !hasPropane } } ``` ### Using `isIntermittent: true`: ```swift @Test func grillHeating() throws { var foodTruck = FoodTruck() try foodTruck.startGrill() withKnownIssue(isIntermittent: true) { #expect(foodTruck.grill.isHeating) } } ``` ``` -------------------------------- ### Example of a function causing process exit Source: https://developer.apple.com/documentation/testing/exit-testing This Swift code demonstrates a function that uses `precondition` to enforce conditions, which can cause the process to exit if the conditions are not met. ```swift extension Customer { func eat(_ food: consuming some Food) { precondition(food.isDelicious, "Tasty food only!") precondition(food.isNutritious, "Healthy food only!") ... } } ``` -------------------------------- ### GET moduleName Property Source: https://developer.apple.com/documentation/testing/sourcelocation/modulename Retrieves the module name associated with a source file instance. ```APIDOC ## GET moduleName ### Description The name of the module containing the source file. The value is derived from the instance's fileID property by taking the substring up to the first forward-slash character. ### Method GET ### Endpoint moduleName ### Response - **moduleName** (String) - The name of the module containing the source file. ### Response Example { "moduleName": "FoodTruck" } ``` -------------------------------- ### Convert XCTest Teardown to Swift Deinit Source: https://developer.apple.com/documentation/testing/migratingfromxctest For teardown logic, declare the test suite as a class or actor and implement deinit. This is an alternative to using init for setup. ```swift // Before class FoodTruckTests: XCTestCase { var batteryLevel: NSNumber! override func setUp() async throws { batteryLevel = 100 } override func tearDown() { batteryLevel = 0 // drain the battery } ... } ``` ```swift // After final class FoodTruckTests { var batteryLevel: NSNumber init() async throws { batteryLevel = 100 } deinit { batteryLevel = 0 // drain the battery } ... } ``` -------------------------------- ### Swift Example: Expecting a Specific Error Source: https://developer.apple.com/documentation/testing/expect%28throws%3A_%3Asourcelocation%3Aperforming%3A%29-7du1h Use this overload of `#expect()` when the expression is expected to throw a specific error. If the expression does not throw, or throws a different error, an issue is recorded. ```swift #expect(throws: EngineFailureError.batteryDied) { FoodTruck.shared.engine.batteryLevel = 0 try FoodTruck.shared.engine.start() } ``` -------------------------------- ### Initialize SourceLocation Source: https://developer.apple.com/documentation/testing/sourcelocation/init%28fileid%3Afilepath%3Aline%3Acolumn%3A%29 Use this initializer to create a SourceLocation instance. Ensure that `fileID` is not empty and correctly formatted, and that `line` and `column` are greater than 0. ```swift init( fileID: String, filePath: String, line: Int, column: Int ) ``` -------------------------------- ### Equivalent Test Suite Structure Source: https://developer.apple.com/documentation/testing/organizingtests Demonstrates an equivalent structure where instance methods are explicitly called on a new instance, illustrating how the testing library handles instance methods within a suite. ```swift @Suite struct FoodTruckTests { func foodTruckExists() { ... } @Test static func staticFoodTruckExists() { let instance = FoodTruckTests() instance.foodTruckExists() } } ``` -------------------------------- ### Define prepare(for:) method Source: https://developer.apple.com/documentation/testing/trait/prepare%28for%3A%29-4pe01 Implement this method to prepare internal state or validate conditions before a test runs. Errors thrown here will skip the test and record an issue. ```Swift func prepare(for test: Test) async throws ``` -------------------------------- ### Report Cross-Library Issues from XCTest Source: https://developer.apple.com/documentation/testing/migratingfromxctest Use `complete` mode to ensure cross-library issues from XCTest maintain their original severity. This example uses `XCTFail` within a Swift Testing test case. ```swift // Cross-library issues from XCTest @Test func `Test Interop`() { XCTFail("Interop failure") } ``` -------------------------------- ### Instance Method: prepare(for:) Source: https://developer.apple.com/documentation/testing/trait/prepare%28for%3A%29-4pe01 Prepares the test environment for a specific test case. This method is invoked after all tests and their traits are discovered and before any tests begin execution. It's used for setting up internal states or deciding test eligibility. The default implementation does nothing. ```APIDOC ## Instance Method: prepare(for:) ### Description Prepare to run the test that has this trait. ### Method Signature ```swift func prepare(for test: Test) async throws ``` ### Parameters #### `test` (Test) - Required The test that has this trait. ### Discussion This method is called by the testing library after it discovers all tests and their traits, and before it begins to run any tests. Use this method to prepare necessary internal state, or to determine whether the test should run. ### Throws Any error that prevents the test from running. If an error is thrown from this method, the test is skipped and the error is recorded as an `Issue`. ### Platforms iOS, iPadOS, Mac Catalyst, macOS, tvOS, visionOS, watchOS ### Requirements Swift 6.0+, Xcode 16.0+ ``` -------------------------------- ### Example: Expecting a Specific Error Type Source: https://developer.apple.com/documentation/testing/expect%28throws%3A_%3Asourcelocation%3Aperforming%3A%29-1hfms Use this overload of `#expect()` when the expression is expected to throw an error of a specific type. If the expression does not throw, or throws an error of a different type, an issue is recorded. ```swift #expect(throws: EngineFailureError.self) { FoodTruck.shared.engine.batteryLevel = 0 try FoodTruck.shared.engine.start() } ``` -------------------------------- ### Initialize AttachableImageFormat with Path Extension Source: https://developer.apple.com/documentation/testing/attachableimageformat Construct an instance using a file path extension and encoding quality. ```swift init?(pathExtension: String, encodingQuality: Float) ``` -------------------------------- ### GET /Attachment/preferredName Source: https://developer.apple.com/documentation/testing/attachment/preferredname Retrieves the preferred filename for an attachment instance. ```APIDOC ## GET preferredName ### Description A filename to use when saving this attachment. The testing library uses this value as a hint and may substitute a different filename if necessary. ### Method GET ### Endpoint preferredName ### Response #### Success Response (200) - **preferredName** (String) - The filename hint for the attachment. ### Response Example { "preferredName": "test_report.txt" } ``` -------------------------------- ### init(_:named:as:sourceLocation:) Source: https://developer.apple.com/documentation/testing/attachment/init%28_%3Anamed%3Aas%3Asourcelocation%3A%29 Initializes an instance of an Attachable type that encloses the given image, with options for preferred naming, image format, and source location. ```APIDOC ## init(_:named:as:sourceLocation:) ### Description Initialize an instance of this type that encloses the given image. ### Parameters `image` (T) - The value that will be attached to the output of the test run. `preferredName` (String?) - The preferred name of the attachment when writing it to a test report or to disk. If `nil`, the testing library attempts to derive a reasonable filename for the attached value. `imageFormat` (AttachableImageFormat?) - The image format with which to encode `image`. Pass `nil` to let the testing library decide. `sourceLocation` (SourceLocation) - The source location of the call to this initializer. This value is used when recording issues associated with the attachment. ### Discussion The testing library uses the image format specified by `imageFormat`. Pass `nil` to let the testing library decide which image format to use. If you pass `nil`, then the image format that the testing library uses depends on the path extension you specify in `preferredName`, if any. If you do not specify a path extension, or if the path extension you specify doesn’t correspond to an image format the operating system knows how to write, the testing library selects an appropriate image format for you. ### Availability Swift 6.3+ Xcode 26.4+ ### Constraints Available when `AttachableValue` conforms to `Attachable`. ### Signature ```swift init( _ image: T, named preferredName: String? = nil, as imageFormat: AttachableImageFormat? = nil, sourceLocation: SourceLocation = #_sourceLocation ) where AttachableValue : _AttachableImageWrapper, AttachableValue : AttachableWrapper, T : AttachableAsImage ``` ``` -------------------------------- ### GET wrappedValue Source: https://developer.apple.com/documentation/testing/attachablewrapper/wrappedvalue Retrieves the underlying value from an AttachableWrapper instance. ```APIDOC ## GET wrappedValue ### Description The underlying value represented by this instance. ### Method GET ### Endpoint wrappedValue ### Response #### Success Response (200) - **wrappedValue** (Self.Wrapped) - The underlying value represented by this instance. ``` -------------------------------- ### GET Trait.comments Source: https://developer.apple.com/documentation/testing/trait/comments Retrieves the user-provided comments associated with a specific trait. ```APIDOC ## GET Trait.comments ### Description Returns the collection of user-provided comments associated with a trait. The default value is an empty array. ### Property Definition `var comments: [Comment] { get }` ### Availability - iOS, iPadOS, Mac Catalyst, macOS, tvOS, visionOS, watchOS - Swift 6.0+ - Xcode 16.0+ ### Response - **comments** ([Comment]) - An array of user-provided comments for the trait. ``` -------------------------------- ### init(pathExtension:encodingQuality:) Source: https://developer.apple.com/documentation/testing/attachableimageformat/init%28pathextension%3Aencodingquality%3A%29 Constructs an instance of AttachableImageFormat. The path extension determines the image format, and encodingQuality specifies the compression level. ```APIDOC ## init(pathExtension:encodingQuality:) ### Description Construct an instance of this type with the given path extension and encoding quality. ### Parameters #### Path Parameters - **pathExtension** (String) - Required - A path extension corresponding to the image format to use when encoding images. - **encodingQuality** (Float) - Optional - The encoding quality to use when encoding images. For the lowest supported quality, pass `0.0`. For the highest supported quality, pass `1.0`. Defaults to `1.0`. ### Discussion If the target image format does not support variable-quality encoding, the value of the `encodingQuality` argument is ignored. If `pathExtension` does not correspond to a recognized image format, this initializer returns `nil`. ``` -------------------------------- ### GET /SuiteTrait/isRecursive Source: https://developer.apple.com/documentation/testing/suitetrait/isrecursive-2z41z Documentation for the isRecursive instance property of the SuiteTrait class. ```APIDOC ## GET isRecursive ### Description Returns a boolean value indicating whether the instance should be applied recursively to child test suites and test functions. ### Method GET ### Endpoint isRecursive ### Response #### Success Response (200) - **isRecursive** (Bool) - If true, the trait is applied recursively to children. If false, it only applies to the suite to which it was added. Defaults to false. ``` -------------------------------- ### init(contentsOf:named:sourceLocation:) Source: https://developer.apple.com/documentation/testing/attachment/init%28contentsof%3Anamed%3Asourcelocation%3A%29 Initializes an Attachment instance with the contents of a given URL, supporting both files and directories. ```APIDOC ## init(contentsOf:named:sourceLocation:) ### Description Initialize an instance of this type with the contents of the given URL. This initializer suspends the calling task while it reads or maps the file contents or zips a directory. ### Parameters #### Path Parameters - **url** (URL) - Required - The URL containing the attachment’s data. - **preferredName** (String?) - Optional - The preferred name of the attachment when writing it to a test report or to disk. If nil, the name is derived from the last path component of the URL. - **sourceLocation** (SourceLocation) - Required - The source location of the call to this initializer, used when recording issues. ### Request Example ```swift let url = try await FoodTruck.saveMenu(as: .pdf) let attachment = try await Attachment(contentsOf: url) Attachment.record(attachment) ``` ### Response #### Success Response - **Attachment** (Instance) - An instance of Attachment representing the local file or directory. #### Errors - Throws any error that occurs attempting to read from the provided URL. ``` -------------------------------- ### GET comments property Source: https://developer.apple.com/documentation/testing/trait/comments-5i8gy Retrieves the user-provided comments associated with a specific trait. ```APIDOC ## GET comments ### Description The comments property returns an array of user-provided comments associated with a trait. The default value is an empty array. ### Method GET ### Endpoint comments ### Response #### Success Response (200) - **comments** ([Comment]) - An array of user-provided comments for the trait. ### Response Example { "comments": [] } ``` -------------------------------- ### GET current Test Source: https://developer.apple.com/documentation/testing/test/current Retrieves the test currently running on the current task, if any. ```APIDOC ## static var current ### Description The test that is running on the current task, if any. If no test is currently running, or if the task is detached from the test execution context, the value is nil. ### Method GET ### Endpoint Test.current ### Response #### Success Response (200) - **current** (Test?) - The test instance currently running, or nil if none is active. ### Response Example { "current": "TestInstance" } ``` -------------------------------- ### SourceLocation Initializer Source: https://developer.apple.com/documentation/testing/sourcelocation/init%28fileid%3Afilepath%3Aline%3Acolumn%3A%29 Initializes a SourceLocation instance with file and line information. ```APIDOC ## init(fileID:filePath:line:column:) ### Description Initialize an instance of this type with the specified location details. ### Method Initializer ### Endpoint N/A (This is a Swift initializer, not a web endpoint) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```swift let location = SourceLocation(fileID: "MyFile.swift", filePath: "/path/to/MyFile.swift", line: 10, column: 5) ``` ### Response #### Success Response (200) N/A (Initializers do not return HTTP responses) #### Response Example N/A ### Parameters - **fileID** (String) - Required - The file ID of the source file, using the format described in the documentation for the `#fileID` macro in the Swift standard library. - **filePath** (String) - Required - The path to the source file. - **line** (Int) - Required - The line in the source file. Must be greater than 0. - **column** (Int) - Required - The column in the source file. Must be greater than 0. ### Discussion Precondition `fileID` must not be empty and must be formatted as described in the documentation for `#fileID`. Precondition `line` must be greater than `0`. Precondition `column` must be greater than `0`. ``` -------------------------------- ### GET isParameterized Property Source: https://developer.apple.com/documentation/testing/test/isparameterized Retrieves the boolean status indicating if a test is parameterized. ```APIDOC ## Property: isParameterized ### Description Returns a boolean value indicating whether or not the test is parameterized. ### Definition `var isParameterized: Bool { get }` ### Compatibility - iOS - iPadOS - Mac Catalyst - macOS - tvOS - visionOS - watchOS - Swift 6.0+ - Xcode 16.0+ ``` -------------------------------- ### GET isParameterized Source: https://developer.apple.com/documentation/testing/test/case/isparameterized Retrieves the boolean status indicating if a test case is parameterized. ```APIDOC ## GET isParameterized ### Description Returns a boolean value indicating whether or not the test case is from a parameterized test. ### Method GET ### Endpoint Test.Case.isParameterized ### Response #### Success Response (200) - **isParameterized** (Bool) - True if the test case is parameterized, false otherwise. ### Response Example { "isParameterized": true } ``` -------------------------------- ### GET SourceLocation.line Source: https://developer.apple.com/documentation/testing/sourcelocation/line Accesses or modifies the line number associated with a source location. ```APIDOC ## var line ### Description The line in the source file. ### Property Definition `var line: Int { get set }` ### Discussion The value of this property must be greater than 0. ### Compatibility - iOS - iPadOS - Mac Catalyst - macOS - tvOS - visionOS - watchOS - Swift 6.0+ - Xcode 16.0+ ``` -------------------------------- ### Method: prepare(for:) Source: https://developer.apple.com/documentation/testing/trait/prepare%28for%3A%29 Prepares the test environment for a test that possesses the trait. ```APIDOC ## prepare(for:) ### Description Prepares to run the test that has this trait. The testing library calls this method after discovering all tests and their traits, but before execution begins. ### Method Instance Method ### Parameters #### Path Parameters - **test** (Test) - Required - The test that has this trait. ### Discussion - **Throws**: Any error that prevents the test from running. If an error is thrown, the test is skipped and the error is recorded as an Issue. - **Default Implementation**: The default implementation does nothing. ``` -------------------------------- ### GET /SwiftTesting/Expectation/isRequired Source: https://developer.apple.com/documentation/testing/expectation/isrequired Documentation for the isRequired instance property in the Swift Testing framework. ```APIDOC ## isRequired ### Description Whether or not the expectation was required to pass. ### Property Definition `var isRequired: Bool` ### Compatibility - iOS - iPadOS - Mac Catalyst - macOS - tvOS - visionOS - watchOS - Swift 6.0+ - Xcode 16.0+ ``` -------------------------------- ### GET /CustomStringConvertible/description Source: https://developer.apple.com/documentation/testing/attachableimageformat/customstringconvertible-implementations Retrieves the string representation of an object conforming to the CustomStringConvertible protocol. ```APIDOC ## GET /CustomStringConvertible/description ### Description Returns a string representation of the object, typically used for debugging or logging purposes. ### Method GET ### Endpoint /CustomStringConvertible/description ### Response #### Success Response (200) - **description** (String) - The string representation of the object. #### Response Example { "description": "Example object description" } ``` -------------------------------- ### GET comments property Source: https://developer.apple.com/documentation/testing/test/comments Access the collection of comments associated with a specific test instance. ```APIDOC ## Property: comments ### Description The complete set of comments about this test from all of its traits. ### Declaration `var comments: [Comment] { get }` ### Compatibility - iOS - iPadOS - Mac Catalyst - macOS - tvOS - visionOS - watchOS - Swift 6.0+ - Xcode 16.0+ ``` -------------------------------- ### Import the Testing Library Source: https://developer.apple.com/documentation/testing/definingtests Add this import statement to your Swift source file to use the Testing library. ```swift import Testing ``` -------------------------------- ### GET /swift-testing/expectation/isPassing Source: https://developer.apple.com/documentation/testing/expectation/ispassing Documentation for the isPassing instance property used to determine the status of an expectation. ```APIDOC ## Property: isPassing ### Description Indicates whether an expectation passed or failed. An expectation is considered to pass when its condition evaluates to true; otherwise, it fails. ### Definition var isPassing: Bool ### Compatibility - iOS, iPadOS, Mac Catalyst, macOS, tvOS, visionOS, watchOS - Swift 6.0+ - Xcode 16.0+ ``` -------------------------------- ### Initializer: init(_:named:sourceLocation:) Source: https://developer.apple.com/documentation/testing/attachment/init%28_%3Anamed%3Asourcelocation%3A%29 Initializes an instance of a type that encloses the given attachable value for Swift Testing. ```APIDOC ## Initializer: init(_:named:sourceLocation:) ### Description Initialize an instance of this type that encloses the given attachable value. ### Method `init` ### Endpoint N/A (This is a Swift initializer, not an API endpoint) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```swift init( _ attachableValue: consuming AttachableValue, named preferredName: String? = nil, sourceLocation: SourceLocation = #_sourceLocation ) ``` ### Response #### Success Response (200) N/A (Initializers do not return HTTP responses) #### Response Example N/A ### Parameters Details - **attachableValue** (consuming AttachableValue) - Required - The value that will be attached to the output of the test run. - **preferredName** (String?) - Optional - The preferred name of the attachment to use when saving it. If `nil`, the testing library attempts to generate a reasonable filename for the attached value. - **sourceLocation** (SourceLocation) - Optional - The source location of the call to this initializer. This value is used when recording issues associated with the attachment. ``` -------------------------------- ### GET ExitTest.Condition.success Source: https://developer.apple.com/documentation/testing/exittest/condition/success Documentation for the success property used to verify that a process exits normally. ```APIDOC ## GET ExitTest.Condition.success ### Description A condition that matches when a process exits normally, specifically matching the exit code EXIT_SUCCESS. ### Method GET ### Endpoint ExitTest.Condition.success ### Response #### Success Response (200) - **success** (static var) - A condition that matches when a process exits normally. ``` -------------------------------- ### Create and Record an Attachment Source: https://developer.apple.com/documentation/testing/attachment/init%28contentsof%3Anamed%3Asourcelocation%3A%29 Demonstrates creating an attachment from a saved file URL and recording it for test reporting. ```Swift let url = try await FoodTruck.saveMenu(as: .pdf) let attachment = try await Attachment(contentsOf: url) Attachment.record(attachment) ``` -------------------------------- ### GET SourceLocation.column Source: https://developer.apple.com/documentation/testing/sourcelocation/column Retrieves or sets the column number in the source file for a given SourceLocation instance. ```APIDOC ## Property: column ### Description The column in the source file. The value of this property must be greater than 0. ### Declaration ```swift var column: Int { get set } ``` ### Compatibility - iOS, iPadOS, Mac Catalyst, macOS, tvOS, visionOS, watchOS - Swift 6.0+ - Xcode 16.0+ ``` -------------------------------- ### Initialize Attachment from URL Source: https://developer.apple.com/documentation/testing/attachment/init%28contentsof%3Anamed%3Asourcelocation%3A%29 Defines the initializer signature for creating an Attachment instance from a URL. ```Swift init( contentsOf url: URL, named preferredName: String? = nil, sourceLocation: SourceLocation = #_sourceLocation ) async throws ``` -------------------------------- ### GET sourceLocation Property Source: https://developer.apple.com/documentation/testing/issue/sourcelocation Access the source location of an issue within the Swift Testing framework. ```APIDOC ## Property: sourceLocation ### Description The location in source where this issue occurred, if available. ### Definition `var sourceLocation: SourceLocation? { get set }` ### Compatibility - iOS - iPadOS - Mac Catalyst - macOS - tvOS - visionOS - watchOS - Swift 6.0+ - Xcode 16.0+ ``` -------------------------------- ### Initialize AttachableImageFormat with Content Type Source: https://developer.apple.com/documentation/testing/attachableimageformat Initialize an instance with a specific content type and encoding quality. ```swift init(contentType: UTType, encodingQuality: Float) ``` -------------------------------- ### Declare a Test Suite with Macro Source: https://developer.apple.com/documentation/testing/organizingtests Use the `Suite` macro to declare a test suite. You can optionally provide a string name and any relevant suite traits. ```swift macro Suite(String?, any SuiteTrait...) ``` -------------------------------- ### Example: Expecting No Error Source: https://developer.apple.com/documentation/testing/expect%28throws%3A_%3Asourcelocation%3Aperforming%3A%29-1hfms Pass `Never.self` to `throws` when the expression should not throw any error. If an error is thrown, an issue is recorded. ```swift #expect(throws: Never.self) { FoodTruck.shared.engine.batteryLevel = 100 try FoodTruck.shared.engine.start() } ``` -------------------------------- ### Initialize AttachableImageFormat Source: https://developer.apple.com/documentation/testing/attachableimageformat/init%28pathextension%3Aencodingquality%3A%29 Use this initializer to create an AttachableImageFormat instance. Provide a path extension for the desired image format and an optional encoding quality. The initializer returns nil if the path extension is not recognized or if the image format does not support variable-quality encoding. ```swift init?( pathExtension: String, encodingQuality: Float = 1.0 ) ``` -------------------------------- ### Instance Method: withUnsafeBytes(for:) Source: https://developer.apple.com/documentation/testing/attachable/withunsafebytes%28for%3A_%3A%29-4m3s9 Encodes an instance into a buffer and executes a closure with that buffer. ```APIDOC ## withUnsafeBytes(for:) ### Description Encode this value into a buffer using either PropertyListEncoder or JSONEncoder, then call a function and pass that buffer to it. ### Method Instance Method ### Parameters #### Parameters - **attachment** (borrowing Attachment) - Required - The attachment that is requesting a buffer. - **body** ((UnsafeRawBufferPointer) throws -> R) - Required - A function to call. A temporary buffer containing a data representation of this instance is passed to it. ### Return Value - **R** - Whatever is returned by body. ### Discussion - **Throws**: Whatever is thrown by body, or any error that prevented the creation of the buffer. - **Encoding Logic**: The encoding used depends on the path extension specified by the value of attachment’s preferredName property: - ".xml": XML property list (PropertyListEncoder) - ".plist": Binary property list (PropertyListEncoder) - None, ".json": JSON (JSONEncoder) ``` -------------------------------- ### Initialize Attachment with Image Source: https://developer.apple.com/documentation/testing/attachableasimage Initializes an Attachment instance by enclosing a given image. The testing library handles the conversion to image data. ```swift init(T, named: String?, as: AttachableImageFormat?, sourceLocation: SourceLocation) ``` -------------------------------- ### Expect and Require Process Exits Source: https://developer.apple.com/documentation/testing/expectations Use `expect` to check if a process terminates with a specific condition and `require` to do the same but throw an error if it doesn't. The `observing` parameter allows monitoring specific result properties. ```swift macro expect(processExitsWith: ExitTest.Condition, observing: [any PartialKeyPath & Sendable], @autoclosure () -> Comment?, sourceLocation: SourceLocation, performing: () async throws -> Void) -> ExitTest.Result? ``` ```swift macro require(processExitsWith: ExitTest.Condition, observing: [any PartialKeyPath & Sendable], @autoclosure () -> Comment?, sourceLocation: SourceLocation, performing: () async throws -> Void) -> ExitTest.Result ``` -------------------------------- ### Invalid Test Suite Type Availability Source: https://developer.apple.com/documentation/testing/organizingtests An example of an invalid test suite type annotated with @available, which is prohibited and results in a compiler error. ```swift @available(macOS 11.0, *) // ❌ ERROR: The suite type must always be available. @Suite struct CashRegisterTests { ... } ``` -------------------------------- ### ConditionTrait Instance Methods Source: https://developer.apple.com/documentation/testing/conditiontrait Details about the instance methods available for ConditionTrait. ```APIDOC ## Instance Methods `func evaluate() async throws -> Bool` Evaluate this instance’s underlying condition. ``` -------------------------------- ### Access attachableValue Property Source: https://developer.apple.com/documentation/testing/attachment/attachablevalue-vkrw Use this property to get the underlying value of an attachment when it conforms to `AttachableWrapper`. Available in Swift 6.2+ and Xcode 26.0+. ```swift var attachableValue: AttachableValue.Wrapped { get } ``` -------------------------------- ### Macro: require(_:_:sourceLocation:) Source: https://developer.apple.com/documentation/testing/require%28_%3A_%3Asourcelocation%3A%29-6w9oo Unwraps an optional value. If the value is nil, it records an issue and throws an ExpectationFailedError. ```APIDOC ## Macro: require(_:_:sourceLocation:) ### Description Unwrap an optional value or, if it is `nil`, fail and throw an error. ### Method Macro ### Endpoint N/A (Swift Macro) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (200) The unwrapped value of `optionalValue`. #### Response Example N/A ### Error Handling Throws an instance of `ExpectationFailedError` if `optionalValue` is `nil`. An `Issue` is recorded for the test that is running in the current task. ``` -------------------------------- ### init(exporting:as:named:sourceLocation:) Source: https://developer.apple.com/documentation/testing/attachment/init%28exporting%3Aas%3Anamed%3Asourcelocation%3A%29 Initializes an Attachment with a transferable value, optionally specifying content type, preferred name, and source location. The initializer suspends the calling task until the export operation is complete. ```APIDOC ## init(exporting:as:named:sourceLocation:) ### Description Initializes an instance of this type that encloses the given transferable value. ### Method Signature ```swift init( exporting transferableValue: T, as contentType: UTType? = nil, named preferredName: String? = nil, sourceLocation: SourceLocation = #_sourceLocation ) async throws where AttachableValue == _AttachableTransferableWrapper, T : Transferable ``` ### Parameters - `transferableValue` (T) - The value that will be attached to the output of the test run. - `contentType` (UTType?) - The content type with which to export `transferableValue`. If `nil`, the testing library uses the first data type returned by `exportedContentTypes(_:)`. - `preferredName` (String?) - The preferred name of the attachment. If `nil`, a filename is generated automatically. - `sourceLocation` (SourceLocation) - The source location of the call to this initializer, used for recording issues. ### Discussion Throws any error that occurs while exporting `transferableValue`. ### Example ```swift let menu = FoodTruck.menu let attachment = try await Attachment(exporting: menu, as: .pdf) Attachment.record(attachment) ``` ``` -------------------------------- ### Get Test Scope Provider Source: https://developer.apple.com/documentation/testing/trait/testscopeprovider Implement this method to provide a custom scope for a specific test. Returns `nil` if the trait does not provide a custom scope. ```swift func scopeProvider(for: Test, testCase: Test.Case?) -> Self.TestScopeProvider? ``` -------------------------------- ### Using Confirmation for Expected Events Source: https://developer.apple.com/documentation/testing/testing-asynchronous-code Explains how to use the `Confirmation` API to verify that specific events occur during the execution of asynchronous code, with options for expected counts and ranges. ```APIDOC ## Using Confirmation for Expected Events ### Description Use `confirmation` to verify that an expected event happens within a block of asynchronous code. You provide a trailing closure that receives a `Confirmation` object, which you call when the event occurs. ### Method `confirmation(_:expectedCount:isolation:sourceLocation:_:)` ### Endpoint N/A (Local test function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```swift @Test("OrderCalculator successfully calculates subtotal for no pizzas") func subtotalForNoPizzas() async { let calculator = OrderCalculator() await confirmation() { confirmation in calculator.successHandler = { _ in confirmation() } _ = await calculator.subtotal(for: PizzaToppings(bases: [])) } } ``` ### Response N/A (Test execution result) ``` -------------------------------- ### Get isRecursive Property Value Source: https://developer.apple.com/documentation/testing/suitetrait/isrecursive-2z41z Access the isRecursive property to check if a trait is applied recursively to child test suites and functions. This is a read-only property. ```swift var isRecursive: Bool { get } ``` -------------------------------- ### filePath Source: https://developer.apple.com/documentation/testing/sourcelocation/filepath The path to the source file. ```APIDOC ## filePath ### Description The path to the source file. ### Type `String` ### Availability Swift 6.3+, Xcode 26.4+ ``` -------------------------------- ### Instance Properties Source: https://developer.apple.com/documentation/testing/attachment/customstringconvertible-implementations Details the properties available for CustomStringConvertible implementations. ```APIDOC ## Instance Properties ### description - **Type**: String - **Description**: A string representation of the object. ``` -------------------------------- ### Construct a bug instance Source: https://developer.apple.com/documentation/testing/trait/bug%28_%3A_%3A%29 Creates a bug tracker reference for a test using a URL string and an optional comment title. ```Swift static func bug( _ url: String, _ title: Comment? = nil ) -> Self ``` ```Swift static func bug(String?, id: String, Comment?) -> Self ``` ```Swift static func bug(String?, id: some Numeric, Comment?) -> Self ``` -------------------------------- ### GET timeLimit Property Source: https://developer.apple.com/documentation/testing/test/timelimit Retrieves the maximum duration allowed for a test case. If multiple limits are set, the shortest duration is returned; otherwise, it returns nil. ```APIDOC ## GET timeLimit ### Description Returns the maximum amount of time the test's cases may run for. ### Property Definition `var timeLimit: Duration? { get }` ### Discussion Associate a time limit with tests by using `timeLimit(_:)`. If a test has more than one time limit associated with it, the value of this property is the shortest one. If a test has no time limits associated with it, the value of this property is `nil`. ### Availability - iOS 16.0+ - iPadOS 16.0+ - Mac Catalyst 16.0+ - macOS 13.0+ - tvOS 16.0+ - visionOS - watchOS 9.0+ - Swift 6.0+ - Xcode 16.0+ ``` -------------------------------- ### init(contentType:encodingQuality:) Source: https://developer.apple.com/documentation/testing/attachableimageformat/init%28contenttype%3Aencodingquality%3A%29 Initializes an instance of AttachableImageFormat with the given content type and encoding quality. The encoding quality is optional and defaults to 1.0 (highest quality). ```APIDOC ## init(contentType:encodingQuality:) ### Description Initialize an instance of this type with the given content type and encoding quality. ### Parameters #### Parameters - **contentType** (UTType) - Required - The image format to use when encoding images. - **encodingQuality** (Float) - Optional - The encoding quality to use when encoding images. For the lowest supported quality, pass `0.0`. For the highest supported quality, pass `1.0`. Defaults to `1.0`. ### Discussion If the target image format does not support variable-quality encoding, the value of the `encodingQuality` argument is ignored. If `contentType` does not conform to `UTType.image`, the result is undefined. ``` -------------------------------- ### Instance Method: preferredName(for:basedOn:) Source: https://developer.apple.com/documentation/testing/attachable/preferredname%28for%3Abasedon%3A%29-9bptj This instance method allows you to get a preferred name for an attachment, given a suggested name. It is available for types conforming to `StringProtocol`. ```APIDOC ## Instance Method: preferredName(for:basedOn:) ### Description Determines a preferred name for an attachment based on a provided suggested name. ### Method `borrowing func preferredName(for attachment: borrowing Attachment, basedOn suggestedName: String) -> String` ### Availability - Swift 6.2+ - Xcode 26.0+ ### Requirements Available when `Self` conforms to `StringProtocol`. ``` -------------------------------- ### Customize Attachment Name Source: https://developer.apple.com/documentation/testing/attachments Implement `preferredName(for:basedOn:)` to customize the name of an attachment. This example appends a '.csv' extension if the suggested name does not already contain a path extension. ```swift extension SalesReport: Attachable { ... borrowing func preferredName( for attachment: borrowing Attachment, basedOn suggestedName: String ) -> String { if suggestedName.contains(".") { // The name already contains a path extension, so don't append another. return suggestedName } // Append ".csv" to the name so the resulting file opens as a spreadsheet. return "\(suggestedName).csv" } } ``` -------------------------------- ### Record Image as Attachment with Format Source: https://developer.apple.com/documentation/testing/attachments Attach an image to a test, specifying the desired format (e.g., .png). If no format is specified, it's inferred from the name. ```swift struct SalesReport { ... } @Test func `sales report adds up`() async throws { let salesReport = await generateSalesReport() let image = try salesReport.renderTrendsGraph() Attachment.record(image, named: "sales report", as: .png) } ``` -------------------------------- ### Swift require Macro Usage Example Source: https://developer.apple.com/documentation/testing/require%28throws%3A_%3Asourcelocation%3Aperforming%3A%29-4djuw Use this overload of #require() when the expression is expected to throw a specific error. If the expression does not throw the specified error, an ExpectationFailedError is thrown. ```swift try #require(throws: EngineFailureError.batteryDied) { FoodTruck.shared.engine.batteryLevel = 0 try FoodTruck.shared.engine.start() } ``` -------------------------------- ### Invalid Nested Test Suite Type Availability Source: https://developer.apple.com/documentation/testing/organizingtests An example where a nested test suite type is invalid because its containing type is annotated with @available, violating the availability constraint. ```swift @available(macOS 11.0, *) struct MenuItemTests { // ❌ ERROR: The suite type's // containing type must always // be available too. @Suite struct BurgerTests { ... } } ``` -------------------------------- ### Construct a bug tracker instance Source: https://developer.apple.com/documentation/testing/trait/bug%28_%3Aid%3A_%3A%29-10yf5 Use this method to create a Bug instance for tracking purposes within a test suite. ```Swift static func bug( _ url: String? = nil, id: String, _ title: Comment? = nil ) -> Self ``` ```Swift static func bug(String, Comment?) -> Self ``` ```Swift static func bug(String?, id: some Numeric, Comment?) -> Self ``` -------------------------------- ### record(_:named:as:sourceLocation:) Source: https://developer.apple.com/documentation/testing/attachment/record%28_%3Anamed%3Aas%3Asourcelocation%3A%29 Attaches an image to the current test, allowing for custom naming and format specification. ```APIDOC ## record(_:named:as:sourceLocation:) ### Description Attach an image to the current test. ### Method static func record( _ image: T, named preferredName: String? = nil, as imageFormat: AttachableImageFormat? = nil, sourceLocation: SourceLocation = #_sourceLocation ) where AttachableValue : _AttachableImageWrapper, AttachableValue : AttachableWrapper, T : AttachableAsImage ### Parameters `image` The value to attach. `preferredName` The preferred name of the attachment when writing it to a test report or to disk. If `nil`, the testing library attempts to derive a reasonable filename for the attached value. `imageFormat` The image format with which to encode `image`. Pass `nil` to let the testing library select which image format to use. `sourceLocation` The source location of the call to this function. ### Discussion This function creates a new instance of `Attachment` wrapping `image` and immediately attaches it to the current test. The testing library uses the image format that `imageFormat` specifies. Pass `nil` to let the testing library select which image format to use. If you pass `nil`, the image format that the testing library uses depends on the path extension you specify in `preferredName`, if any. If you don’t specify a path extension, or if the path extension you specify doesn’t correspond to an image format the operating system knows how to write, the testing library selects an appropriate image format for you. ### See Also * `protocol AttachableAsImage` * `struct AttachableImageFormat` * `init(T, named: String?, as: AttachableImageFormat?, sourceLocation: SourceLocation)` ``` -------------------------------- ### Constructing tags for tests Source: https://developer.apple.com/documentation/testing/trait/comments Creates a list of tags to be applied to a test. ```Swift static func tags(Tag...) -> Self ``` -------------------------------- ### Exit test with captured state using function arguments Source: https://developer.apple.com/documentation/testing/exit-testing When capturing function arguments or `self` in an exit test, the compiler can infer the type. This example captures a `food` argument. ```swift @Test(arguments: Food.allJunkFood) func `Customer won't eat food unless it's nutritious`(_ food: Food) async { await #expect(processExitsWith: .failure) { [food] in Customer.current.eat(food) } } ```