Skip to content

Commit

Permalink
Merge pull request Quick#233 from jwfriese/equality_for_array_of_opti…
Browse files Browse the repository at this point in the history
…onals

Add equality matcher for collections of optionals
  • Loading branch information
jeffh committed Jan 17, 2016
2 parents 676d1c8 + d9e814f commit b05318f
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 0 deletions.
31 changes: 31 additions & 0 deletions Nimble/Matchers/Equal.swift
Expand Up @@ -53,6 +53,37 @@ public func equal<T: Equatable>(expectedValue: [T]?) -> NonNilMatcherFunc<[T]> {
}
}

/// A Nimble matcher allowing comparison of collection with optional type
public func equal<T: Equatable>(expectedValue: [T?]) -> NonNilMatcherFunc<[T?]> {
return NonNilMatcherFunc { actualExpression, failureMessage in
failureMessage.postfixMessage = "equal <\(stringify(expectedValue))>"
if let actualValue = try actualExpression.evaluate() {
if expectedValue.count != actualValue.count {
return false
}

for (index, item) in actualValue.enumerate() {
let otherItem = expectedValue[index]
if item == nil && otherItem == nil {
continue
} else if item == nil && otherItem != nil {
return false
} else if item != nil && otherItem == nil {
return false
} else if item! != otherItem! {
return false
}
}

return true
} else {
failureMessage.postfixActual = " (use beNil() to match nils)"
}

return false
}
}

/// A Nimble matcher that succeeds when the actual set is equal to the expected set.
public func equal<T>(expectedValue: Set<T>?) -> NonNilMatcherFunc<Set<T>> {
return equal(expectedValue, stringify: stringify)
Expand Down
29 changes: 29 additions & 0 deletions NimbleTests/Matchers/EqualTest.swift
Expand Up @@ -159,6 +159,35 @@ class EqualTest: XCTestCase {

expect(1).toNot(equal(nil))
}

func testArrayOfOptionalsEquality() {
let array1: Array<Int?> = [1, nil, 3]
let array2: Array<Int?> = [nil, 2, 3]
let array3: Array<Int?> = [1, nil, 3]

expect(array1).toNot(equal(array2))
expect(array1).to(equal(array3))
expect(array2).toNot(equal(array3))

let allNils1: Array<String?> = [nil, nil, nil, nil]
let allNils2: Array<String?> = [nil, nil, nil, nil]
let notReallyAllNils: Array<String?> = [nil, nil, nil, "turtles"]

expect(allNils1).to(equal(allNils2))
expect(allNils1).toNot(equal(notReallyAllNils))

let noNils1: Array<Int?> = [1, 2, 3, 4, 5]
let noNils2: Array<Int?> = [1, 3, 5, 7, 9]

expect(noNils1).toNot(equal(noNils2))

failsWithErrorMessage("expected to equal <[Optional(1), nil]>, got <[nil, Optional(2)]>") {
let arrayOfOptionalInts: Array<Int?> = [nil, 2]
let anotherArrayOfOptionalInts: Array<Int?> = [1, nil]
expect(arrayOfOptionalInts).to(equal(anotherArrayOfOptionalInts))
return
}
}

func testDictionariesWithDifferentSequences() {
// see: https://github.com/Quick/Nimble/issues/61
Expand Down

0 comments on commit b05318f

Please sign in to comment.