HORIZON HASKELLDocslts/ghc-9.10.xc74966e2026-09-27Search names, modules, packages, or :: a typeCtrl K

GHC 9.10.3 · lts/ghc-9.10.x · c74966e · 2026-09-27

ModuleQuickCheck-2.15.0.1Haskell2010

Test.QuickCheck.Property

Combinators for constructing properties.

  • 8 types
  • 1 class
  • 70 values

Property and Testable types

6 declarations
newtypenewtype Property
#

The type of properties.

Constructors

  • MkProperty
    • unProperty :: Gen Prop
Instances1Testable
classclass Testable prop where
#

The class of properties, i.e., types which QuickCheck knows how to test. Typically a property will be a function returning Bool or Property.

Methods

  • property :: prop -> Property

    Convert the thing to a property.

  • propertyForAllShrinkShow :: Gen a -> (a -> [a]) -> (a -> [String]) -> (a -> prop) -> Property

    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, …
  • Testable DiscardDefined in QuickCheck-2.15.0.1 · Test.QuickCheck.Property
  • Testable PropDefined in QuickCheck-2.15.0.1 · Test.QuickCheck.Property
  • Testable PropertyDefined in QuickCheck-2.15.0.1 · Test.QuickCheck.Property
  • Testable ResultDefined in QuickCheck-2.15.0.1 · Test.QuickCheck.Property
  • Testable BoolDefined in QuickCheck-2.15.0.1 · Test.QuickCheck.Property
  • Testable ()Defined in QuickCheck-2.15.0.1 · Test.QuickCheck.Property
  • Testable prop => Testable (Gen prop)Defined in QuickCheck-2.15.0.1 · Test.QuickCheck.Property
  • Testable prop => Testable (Maybe prop)Defined in QuickCheck-2.15.0.1 · Test.QuickCheck.Property
  • (Arbitrary a, Show a, Testable prop) => Testable (a -> prop)Defined in QuickCheck-2.15.0.1 · Test.QuickCheck.Property
datadata Discard
#

If a property returns Discard, the current test case is discarded, the same as if a precondition was false.

An example is the definition of ==>:

(==>) :: Testable prop => Bool -> prop -> Property
False ==> _ = property Discard
True  ==> p = property p
Instances1Testable
valueioProperty :: Testable prop => IO prop -> Property
#

Do I/O inside a property.

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.

valueidempotentIOProperty :: Testable prop => IO prop -> Property
#

Do I/O inside a property.

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.

Exception handling

valueprotect :: (AnException -> a) -> IO a -> IO a
#

Type Prop

newtypenewtype Prop
#

Constructors

  • MkProp
    • unProp :: Rose Result
Instances1Testable
  • Testable PropDefined in QuickCheck-2.15.0.1 · Test.QuickCheck.Property

type Rose

datadata Rose a
#

Constructors

  • MkRose a [Rose a]
  • IORose (IO (Rose a))
Instances3Monad, Functor, Applicative
  • Monad RoseDefined in QuickCheck-2.15.0.1 · Test.QuickCheck.Property
  • Functor RoseDefined in QuickCheck-2.15.0.1 · Test.QuickCheck.Property
  • Applicative RoseDefined in QuickCheck-2.15.0.1 · Test.QuickCheck.Property
valueioRose :: IO (Rose Result) -> Rose Result
#
valuejoinRose :: Rose (Rose a) -> Rose a
#
valuereduceRose :: Rose Result -> IO (Rose Result)
#

Execute the IORose bits of a rose tree, returning a tree constructed by MkRose.

valueonRose :: (a -> [Rose a] -> Rose a) -> Rose a -> Rose a
#

Apply a function to the outermost MkRose constructor of a rose tree. The function must be total!

valueprotectRose :: IO (Rose Result) -> IO (Rose Result)
#

Wrap a rose tree in an exception handler.

valueprotectProp :: Prop -> Prop
#

Wrap the top level of a Prop in an exception handler.

valueprotectResults :: Rose Result -> Rose Result
#

Wrap all the Results in a rose tree in exception handlers.

Result type

datadata Callback
#

Different kinds of callbacks

Constructors

  • PostTest CallbackKind (State -> Result -> IO ())

    Called just after a test

  • PostFinalFailure CallbackKind (State -> Result -> IO ())

    Called with the final failing test-case

datadata CallbackKind
#

Constructors

  • Counterexample

    Affected by the verbose combinator

  • NotCounterexample

    Not affected by the verbose combinator

datadata Result
#

The result of a single test.

