Search code examples
haskellhunithspec

Is it possible with HSpec (or HUnit) to attach further information to assertions that get printed in and only in case of failure?


Similarly to how quickcheck supports counterexamples:

property \x ->
  counterexample ("Foo failed with: " ++ ...) $
    foo x

but in a way that it works with shouldBe, e.g.

failDetails (" details: " ++ baz a) $
  a `shouldBe` 2

And I would like it to print something along the lines of:

expected: 2
 but got: 3
 details: ...

Solution

  • Yes, it seems to be possible:

    import Control.Exception
    import Test.HUnit.Lang (HUnitFailure(..))
    
    failDetails details assert = do
      assert `catch` \(HUnitFailure loc msg) -> do
        throw $ HUnitFailure loc $ msg ++ "\n" ++ details
    

    We catch the exception thrown by shouldBe, amend the message, and rethrow it.

    We can even use it like:

    1 `shouldBe` 2
      $> failDetails "foobar"
    

    if we define:

    ($>) = flip ($)
    infixl 0 $>
    {-# INLINE ($>) #-}