Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to check cases when exception is thrown with QuickCheck?

Suppose I have a function that should calculate some value in one case and throw an exception otherwise. I would like to use QuickCheck to ensure my function behaves correctly, however is not obvious how to perform this sort of check. Is it possible and if yes, how to check that exception of certain type is thrown and it contains correct information about its cause?

like image 391
Mark Karpov Avatar asked Nov 09 '22 02:11

Mark Karpov


1 Answers

Indeed ioProperty is the key to this sort of test. You will need to use it in combination with catch or try. Here I show the latter:

prop_exceptional :: Int -> Property
prop_exceptional n = ioProperty $ do
  result <- try . evaluate $ myDangerousFunction n
  return $ r === result
  where r | n == 0    = Left  MyException
          | otherwise = Right 42

Quite obviously, myDangerousFunction should throw MyException whenever it gets 0 and return 42 otherwise. Note the useful function evaluate, which you need to use to evaluate pure function in IO context to catch exceptions produced there.

like image 62
Mark Karpov Avatar answered Nov 15 '22 06:11

Mark Karpov