Constructors

  • MkResult
    • ok :: Maybe Bool

      result of the test case; Nothing = discard

    • expect :: Bool

      indicates what the expected result of the property is

    • reason :: String

      a message indicating what went wrong

    • theException :: Maybe AnException

      the exception thrown, if any

    • abort :: Bool

      if True, the test should not be repeated

    • maybeNumTests :: Maybe Int

      stop after this many tests

    • maybeCheckCoverage :: Maybe Confidence

      required coverage confidence

    • maybeDiscardedRatio :: Maybe Int

      maximum number of discarded tests per successful test

    • maybeMaxShrinks :: Maybe Int

      maximum number of shrinks

    • maybeMaxTestSize :: Maybe Int

      maximum test size

    • labels :: [String]

      test case labels

    • classes :: [(String, Bool)]

      test case classes

    • tables :: [(String, String)]

      test case tables

    • requiredCoverage :: [(Maybe String, String, Double)]

      required coverage

    • callbacks :: [Callback]

      the callbacks for this test case

    • testCase :: [String]

      the generated test case

    • theWitnesses :: [Witness]
Instances1Testable
  • Testable ResultDefined in QuickCheck-2.15.0.1 · Test.QuickCheck.Property
valueexception :: String -> AnException -> Result
#
valueprotectResult :: IO Result -> IO Result
#
valuefailed :: Result
#
valuerejected :: Result
#
valuesucceeded :: Result
#

Lifting and mapping functions

valueliftBool :: Bool -> Result
#
valuemapRoseResult
  1. :: Testable prop
  2. => Rose Result -> Rose Result
  3. -> prop
  4. -> Property
#

Property combinators

valuemapSize :: Testable prop => (Int -> Int) -> prop -> Property
#

Adjust the test case size for a property, by transforming it with the given function.

valueshrinking
  1. :: Testable prop
  2. => (a -> [a])

    shrink-like function.

  3. -> a

    The original argument

  4. -> (a -> prop)
  5. -> 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.

valuewhenFail' :: Testable prop => IO () -> prop -> Property
#

Performs an IO action every time a property fails. Thus, if shrinking is done, this can be used to keep track of the failures along the way.

valueverbose :: Testable prop => prop -> Property
#

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.

valueverboseShrinking :: Testable prop => prop -> Property
#

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.

valueexpectFailure :: Testable prop => prop -> Property
#

Indicates that a property is supposed to fail. QuickCheck will report an error if it does not fail.

valuewithMaxSuccess :: Testable prop => Int -> prop -> Property
#

Configures how many times a property will be tested.

For example,

quickCheck (withMaxSuccess 1000 p)

will test p up to 1000 times.

valuewithDiscardRatio :: Testable prop => Int -> prop -> Property
#

Configures how many times a property is allowed to be discarded before failing.

For example,

quickCheck (withDiscardRatio 10 p)

will allow p to fail up to 10 times per successful test.

valuewithMaxShrinks :: Testable prop => Int -> prop -> Property
#

Configure the maximum number of times a property will be shrunk.

For example,

quickCheck (withMaxShrinks 100 p)

will cause p to only attempt 100 shrinks on failure.

valuewitness :: (Typeable a, Show a, Testable prop) => a -> prop -> Property
#

Return a value in the witnesses field of the Result returned by quickCheckResult. Witnesses are returned outer-most first.

In ghci, for example:

Example3 expressions
[Wit x] <- fmap witnesses . quickCheckResult $ \ x -> witness x $ x == (0 :: Int)*** Failed! Falsified (after 2 tests):1x1:t xx :: Int
valuecheckCoverage :: Testable prop => prop -> Property
#

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.

Example:

quickCheck (checkCoverage prop_foo)
valuecheckCoverageWith :: Testable prop => Confidence -> prop -> Property
#

Check coverage requirements using a custom confidence level. See stdConfidence.

An example of making the statistical test less stringent in order to improve performance:

quickCheck (checkCoverageWith stdConfidence{certainty = 10^6} prop_foo)
valuelabel :: Testable prop => String -> prop -> Property
#

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.

valuecollect :: (Show a, Testable prop) => a -> prop -> Property
#

Attaches a label to a test case. This is used for reporting test case distribution.

collect x = label (show x)

For example:

prop_reverse_reverse :: [Int] -> Property
prop_reverse_reverse xs =
  collect (length xs) $
    reverse (reverse xs) === xs
Example1 expression
quickCheck prop_reverse_reverse+++ OK, passed 100 tests:7% 76% 35% 44% 6...

Each use of collect in your property results in a separate table of test case distribution in the output. If this is not what you want, use tabulate.

