To start using QuickCheck, write down your property as a function returning Bool.
For example, to check that reversing a list twice gives back the same list you can write:
To use QuickCheck on your own data types you will need to write Arbitrary
instances for those types. See the
QuickCheck manual for
details about how to do that.
When testing fails quickCheck will try to give you a minimal counterexample to
your property:
@
import Test.QuickCheck
However, beware because not all properties that ought to fail will fail when you expect
them to:
>>> quickCheck $ x y -> x == y
+++ Ok, passed 100 tests.
That's because GHCi will default any type variables in your property to (), so in the example
above quickCheck was really testing that () is equal to itself. To avoid this behaviour it
is best practise to monomorphise your polymorphic properties when testing:
>>> quickCheck $ x y -> (x :: Int) == y
*** Failed! Falsified (after 4 tests and 3 shrinks):
0
1
Should we replay a previous test?
Note: saving a seed from one version of QuickCheck and
replaying it in another is not supported.
If you want to store a test case permanently you should save
the test case itself.
Maximum number of successful tests before succeeding. Testing stops
at the first failure. If all tests are passing and you want to run more tests,
increase this number.
Tests a property and prints the results and all test cases generated to stdout.
This is just a convenience function that means the same as quickCheck . verbose.
Note: for technical reasons, the test case is printed out after
the property is tested. To debug a property that goes into an
infinite loop, use within to add a timeout instead.
Tests a property, using test arguments, and prints the results and all test cases generated to stdout.
This is just a convenience function that combines quickCheckWith and verbose.
Note: for technical reasons, the test case is printed out after
the property is tested. To debug a property that goes into an
infinite loop, use within to add a timeout instead.
Tests a property, using test arguments, produces a test result, and prints the results and all test cases generated to stdout.
This is just a convenience function that combines quickCheckWithResult and verbose.
Note: for technical reasons, the test case is printed out after
the property is tested. To debug a property that goes into an
infinite loop, use within to add a timeout instead.
Tests a property, produces a test result, and prints the results and all test cases generated to stdout.
This is just a convenience function that combines quickCheckResult and verbose.
Note: for technical reasons, the test case is printed out after
the property is tested. To debug a property that goes into an
infinite loop, use within to add a timeout instead.
Testing all properties in a module
These functions test all properties in the current module, using
Template Haskell. You need to have a {-# LANGUAGE TemplateHaskell #-}
pragma in your module for any of these to work.
Test all properties in the current module.
The name of the property must begin with prop_.
Polymorphic properties will be defaulted to Integer.
Returns True if all tests succeeded, False otherwise.
To use quickCheckAll, add a definition to your module along
the lines of
return []
runTests = $quickCheckAll
and then execute runTests.
Note: the bizarre return [] in the example above is needed on
GHC 7.8 and later; without it, quickCheckAll will not be able to find
any of the properties. For the curious, the return [] is a
Template Haskell splice that makes GHC insert the empty list
of declarations at that point in the program; GHC typechecks
everything before the return [] before it starts on the rest
of the module, which means that the later call to quickCheckAll
can see everything that was defined before the return []. Yikes!
Test a polymorphic property, defaulting all type variables to Integer.
Invoke as $(polyQuickCheck 'prop), where prop is a property.
Note that just evaluating quickCheck prop in GHCi will seem to
work, but will silently default all type variables to ()!
If you want to use polyQuickCheck in the same file where you defined the
property, the same scoping problems pop up as in quickCheckAll:
see the note there about return [].
Test a polymorphic property, defaulting all type variables to Integer.
This is just a convenience function that combines verboseCheck and monomorphic.
If you want to use polyVerboseCheck in the same file where you defined the
property, the same scoping problems pop up as in quickCheckAll:
see the note there about return [].
If you want to use monomorphic in the same file where you defined the
property, the same scoping problems pop up as in quickCheckAll:
see the note there about return [].
The Arbitrary typeclass: generation of random values
QuickCheck provides Arbitrary instances for most types in base,
except those which incur extra dependencies.
For a wider range of Arbitrary instances see the
quickcheck-instances
package.
It is worth spending time thinking about what sort of test data
you want - good generators are often the difference between
finding bugs and not finding them. You can use sample,
label and classify to check the quality of your test data.
There is no generic arbitrary implementation included because we don't
know how to make a high-quality one. If you want one, consider using the
testing-feat or
generic-random packages.
The QuickCheck manual
goes into detail on how to write good generators. Make sure to look at it,
especially if your type is recursive!
Produces a (possibly) empty list of all the possible
immediate shrinks of the given value.
The default implementation returns the empty list, so will not try to
shrink the value. If your data type has no special invariants, you can
enable shrinking by defining shrink = genericShrink, but by customising
the behaviour of shrink you can often get simpler counterexamples.
Most implementations of shrink should try at least three things:
Shrink a term to any of its immediate subterms.
You can use subterms to do this.
Recursively apply shrink to all immediate subterms.
You can use recursivelyShrink to do this.
Type-specific shrinkings such as replacing a constructor by a
simpler constructor.
For example, suppose we have the following implementation of binary trees:
shrink Nil = []
shrink (Branch x l r) =
-- shrink Branch to Nil
[Nil] ++
-- shrink to subterms
[l, r] ++
-- recursively shrink subterms
[Branch x' l' r' | (x', l', r') <- shrink (x, l, r)]
There are a couple of subtleties here:
QuickCheck tries the shrinking candidates in the order they
appear in the list, so we put more aggressive shrinking steps
(such as replacing the whole tree by Nil) before smaller
ones (such as recursively shrinking the subtrees).
It is tempting to write the last line as
[Branch x' l' r' | x' <- shrink x, l' <- shrink l, r' <- shrink r]
but this is the wrong thing! It will force QuickCheck to shrink
x, l and r in tandem, and shrinking will stop once one of
the three is fully shrunk.
There is a fair bit of boilerplate in the code above.
We can avoid it with the help of some generic functions.
The function genericShrink tries shrinking a term to all of its
subterms and, failing that, recursively shrinks the subterms.
Using it, we can define shrink as:
shrink x = shrinkToNil x ++ genericShrink x
where
shrinkToNil Nil = []
shrinkToNil (Branch _ l r) = [Nil]
genericShrink is a combination of subterms, which shrinks
a term to any of its subterms, and recursivelyShrink, which shrinks
all subterms of a term. These may be useful if you need a bit more
control over shrinking than genericShrink gives you.
A final gotcha: we cannot define shrink as simply shrink x = Nil:genericShrink x
as this shrinks Nil to Nil, and shrinking will go into an
infinite loop.
If all this leaves you bewildered, you might try shrink = genericShrink to begin with,
after deriving Generic for your type. However, if your data type has any
special invariants, you will need to check that genericShrink can't break those invariants.
(Orda, Arbitrarya) => Arbitrary (Seta)Defined in QuickCheck-2.15.0.1 · Test.QuickCheck.Arbitrary
WARNING: Users working on the internals of the Set type via e.g. Data.Set.Internal
should be aware that this instance aims to give a good representation of Set a
as mathematical sets but *does not* aim to provide a varied distribution over the
underlying representation.
Map a shrink function to another domain. This is handy if your data type
has special invariants, but is almost isomorphic to some other type.
shrinkOrderedList :: (Ord a, Arbitrary a) => [a] -> [[a]]
shrinkOrderedList = shrinkMap sort id
shrinkSet :: (Ord a, Arbitrary a) => Set a -> [Set a]
shrinkSet = shrinkMap fromList toList
vvalueshrinkMapBy :: (a -> b) -> (b -> a) -> (a -> [a]) -> b -> [b]
Takes a list of elements of increasing size, and chooses
among an initial segment of the list. The size of this initial
segment increases with the size parameter.
The input list must be non-empty.
Generates an integral number from a bounded domain. The number is
chosen from the entire range of the type, but small numbers are
generated more often than big numbers. Inspired by demands from
Phil Wadler.
Generates an integral number. The number is chosen uniformly from
the entire range of the type. You may want to use
arbitrarySizedBoundedIntegral instead.
The Function typeclass: generation of random shrinkable, showable functions
14 declarations
Example of use:
Example5 expressions
>>> :{>>> let prop :: Fun String Integer -> Bool>>> prop (Fun _ f) = f "monkey" == f "banana" || f "banana" == f "elephant">>> :}>>> quickCheck prop*** Failed! Falsified (after 3 tests and 134 shrinks):{"elephant"->1, "monkey"->1, _->0}
To generate random values of type Fun a b,
you must have an instance Function a.
If your type has a Show instance, you can use functionShow to write the instance; otherwise,
use functionMap to give a bijection between your type and a type that is already an instance of Function.
See the Function [a] instance for an example of the latter.
For more information, see the paper "Shrinking and showing functions" by Koen Claessen.
The class Function a is used for random generation of showable
functions of type a -> b.
There is a default implementation for function, which you can use
if your type has structural equality. Otherwise, you can normally
use functionMap or functionShow.
Used for random generation of functions.
You should consider using Test.QuickCheck.Fun instead, which
can show the generated functions as strings.
If you are using a recent GHC, there is a default definition of
coarbitrary using genericCoarbitrary, so if your type has a
Generic instance it's enough to say
instance CoArbitrary MyType
You should only use genericCoarbitrary for data types where
equality is structural, i.e. if you can't have two different
representations of the same value. An example where it's not
safe is sets implemented using binary search trees: the same
set can be represented as several different trees.
Here you would have to explicitly define
coarbitrary s = coarbitrary (toList s).
Used to generate a function of type a -> b.
The first argument is a value, the second a generator.
You should use variant to perturb the random generator;
the goal is that different values for the first argument will
lead to different calls to variant. An example will help:
instance CoArbitrary a => CoArbitrary [a] where
coarbitrary [] = variant 0
coarbitrary (x:xs) = variant 1 . coarbitrary (x,xs)
Instances56CoArbitrary, …
CoArbitraryADefined in QuickCheck-2.15.0.1 · Test.QuickCheck.Poly
CoArbitraryBDefined in QuickCheck-2.15.0.1 · Test.QuickCheck.Poly
CoArbitraryCDefined in QuickCheck-2.15.0.1 · Test.QuickCheck.Poly
CoArbitraryOrdADefined in QuickCheck-2.15.0.1 · Test.QuickCheck.Poly
CoArbitraryOrdBDefined in QuickCheck-2.15.0.1 · Test.QuickCheck.Poly
CoArbitraryOrdCDefined in QuickCheck-2.15.0.1 · Test.QuickCheck.Poly
CoArbitraryIntSetDefined in QuickCheck-2.15.0.1 · Test.QuickCheck.Arbitrary
CoArbitraryIntegerDefined in QuickCheck-2.15.0.1 · Test.QuickCheck.Arbitrary
CoArbitraryAllDefined in QuickCheck-2.15.0.1 · Test.QuickCheck.Arbitrary
CoArbitraryAnyDefined in QuickCheck-2.15.0.1 · Test.QuickCheck.Arbitrary
CoArbitraryVersionDefined in QuickCheck-2.15.0.1 · Test.QuickCheck.Arbitrary
CoArbitraryNewlineDefined in QuickCheck-2.15.0.1 · Test.QuickCheck.Arbitrary
Deprecated. Use ordinary function composition instead
Combine two generator perturbing functions, for example the
results of calls to variant or coarbitrary.
Type-level modifiers for changing generator behavior
20 declarations
These types do things such as restricting the kind of test data that can be generated.
They can be pattern-matched on in properties as a stylistic
alternative to using explicit quantification.
Examples:
-- Functions cannot be shown (but see Function)
prop_TakeDropWhile (Blind p) (xs :: [A]) =
takeWhile p xs ++ dropWhile p xs == xs
prop_TakeDrop (NonNegative n) (xs :: [A]) =
take n xs ++ drop n xs == xs
-- cycle does not work for empty lists
prop_Cycle (NonNegative n) (NonEmpty (xs :: [A])) =
take n (cycle xs) == take n (xs ++ cycle xs)
Optional; used internally in order to improve shrinking.
Tests a property but also quantifies over an extra value
(with a custom shrink and show function).
The Testable instance for functions defines
propertyForAllShrinkShow in a way that improves shrinking.
Instances9Testable, …
TestableDiscardDefined in QuickCheck-2.15.0.1 · Test.QuickCheck.Property
TestablePropDefined in QuickCheck-2.15.0.1 · Test.QuickCheck.Property
TestablePropertyDefined in QuickCheck-2.15.0.1 · Test.QuickCheck.Property
TestableResultDefined in QuickCheck-2.15.0.1 · Test.QuickCheck.Property
TestableBoolDefined in QuickCheck-2.15.0.1 · Test.QuickCheck.Property
Testable ()Defined in QuickCheck-2.15.0.1 · Test.QuickCheck.Property
Testableprop => Testable (Genprop)Defined in QuickCheck-2.15.0.1 · Test.QuickCheck.Property
Testableprop => Testable (Maybeprop)Defined in QuickCheck-2.15.0.1 · Test.QuickCheck.Property
Shrinks the argument to a property if it fails. Shrinking is done
automatically for most types. This function is only needed when you want to
override the default behavior.
Implication for properties: The resulting property holds if
the first argument is False (in which case the test case is discarded),
or if the given property holds. Note that using implication carelessly can
severely skew test case distribution: consider using cover to make sure
that your test data is still good quality.
A special error value. If a property evaluates discard, it
causes QuickCheck to discard the current test case.
This can be useful if you want to discard the current test case,
but are somewhere you can't use ==>, such as inside a
generator.
Warning: any random values generated inside of the argument to ioProperty
will not currently be shrunk. For best results, generate all random values
before calling ioProperty, or use idempotentIOProperty if that is safe.
Warning: during shrinking, the I/O may not always be re-executed.
Instead, the I/O may be executed once and then its result retained.
If this is not acceptable, use ioProperty instead.
Prints out the generated test case every time the property is tested.
Only variables quantified over inside the verbose are printed.
Note: for technical reasons, the test case is printed out after
the property is tested. To debug a property that goes into an
infinite loop, use within to add a timeout instead.
Prints out the generated test case every time the property fails, including during shrinking.
Only variables quantified over inside the verboseShrinking are printed.
Note: for technical reasons, the test case is printed out after
the property is tested. To debug a property that goes into an
infinite loop, use within to add a timeout instead.
Considers a property failed if it does not complete within
the given number of microseconds.
Note: if the property times out, variables quantified inside the
within will not be printed. Therefore, you should use within
only in the body of your property.
Good: prop_foo a b c = within 1000000 ...
Bad: prop_foo = within 1000000 $ \a b c -> ...
Bad: prop_foo a b c = ...; main = quickCheck (within 1000000 prop_foo)
Discards the test case if it does not complete within the given
number of microseconds. This can be useful when testing algorithms
that have pathological cases where they run extremely slowly.
Attaches a label to a test case. This is used for reporting
test case distribution.
For example:
prop_reverse_reverse :: [Int] -> Property
prop_reverse_reverse xs =
label ("length of input is " ++ show (length xs)) $
reverse (reverse xs) === xs
Example1 expression
>>> quickCheck prop_reverse_reverse+++ OK, passed 100 tests:7% length of input is 76% length of input is 35% length of input is 44% length of input is 6...
Each use of label in your property results in a separate
table of test case distribution in the output. If this is
not what you want, use tabulate.
Collects information about test case distribution into a table.
The arguments to tabulate are the table's name and a list of values
associated with the current test case. After testing, QuickCheck prints the
frequency of all collected values. The frequencies are expressed as a
percentage of the total number of values collected.
You should prefer tabulate to label when each test case is associated
with a varying number of values. Here is a (not terribly useful) example,
where the test data is a list of integers and we record all values that
occur in the list:
Here is a more useful example. We are testing a chatroom, where the user can
log in, log out, or send a message:
data Command = LogIn | LogOut | SendMessage String deriving (Data, Show)
instance Arbitrary Command where ...
There are some restrictions on command sequences; for example, the user must
log in before doing anything else. The function valid :: [Command] -> Bool
checks that a command sequence is allowed. Our property then has the form:
The use of ==> may skew test case distribution. We use collect to see the
length of the command sequences, and tabulate to get the frequencies of the
individual commands:
Checks that at least the given proportion of successful test
cases belong to the given class. Discarded tests (i.e. ones
with a false precondition) do not affect coverage.
Note: If the coverage check fails, QuickCheck prints out a warning, but
the property does not fail. To make the property fail, use checkCoverage.
Checks that the values in a given table appear a certain proportion of
the time. A call to coverTabletable[(x1, p1), ..., (xn, pn)] asserts
that of the values in table, x1 should appear at least p1 percent of
the time that table appears, x2 at least p2 percent of the time that
table appears, and so on.
Note: If the coverage check fails, QuickCheck prints out a warning, but
the property does not fail. To make the property fail, use checkCoverage.
Continuing the example from the tabular combinator...
Check that all coverage requirements defined by cover and coverTable
are met, using a statistically sound test, and fail if they are not met.
Ordinarily, a failed coverage check does not cause the property to fail.
This is because the coverage requirement is not tested in a statistically
sound way. If you use cover to express that a certain value must appear 20%
of the time, QuickCheck will warn you if the value only appears in 19 out of
100 test cases - but since the coverage varies randomly, you may have just
been unlucky, and there may not be any real problem with your test
generation.
When you use checkCoverage, QuickCheck uses a statistical test to account
for the role of luck in coverage failures. It will run as many tests as
needed until it is sure about whether the coverage requirements are met. If a
coverage requirement is not met, the property fails.
How certain checkCoverage must be before the property fails.
If the coverage requirement is met, and the certainty parameter is n,
then you should get a false positive at most one in n runs of QuickCheck.
The default value is 10^9.
Lower values will speed up checkCoverage at the cost of false
positives.
If you are using checkCoverage as part of a test suite, you should
be careful not to set certainty too low. If you want, say, a 1% chance
of a false positive during a project's lifetime, then certainty should
be set to at least 100 * m * n, where m is the number of uses of
cover in the test suite, and n is the number of times you expect the
test suite to be run during the project's lifetime. The default value
is chosen to be big enough for most projects.
For statistical reasons, checkCoverage will not reject coverage
levels that are only slightly below the required levels.
If the required level is p then an actual level of tolerance * p
will be accepted. The default value is 0.9.
Lower values will speed up checkCoverage at the cost of not detecting
minor coverage violations.
Instances1Show
ShowConfidenceDefined in QuickCheck-2.15.0.1 · Test.QuickCheck.State
Given a property, which must use label, collect, classify or cover
to associate labels with test cases, find an example test case for each possible label.
The example test cases are minimised using shrinking.
For example, suppose we test delete x xs and record the number
of times that x occurs in xs:
prop_delete :: Int -> [Int] -> Property
prop_delete x xs =
classify (count x xs == 0) "count x xs == 0" $
classify (count x xs == 1) "count x xs == 1" $
classify (count x xs >= 2) "count x xs >= 2" $
counterexample (show (delete x xs)) $
count x (delete x xs) == max 0 (count x xs-1)
where count x xs = length (filter (== x) xs)
labelledExamples generates three example test cases, one for each label:
Example1 expression
>>> labelledExamples prop_delete*** Found example of count x xs == 00[][]*** Found example of count x xs == 10[0][]*** Found example of count x xs >= 25[5,5][5]+++ OK, passed 100 tests:78% count x xs == 021% count x xs == 1 1% count x xs >= 2