Skip to content

Warn when passing a non-optional value to try #require(T?). #620

New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions Sources/Testing/Expectations/Expectation+Macro.swift
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,34 @@ public macro require(
sourceLocation: SourceLocation = #_sourceLocation
) -> Bool = #externalMacro(module: "TestingMacros", type: "AmbiguousRequireMacro")

/// Unwrap an optional value or, if it is `nil`, fail and throw an error.
///
/// - Parameters:
/// - optionalValue: The optional value to be unwrapped.
/// - comment: A comment describing the expectation.
/// - sourceLocation: The source location to which recorded expectations and
/// issues should be attributed.
///
/// - Returns: The unwrapped value of `optionalValue`.
///
/// - Throws: An instance of ``ExpectationFailedError`` if `optionalValue` is
/// `nil`.
///
/// If `optionalValue` is `nil`, an ``Issue`` is recorded for the test that is
/// running in the current task and an instance of ``ExpectationFailedError`` is
/// thrown.
///
/// This overload of ``require(_:_:sourceLocation:)-6w9oo`` is used when a
/// non-optional, non-`Bool` value is passed to `#require()`. It emits a warning
/// diagnostic indicating that the expectation is redundant.
@freestanding(expression)
@_documentation(visibility: private)
public macro require<T>(
_ optionalValue: T,
_ comment: @autoclosure () -> Comment? = nil,
sourceLocation: SourceLocation = #_sourceLocation
) -> T = #externalMacro(module: "TestingMacros", type: "NonOptionalRequireMacro")

// MARK: - Matching errors by type

/// Check that an expression always throws an error of a given type.
Expand Down
20 changes: 20 additions & 0 deletions Sources/TestingMacros/ConditionMacro.swift
Original file line number Diff line number Diff line change
Expand Up @@ -293,6 +293,26 @@ public struct AmbiguousRequireMacro: RefinedConditionMacro {
}
}

/// A type describing the expansion of the `#require()` macro when it is passed
/// a non-optional, non-`Bool` value.
///
/// This type is otherwise exactly equivalent to ``RequireMacro``.
public struct NonOptionalRequireMacro: RefinedConditionMacro {
public typealias Base = RequireMacro

public static func expansion(
of macro: some FreestandingMacroExpansionSyntax,
in context: some MacroExpansionContext
) throws -> ExprSyntax {
if let argument = macro.arguments.first {
context.diagnose(.nonOptionalRequireIsRedundant(argument.expression, in: macro))
}

// Perform the normal macro expansion for #require().
return try RequireMacro.expansion(of: macro, in: context)
}
}

// MARK: -

/// A syntax visitor that looks for uses of `#expect()` and `#require()` nested
Expand Down
20 changes: 20 additions & 0 deletions Sources/TestingMacros/Support/DiagnosticMessage.swift
Original file line number Diff line number Diff line change
Expand Up @@ -670,6 +670,26 @@ struct DiagnosticMessage: SwiftDiagnostics.DiagnosticMessage {
)
}

/// Create a diagnostic messages stating that the expression passed to
/// `#require()` is not optional and the macro is redundant.
///
/// - Parameters:
/// - expr: The non-optional expression.
///
/// - Returns: A diagnostic message.
static func nonOptionalRequireIsRedundant(_ expr: ExprSyntax, in macro: some FreestandingMacroExpansionSyntax) -> Self {
// We do not provide fix-its because we cannot see the leading "try" keyword
// so we can't provide a valid fix-it to remove the macro either. We can
// provide a fix-it to add "as Optional", but only providing that fix-it may
// confuse or mislead developers (and that's presumably usually the *wrong*
// fix-it to select anyway.)
Self(
syntax: Syntax(expr),
message: "\(_macroName(macro)) is redundant because '\(expr.trimmed)' never equals 'nil'",
severity: .warning
)
}

