I have interest in using the quick check library but it seems that it is designed to test properties. What I would like to do is generate random data for my defined data types and test functions I have written. I do not care about what the result is, just if the function produces a runtime error when fed random data. All of the quick check examples I have seen are for testing properties of functions like is the result greater than 5 when fed random data. Is there a way to use quick check in this manner? Something like
data Result = A | B
fun :: Result -> Int
fun A = 5
main = check fun
In the above code I have a custom data type, and a incomplete function. This function will fail if passed B. There are of course more types of runtime errors than just incomplete functions. I would like to have check generate data, and feed it to the function. Not caring what the result is. Is quick check able to do this?
Edit - I should note that I am not looking for flags that check for incomplete patterns, and what not. I am interested in general purpose runtime error checks.
Rather make sure that functions that don't handle
IO
don't throw exceptions if possible. Exceptions can only get caught inIO
, and they kind of break the things you otherwise expect from a pure function.It's possible with some helpers from
Control.Exception
andTest.QuickCheck.Monadic
:For starters, let's write a function that enables us to check that a certain exception is thrown:
This enables you to write tests like this:
throwsExceptionOr
is very general, so that you can define your own helpers:Now you can write your tests as usual:
You can go further and move the
monadicIO . run
into another helper, but that's left as an exercise. Furthermore, you can make the functions compatible with other testing frameworks, such ashspec
ortasty
:That being said, regardless of the used languages you want to get rid of possible runtime errors at compile time if possible. This includes getting rid of partial functions or possible type nonsense. This depends on the actual use, of course. If you can verify that
head
always gets called on a non-empty list throughout your program, go ahead and use it. If you can't, use pattern matching (see this discussion onhead
's type).Either way, given that older versions of GHC don't provide stack calls, you rather want to have errors at compile time than errors without a stack trace at runtime (recent versions of GHC have some nice features for this).