Skip to content

Commit da1d5ac

Browse files
authored
Allow nil comments to be passed to #expect() or #require(). (#489)
This PR allows `nil` to be passed to the expectation macros as their documented signatures allow. Resolves #485. ### Checklist: - [x] Code and documentation should follow the style of the [Style Guide](https://github.com/apple/swift-testing/blob/main/Documentation/StyleGuide.md). - [x] If public symbols are renamed or modified, DocC references should be updated.
1 parent a36bbe0 commit da1d5ac

File tree

2 files changed

+23
-10
lines changed

2 files changed

+23
-10
lines changed

Sources/TestingMacros/ConditionMacro.swift

Lines changed: 18 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -138,17 +138,25 @@ extension ConditionMacro {
138138
}
139139

140140
// Capture any comments as well (either in source or as a macro argument.)
141-
checkArguments.append(Argument(
142-
label: "comments",
143-
expression: ArrayExprSyntax {
144-
for commentTraitExpr in createCommentTraitExprs(for: macro) {
145-
ArrayElementSyntax(expression: commentTraitExpr)
146-
}
147-
if let commentIndex {
148-
ArrayElementSyntax(expression: macroArguments[commentIndex].expression.trimmed)
149-
}
141+
let commentsArrayExpr = ArrayExprSyntax {
142+
for commentTraitExpr in createCommentTraitExprs(for: macro) {
143+
ArrayElementSyntax(expression: commentTraitExpr)
150144
}
151-
))
145+
if let commentIndex {
146+
ArrayElementSyntax(expression: macroArguments[commentIndex].expression.trimmed)
147+
}
148+
}
149+
if let commentIndex, !macroArguments[commentIndex].expression.is(StringLiteralExprSyntax.self) {
150+
// The developer supplied a comment argument that isn't a string
151+
// literal. It might be nil, so explicitly filter out nil values from
152+
// the resulting comment array.
153+
checkArguments.append(Argument(
154+
label: "comments",
155+
expression: #"(\#(commentsArrayExpr) as [Comment?]).compactMap(\.self)"#
156+
))
157+
} else {
158+
checkArguments.append(Argument(label: "comments", expression: commentsArrayExpr))
159+
}
152160

153161
checkArguments.append(Argument(label: "isRequired", expression: BooleanLiteralExprSyntax(isThrowing)))
154162

Tests/TestingTests/Traits/CommentTests.swift

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,11 @@ struct CommentTests {
5252
#expect(inner2Type.comments == ["// L"])
5353
#endif
5454
}
55+
56+
@Test("Explicitly nil comment")
57+
func explicitlyNilComment() {
58+
#expect(true as Bool, nil as Comment?)
59+
}
5560
}
5661

5762
// MARK: - Fixtures

0 commit comments

Comments
 (0)