/// Create a diagnostic message stating that a condition macro nested inside
/// an exit test will not record any diagnostics.
///
Expand Down
1 change: 1 addition & 0 deletions Sources/TestingMacros/TestingMacrosMain.swift
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ struct TestingMacrosMain: CompilerPlugin {
ExpectMacro.self,
RequireMacro.self,
AmbiguousRequireMacro.self,
NonOptionalRequireMacro.self,
ExitTestExpectMacro.self,
ExitTestRequireMacro.self,
TagMacro.self,
Expand Down
13 changes: 13 additions & 0 deletions Tests/TestingMacrosTests/ConditionMacroTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -331,6 +331,19 @@ struct ConditionMacroTests {
#expect(diagnostics.isEmpty)
}

@Test("#require(non-optional value) produces a diagnostic",
arguments: [
"#requireNonOptional(expression)",
]
)
func requireNonOptionalProducesDiagnostic(input: String) throws {
let (_, diagnostics) = try parse(input)

let diagnostic = try #require(diagnostics.first)
#expect(diagnostic.diagMessage.severity == .warning)
#expect(diagnostic.message.contains("is redundant"))
}

#if !SWT_NO_EXIT_TESTS
@Test("Expectation inside an exit test diagnoses",
arguments: [
Expand Down
1 change: 1 addition & 0 deletions Tests/TestingMacrosTests/TestSupport/Parse.swift
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ fileprivate let allMacros: [String: any Macro.Type] = [
"expect": ExpectMacro.self,
"require": RequireMacro.self,
"requireAmbiguous": AmbiguousRequireMacro.self, // different name needed only for unit testing
"requireNonOptional": NonOptionalRequireMacro.self, // different name needed only for unit testing
"expectExitTest": ExitTestRequireMacro.self, // different name needed only for unit testing
"requireExitTest": ExitTestRequireMacro.self, // different name needed only for unit testing
"Suite": SuiteDeclarationMacro.self,
Expand Down
4 changes: 2 additions & 2 deletions Tests/TestingTests/BacktraceTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,8 @@ struct BacktraceTests {
}

@Test("Backtrace.current() is populated")
func currentBacktrace() throws {
let backtrace = try #require(Backtrace.current())
func currentBacktrace() {
let backtrace = Backtrace.current()
#expect(!backtrace.addresses.isEmpty)
}

Expand Down
2 changes: 1 addition & 1 deletion Tests/TestingTests/IssueTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ final class IssueTests: XCTestCase {

await Test {
let x: String? = nil
_ = try #require(x ?? "hello")
_ = try #require(x ?? ("hello" as String?))
}.run(configuration: configuration)
}

Expand Down
10 changes: 4 additions & 6 deletions Tests/TestingTests/MiscellaneousTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -369,9 +369,8 @@ struct MiscellaneousTests {
#expect(firstParameter.index == 0)
#expect(firstParameter.firstName == "i")
#expect(firstParameter.secondName == nil)
let firstParameterTypeInfo = try #require(firstParameter.typeInfo)
#expect(firstParameterTypeInfo.fullyQualifiedName == "Swift.Int")
#expect(firstParameterTypeInfo.unqualifiedName == "Int")
#expect(firstParameter.typeInfo.fullyQualifiedName == "Swift.Int")
#expect(firstParameter.typeInfo.unqualifiedName == "Int")
} catch {}

do {
Expand All @@ -386,9 +385,8 @@ struct MiscellaneousTests {
#expect(secondParameter.index == 1)
#expect(secondParameter.firstName == "j")
#expect(secondParameter.secondName == "k")
let secondParameterTypeInfo = try #require(secondParameter.typeInfo)
#expect(secondParameterTypeInfo.fullyQualifiedName == "Swift.String")
#expect(secondParameterTypeInfo.unqualifiedName == "String")
#expect(secondParameter.typeInfo.fullyQualifiedName == "Swift.String")
#expect(secondParameter.typeInfo.unqualifiedName == "String")
} catch {}
}

Expand Down