======================== CODE SNIPPETS ======================== TITLE: Swift Example Application Naming DESCRIPTION: Defines the standard naming convention for example applications, projects, and packages used in documentation. 'FoodTruck' is the recommended imaginary application. SOURCE: https://github.com/swiftlang/swift-testing/blob/main/Documentation/StyleGuide.md#_snippet_5 LANGUAGE: APIDOC CODE: ``` Swift Example Application Naming: - Use 'FoodTruck' as the standard imaginary application for examples. - FoodTruck is based on a mobile restaurant concept. - When referencing foods, prefer internationally recognizable items or a diverse set from multiple cultures. - Example code must be syntactically correct and runnable. - External dependencies in examples should be easy to understand or replaceable. ``` ---------------------------------------- TITLE: Convert XCTest setUp() to Swift init() DESCRIPTION: In XCTest, setup code runs using setUp() and tearDown(). In the Swift testing library, use init() for setup logic. The use of async and throws is optional for init(). SOURCE: https://github.com/swiftlang/swift-testing/blob/main/Sources/Testing/Testing.docc/MigratingFromXCTest.md#_snippet_2 LANGUAGE: swift CODE: ``` // Before class FoodTruckTests: XCTestCase { var batteryLevel: NSNumber! override func setUp() async throws { batteryLevel = 100 } ... } ``` LANGUAGE: swift CODE: ``` // After struct FoodTruckTests { var batteryLevel: NSNumber init() async throws { batteryLevel = 100 } ... } ``` ---------------------------------------- TITLE: Swift Documentation Style References DESCRIPTION: Outlines the preferred style guides for documentation within the Swift project. This includes the Swift Book style guide and the Apple Style Guide. SOURCE: https://github.com/swiftlang/swift-testing/blob/main/Documentation/StyleGuide.md#_snippet_4 LANGUAGE: APIDOC CODE: ``` Swift Documentation Style References: - General documentation should follow the Swift Book style guide. - Apple Style Guide should be followed contextually where appropriate. - References: - Swift Book Style Guide: https://github.com/swiftlang/swift-book/blob/main/Style.md - Apple Style Guide: https://support.apple.com/guide/applestyleguide/ ``` ---------------------------------------- TITLE: Install Swift Testing Target DESCRIPTION: Installs the '_TestDiscovery' target using a custom macro `_swift_testing_install_target`. This command handles the installation process for the library. SOURCE: https://github.com/swiftlang/swift-testing/blob/main/Sources/_TestDiscovery/CMakeLists.txt#_snippet_4 LANGUAGE: CMake CODE: ``` _swift_testing_install_target(_TestDiscovery) ``` ---------------------------------------- TITLE: Install Project with CMake DESCRIPTION: Configures and installs the built Swift Testing project content into a specified directory using CMake. This is useful for validating the build output. SOURCE: https://github.com/swiftlang/swift-testing/blob/main/CONTRIBUTING.md#_snippet_6 LANGUAGE: cmake CODE: ``` cmake -G Ninja --install-prefix "$(pwd)/build/install" -B build cmake --install build ``` ---------------------------------------- TITLE: Build Swift Testing Docker Image DESCRIPTION: Builds the Docker image for Swift Testing on macOS. Requires Docker Desktop installed. Tags the image as 'swift-testing:latest'. SOURCE: https://github.com/swiftlang/swift-testing/blob/main/CONTRIBUTING.md#_snippet_7 LANGUAGE: bash CODE: ``` $> docker build -t swift-testing:latest . ``` ---------------------------------------- TITLE: Interactive Docker Session for Swift Testing DESCRIPTION: Starts an interactive Docker container session for Swift Testing development. Mounts the current directory and provides a bash shell inside the container. SOURCE: https://github.com/swiftlang/swift-testing/blob/main/CONTRIBUTING.md#_snippet_9 LANGUAGE: bash CODE: ``` $> docker run -i -t -v "$(pwd)":/swift-testing swift-testing /bin/bash ``` ---------------------------------------- TITLE: CMake Project Setup and Dependencies DESCRIPTION: Initializes the CMake project, sets the minimum required version, and finds necessary packages like SwiftSyntax. It also handles conditional fetching of SwiftSyntax for building macros as executables. SOURCE: https://github.com/swiftlang/swift-testing/blob/main/Sources/TestingMacros/CMakeLists.txt#_snippet_0 LANGUAGE: cmake CODE: ``` cmake_minimum_required(VERSION 3.19.6...3.29) if(POLICY CMP0157) cmake_policy(SET CMP0157 NEW) endif() project(TestingMacros LANGUAGES Swift) list(APPEND CMAKE_MODULE_PATH ${CMAKE_SOURCE_DIR}/../../cmake/modules/shared) if(WIN32) add_compile_definitions(_CRT_SECURE_NO_WARNINGS) endif() find_package(SwiftSyntax CONFIG GLOBAL) if(SwiftTesting_BuildMacrosAsExecutables) # When building the macro plugin as an executable, clone and build # swift-syntax. include(FetchContent) set(FETCHCONTENT_BASE_DIR ${CMAKE_BINARY_DIR}/_d) FetchContent_Declare(SwiftSyntax GIT_REPOSITORY https://github.com/swiftlang/swift-syntax GIT_TAG 340f8400262d494c7c659cd838223990195d7fed) # 602.0.0-prerelease-2025-04-10 FetchContent_MakeAvailable(SwiftSyntax) endif() # Include these modules _after_ swift-syntax is declared above, but _before_ the # macro plugin target is declared below, so that its settings are not applied to # the former but are applied to the latter. include(AvailabilityDefinitions) include(CompilerSettings) ``` ---------------------------------------- TITLE: Swift #expect() Macro Expansion Example DESCRIPTION: Provides a concrete example of how the #expect() macro transforms a simple comparison expression into a more verbose internal testing function call. SOURCE: https://github.com/swiftlang/swift-testing/blob/main/Documentation/ExpectationCapture.md#_snippet_11 LANGUAGE: swift CODE: ``` ```swift // Before #expect(f() < g()) // After expansion (simplified) Testing.__checkBinaryOperation( f(), { $0 < $1() }, g(), expression: .__fromBinaryOperation( .__fromSyntaxNode("f()"), "<", .__fromSyntaxNode("g()") ), comments: [], isRequired: false, sourceLocation: Testing.SourceLocation.__here() ).__expected() ``` ``` ---------------------------------------- TITLE: Swift Compile-Time Diagnostics Style DESCRIPTION: Specifies the style guide for writing compile-time diagnostics within the Swift package. Diagnostics should adhere to the Swift style guide for compiler diagnostics. SOURCE: https://github.com/swiftlang/swift-testing/blob/main/Documentation/StyleGuide.md#_snippet_3 LANGUAGE: APIDOC CODE: ``` Swift Compile-Time Diagnostics Style: - Write diagnostics according to the Swift style guide for compiler diagnostics. - Reference: https://github.com/swiftlang/swift/blob/main/docs/Diagnostics.md ``` ---------------------------------------- TITLE: Swift Symbol Abstract Guidelines DESCRIPTION: Provides rules for writing concise and effective abstracts for Swift symbols. Abstracts should be a single sentence, 150 characters or less, avoid repeating technical terms, and not include links or code formatting. SOURCE: https://github.com/swiftlang/swift-testing/blob/main/Documentation/StyleGuide.md#_snippet_2 LANGUAGE: APIDOC CODE: ``` Swift Symbol Abstract Guidelines: - Limit abstracts to a single sentence (150 characters or fewer). - Move additional information to Overview or Discussion sections. - Do not repeat technical terms from the entity's name. - Avoid links to other symbols within the abstract. - Use plain English instead of code font for terms. - Avoid parentheses or slashes, except for acronyms (spell out on first use). - Avoid locational modifiers like 'the following' or 'below'. - Use correct grammatical style: noun phrase or verb phrase (verb ending in 's' or imperative). Example Abstract (Class): An object that stores the details for a specific order from a vendor. Example Abstract (Enumeration): Describes the flavors of an ingredient. ``` ---------------------------------------- TITLE: Define Swift Testing Executable Target DESCRIPTION: Shows how to define a CMake executable target for tests. It sets the target name, links necessary libraries (e.g., 'Example', 'Testing'), and configures the executable suffix to '.swift-testing'. SOURCE: https://github.com/swiftlang/swift-testing/blob/main/Documentation/CMake.md#_snippet_1 LANGUAGE: cmake CODE: ``` add_executable(ExamplePackageTests ExampleTests.swift ...) set_target_properties(ExamplePackageTests PROPERTIES SUFFIX .swift-testing) target_link_libraries(ExamplePackageTests PRIVATE Example Testing ...) ``` ---------------------------------------- TITLE: C/C++ Symbol Naming and Visibility DESCRIPTION: Illustrates C/C++ naming conventions, including prefixes for internal symbols (`swt_`), public symbols (`swift_testing_`), and types (`SWT`). Uses `SWT_EXTERN` for consistent visibility. SOURCE: https://github.com/swiftlang/swift-testing/blob/main/Documentation/StyleGuide.md#_snippet_1 LANGUAGE: c CODE: ``` SWT_EXTERN bool swt_isDebugModeEnabled(void); SWT_EXTERN void swt_setDebugModeEnabled(bool isEnabled); ``` LANGUAGE: c CODE: ``` SWT_EXTERN void swift_testing_debugIfNeeded(void); ``` LANGUAGE: c CODE: ``` typedef intmax_t SWTBigInteger; typedef struct SWTContainer { ... } SWTContainer; ``` ---------------------------------------- TITLE: Install Internal Library Archive DESCRIPTION: Conditionally installs the '_TestingInternals' static library archive. This installation occurs only when building shared libraries is disabled (i.e., when building static libraries), ensuring the internal library is available alongside the main library. SOURCE: https://github.com/swiftlang/swift-testing/blob/main/Sources/_TestingInternals/CMakeLists.txt#_snippet_5 LANGUAGE: cmake CODE: ``` if(NOT BUILD_SHARED_LIBS) # When building a static library, install the internal library archive # alongside the main library. In shared library builds, the internal library # is linked into the main library and does not need to be installed separately. install(TARGETS _TestingInternals ARCHIVE DESTINATION "${SwiftTesting_INSTALL_LIBDIR}") endif() ``` ---------------------------------------- TITLE: Precondition Failure Example DESCRIPTION: Demonstrates how a `precondition` failure in Swift can cause a process to exit. This is useful for testing error handling paths. SOURCE: https://github.com/swiftlang/swift-testing/blob/main/Sources/Testing/Testing.docc/exit-testing.md#_snippet_0 LANGUAGE: Swift CODE: ``` extension Customer { func eat(_ food: consuming some Food) { precondition(food.isDelicious, "Tasty food only!") precondition(food.isNutritious, "Healthy food only!") ... } } ``` ---------------------------------------- TITLE: Test Scoping and Preparation DESCRIPTION: Traits related to defining the scope of tests and executing setup or teardown code. SOURCE: https://github.com/swiftlang/swift-testing/blob/main/Sources/Testing/Testing.docc/Traits/Trait.md#_snippet_4 LANGUAGE: APIDOC CODE: ``` TestScoping A protocol for defining test scoping behavior. Trait/scopeProvider(for:testCase:)-cjmg Provides a scope provider for a given test case. - Parameters: - testCase: The test case for which to provide a scope. - Returns: An object conforming to TestScoping. Trait/TestScopeProvider A type alias for a scope provider. Trait/prepare(for:)-3s3zo Prepares the test environment before a test or suite runs. - Parameters: - context: The context in which the preparation is happening. ``` ---------------------------------------- TITLE: Swift Testing Project CMake Configuration DESCRIPTION: This CMakeLists.txt file configures the build system for the Swift Testing project. It sets minimum CMake version, handles platform-specific policies (like CMP0157 on Windows/Android), defines project languages (C++ and Swift), finds necessary packages (dispatch, Foundation), sets output directories, and configures installation paths and compiler options. SOURCE: https://github.com/swiftlang/swift-testing/blob/main/CMakeLists.txt#_snippet_0 LANGUAGE: CMake CODE: ``` # This source file is part of the Swift.org open source project # # Copyright (c) 2024 Apple Inc. and the Swift project authors # Licensed under Apache License v2.0 with Runtime Library Exception # # See http://swift.org/LICENSE.txt for license information # See http://swift.org/CONTRIBUTORS.txt for Swift project authors cmake_minimum_required(VERSION 3.19.6...3.29) if(POLICY CMP0157) if(CMAKE_HOST_SYSTEM_NAME STREQUAL Windows AND CMAKE_SYSTEM_NAME STREQUAL Android) # CMP0157 causes builds to fail when targetting Android with the Windows # toolchain, because the early swift-driver isn't (yet) available. Disable # it for now. cmake_policy(SET CMP0157 OLD) else() cmake_policy(SET CMP0157 NEW) endif() endif() project(SwiftTesting LANGUAGES CXX Swift) if(NOT APPLE) if(NOT CMAKE_SYSTEM_NAME STREQUAL WASI) find_package(dispatch CONFIG) endif() find_package(Foundation CONFIG) endif() include(GNUInstallDirs) list(APPEND CMAKE_MODULE_PATH ${PROJECT_SOURCE_DIR}/cmake/modules ${PROJECT_SOURCE_DIR}/cmake/modules/shared) set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib) set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib) set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin) set(CMAKE_INSTALL_RPATH "$,@loader_path/..,$ORIGIN>") set(CMAKE_INSTALL_REMOVE_ENVIRONMENT_RPATH YES) set(CMAKE_MSVC_RUNTIME_LIBRARY MultiThreadedDLL) set(CMAKE_CXX_STANDARD 20) set(CMAKE_Swift_LANGUAGE_VERSION 6) set(CMAKE_Swift_MODULE_DIRECTORY ${CMAKE_BINARY_DIR}/swift) include(PlatformInfo) include(SwiftModuleInstallation) option(SwiftTesting_INSTALL_NESTED_SUBDIR "Install libraries under a platform and architecture subdirectory" NO) set(SwiftTesting_INSTALL_LIBDIR "${CMAKE_INSTALL_LIBDIR}/swift$<$>:_static>/${SwiftTesting_PLATFORM_SUBDIR}$<$,$>>:/testing>$<$:/${SwiftTesting_ARCH_SUBDIR}>") set(SwiftTesting_INSTALL_SWIFTMODULEDIR "${CMAKE_INSTALL_LIBDIR}/swift$<$>:_static>/${SwiftTesting_PLATFORM_SUBDIR}$<$,$>>:/testing>") add_compile_options($<$:-no-toolchain-stdlib-rpath>) add_subdirectory(Sources) ``` ---------------------------------------- TITLE: Swift Testing Library Build Configuration DESCRIPTION: This CMake script configures the build for the Swift Testing library. It defines the library, links necessary internal and external libraries, sets compiler flags for Swift features like library evolution and module interfaces, and specifies installation procedures. SOURCE: https://github.com/swiftlang/swift-testing/blob/main/Sources/Testing/CMakeLists.txt#_snippet_0 LANGUAGE: cmake CODE: ``` add_library(Testing ABI/EntryPoints/ABIEntryPoint.swift ABI/EntryPoints/EntryPoint.swift ABI/EntryPoints/SwiftPMEntryPoint.swift ABI/ABI.Record.swift ABI/ABI.Record+Streaming.swift ABI/ABI.swift ABI/ABI.VersionNumber.swift ABI/Encoded/ABI.EncodedAttachment.swift ABI/Encoded/ABI.EncodedBacktrace.swift ABI/Encoded/ABI.EncodedError.swift ABI/Encoded/ABI.EncodedEvent.swift ABI/Encoded/ABI.EncodedInstant.swift ABI/Encoded/ABI.EncodedIssue.swift ABI/Encoded/ABI.EncodedMessage.swift ABI/Encoded/ABI.EncodedTest.swift Attachments/Attachable.swift Attachments/AttachableWrapper.swift Attachments/Attachment.swift Events/Clock.swift Events/Event.swift Events/Recorder/Event.ConsoleOutputRecorder.swift Events/Recorder/Event.HumanReadableOutputRecorder.swift Events/Recorder/Event.JUnitXMLRecorder.swift Events/Recorder/Event.Symbol.swift Events/TimeValue.swift ExitTests/ExitTest.swift ExitTests/ExitTest.CapturedValue.swift ExitTests/ExitTest.Condition.swift ExitTests/ExitTest.Result.swift ExitTests/SpawnProcess.swift ExitTests/ExitStatus.swift ExitTests/WaitFor.swift Expectations/Expectation.swift Expectations/Expectation+Macro.swift Expectations/ExpectationChecking+Macro.swift Issues/Confirmation.swift Issues/ErrorSnapshot.swift Issues/Issue.swift Issues/Issue+Recording.swift Issues/KnownIssue.swift Parameterization/CustomTestArgumentEncodable.swift Parameterization/Test.Case.Generator.swift Parameterization/Test.Case.ID.swift Parameterization/Test.Case.swift Parameterization/TypeInfo.swift Running/Configuration.swift Running/Configuration.TestFilter.swift Running/Configuration+EventHandling.swift Running/Runner.Plan.swift Running/Runner.Plan+Dumping.swift Running/Runner.RuntimeState.swift Running/Runner.swift Running/SkipInfo.swift SourceAttribution/Backtrace.swift SourceAttribution/Backtrace+Symbolication.swift SourceAttribution/CustomTestStringConvertible.swift SourceAttribution/Expression.swift SourceAttribution/Expression+Macro.swift SourceAttribution/SourceContext.swift SourceAttribution/SourceLocation.swift SourceAttribution/SourceLocation+Macro.swift Support/Additions/ArrayAdditions.swift Support/Additions/CollectionDifferenceAdditions.swift Support/Additions/CommandLineAdditions.swift Support/Additions/NumericAdditions.swift Support/Additions/ResultAdditions.swift Support/Additions/WinSDKAdditions.swift Support/CartesianProduct.swift Support/CError.swift Support/CustomIssueRepresentable.swift Support/Environment.swift Support/FileHandle.swift Support/GetSymbol.swift Support/Graph.swift Support/JSON.swift Support/Locked.swift Support/Locked+Platform.swift Support/Versions.swift Discovery+Macro.swift Test.ID.Selection.swift Test.ID.swift Test.swift Test+Discovery.swift Test+Discovery+Legacy.swift Test+Macro.swift Traits/Bug.swift Traits/Comment.swift Traits/Comment+Macro.swift Traits/ConditionTrait.swift Traits/ConditionTrait+Macro.swift Traits/HiddenTrait.swift Traits/IssueHandlingTrait.swift Traits/ParallelizationTrait.swift Traits/Tags/Tag.Color.swift Traits/Tags/Tag.Color+Loading.swift Traits/Tags/Tag.List.swift Traits/Tags/Tag.swift Traits/Tags/Tag+Macro.swift Traits/Tags/Tag+Predefined.swift Traits/TimeLimitTrait.swift Traits/Trait.swift) target_link_libraries(Testing PRIVATE _TestDiscovery _TestingInternals) if(NOT APPLE) if(NOT CMAKE_SYSTEM_NAME STREQUAL WASI) target_link_libraries(Testing PUBLIC dispatch) endif() target_link_libraries(Testing PUBLIC Foundation) if (CMAKE_SYSTEM_NAME STREQUAL "FreeBSD") target_link_libraries(Testing PUBLIC execinfo) endif() endif() if(NOT BUILD_SHARED_LIBS) # When building a static library, tell clients to autolink the internal # libraries. target_compile_options(Testing PRIVATE "SHELL:-Xfrontend -public-autolink-library -Xfrontend _TestDiscovery" "SHELL:-Xfrontend -public-autolink-library -Xfrontend _TestingInternals") endif() add_dependencies(Testing TestingMacros) target_compile_options(Testing PRIVATE -enable-library-evolution -emit-module-interface -emit-module-interface-path $/Testing.swiftinterface) _swift_testing_install_target(Testing) # Install the Swift cross-import overlay directory. _swift_testing_install_swiftcrossimport(Testing Testing.swiftcrossimport) ``` ---------------------------------------- TITLE: Add Swift Testing Foundation Subdirectory (CMake) DESCRIPTION: Integrates the Swift Testing Foundation module into the build system. This CMake command recursively processes the build script in the specified subdirectory, adding its targets to the current project. It's essential for modularizing the build and managing dependencies within the Swift-Testing project. SOURCE: https://github.com/swiftlang/swift-testing/blob/main/Sources/Overlays/CMakeLists.txt#_snippet_0 LANGUAGE: cmake CODE: ``` add_subdirectory(_Testing_Foundation) ``` ---------------------------------------- TITLE: Conditional Installation of Static Library Archive DESCRIPTION: Conditionally installs the archive of the '_TestDiscovery' static library. This is performed only when building static libraries, ensuring the internal library is available separately. SOURCE: https://github.com/swiftlang/swift-testing/blob/main/Sources/_TestDiscovery/CMakeLists.txt#_snippet_5 LANGUAGE: CMake CODE: ``` if(NOT BUILD_SHARED_LIBS) # When building a static library, install the internal library archive # alongside the main library. In shared library builds, the internal library # is linked into the main library and does not need to be installed separately. install(TARGETS _TestDiscovery ARCHIVE DESTINATION "${SwiftTesting_INSTALL_LIBDIR}") endif() ``` ---------------------------------------- TITLE: Swift Documentation Language and Tone DESCRIPTION: Specifies the language and tone requirements for Swift documentation. Documentation should be in U.S. English for an international audience, avoiding culturally specific references. SOURCE: https://github.com/swiftlang/swift-testing/blob/main/Documentation/StyleGuide.md#_snippet_6 LANGUAGE: APIDOC CODE: ``` Swift Documentation Language and Tone: - Write documentation in U.S. English. - Target an international audience. - Avoid culturally specific references unless directly relevant. - Culturally insensitive or inappropriate language is not tolerated. - Refer to the Swift Code of Conduct: https://swift.org/code-of-conduct ``` ---------------------------------------- TITLE: Set Swift Toolchain Path (macOS) DESCRIPTION: Configures the environment to use the Swift toolchain when Xcode is installed on macOS. This ensures the system can locate and use the correct Swift compiler and tools. SOURCE: https://github.com/swiftlang/swift-testing/blob/main/CONTRIBUTING.md#_snippet_0 LANGUAGE: bash CODE: ``` export TOOLCHAINS=swift xcrun --find swift ``` ---------------------------------------- TITLE: Swift Testing Sequential Test Execution DESCRIPTION: Illustrates how to run tests sequentially in Swift Testing using the `@Suite(.serialized)` annotation. The example shows the equivalent `RefrigeratorTests` suite, now annotated to ensure serial execution, and uses `#expect` for assertions. SOURCE: https://github.com/swiftlang/swift-testing/blob/main/Sources/Testing/Testing.docc/MigratingFromXCTest.md#_snippet_25 LANGUAGE: swift CODE: ``` // After @Suite(.serialized) class RefrigeratorTests { @Test func lightComesOn() throws { try FoodTruck.shared.refrigerator.openDoor() #expect(FoodTruck.shared.refrigerator.lightState == .on) } @Test func lightGoesOut() throws { try FoodTruck.shared.refrigerator.openDoor() try FoodTruck.shared.refrigerator.closeDoor() #expect(FoodTruck.shared.refrigerator.lightState == .off) } } ``` ---------------------------------------- TITLE: Include System Headers for Platform-Specific Functionality DESCRIPTION: Demonstrates how to conditionally include platform-specific C headers within the Swift Testing internals module. This example shows adding `DateTimeUtils.h` for the Classic Mac OS platform to enable access to functions like `GetDateTime()`. SOURCE: https://github.com/swiftlang/swift-testing/blob/main/Documentation/Porting.md#_snippet_0 LANGUAGE: diff CODE: ``` --- a/Sources/_TestingInternals/include/Includes.h +++ b/Sources/_TestingInternals/include/Includes.h +#if defined(macintosh) +#include +#endif ``` ---------------------------------------- TITLE: Loading Discovered Test Content Records DESCRIPTION: Provides an example of iterating through all discovered test content records for a specific type, checking a condition on the record's context, and then loading the actual test content instance using its `load()` method, optionally providing a hint. SOURCE: https://github.com/swiftlang/swift-testing/blob/main/Documentation/ABI/TestContent.md#_snippet_7 LANGUAGE: swift CODE: ``` for diagnosticRecord in FoodTruckDiagnostic.allTestContentRecords() { if diagnosticRecord.context.pointee == .briansBranMuffins { if let diagnostic = diagnosticRecord.load(withHint: "...") { diagnostic.run() } } } ``` ---------------------------------------- TITLE: Executable Target Configuration for Macros DESCRIPTION: Configures the 'TestingMacros' target as an executable when 'SwiftTesting_BuildMacrosAsExecutables' is enabled. It sets properties like ENABLE_EXPORTS, parses the module as a library, and defines installation rules. SOURCE: https://github.com/swiftlang/swift-testing/blob/main/Sources/TestingMacros/CMakeLists.txt#_snippet_1 LANGUAGE: cmake CODE: ``` if(SwiftTesting_BuildMacrosAsExecutables) # When swift-syntax is built locally, the macro plugin must be built as an # executable. add_executable(TestingMacros) set_target_properties(TestingMacros PROPERTIES ENABLE_EXPORTS TRUE) # Parse the module as a library, even though it's an executable, because it # uses an `@main` type to define its entry point. target_compile_options(TestingMacros PRIVATE -parse-as-library) # Include the .swift file which contains its `@main` entry point type. target_compile_definitions(TestingMacros PRIVATE SWT_NO_LIBRARY_MACRO_PLUGINS) install(TARGETS TestingMacros RUNTIME DESTINATION bin) else() add_library(TestingMacros SHARED) target_link_options(TestingMacros PRIVATE "-no-toolchain-stdlib-rpath") set_property(TARGET TestingMacros PROPERTY BUILD_WITH_INSTALL_RPATH YES) if(CMAKE_SYSTEM_NAME STREQUAL "Darwin") set(plugin_destination_dir "lib/swift/host/plugins/testing") set_property(TARGET TestingMacros PROPERTY INSTALL_RPATH) else() set(plugin_destination_dir "lib/swift/host/plugins") # RPATH 'lib/swift/{system}' and 'lib/swift/host' set_property(TARGET TestingMacros PROPERTY INSTALL_RPATH "$ORIGIN/../../$;$ORIGIN/..") endif() install(TARGETS TestingMacros LIBRARY DESTINATION "${plugin_destination_dir}" RUNTIME DESTINATION bin) endif() ``` ---------------------------------------- TITLE: Swift Symbol Naming Conventions DESCRIPTION: Demonstrates Swift symbol naming conventions for internal-use public symbols (double underscore) and private symbols (single underscore). SOURCE: https://github.com/swiftlang/swift-testing/blob/main/Documentation/StyleGuide.md#_snippet_0 LANGUAGE: swift CODE: ``` public func __check() ``` LANGUAGE: swift CODE: ``` private var _errorCount: Int public var errorCount: Int { get { _errorCount } set { precondition(newValue >= 0, "Error count cannot be negative") _errorCount = newValue } } ``` ---------------------------------------- TITLE: Configuring Fulfillment Count with Confirmation DESCRIPTION: Illustrates how to configure the number of times an expectation or confirmation should be met. This example shows setting `expectedFulfillmentCount` for XCTestExpectation and using a range for the `expectedCount` parameter in Confirmation. SOURCE: https://github.com/swiftlang/swift-testing/blob/main/Sources/Testing/Testing.docc/MigratingFromXCTest.md#_snippet_11 LANGUAGE: swift CODE: ``` // Before: XCTestExpectation with expectedFulfillmentCount func testRegularCustomerOrders() async { let soldFood = expectation(description: "...") soldFood.expectedFulfillmentCount = 10 soldFood.assertForOverFulfill = false FoodTruck.shared.eventHandler = { event in if case .soldFood = event { soldFood.fulfill() } } for customer in regularCustomers() { await customer.buy(customer.regularOrder) } await fulfillment(of: [soldFood]) ... } ``` LANGUAGE: swift CODE: ``` // After: Confirmation with expectedCount range @Test func regularCustomerOrders() async { await confirmation( "...", expectedCount: 10... ) { soldFood in FoodTruck.shared.eventHandler = { event in if case .soldFood = event { soldFood() } } for customer in regularCustomers() { await customer.buy(customer.regularOrder) } } ... } ``` ---------------------------------------- TITLE: Creating an Exit Test with Expect DESCRIPTION: Shows how to use the `expect(processExitsWith:)` macro to create an exit test. The macro starts a child process to execute the provided closure and asserts that the child process exits with the specified condition. SOURCE: https://github.com/swiftlang/swift-testing/blob/main/Sources/Testing/Testing.docc/exit-testing.md#_snippet_1 LANGUAGE: Swift CODE: ``` @Test func `Customer won't eat food unless it's delicious`() async { let result = await #expect(processExitsWith: .failure) { var food = ... food.isDelicious = false Customer.current.eat(food) } } ``` ---------------------------------------- TITLE: Tag Color Configuration JSON DESCRIPTION: Example JSON structure for `tag-colors.json` to map Swift test tags to specific colors. Colors can be predefined names or hexadecimal RGB values. SOURCE: https://github.com/swiftlang/swift-testing/blob/main/Sources/Testing/Testing.docc/AddingTags.md#_snippet_4 LANGUAGE: JSON CODE: ``` { ".critical": "orange", ".legallyRequired": "#66FFCC" } ``` ---------------------------------------- TITLE: XCTest Sequential Test Execution DESCRIPTION: Demonstrates how to define tests in XCTest that may exhibit unexpected behavior when run in parallel due to shared state. The example shows two test functions, `testLightComesOn` and `testLightGoesOut`, within the `RefrigeratorTests` class. SOURCE: https://github.com/swiftlang/swift-testing/blob/main/Sources/Testing/Testing.docc/MigratingFromXCTest.md#_snippet_24 LANGUAGE: swift CODE: ``` // Before class RefrigeratorTests : XCTestCase { func testLightComesOn() throws { try FoodTruck.shared.refrigerator.openDoor() XCTAssertEqual(FoodTruck.shared.refrigerator.lightState, .on) } func testLightGoesOut() throws { try FoodTruck.shared.refrigerator.openDoor() try FoodTruck.shared.refrigerator.closeDoor() XCTAssertEqual(FoodTruck.shared.refrigerator.lightState, .off) } } ``` ---------------------------------------- TITLE: XCTest Value Attachment DESCRIPTION: Shows how to attach an object to a test result in XCTest using `XCTAttachment`. The example demonstrates attaching a `Tortilla` object (conforming to `NSSecureCoding`) to the test results. SOURCE: https://github.com/swiftlang/swift-testing/blob/main/Sources/Testing/Testing.docc/MigratingFromXCTest.md#_snippet_26 LANGUAGE: swift CODE: ``` // Before import Foundation class Tortilla: NSSecureCoding { /* ... */ } func testTortillaIntegrity() async { let tortilla = Tortilla(diameter: .large) ... let attachment = XCTAttachment( archivableObject: tortilla ) self.add(attachment) } ``` ---------------------------------------- TITLE: Get System Time on Classic OS DESCRIPTION: Retrieves the current system time on platforms with the 'Classic' OS identifier. It calculates the time difference from a specific epoch and returns it as a TimeValue. This implementation is conditional and relies on the GetDateTime function. SOURCE: https://github.com/swiftlang/swift-testing/blob/main/Documentation/Porting.md#_snippet_1 LANGUAGE: swift CODE: ``` filefileprivate(set) var wall: TimeValue = { #if !SWT_NO_TIMESPEC // ... #elseif os(Classic) var seconds = CUnsignedLong(0) GetDateTime(&seconds) seconds -= 2_082_844_800 // seconds between epochs return TimeValue((seconds: Int64(seconds), attoseconds: 0)) #else #warning("Platform-specific implementation missing: UTC time unavailable (no timespec)") #endif } ``` ---------------------------------------- TITLE: Invalid Test Suite Due to Availability Attribute in Swift DESCRIPTION: This example shows that a test suite type cannot be annotated with the `@available` attribute, as test suites must always be available. SOURCE: https://github.com/swiftlang/swift-testing/blob/main/Sources/Testing/Testing.docc/OrganizingTests.md#_snippet_5 LANGUAGE: Swift CODE: ``` @Suite struct FoodTruckTests { ... } // ✅ OK: The type is always available. @available(macOS 11.0, *) // ❌ ERROR: The suite type must always be available. @Suite struct CashRegisterTests { ... } @available(macOS 11.0, *) struct MenuItemTests { // ❌ ERROR: The suite type's // containing type must always // be available too. @Suite struct BurgerTests { ... } } ``` ---------------------------------------- TITLE: Declare Test Functions: XCTest vs Swift Testing DESCRIPTION: Demonstrates the syntax difference for declaring test functions. XCTest requires methods to be part of a class and start with 'test', while the Swift Testing library uses the `@Test` attribute on functions within structs or classes. SOURCE: https://github.com/swiftlang/swift-testing/blob/main/Sources/Testing/Testing.docc/MigratingFromXCTest.md#_snippet_4 LANGUAGE: swift CODE: ``` // Before (XCTest) class FoodTruckTests: XCTestCase { func testEngineWorks() { ... } ... } // After (Swift Testing) struct FoodTruckTests { @Test func engineWorks() { ... } ... } ``` ---------------------------------------- TITLE: Swift Testing Value Attachment DESCRIPTION: Demonstrates how to attach a value to a test result in Swift Testing using the `Attachment.record` method. The example shows attaching a `Tortilla` object (conforming to `Codable` and `Attachable`) to the test results. SOURCE: https://github.com/swiftlang/swift-testing/blob/main/Sources/Testing/Testing.docc/MigratingFromXCTest.md#_snippet_27 LANGUAGE: swift CODE: ``` // After import Foundation struct Tortilla: Codable, Attachable { /* ... */ } @Test func tortillaIntegrity() async { let tortilla = Tortilla(diameter: .large) ... Attachment.record(tortilla) } ``` ---------------------------------------- TITLE: Swift Macro Expansion for Type/Variable Name Ambiguity DESCRIPTION: Shows an example where Swift Testing might append '.self' to a syntax node to resolve ambiguity between type and variable names. Users should report cases where this logic fails. SOURCE: https://github.com/swiftlang/swift-testing/blob/main/Documentation/ExpectationCapture.md#_snippet_8 LANGUAGE: swift CODE: ``` ```swift #expect(a.b == c) // a may not be expressible in isolation ``` ``` ---------------------------------------- TITLE: Running Swift Tests DESCRIPTION: This command executes the Swift test suite in the current directory. SOURCE: https://github.com/swiftlang/swift-testing/blob/main/CONTRIBUTING.md#_snippet_12 LANGUAGE: bash CODE: ``` $> swift test ``` ---------------------------------------- TITLE: Fetch Swift Testing with CMake DESCRIPTION: Demonstrates how to include the Swift Testing library in a CMake project using FetchContent. It specifies the Git repository and tag for fetching the library. SOURCE: https://github.com/swiftlang/swift-testing/blob/main/Documentation/CMake.md#_snippet_0 LANGUAGE: cmake CODE: ``` include(FetchContent) FetchContent_Declare(SwiftTesting GIT_REPOSITORY https://github.com/swiftlang/swift-testing.git GIT_TAG main) FetchContent_MakeAvailable(SwiftTesting) ``` ---------------------------------------- TITLE: Swift: Create Bug Trait with Unique Identifier DESCRIPTION: Shows how to create a Bug trait instance using a unique identifier. The library does not enforce a specific format for identifiers, but recognizes identifiers starting with "FB" as belonging to Apple Feedback Assistant. Integers can also be passed directly. SOURCE: https://github.com/swiftlang/swift-testing/blob/main/Sources/Testing/Testing.docc/BugIdentifiers.md#_snippet_1 LANGUAGE: swift CODE: ``` Trait.bug(id: 12345) Trait.bug(id: "12345") Trait.bug(id: "FB12345") ``` ---------------------------------------- TITLE: Configure CMake Project DESCRIPTION: Configures the Swift Testing project to be built using CMake with the Ninja generator. This command sets up the build system and output directory. SOURCE: https://github.com/swiftlang/swift-testing/blob/main/CONTRIBUTING.md#_snippet_4 LANGUAGE: cmake CODE: ``` cmake -G Ninja -B build ``` ---------------------------------------- TITLE: Swift Entry Point for Test Runner DESCRIPTION: Provides the '@main' entry point for a Swift test executable. It defines the expected ABI signature for the entry point function and uses it to run tests, exiting with success or failure. SOURCE: https://github.com/swiftlang/swift-testing/blob/main/Documentation/CMake.md#_snippet_3 LANGUAGE: swift CODE: ``` typealias EntryPoint = @convention(thin) @Sendable (_ configurationJSON: UnsafeRawBufferPointer?, _ recordHandler: @escaping @Sendable (_ recordJSON: UnsafeRawBufferPointer) -> Void) async throws -> Bool @_extern(c, "swt_abiv0_getEntryPoint") func swt_abiv0_getEntryPoint() -> UnsafeRawPointer @main struct Runner { static func main() async throws { nonisolated(unsafe) let configurationJSON: UnsafeRawBufferPointer? = nil let recordHandler: @Sendable (UnsafeRawBufferPointer) -> Void = { _ in } let entryPoint = unsafeBitCast(swt_abiv0_getEntryPoint(), to: EntryPoint.self) if try await entryPoint(configurationJSON, recordHandler) { exit(EXIT_SUCCESS) } else { exit(EXIT_FAILURE) } } } ``` ---------------------------------------- TITLE: Basic Test with Expectation DESCRIPTION: Demonstrates a simple test case using the `@Test` macro and the `#expect` macro for asserting conditions. It shows how to declare a test function and perform a basic equality check. SOURCE: https://github.com/swiftlang/swift-testing/blob/main/README.md#_snippet_0 LANGUAGE: swift CODE: ``` import Testing @Test func helloWorld() { let greeting = "Hello, world!" #expect(greeting == "Hello") // Expectation failed: (greeting → "Hello, world!") == "Hello" } ``` ---------------------------------------- TITLE: Build Swift Project DESCRIPTION: Builds the Swift Testing project using the Swift Package Manager. This command compiles the project's source code and dependencies. SOURCE: https://github.com/swiftlang/swift-testing/blob/main/CONTRIBUTING.md#_snippet_2 LANGUAGE: bash CODE: ``` swift build ``` ---------------------------------------- TITLE: Test Swift Project DESCRIPTION: Runs the test suite for the Swift Testing project using the Swift Package Manager. This command executes all defined tests to verify the project's functionality. SOURCE: https://github.com/swiftlang/swift-testing/blob/main/CONTRIBUTING.md#_snippet_3 LANGUAGE: bash CODE: ``` swift test ``` ---------------------------------------- TITLE: List Tests in WebAssembly Executable DESCRIPTION: Lists all available tests within the WebAssembly executable using Wasmtime. This is useful for inspecting the test suite before execution. Replace `{YOURPACKAGE}` with your package's name. SOURCE: https://github.com/swiftlang/swift-testing/blob/main/Documentation/WASI.md#_snippet_2 LANGUAGE: sh CODE: ``` wasmtime .build/debug/{YOURPACKAGE}PackageTests.wasm list --testing-library swift-testing ``` ---------------------------------------- TITLE: Build Swift Tests for WebAssembly DESCRIPTION: Builds Swift tests specifically for the WebAssembly target using the `wasm32-unknown-wasi` SDK. This command prepares the test executables for execution in a WASI environment. SOURCE: https://github.com/swiftlang/swift-testing/blob/main/Documentation/WASI.md#_snippet_0 LANGUAGE: sh CODE: ``` swift build --swift-sdk wasm32-unknown-wasi --build-tests ``` ---------------------------------------- TITLE: Run WebAssembly Tests with Wasmtime DESCRIPTION: Executes the compiled WebAssembly test executable using Wasmtime. It requires the path to the test executable and specifies the testing library to use. Replace `{YOURPACKAGE}` with your package's name. SOURCE: https://github.com/swiftlang/swift-testing/blob/main/Documentation/WASI.md#_snippet_1 LANGUAGE: sh CODE: ``` wasmtime .build/debug/{YOURPACKAGE}PackageTests.wasm --testing-library swift-testing ``` ---------------------------------------- TITLE: Test Suite Instance vs. Static Methods DESCRIPTION: Illustrates how the testing library handles instance methods within a `@Suite` type by creating an instance and calling the method. It also shows the equivalent static method call, highlighting that each instance method is called on a distinct instance of the suite type. SOURCE: https://github.com/swiftlang/swift-testing/blob/main/Sources/Testing/Testing.docc/OrganizingTests.md#_snippet_1 LANGUAGE: swift CODE: ``` @Suite struct FoodTruckTests { @Test func foodTruckExists() { ... } } // Equivalent to: @Suite struct FoodTruckTests { func foodTruckExists() { ... } @Test static func staticFoodTruckExists() { let instance = FoodTruckTests() instance.foodTruckExists() } } ``` ---------------------------------------- TITLE: Build Project with CMake DESCRIPTION: Performs the build process for the Swift Testing project using CMake and the Ninja generator. This command compiles the project based on the configuration. SOURCE: https://github.com/swiftlang/swift-testing/blob/main/CONTRIBUTING.md#_snippet_5 LANGUAGE: cmake CODE: ``` cmake --build build ``` ---------------------------------------- TITLE: Run Swift Testing Suite via Docker DESCRIPTION: Executes the Swift Testing suite within a Docker container. Mounts the current directory into the container and sets the working directory. Skips update checks. SOURCE: https://github.com/swiftlang/swift-testing/blob/main/CONTRIBUTING.md#_snippet_8 LANGUAGE: bash CODE: ``` $> docker run -v "$(pwd)":/swift-testing -w /swift-testing swift-testing swift test --skip-update ``` ---------------------------------------- TITLE: Swift: API Documentation for Testing Expectations DESCRIPTION: Provides an overview of key types and functions used for creating and managing expectations in Swift tests. This includes macros for asserting conditions, checking for thrown errors, and confirming asynchronous events. SOURCE: https://github.com/swiftlang/swift-testing/blob/main/Sources/Testing/Testing.docc/Expectations.md#_snippet_2 LANGUAGE: APIDOC CODE: ``` Swift Testing Library API Overview: Core Expectation Macros: - expect(_:_:sourceLocation:) - Validates an expression against an expected value. Continues test execution on failure. - Parameters: - expression: The expression to evaluate. - expected: The expected value. - sourceLocation: The source location of the assertion. - Example: #expect(result == expectedValue) - require(_:_:sourceLocation:) - Validates a critical expression. Stops test execution on failure by throwing `ExpectationFailedError`. - Parameters: - expression: The expression to evaluate. - expected: The expected value. - sourceLocation: The source location of the assertion. - Example: let value = try #require(optionalValue) Error Handling Macros: - expect(throws:_:sourceLocation:performing:) - expect(throws:_:sourceLocation:performing:) - expect(_:sourceLocation:performing:throws:) - Asserts that a closure throws a specific error or any error. - Parameters: - error: The expected error type or instance. - sourceLocation: The source location of the assertion. - performing: The closure to execute. - Example: #expect(throws: MyError.self, performing: { try performAction() }) - require(throws:_:sourceLocation:performing:) - require(throws:_:sourceLocation:performing:) - require(_:sourceLocation:performing:throws:) - Asserts that a closure throws a specific error or any error, stopping the test on failure. - Parameters: - error: The expected error type or instance. - sourceLocation: The source location of the assertion. - performing: The closure to execute. - Example: try #require(throws: MyError.self, performing: { try performCriticalAction() }) Asynchronous Event Confirmation: - confirmation(_:expectedCount:isolation:sourceLocation:_:) - confirmation(_:expectedCount:isolation:sourceLocation:_:) - Confirms the occurrence of asynchronous events, optionally with an expected count. - Parameters: - description: A description of the event. - expectedCount: The number of times the event is expected. - isolation: The actor isolation context for the confirmation. - sourceLocation: The source location of the assertion. - closure: The closure to execute that triggers the event. - Example: let confirmation = confirmation("data loaded") { await loadData() } Exit Status Testing: - expect(processExitsWith:observing:_:sourceLocation:performing:) - require(processExitsWith:observing:_:sourceLocation:performing:) - Asserts or requires that a process exits with a specific status code. - Parameters: - expectedExitStatus: The expected exit status. - observing: A closure to observe the process output. - sourceLocation: The source location of the assertion. - performing: The closure to execute that starts the process. - Example: #expect(processExitsWith: 0, performing: { launchProcess() }) Key Types: - Confirmation: Manages the state and verification of asynchronous events. - Expectation: Represents a single assertion within a test. - ExpectationFailedError: The error thrown when a `#require` assertion fails. - CustomTestStringConvertible: Protocol for custom string representations in test failures. - SourceLocation: Represents the file and line number of an assertion. ``` ---------------------------------------- TITLE: Define Swift Static Library DESCRIPTION: Defines a static library target named '_TestDiscovery' and lists its associated Swift source files. This is a core step in building the library. SOURCE: https://github.com/swiftlang/swift-testing/blob/main/Sources/_TestDiscovery/CMakeLists.txt#_snippet_0 LANGUAGE: CMake CODE: ``` add_library(_TestDiscovery STATIC Additions/WinSDKAdditions.swift DiscoverableAsTestContent.swift SectionBounds.swift TestContentKind.swift TestContentRecord.swift) ``` ---------------------------------------- TITLE: Parameterized Test with Arguments DESCRIPTION: Demonstrates parameterized testing, allowing the same test logic to be executed with a sequence of different inputs. This reduces code duplication and improves test coverage by iterating over provided arguments. SOURCE: https://github.com/swiftlang/swift-testing/blob/main/README.md#_snippet_3 LANGUAGE: swift CODE: ``` import Testing @Test("Continents mentioned in videos", arguments: [ "A Beach", "By the Lake", "Camping in the Woods" ]) func mentionedContinents(videoName: String) async throws { let videoLibrary = try await VideoLibrary() let video = try #require(await videoLibrary.video(named: videoName)) #expect(video.mentionedContinents.count <= 3) } ``` ---------------------------------------- TITLE: Test with Conditional Behavior and Require DESCRIPTION: Illustrates how to apply traits to tests, such as conditional enabling based on application features. It also shows the use of the `#require` macro to unwrap optional values or throw errors, ensuring necessary conditions are met before proceeding. SOURCE: https://github.com/swiftlang/swift-testing/blob/main/README.md#_snippet_1 LANGUAGE: swift CODE: ``` import Testing @Test(.enabled(if: AppFeatures.isCommentingEnabled)) func videoCommenting() async throws { let video = try #require(await videoLibrary.video(named: "A Beach")) #expect(video.comments.contains("So picturesque!")) } ``` ---------------------------------------- TITLE: Simple Expression Capture with #expect DESCRIPTION: Demonstrates how Swift Testing's #expect() macro captures simple expressions, allowing for detailed runtime diagnostics by examining the expression's Abstract Syntax Tree (AST). SOURCE: https://github.com/swiftlang/swift-testing/blob/main/Documentation/ExpectationCapture.md#_snippet_0 LANGUAGE: swift CODE: ``` #expect(f() < g()) ``` ---------------------------------------- TITLE: Navigating to Swift Testing Directory DESCRIPTION: This command changes the current directory to '/swift-testing' inside the Docker container. SOURCE: https://github.com/swiftlang/swift-testing/blob/main/CONTRIBUTING.md#_snippet_11 LANGUAGE: bash CODE: ``` $> cd /swift-testing ``` ---------------------------------------- TITLE: Test with Descriptive Name and Tags DESCRIPTION: Shows how to provide a descriptive string name for a test and apply tags for flexible organization and filtering. This helps in managing tests with common characteristics across a suite. SOURCE: https://github.com/swiftlang/swift-testing/blob/main/README.md#_snippet_2 LANGUAGE: swift CODE: ``` import Testing @Test("Check video metadata", .tags(.metadata)) func videoMetadata() { let video = Video(fileName: "By the Lake.mov") let expectedMetadata = Metadata(duration: .seconds(90)) #expect(video.metadata == expectedMetadata) } ``` ---------------------------------------- TITLE: Importing the Testing Module DESCRIPTION: Shows the basic import statement required to use the Swift Testing package in your Swift code. This is the foundational step for leveraging any of its testing functionalities. SOURCE: https://github.com/swiftlang/swift-testing/blob/main/README.md#_snippet_4 LANGUAGE: swift CODE: ``` import Testing ``` ---------------------------------------- TITLE: Swift: Parameterized Tests with Multiple Collections DESCRIPTION: Demonstrates how to use multiple collections of arguments for parameterized tests in Swift. It shows the default Cartesian product behavior and how to use `zip()` to combine collections for a more controlled test execution. SOURCE: https://github.com/swiftlang/swift-testing/blob/main/Sources/Testing/Testing.docc/ParameterizedTesting.md#_snippet_5 LANGUAGE: swift CODE: ``` @Test("Can make large orders", arguments: Food.allCases, 1 ... 100) func makeLargeOrder(of food: Food, count: Int) async throws { let foodTruck = FoodTruck(selling: food) #expect(await foodTruck.cook(food, quantity: count)) } ``` LANGUAGE: swift CODE: ``` @Test("Can make large orders", arguments: zip(Food.allCases, 1 ... 100)) func makeLargeOrder(of food: Food, count: Int) async throws { let foodTruck = FoodTruck(selling: food) #expect(await foodTruck.cook(food, quantity: count)) } ``` ---------------------------------------- TITLE: SwiftTesting Macro Configuration DESCRIPTION: Configures the SwiftTesting macro plugin path. It supports automatic building via ExternalProject or using a pre-defined path. Includes logic to determine build parameters based on the host system and SwiftSyntax availability. SOURCE: https://github.com/swiftlang/swift-testing/blob/main/Sources/CMakeLists.txt#_snippet_0 LANGUAGE: cmake CODE: ``` set(SwiftTesting_MACRO "" CACHE STRING "Path to SwiftTesting macro plugin, or '' for automatically building it") if(SwiftTesting_MACRO STREQUAL "") # Macros must be built for the build machine, not the host. include(ExternalProject) if(NOT SwiftTesting_MACRO_MAKE_PROGRAM) set(SwiftTesting_MACRO_MAKE_PROGRAM ${CMAKE_MAKE_PROGRAM}) endif() if(NOT SwiftTesting_MACRO_Swift_COMPILER) set(SwiftTesting_MACRO_Swift_COMPILER ${CMAKE_Swift_COMPILER}) endif() if(NOT SwiftTesting_MACRO_Swift_FLAGS) set(SwiftTesting_MACRO_Swift_FLAGS ${CMAKE_Swift_FLAGS}) set(SwiftTesting_MACRO_SWIFT_FLAGS_RELEASE ${CMAKE_Swift_FLAGS_RELEASE}) set(SwiftTesting_MACRO_SWIFT_FLAGS_RELWITHDEBINFO ${CMAKE_Swift_FLAGS_RELWITHDEBINFO}) endif() if(NOT SwiftTesting_MACRO_AR) set(SwiftTesting_MACRO_AR ${CMAKE_AR}) endif() if(NOT SwiftTesting_MACRO_RANLIB) set(SwiftTesting_MACRO_RANLIB ${CMAKE_RANLIB}) endif() if(NOT SwiftTesting_MACRO_BUILD_TYPE) set(SwiftTesting_MACRO_BUILD_TYPE ${CMAKE_BUILD_TYPE}) endif() find_package(SwiftSyntax CONFIG GLOBAL) if(SwiftSyntax_FOUND) set(SwiftTesting_BuildMacrosAsExecutables NO) else() set(SwiftTesting_BuildMacrosAsExecutables YES) endif() # Build and install the plugin into the current build directry. set(SwiftTesting_MACRO_INSTALL_PREFIX "${CMAKE_BINARY_DIR}") ExternalProject_Add(TestingMacros PREFIX "tm" SOURCE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/TestingMacros" BUILD_ALWAYS ON CMAKE_ARGS -DCMAKE_MAKE_PROGRAM=${SwiftTesting_MACRO_MAKE_PROGRAM} -DCMAKE_Swift_COMPILER=${SwiftTesting_MACRO_Swift_COMPILER} -DCMAKE_Swift_FLAGS=${SwiftTesting_MACRO_Swift_FLAGS} -DCMAKE_Swift_FLAGS_RELEASE=${SwiftTesting_MACRO_Swift_FLAGS_RELEASE} -DCMAKE_Swift_FLAGS_RELWITHDEBINFO=${SwiftTesting_MACRO_SWIFT_FLAGS_RELWITHDEBINFO} -DCMAKE_AR=${SwiftTesting_MACRO_AR} -DCMAKE_RANLIB=${SwiftTesting_MACRO_RANLIB} -DCMAKE_BUILD_TYPE=${CSwiftTesting_MACRO_BUILD_TYPE} -DSwiftTesting_BuildMacrosAsExecutables=${SwiftTesting_BuildMacrosAsExecutables} -DSwiftSyntax_DIR=${SwiftSyntax_DIR} -DCMAKE_INSTALL_PREFIX=${SwiftTesting_MACRO_INSTALL_PREFIX}) # Hardcode the known file names based on system name as a workaround since # TestingMacros uses `ExternalProject` and we cannot directly query the # properties of its targets here. if(NOT SwiftTesting_BuildMacrosAsExecutables) if(CMAKE_HOST_SYSTEM_NAME STREQUAL "Darwin") set(SwiftTesting_MACRO_PATH "${SwiftTesting_MACRO_INSTALL_PREFIX}/lib/swift/host/plugins/testing/libTestingMacros.dylib") elseif(CMAKE_HOST_SYSTEM_NAME STREQUAL "Linux" OR CMAKE_HOST_SYSTEM_NAME STREQUAL "FreeBSD") set(SwiftTesting_MACRO_PATH "${SwiftTesting_MACRO_INSTALL_PREFIX}/lib/swift/host/plugins/libTestingMacros.so") elseif(CMAKE_HOST_SYSTEM_NAME STREQUAL "Windows") set(SwiftTesting_MACRO_PATH "${SwiftTesting_MACRO_INSTALL_PREFIX}/bin/TestingMacros.dll") else() message(FATAL_ERROR "Unable to determine the library name for TestingMacros based on system name: ${CMAKE_HOST_SYSTEM_NAME}") endif() else() if(CMAKE_HOST_SYSTEM_NAME STREQUAL "Windows") set(SwiftTesting_MACRO_PATH "${SwiftTesting_MACRO_INSTALL_PREFIX}/bin/TestingMacros.exe") else() set(SwiftTesting_MACRO_PATH "${SwiftTesting_MACRO_INSTALL_PREFIX}/bin/TestingMacros") endif() endif() elseif(SwiftTesting_MACRO) # Use the passed-in plugin path. set(SwiftTesting_MACRO_PATH "${SwiftTesting_MACRO}") add_custom_target(TestingMacros DEPENDS "${SwiftTesting_MACRO_PATH}") else() # If it's explicitly "NO", do not compile the library with macros. add_custom_target(TestingMacros) endif() if(NOT SwiftTesting_MACRO_PATH) message(STATUS "TestingMacros: (none)") elseif(SwiftTesting_MACRO_PATH) if(SwiftTesting_MACRO_PATH MATCHES [[.(dylib|so|dll)$]]) message(STATUS "TestingMacros: ${SwiftTesting_MACRO_PATH} (shared library)") add_compile_options("$<$:SHELL:-load-plugin-library \"${SwiftTesting_MACRO_PATH}\">") else() message(STATUS "TestingMacros: ${SwiftTesting_MACRO_PATH} (executable)") add_compile_options("$<$:SHELL:-load-plugin-executable \"${SwiftTesting_MACRO_PATH}#TestingMacros\">") endif() endif() ```