Search code examples
haskellquickcheck

Test a function with a list of bounded value with quickCheck


I need to test some function with quickCheck do validate these function.

I need to send value in the range 1 to 40 to the function but I'm very beginner with quickCheck and it's modificator.

I tried :

myTestFunction (x,y,z) (Positive div) = ....

with

quickCheck myTestFunction

div remain positive but can take very high value (and I don't want)

What is the correct way to give div random value in the range a to b ?

Is it also possible to impose a list of value (non random) to quickCheck ?


Solution

  • You need to combine two parts. The first is generation—you need to write a QuickCheck random generator that outputs numbers in your desired range. Happily, we can do this with a built-in function:

    choose :: Random a => (a, a) -> Gen a
    

    Next, we need to specify a property that uses this custom generator. This is where the property combinators really come in handy. Again, the function we want is the first one in the documentation section:

    forAll :: (Show a, Testable prop) => Gen a -> (a -> prop) -> Property
    

    This lets us pass our custom generator in for a function parameter.

    Putting all this together, the test case will look something like this:

    prop_myTest (x, y, z) = forAll (choose (1, 40)) $ \ ndiv -> ...
    

    The "prop_" naming scheme is conventionally used for QuickCheck tests. This will help people quickly understand what's going on in your code and is used by some test frameworks, so it's a good habit to get into now.