From 70d41c60dd685f3ffeea545bdcd2ddae633fd258 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 | 31 +++++++++++++++++++++++++++++++ 2 files changed, 45 insertions(+) diff --git a/Sources/Nimble/DSL+Require.swift b/Sources/Nimble/DSL+Require.swift index 189d23ef7..d26bc5b61 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, _ expression: @autoclosure () -> (() async throws -> T?)) async throws -> T { try await requirea(fileID: fileID, file: file, line: line, column: column, customError: customError, expression()).toNot(beNil()) } + +/// 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 d164226c2..b6e06e2d5 100644 --- a/Tests/NimbleTests/DSLTest.swift +++ b/Tests/NimbleTests/DSLTest.swift @@ -1,5 +1,8 @@ import XCTest import Nimble +#if SWIFT_PACKAGE +import NimbleSharedTestHelpers +#endif private func nonThrowingInt() -> Int { return 1 @@ -177,4 +180,32 @@ final class DSLTest: XCTestCase { expect(records.first?.success).to(beFalse()) expect(records.last?.success).to(beTrue()) } + + 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()) + } + } + } }