From 5ee58166cf4394741f06dc178a38021728d3c96c Mon Sep 17 00:00:00 2001 From: Rachel Brindle Date: Thu, 10 Oct 2024 20:32:35 -0700 Subject: [PATCH] Add requireFail. Like fail(), but it also always throws an error --- Sources/Nimble/DSL+Require.swift | 14 ++++++++++++++ Tests/NimbleTests/DSLTest.swift | 28 ++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+) diff --git a/Sources/Nimble/DSL+Require.swift b/Sources/Nimble/DSL+Require.swift index 4df5c5b4..bd73f72f 100644 --- a/Sources/Nimble/DSL+Require.swift +++ b/Sources/Nimble/DSL+Require.swift @@ -289,3 +289,17 @@ public func unwrapa(fileID: String = #fileID, file: FileString = #filePath, l public func unwrapa(fileID: String = #fileID, file: FileString = #filePath, line: UInt = #line, column: UInt = #column, customError: Error? = nil, description: String? = nil, _ expression: @autoclosure () -> (() async throws -> T?)) async throws -> T { try await requirea(fileID: fileID, file: file, line: line, column: column, customError: customError, expression()).toNot(beNil(), description: description) } + +/// Always fails the test and throw an error to prevent further test execution. +/// +/// - Parameter message: A custom message to use in place of the default one. +/// - Parameter customError: A custom error to throw in place of a ``RequireError``. +public func requireFail(_ message: String? = nil, customError: Error? = nil, fileID: String = #fileID, filePath: FileString = #filePath, line: UInt = #line, column: UInt = #column) throws { + let location = SourceLocation(fileID: fileID, filePath: filePath, line: line, column: column) + let handler = NimbleEnvironment.activeInstance.assertionHandler + + let msg = message ?? "requireFail() always fails" + handler.assert(false, message: FailureMessage(stringValue: msg), location: location) + + throw customError ?? RequireError(message: msg, location: location) +} diff --git a/Tests/NimbleTests/DSLTest.swift b/Tests/NimbleTests/DSLTest.swift index 1c828686..12d3f97a 100644 --- a/Tests/NimbleTests/DSLTest.swift +++ b/Tests/NimbleTests/DSLTest.swift @@ -219,4 +219,32 @@ final class DSLTest: XCTestCase { try await unwrapa(description: "Other Message", await asyncOptional(nil)) } } + + func testRequireFail() throws { + struct MyCustomError: Error {} + + failsWithErrorMessage("requireFail() always fails") { + do { + try requireFail() + } catch { + expect(error as? RequireError).toNot(beNil()) + } + } + + failsWithErrorMessage("Custom error message") { + do { + try requireFail("Custom error message") + } catch { + expect(error as? RequireError).toNot(beNil()) + } + } + + failsWithErrorMessage("Custom message with custom error") { + do { + try requireFail("Custom message with custom error", customError: MyCustomError()) + } catch { + expect(error as? MyCustomError).toNot(beNil()) + } + } + } }