valueclassify
  1. :: Testable prop
  2. => Bool

    True if the test case should be labelled.

  3. -> String

    Label.

  4. -> prop
  5. -> Property
#

Reports how many test cases satisfy a given condition.

For example:

prop_sorted_sort :: [Int] -> Property
prop_sorted_sort xs =
  sorted xs ==>
  classify (length xs > 1) "non-trivial" $
  sort xs === xs
Example1 expression
quickCheck prop_sorted_sort+++ OK, passed 100 tests (22% non-trivial).
valuecover
  1. :: Testable prop
  2. => Double

    The required percentage (0-100) of test cases.

  3. -> Bool

    True if the test case belongs to the class.

  4. -> String

    Label for the test case class.

  5. -> prop
  6. -> Property
#

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.

For example:

prop_sorted_sort :: [Int] -> Property
prop_sorted_sort xs =
  sorted xs ==>
  cover 50 (length xs > 1) "non-trivial" $
  sort xs === xs
Example1 expression
quickCheck prop_sorted_sort+++ OK, passed 100 tests; 135 discarded (26% non-trivial).Only 26% non-trivial, but expected 50%
valuetabulate :: Testable prop => String -> [String] -> prop -> Property
#

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:

prop_sorted_sort :: [Int] -> Property
prop_sorted_sort xs =
  sorted xs ==>
  tabulate "List elements" (map show xs) $
  sort xs === xs
Example1 expression
quickCheck prop_sorted_sort+++ OK, passed 100 tests; 1684 discarded.List elements (109 in total): 3.7% 0 3.7% 17 3.7% 2 3.7% 6 2.8% -6 2.8% -7

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:

prop_chatroom :: [Command] -> Property
prop_chatroom cmds =
  valid cmds ==>
    ...

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:

prop_chatroom :: [Command] -> Property
prop_chatroom cmds =
  wellFormed cmds LoggedOut ==>
  'collect' (length cmds) $
  'tabulate' "Commands" (map (show . 'Data.Data.toConstr') cmds) $
    ...
Example1 expression
quickCheckWith stdArgs{maxDiscardRatio = 1000} prop_chatroom+++ OK, passed 100 tests; 2775 discarded:60% 020% 115% 2 3% 3 1% 4 1% 5Commands (68 in total):62% LogIn22% SendMessage16% LogOut
valuecoverTable
  1. :: Testable prop
  2. => String
  3. -> [(String, Double)]
  4. -> prop
  5. -> Property
#

Checks that the values in a given table appear a certain proportion of the time. A call to coverTable table [(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...

data Command = LogIn | LogOut | SendMessage String deriving (Data, Show)
prop_chatroom :: [Command] -> Property
prop_chatroom cmds =
  wellFormed cmds LoggedOut ==>
  'tabulate' "Commands" (map (show . 'Data.Data.toConstr') cmds) $
    ...

...we can add a coverage requirement as follows, which checks that LogIn, LogOut and SendMessage each occur at least 25% of the time:

prop_chatroom :: [Command] -> Property
prop_chatroom cmds =
  wellFormed cmds LoggedOut ==>
  coverTable "Commands" [("LogIn", 25), ("LogOut", 25), ("SendMessage", 25)] $
  'tabulate' "Commands" (map (show . 'Data.Data.toConstr') cmds) $
    ... property goes here ...
Example1 expression
quickCheck prop_chatroom+++ OK, passed 100 tests; 2909 discarded:56% 017% 110% 2 6% 3 5% 4 3% 5 3% 7Commands (111 in total):51.4% LogIn30.6% SendMessage18.0% LogOutTable 'Commands' had only 18.0% LogOut, but expected 25.0%
value(==>) :: Testable prop => Bool -> prop -> Property
#

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.

valuewithin :: Testable prop => Int -> prop -> Property
#

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)

valuediscardAfter :: Testable prop => Int -> prop -> Property
#

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.

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

Explicit universal quantification: uses an explicitly given test case generator.

value(.&.) :: (Testable prop1, Testable prop2) => prop1 -> prop2 -> Property
#

Nondeterministic choice: p1 .&. p2 picks randomly one of p1 and p2 to test. If you test the property 100 times it makes 100 random choices.

value(===) :: (Eq a, Show a) => a -> a -> Property
#

Like ==, but prints a counterexample when it fails.

value(=/=) :: (Eq a, Show a) => a -> a -> Property
#

Like /=, but prints a counterexample when it fails.

valuetotal :: NFData a => a -> Property
#

Checks that a value is total, i.e., doesn't crash when evaluated.