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 f459a20 commit 5ee5816
Show file tree
Hide file tree
Showing 2 changed files with 42 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, 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)
}
28 changes: 28 additions & 0 deletions Tests/NimbleTests/DSLTest.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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())
}
}
}
}

0 comments on commit 5ee5816

Please sign in to comment.