@@ -11,6 +11,7 @@ module Test.Hspec.Expectations (
11
11
Expectation
12
12
, expectationFailure
13
13
, shouldBe
14
+ , shouldBeNear
14
15
, shouldSatisfy
15
16
, shouldStartWith
16
17
, shouldEndWith
@@ -78,7 +79,7 @@ expectationFailure = Test.HUnit.assertFailure
78
79
with_loc(expectTrue, String -> Bool -> Expectation )
79
80
expectTrue msg b = unless b (expectationFailure msg)
80
81
81
- infix 1 `shouldBe` , `shouldSatisfy` , `shouldStartWith` , `shouldEndWith` , `shouldContain` , `shouldMatchList` , `shouldReturn` , `shouldThrow`
82
+ infix 1 `shouldBe` , `shouldBeNear` , ` shouldSatisfy` , `shouldStartWith` , `shouldEndWith` , `shouldContain` , `shouldMatchList` , `shouldReturn` , `shouldThrow`
82
83
infix 1 `shouldNotBe` , `shouldNotSatisfy` , `shouldNotContain` , `shouldNotReturn`
83
84
84
85
-- |
@@ -87,6 +88,23 @@ infix 1 `shouldNotBe`, `shouldNotSatisfy`, `shouldNotContain`, `shouldNotReturn`
87
88
with_loc(shouldBe, (Show a, Eq a) => a -> a -> Expectation )
88
89
actual `shouldBe` expected = expectTrue (" expected: " ++ show expected ++ " \n but got: " ++ show actual) (actual == expected)
89
90
91
+ -- |
92
+ -- @actual \`shouldBeNear\` expected@ sets the expectation that @actual@ be a
93
+ -- floating point value near @expected@. If either value is zero we check that
94
+ -- the absolute difference is less than epsilon (1e-15) otherwise we check if
95
+ -- the relative difference is less than epsilon.
96
+ with_loc(shouldBeNear, (Show a, Ord a, Floating a) => a -> a -> Expectation )
97
+ actual `shouldBeNear` expected
98
+ -- Short circuit if they are actually equal.
99
+ | actual == expected = reportFail (actual == expected)
100
+ | actual == 0 || expected == 0 = reportFail (absoluteDifference < epsilon)
101
+ | otherwise = reportFail (relativeDifference < epsilon)
102
+ where
103
+ epsilon = 1e-15
104
+ absoluteDifference = abs (actual - expected)
105
+ relativeDifference = abs (actual - expected) / (abs actual + abs expected)
106
+ reportFail =
107
+ expectTrue (" expected: " ++ show expected ++ " \n but got: " ++ show actual)
90
108
-- |
91
109
-- @v \`shouldSatisfy\` p@ sets the expectation that @p v@ is @True@.
92
110
with_loc(shouldSatisfy, (Show a) => a -> (a -> Bool ) -> Expectation )
0 commit comments