HSpec(或 HUnit)是否有可能将更多信息附加到打印的断言中,并且仅在失败的情况下?

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

类似于quickcheck如何支持反例:

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

但在某种程度上它可以与 shouldBe 一起使用,例如

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

我希望它打印出如下内容:

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

是的,好像可以:

import Control.Exception
import Test.HUnit.Lang (HUnitFailure(..))

failDetails details assert = do
  assert `catch` \(HUnitFailure loc msg) -> do
    throw $ HUnitFailure loc $ msg ++ "\n" ++ details

我们捕获 shouldBe 抛出的异常,修改消息并重新抛出。

我们甚至可以像这样使用它:

1 `shouldBe` 2
  $> failDetails "foobar"

如果我们定义:

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

受@Wizek 回答的启发,这里有一个适用于较新版本 HUnit 的版本,适用于 Selenium/WebDriver。

它适当地解包和重新打包 FailureReason 的不同构造函数

主要区别在于 Control.Monad.Catch 的使用,它让您可以使用 WD 而不是 IO。

此外,无需编写 $> 运算符 - Data.Function

中已经有 &
import Test.HUnit.Lang
import Control.Monad.Catch
import qualified Data.Text as Text
import Data.Function ((&))

failDetails :: Text -> WD () -> WD ()
failDetails textMessage expectation =
  expectation `catch` \(HUnitFailure loc reason) ->
    throwM $ HUnitFailure loc $ addMessageTo reason
  where
  message :: String 
  message = Text.unpack textMessage

  addMessageTo :: FailureReason -> FailureReason
  addMessageTo (Reason reason) = Reason $ reason ++ "\n" ++ message
  addMessageTo (ExpectedButGot preface expected actual) = 
    ExpectedButGot newPreface expected actual
    where
    newPreface = 
      case preface of 
      Nothing -> Just message
      Just existingMessage -> Just $ existingMessage ++ "\n" ++ message