From 3108b10161d4755b189882d77d47c7486a919f9b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Galen=20O=E2=80=99Hanlon?= Date: Fri, 22 Dec 2023 17:50:52 -0800 Subject: [PATCH] Add test showing that a fix-it wrongly replaces parent instead of targeted child See #15. --- Tests/MacroTestingTests/FixItTests.swift | 92 ++++++++++++++++++++++++ 1 file changed, 92 insertions(+) create mode 100644 Tests/MacroTestingTests/FixItTests.swift diff --git a/Tests/MacroTestingTests/FixItTests.swift b/Tests/MacroTestingTests/FixItTests.swift new file mode 100644 index 0000000..bc8ba95 --- /dev/null +++ b/Tests/MacroTestingTests/FixItTests.swift @@ -0,0 +1,92 @@ +import MacroTesting +import SwiftDiagnostics +import SwiftSyntax +import SwiftSyntaxBuilder +import SwiftSyntaxMacros +import XCTest + +private enum ReplaceFirstMemberMacro: MemberMacro { + public static func expansion( + of node: AttributeSyntax, + providingMembersOf declaration: some DeclGroupSyntax, + in context: some MacroExpansionContext + ) throws -> [DeclSyntax] { + guard + let nodeToReplace = declaration.memberBlock.members.first, + let newNode = try? MemberBlockItemSyntax( + decl: VariableDeclSyntax(SyntaxNodeString(stringLiteral: "\n let oye: Oye")) + ) + else { return [] } + + context.diagnose( + Diagnostic( + node: node.attributeName, + message: SimpleDiagnosticMessage( + message: "First member needs to be replaced", + diagnosticID: MessageID(domain: "domain", id: "diagnostic2"), + severity: .warning + ), + fixIts: [ + FixIt( + message: SimpleDiagnosticMessage( + message: "Replace the first member", + diagnosticID: MessageID(domain: "domain", id: "fixit1"), + severity: .error + ), + changes: [ + .replace(oldNode: Syntax(nodeToReplace), newNode: Syntax(newNode)) + ] + ) + ] + ) + ) + + return [] + } +} + +final class FixItTests: BaseTestCase { + override func invokeTest() { + withMacroTesting(macros: [ReplaceFirstMemberMacro.self]) { + super.invokeTest() + } + } + + func testReplaceFirstMember_IncorrectlyReplacesParent() { + assertMacro { + """ + @ReplaceFirstMember + struct FooBar { + let foo: Foo + let bar: Bar + let baz: Baz + } + """ + } diagnostics: { + """ + @ReplaceFirstMember + ┬───────────────── + ╰─ ⚠️ First member needs to be replaced + ✏️ Replace the first member + struct FooBar { + let foo: Foo + let bar: Bar + let baz: Baz + } + """ + } fixes: { + """ + @ReplaceFirstMember + struct FooBar { + let oye: Oye + } + """ + } expansion: { + """ + struct FooBar { + let oye: Oye + } + """ + } + } +}