Consider the following code:
(defn assertFuzzyEquals [act exp]
(do (println "asserting equality over " act exp)
(let [inrange (<= (Math/abs (- act exp)) 1e-2)]
(if (= inrange false)
(println "abs(actual - expected) must be <= 1e-2. Expected was " exp " but got: " act))
(is (= inrange true))))
)
(defn assertVectorsFuzzyEqual [act exp]
(do (println "asserting fuzzy equality over" act exp)
(map assertFuzzyEquals act exp))
)
(deftest a-test5
(testing "Solve quadratic equations"
(assertVectorsFuzzyEqual [] [])
(assertVectorsFuzzyEqual [1] [1])
(assertVectorsFuzzyEqual [1] [2])
(assertVectorsFuzzyEqual [1] [1 1])
))
The output will be as follows:
asserting fuzzy equality over [] []
asserting fuzzy equality over [1] [1]
asserting fuzzy equality over [1] [2]
asserting fuzzy equality over [1] [1 1]
Ran 1 tests containing 0 assertions.
0 failures, 0 errors.
Why? Because, as the documentation of 'map' states, "[It] returns a lazy sequence consisting of the result of applying f to the set of first items of each coll, followed by applying f to the set of second items in each coll, until any one of the colls is exhausted." (Emphasis mine.)
What does this mean? Well, it means that in our case, assertFuzzyEquals was never called.
How can the realization of a lazy sequence be forced? Using doall. Let's modify the code accordingly:
; ...
(defn assertVectorsFuzzyEqual [act exp]
(do (println "asserting fuzzy equality over" act exp)
(doall (map assertFuzzyEquals act exp))) ; (1)
)
; ...
By using doall at (1), we force the sequence to be realized, and thus really execute the comparison.
The output is now as follows:
asserting fuzzy equality over [] []
asserting fuzzy equality over [1] [1]
asserting equality over 1 1
asserting fuzzy equality over [1] [2]
asserting equality over 1 2
abs(actual - expected) must be <= 1e-2. Expected was 2 but got: 1
lein test :only breaking.core-test/a-test5
FAIL in (a-test5) (core_test.clj:10)
Solve quadratic equations
expected: (= inrange true)
actual: (not (= false true))
asserting fuzzy equality over [1] [1 1]
asserting equality over 1 1
Ran 1 tests containing 3 assertions.
1 failures, 0 errors.
Tests failed.
As we expected. (N.B.: It is another story, that two vectors with different lengths are not detected... yet!)