swiftlang / swift-syntax

A set of Swift libraries for parsing, inspecting, generating, and transforming Swift source code.
Apache License 2.0
3.13k stars 393 forks source link

Adopt Swift-Testing in test utils such as `SwiftSyntaxMacrosTestSupport` #2720

Open MahdiBM opened 2 weeks ago

MahdiBM commented 2 weeks ago

Description

Currently you need to use XCTest to run macro tests with SwiftSyntaxMacrosTestSupport functions because they rely on some XCTest functions such as XCTFail.

swift-syntax tests utils should also support Swift-Testing.

MahdiBM commented 2 weeks ago

Not that hard to do, even manually. This works like the currently-provided XCTest-related functions.

import SwiftSyntax
import SwiftSyntaxMacrosGenericTestSupport
import SwiftSyntaxMacros
import SwiftSyntaxMacroExpansion
import Testing

func assertMacroExpansionWithSwiftTesting(
    _ originalSource: String,
    expandedSource expectedExpandedSource: String,
    diagnostics: [DiagnosticSpec] = [],
    macros: [String: any Macro.Type],
    applyFixIts: [String]? = nil,
    fixedSource expectedFixedSource: String? = nil,
    testModuleName: String = "TestModule",
    testFileName: String = "test.swift",
    indentationWidth: Trivia = .spaces(4),
    sourceLocation: Testing.SourceLocation = Testing.SourceLocation()
) {
    let macroSpecs = macros.mapValues { MacroSpec(type: $0) }
    SwiftSyntaxMacrosGenericTestSupport.assertMacroExpansion(
        originalSource,
        expandedSource: expectedExpandedSource,
        diagnostics: diagnostics,
        macroSpecs: macroSpecs,
        applyFixIts: applyFixIts,
        fixedSource: expectedFixedSource,
        testModuleName: testModuleName,
        testFileName: testFileName,
        indentationWidth: indentationWidth,
        failureHandler: {
            #expect(Bool(false), .init(stringLiteral: $0.message), sourceLocation: sourceLocation)
        },
        fileID: "",  // Not used in the failure handler
        filePath: "", /// MahdiBM comment: requires StaticString so just set it to "" for now.
        line: UInt(sourceLocation.line),
        column: 0  // Not used in the failure handler
    )
}

[Update]: added some more imports to the code.

ahoppen commented 2 weeks ago

Synced to Apple’s issue tracker as rdar://131312113