### Test Macro with Swift Testing Framework Source: https://github.com/pointfreeco/swift-macro-testing/blob/main/README.md Demonstrates how to test a Swift macro using the built-in Swift Testing framework. It configures macro testing with the `Trait` system and asserts macro expansions. This example requires the `Testing` and `MacroTesting` libraries. ```swift import Testing import MacroTesting @Suite( .macros( ["stringify": StringifyMacro.self], record: .missing // Record only missing snapshots ) ) struct StringifyMacroSwiftTestingTests { @Test func testStringify() { assertMacro { """ #stringify(a + b) """ } expansion: { """ (a + b, "a + b") """ } } } ``` -------------------------------- ### Record Swift Macro Expansions Automatically Source: https://github.com/pointfreeco/swift-macro-testing/blob/main/README.md This example shows how to automatically record the expansion of Swift macros directly into the test file. By adding `record: .all` to the `.macros` trait, the library updates the `expansion` trailing closure with the latest macro output when tests are run. ```swift @Suite(.macros([StringifyMacro.self], record: .all)) struct StringifyTests { @Test func stringify() { assertMacro { """ #stringify(a + b) """ } expansion: { // The expansion will be automatically recorded here } } } ``` -------------------------------- ### Swift Testing Integration with .macros Trait Source: https://context7.com/pointfreeco/swift-macro-testing/llms.txt Demonstrates how to use the `.macros` trait from MacroTesting within Swift's native Testing framework to configure and test Swift macros. This integration allows for seamless setup of macro tests, including specifying macros to test and controlling snapshot recording behavior directly within the test suite configuration. ```swift import MacroTesting import Testing @Suite( .macros( ["URL": URLMacro.self], record: .failed // Only re-record failed snapshots ) ) struct URLMacroTests { @Test func expansionWithMalformedURLEmitsError() { assertMacro { """ let invalid = #URL("https://not a url.com") """ } diagnostics: { """ let invalid = #URL("https://not a url.com") ┬──────────────────────────── ╰─ 🛑 malformed url: "https://not a url.com" """ } } @Test func expansionWithStringInterpolationEmitsError() { assertMacro { #""" #URL("https://\(domain)/api/path") #""# } diagnostics: { #""" #URL("https://\(domain)/api/path") ┬───────────────────────────────── ╰─ 🛑 #URL requires a static string literal #""" } } @Test func expansionWithValidURL() { assertMacro { """ let valid = #URL("https://swift.org/") """ } expansion: { """ let valid = URL(string: "https://swift.org/")! """ } } } // Using array syntax for macros @Suite(.macros([StringifyMacro.self], record: .missing)) struct StringifyMacroSwiftTestingTests { @Test func testStringify() { assertMacro { """ #stringify(a + b) """ } expansion: { """ (a + b, "a + b") """ } } } ``` -------------------------------- ### Control Snapshot Recording Strategies with MacroTesting Source: https://context7.com/pointfreeco/swift-macro-testing/llms.txt Illustrates various recording strategies in MacroTesting for managing macro expansion snapshots. These strategies, including `.all`, `.missing`, `.failed`, and `.never`, can be configured using `withMacroTesting`, the `.macros` trait, or the `SNAPSHOT_TESTING_RECORD` environment variable to control when snapshots are written or updated. ```swift import MacroTesting import XCTest final class RecordingStrategiesTests: XCTestCase { func testRecordAll() { // Record all snapshots, overwriting existing ones withMacroTesting(record: .all, macros: [StringifyMacro.self]) { assertMacro { """ #stringify(1 + 2) """ } expansion: { """ (1 + 2, "1 + 2") """ } } } func testRecordMissing() { // Only record snapshots that don't exist yet withMacroTesting(record: .missing, macros: [StringifyMacro.self]) { assertMacro { """ #stringify(x * y) """ } expansion: { """ (x * y, "x * y") """ } } } func testRecordFailed() { // Only re-record snapshots that fail comparison withMacroTesting(record: .failed, macros: [StringifyMacro.self]) { assertMacro { """ #stringify(a - b) """ } expansion: { """ (a - b, "a - b") """ } } } func testRecordNever() { // Never record, only compare (useful for CI) withMacroTesting(record: .never, macros: [StringifyMacro.self]) { assertMacro { """ #stringify(foo) """ } expansion: { """ (foo, "foo") """ } } } } // Environment variable configuration: // Set SNAPSHOT_TESTING_RECORD=all to record all snapshots // Set SNAPSHOT_TESTING_RECORD=missing to record only missing // Set SNAPSHOT_TESTING_RECORD=failed to record only failed // Set SNAPSHOT_TESTING_RECORD=never to disable recording ``` -------------------------------- ### MacroTesting/withMacroTesting Source: https://github.com/pointfreeco/swift-macro-testing/blob/main/Sources/MacroTesting/Documentation.docc/WithMacroTesting.md The `withMacroTesting` function is used to test Swift macros. It provides several overloads to configure testing behavior, including indentation width, recording mode, and the macros to be tested. ```APIDOC ## `withMacroTesting` Function ### Description The `withMacroTesting` function is a core utility in the MacroTesting library for facilitating the testing of Swift macros. It allows developers to specify various parameters to control the testing environment and the macro execution. ### Method N/A (This is a function call, not a REST API endpoint) ### Endpoint N/A ### Parameters This function has multiple overloads, each accepting different combinations of parameters. Common parameters include: #### Path Parameters None #### Query Parameters None #### Request Body None **Common Parameters Across Overloads:** - **`indentationWidth`** (Int) - Optional - Specifies the indentation width for macro expansion output. - **`record`** (Bool) - Optional - Determines whether to record macro expansions for future comparison. - **`macros`** ([any Macro.Type]) - Required - An array of macro types to be tested. - **`operation`** (() throws -> Void) - Required - The code block containing the macro operations to be executed and tested. ### Request Example ```swift // Example usage with specific parameters withMacroTesting(indentationWidth: 4, record: true, macros: [MyMacro.self]) { // Your macro testing code here } ``` ### Response #### Success Response (N/A) This function does not return a value in the traditional sense. Its effect is in executing the `operation` block and potentially recording macro expansions. #### Response Example N/A ### Deprecated Overloads The following overloads are deprecated and may be removed in future versions. It is recommended to use the non-deprecated versions where possible. - `withMacroTesting(indentationWidth:isRecording:macros:operation:)-1yql2` - `withMacroTesting(indentationWidth:isRecording:macros:operation:)-9du8s` - `withMacroTesting(indentationWidth:isRecording:macros:operation:)-91prk` - `withMacroTesting(indentationWidth:isRecording:macros:operation:)-5id9j` ### Overloads The following are available overloads for the `withMacroTesting` function: - `withMacroTesting(indentationWidth:record:macros:operation:)-7cm1s` - `withMacroTesting(indentationWidth:record:macros:operation:)-5a7qi` - `withMacroTesting(indentationWidth:record:macros:operation:)-9ghea` ``` -------------------------------- ### Swift Macro Testing with Recording Expansions Source: https://github.com/pointfreeco/swift-macro-testing/blob/main/Sources/MacroTesting/Documentation.docc/MacroTesting.md Shows how to configure MacroTesting to automatically record macro expansions directly into the test file. By setting the `record` argument in `Trait.macros`, future test runs will update the `expansion` closure with the latest macro output. ```swift @Suite(.macros([StringifyMacro.self], record: .all)) struct StringifyTests { @Test func stringify() { assertMacro { """ #stringify(a + b) """ } } } ``` -------------------------------- ### Test Swift Macro Expansion with Assertions Source: https://github.com/pointfreeco/swift-macro-testing/blob/main/README.md This snippet demonstrates how to test a Swift macro's expansion using the `assertMacro` function. It takes a string of Swift source code that uses the macro and optionally an `expansion` closure to verify the output. Dependencies include `MacroTesting` and `Testing` libraries. ```swift import MacroTesting import Testing @Suite(.macros([StringifyMacro.self])) struct StringifyTests { @Test func stringify() { assertMacro { """ #stringify(a + b) """ } } } ``` -------------------------------- ### Swift Macro Testing with assertMacro Source: https://github.com/pointfreeco/swift-macro-testing/blob/main/Sources/MacroTesting/Documentation.docc/MacroTesting.md Demonstrates how to use the `assertMacro` function to test a Swift macro. It takes a string of Swift source code, expands the specified macros, and compares the expansion against an expected output. This function is part of the MacroTesting library. ```swift import MacroTesting import Testing @Suite(.macros([StringifyMacro.self])) struct StringifyTests { @Test func stringify() { assertMacro { """ #stringify(a + b) """ } expansion: { """ (a + b, "a + b") """ } } } ``` -------------------------------- ### Configure Macro Test Environment with withMacroTesting - Swift Source: https://context7.com/pointfreeco/swift-macro-testing/llms.txt Configures the testing environment for Swift macros, allowing specification of macros to expand, indentation width, and recording behavior. It is typically used within the `invokeTest()` method of a test case to apply settings globally to all tests within that case. ```swift import MacroTesting import XCTest class BaseTestCase: XCTestCase { override func invokeTest() { // Configure recording strategy for all tests withMacroTesting(record: .missing) { super.invokeTest() } } } final class StringifyMacroTests: BaseTestCase { override func invokeTest() { // Layer additional configuration: specify macros to expand withMacroTesting(macros: [StringifyMacro.self]) { super.invokeTest() } } func testStringify() { // assertMacro uses configuration from withMacroTesting assertMacro { """ #stringify(a + b) """ } expansion: { """ (a + b, "a + b") """ } } } final class IndentationTests: XCTestCase { func testCustomIndentation() { // Configure indentation inline for specific tests withMacroTesting( indentationWidth: .spaces(2), macros: [AddMemberMacro.self] ) { assertMacro { """ @AddMember struct S { } """ } expansion: { """ struct S { let v: T } """ } } } } ``` -------------------------------- ### Test Macro Expansions with assertMacro in Swift Source: https://context7.com/pointfreeco/swift-macro-testing/llms.txt The primary function for testing Swift macro expansions using XCTest. It takes Swift source code with macro invocations and verifies the expanded output. The library automatically writes expected output into your test file when run in record mode. Requires the MacroTesting and XCTest frameworks. ```swift import MacroTesting import XCTest final class StringifyMacroTests: XCTestCase { override func invokeTest() { // Configure macros once for all tests in this class withMacroTesting(macros: [StringifyMacro.self]) { super.invokeTest() } } func testBasicExpansion() { // Test that #stringify expands correctly assertMacro { """ let result = #stringify(x + y) """ } expansion: { """ let result = (x + y, "x + y") """ } } func testWithStringInterpolation() { assertMacro { #"let greeting = #stringify("Hello, (name)")"# } expansion: { #"let greeting = ("Hello, (name)", #""Hello, (name)""#)"# } } } ``` -------------------------------- ### Assert Macro with Fix-Its and Expansion - Swift Source: https://context7.com/pointfreeco/swift-macro-testing/llms.txt Tests Swift macros by asserting the diagnostic suggestions, including fix-it indicators, and the resulting source code after applying fix-its. It also captures the final macro expansion. This function is useful for verifying that macros provide correct diagnostics and transformations. ```swift import MacroTesting import XCTest final class AddCompletionHandlerTests: XCTestCase { override func invokeTest() { withMacroTesting(macros: [AddCompletionHandlerMacro.self]) { super.invokeTest() } } func testNonAsyncFunctionEmitsErrorWithFixIt() { assertMacro { """ struct Test { @AddCompletionHandler func fetchData() -> String { return "Hello, World!" } } """ } diagnostics: { """ struct Test { @AddCompletionHandler func fetchData() -> String { ┬─── ╰─ 🛑 can only add a completion-handler variant to an 'async' function ✏️ add 'async' return "Hello, World!" } } """ } fixes: { """ struct Test { @AddCompletionHandler func fetchData() async-> String { return "Hello, World!" } } """ } expansion: { """ struct Test { func fetchData() async-> String { return "Hello, World!" } func fetchData(completionHandler: @escaping (String) -> Void) { Task { completionHandler(await fetchData()) } } } """ } } func testSuccessfulAsyncFunctionExpansion() { assertMacro { """ @AddCompletionHandler func f(a: Int, for b: String, _ value: Double) async -> String { return b } """ } expansion: { """ func f(a: Int, for b: String, _ value: Double) async -> String { return b } func f(a: Int, for b: String, _ value: Double, completionHandler: @escaping (String) -> Void) { Task { completionHandler(await f(a: a, for: b, value)) } } """ } } } ``` -------------------------------- ### Test Macro Diagnostics with assertMacro in Swift Source: https://context7.com/pointfreeco/swift-macro-testing/llms.txt Tests macro diagnostics (errors, warnings, notes) using assertMacro within XCTest. It renders diagnostics inline with visual indicators, allowing comprehensive testing of macro error handling and user-facing messages. Requires the MacroTesting and XCTest frameworks. ```swift import MacroTesting import XCTest final class MetaEnumMacroTests: XCTestCase { override func invokeTest() { withMacroTesting(macros: [MetaEnumMacro.self]) { super.invokeTest() } } func testExpansionOnStructEmitsError() { // Test that applying @MetaEnum to a struct produces the expected error assertMacro { """ @MetaEnum struct Cell { let integer: Int let text: String let boolean: Bool } """ } diagnostics: { """ @MetaEnum struct Cell { ┬──────── ╰─ 🛑 '@MetaEnum' can only be attached to an enum, not a struct let integer: Int let text: String let boolean: Bool } """ } } func testSuccessfulExpansion() { assertMacro { """ @MetaEnum enum Cell { case integer(Int) case text(String) case boolean(Bool) case null } """ } expansion: { """ enum Cell { case integer(Int) case text(String) case boolean(Bool) case null enum Meta { case integer case text case boolean case null init(_ __macro_local_6parentfMu_: Cell) { switch __macro_local_6parentfMu_ { case .integer: self = .integer case .text: self = .text case .boolean: self = .boolean case .null: self = .null } } } } """ } } } ``` -------------------------------- ### Swift Macro Testing with Diagnostics and Fixes Source: https://github.com/pointfreeco/swift-macro-testing/blob/main/Sources/MacroTesting/Documentation.docc/MacroTesting.md Illustrates testing Swift macros that emit diagnostics (errors, warnings, notes) and fix-its. The `assertMacro` function can capture these diagnostics and expected fixes, along with the final macro expansion. This is useful for macros that modify code based on certain conditions. ```swift func testNonAsyncFunctionDiagnostic() { assertMacro { """ @AddCompletionHandler func f(a: Int, for b: String) -> String { return b } """ } diagnostics: { """ @AddCompletionHandler func f(a: Int, for b: String) -> String { ┬─── ╰─ 🛑 can only add a completion-handler variant to an 'async' function ✏️ add 'async' return b } """ } fixes: { """ @AddCompletionHandler func f(a: Int, for b: String) async -> String { return b } """ } expansion: { """ func f(a: Int, for b: String) async -> String { return b } func f(a: Int, for b: String, completionHandler: @escaping (String) -> Void) { Task { completionHandler(await f(a: a, for: b, value)) } } """ } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.