Skip to content

Instantly share code, notes, and snippets.

@cjnevin
Created October 31, 2022 07:32
Show Gist options
  • Select an option

  • Save cjnevin/b7561e6e331520c1eefb395400e5a91e to your computer and use it in GitHub Desktop.

Select an option

Save cjnevin/b7561e6e331520c1eefb395400e5a91e to your computer and use it in GitHub Desktop.
import XCTest
@resultBuilder
struct AssertionBuilder {
static func buildArray(_ components: [Bool]) -> Bool {
components.reduce(true) { $0 && $1 }
}
static func buildBlock(_ components: Bool...) -> Bool {
components.reduce(true) { $0 && $1 }
}
static func buildEither(first component: Bool) -> Bool {
component
}
static func buildEither(second component: Bool) -> Bool {
component
}
static func buildOptional(_ component: Bool?) -> Bool {
component ?? false
}
static func buildExpression<T>(_ expression: Optional<T>) -> Bool {
switch expression {
case .some: return true
case .none: return false
}
}
}
func pass(file: StaticString = #file, line: UInt = #line) {
XCTAssertTrue(true)
}
func pass(@AssertionBuilder _ builder: () throws -> Bool, file: StaticString = #file, line: UInt = #line) rethrows {
XCTAssertTrue(try builder(), file: file, line: line)
}
func unwrap<T>(_ expression: Optional<T>, file: StaticString = #file, line: UInt = #line) throws -> T {
try XCTUnwrap(expression, file: file, line: line)
}
func unwrap<T>(_ expression: Optional<T>, @AssertionBuilder _ builder: (T) -> Bool, file: StaticString = #file, line: UInt = #line) throws {
XCTAssertTrue(builder(try unwrap(expression, file: file, line: line)), file: file, line: line)
}
struct DidNotExplode: Error {}
func fail<T>(_ expression: @autoclosure () throws -> T, file: StaticString = #file, line: UInt = #line) throws {
do {
_ = try expression()
throw DidNotExplode()
} catch {
pass(file: file, line: line)
}
}
func fail(_ message: String = "", file: StaticString = #file, line: UInt = #line) {
XCTFail(message, file: file, line: line)
}
// Tests:
final class PassOrFailTests: XCTestCase {
func testEquals() {
let a = 1, b = 1
pass { a == b }
}
func testUnwrap() {
let a: String? = ""
pass { a }
}
func testTryUnwrap() throws {
let a: String? = ""
try unwrap(a) { $0.isEmpty }
}
func testTryUnwrapInPass() throws {
let a: String? = ""
let value = { try unwrap(a) }
try pass { try value().isEmpty }
}
func testFail() throws {
var a: String? = nil
try fail { try unwrap(a) }
a = ""
do {
try fail { try unwrap(a) }
pass()
} catch {
fail()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment