Skip to content

Commit

Permalink
Add requireFail. Like fail(), but it also always throws an error
Browse files Browse the repository at this point in the history
  • Loading branch information
younata committed Oct 11, 2024
1 parent cecacf0 commit 70d41c6
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 0 deletions.
14 changes: 14 additions & 0 deletions Sources/Nimble/DSL+Require.swift
Original file line number Diff line number Diff line change
Expand Up @@ -289,3 +289,17 @@ public func unwrapa<T>(fileID: String = #fileID, file: FileString = #filePath, l
public func unwrapa<T>(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)
}
31 changes: 31 additions & 0 deletions Tests/NimbleTests/DSLTest.swift
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import XCTest
import Nimble
#if SWIFT_PACKAGE
import NimbleSharedTestHelpers
#endif

private func nonThrowingInt() -> Int {
return 1
Expand Down Expand Up @@ -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())
}
}
}
}

0 comments on commit 70d41c6

Please sign in to comment.