Skip to content

Commit

Permalink
adding shouldThrowException function
Browse files Browse the repository at this point in the history
  • Loading branch information
akhesaCaro committed Mar 17, 2021
1 parent 135309d commit 2b0ac72
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
2 changes: 2 additions & 0 deletions hspec-expectations-lifted.cabal
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,10 @@ library
-Wall
build-depends:
base == 4.*
, exceptions
, hspec-expectations >= 0.8.2
, transformers
, mtl
hs-source-dirs:
src
exposed-modules:
Expand Down
23 changes: 23 additions & 0 deletions src/Test/Hspec/Expectations/Lifted.hs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ module Test.Hspec.Expectations.Lifted (
, shouldMatchList
, shouldReturn

, shouldThrowException

, shouldNotBe
, shouldNotSatisfy
, shouldNotContain
Expand All @@ -23,7 +25,11 @@ module Test.Hspec.Expectations.Lifted (
, HasCallStack
) where

import Control.Monad (unless)
import Control.Monad.IO.Class
import Control.Monad.Catch (MonadCatch, try)
import Control.Exception (Exception)
import Data.Typeable (typeOf)
import qualified Test.Hspec.Expectations as E
import Test.Hspec.Expectations (HasCallStack)

Expand Down Expand Up @@ -97,3 +103,20 @@ shouldNotContain = liftIO2 E.shouldNotContain
-- does not return @notExpected@.
shouldNotReturn :: (HasCallStack, MonadIO m, Show a, Eq a) => m a -> a -> m ()
shouldNotReturn action expected = action >>= liftIO . (`E.shouldNotBe` expected)

-- |
-- @action \`shouldThrowException\` expected@ Exception
shouldThrowException :: (HasCallStack, MonadIO m, MonadCatch m, Exception e, Eq e) => m a -> e -> m ()
action `shouldThrowException` e = do
r <- try action
case r of
Right _ ->
expectationFailure $
"did not get expected exception: " <> exceptionType e
Left err -> unless (err == e) $
expectationFailure $
"predicate failed on expected exception: "
<> exceptionType e
<> " (" <> show err <> ")"
where
exceptionType = (show . typeOf)

0 comments on commit 2b0ac72

Please sign in to comment.