hspec-expectations-match-0.2.0.0: An hspec expectation that asserts a value matches a pattern.

Safe HaskellNone
LanguageHaskell2010

Test.Hspec.Expectations.Match

Description

This package provides expectations for use with hspec that use Template Haskell to assert that a value matches a particular pattern. Furthermore, any bindings created by the pattern will be returned if the pattern is successfully matched, making it easier to extract the result of some assertion and use it to make further assertions.

These functions should be used with Template Haskell’s expression and pattern quoters, notated by [| ... |] and [p| ... |], respectively.

Synopsis

Documentation

shouldMatch :: Q Exp -> Q Pat -> Q Exp Source #

Asserts that a value matches a given pattern and returns the pattern’s bindings if the match succeeds.

>>> a <- $([|Just True|] `shouldMatch` [p|Just x|])
>>> a
True
>>> a <- $([|Nothing|] `shouldMatch` [p|Just x|])
*** Exception: Nothing failed to match pattern (Just x)

If multiple values are bound by a pattern, they are returned in a tuple, in the order they appear in the pattern.

>>> (b, c) <- $([|['x', 'y']|] `shouldMatch` [p|[x, y]|])
>>> b
'x'
>>> c
'y'
>>> (b, c) <- $([|['x', 'y']|] `shouldMatch` [p|[x, y, z]|])
*** Exception: ['x','y'] failed to match pattern [x, y, z]

shouldReturnAndMatch :: Q Exp -> Q Pat -> Q Exp Source #

Like shouldReturn combined with shouldMatch. Like shouldReturn, the provided expression should produce an action that, once run, produces a value. Like shouldMatch, the resulting value will be matched against the provided pattern.

assertDo :: Q Exp -> Q Exp Source #

Instruments a do block by automatically inserting uses of shouldReturnAndMatch for monadic bindings. Specifically, the transformation converts this:

$(assertDo [|do
  [x, y] <- return [1, 2]
  x `shouldBe` 1
  y `shouldBe` 2|])

...into this:

do (x, y) <- $([|return [1, 2]|] `shouldReturnAndMatch' [p|[x, y]|])
   x `shouldBe` 1
   y `shouldBe` 2

This makes it much easier to read do blocks that make significant use of shouldReturnAndMatch.

Note that this transformation only applies to monadic bindings (not let bindings), and it does not occur when the pattern on the left hand side already fully covers all potential values (that is, when the pattern could not possibly fail to match).