Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Custom Nimble matcher for use with the Promissum library
import Promissum
import Nimble
private func stringifyPromise<T, U>(promise: Promise<T, U>) -> String {
switch promise.result {
case nil: return "<pending>"
case let .Value(value)?: return "<resolved: \(value)>"
case let .Error(error)?: return "<rejected: \(error)>"
}
}
private func promiseMatcher<T, U>(
postfixMessage postfixMessage: String,
checker: Result<T, U>? -> Bool) -> NonNilMatcherFunc<Promise<T, U>> {
return NonNilMatcherFunc { actualExpression, failureMessage in
failureMessage.postfixMessage = postfixMessage
if let actualValue = try actualExpression.evaluate() {
failureMessage.actualValue = stringifyPromise(actualValue)
return checker(actualValue.result)
}
return false
}
}
func beResolved<T, U>() -> NonNilMatcherFunc<Promise<T, U>> {
return promiseMatcher(postfixMessage: "be resolved", checker: { result in
switch result {
case .Value?: return true
default: return false
}
})
}
func beRejected<T, U>() -> NonNilMatcherFunc<Promise<T, U>> {
return promiseMatcher(postfixMessage: "be rejected", checker: { result in
switch result {
case .Error?: return true
default: return false
}
})
}
func bePending<T, U>() -> NonNilMatcherFunc<Promise<T, U>> {
return promiseMatcher(postfixMessage: "be pending", checker: { result in
switch result {
case nil: return true
default: return false
}
})
}
/////
struct Handler: AssertionHandler {
func assert(assertion: Bool, message: FailureMessage, location: SourceLocation) {
if !assertion {
print("\(location): \(message.stringValue)")
}
}
}
NimbleAssertionHandler = Handler()
/////
let resolvedPromise: Promise<Int, NoError> = Promise(value: 42)
expect(resolvedPromise).to(beResolved())
expect(resolvedPromise).to(beRejected())
expect(resolvedPromise).to(bePending())
let rejectedPromise : Promise<(), NSError> = Promise(error: NSError(domain: "", code: 0, userInfo: nil))
expect(rejectedPromise).to(beResolved())
expect(rejectedPromise).to(beRejected())
expect(rejectedPromise).to(bePending())
let pendingPromise: Promise<Int, NoError> = PromiseSource().promise
expect(pendingPromise).to(beResolved())
expect(pendingPromise).to(beRejected())
expect(pendingPromise).to(bePending())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment