From d9e814fdf71f2b4a67ddd236a2ef7345e4efc2be Mon Sep 17 00:00:00 2001 From: Jared Friese Date: Mon, 11 Jan 2016 19:18:47 -0800 Subject: [PATCH] Add equality matcher for collections of optionals --- Nimble/Matchers/Equal.swift | 31 ++++++++++++++++++++++++++++ NimbleTests/Matchers/EqualTest.swift | 29 ++++++++++++++++++++++++++ 2 files changed, 60 insertions(+) diff --git a/Nimble/Matchers/Equal.swift b/Nimble/Matchers/Equal.swift index 96b770518..2a6efa710 100644 --- a/Nimble/Matchers/Equal.swift +++ b/Nimble/Matchers/Equal.swift @@ -53,6 +53,37 @@ public func equal(expectedValue: [T]?) -> NonNilMatcherFunc<[T]> { } } +/// A Nimble matcher allowing comparison of collection with optional type +public func equal(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(expectedValue: Set?) -> NonNilMatcherFunc> { return equal(expectedValue, stringify: stringify) diff --git a/NimbleTests/Matchers/EqualTest.swift b/NimbleTests/Matchers/EqualTest.swift index decdb1dad..b0e07ba73 100644 --- a/NimbleTests/Matchers/EqualTest.swift +++ b/NimbleTests/Matchers/EqualTest.swift @@ -159,6 +159,35 @@ class EqualTest: XCTestCase { expect(1).toNot(equal(nil)) } + + func testArrayOfOptionalsEquality() { + let array1: Array = [1, nil, 3] + let array2: Array = [nil, 2, 3] + let array3: Array = [1, nil, 3] + + expect(array1).toNot(equal(array2)) + expect(array1).to(equal(array3)) + expect(array2).toNot(equal(array3)) + + let allNils1: Array = [nil, nil, nil, nil] + let allNils2: Array = [nil, nil, nil, nil] + let notReallyAllNils: Array = [nil, nil, nil, "turtles"] + + expect(allNils1).to(equal(allNils2)) + expect(allNils1).toNot(equal(notReallyAllNils)) + + let noNils1: Array = [1, 2, 3, 4, 5] + let noNils2: Array = [1, 3, 5, 7, 9] + + expect(noNils1).toNot(equal(noNils2)) + + failsWithErrorMessage("expected to equal <[Optional(1), nil]>, got <[nil, Optional(2)]>") { + let arrayOfOptionalInts: Array = [nil, 2] + let anotherArrayOfOptionalInts: Array = [1, nil] + expect(arrayOfOptionalInts).to(equal(anotherArrayOfOptionalInts)) + return + } + } func testDictionariesWithDifferentSequences() { // see: https://github.com/Quick/Nimble/issues/61