簡體   English   中英

使用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一起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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM