liveBook · Manning

Precondition

As explained in Learn Haskell by Example

A precondition is a condition that causes generated test cases failing the condition to be discarded before the property is evaluated.

A precondition filters generated test cases before the property runs. Cases that fail the condition are discarded rather than evaluated. section 9.5.1

Restricting a sorting property

QuickCheck can require lists to contain at least two elements: `length xs >= 2 ==> sort `sorts` xs`. The property still passes 100 tests, while 43 generated cases that fail the condition are discarded. section 9.5.1

Use a precondition when an input does not reflect the specification or is irrelevant to the functionality under test. Do not use it merely to improve coverage: excluding cases can hide an unhelpful generator, whereas `cover` reports whether useful cases occurred. section 9.5.1

ghci> :{
ghci| prop_sortSorts :: [Int] -> Property
ghci| prop_sortSorts xs = length xs >= 2 ==> sort `sorts` xs
ghci| :}
ghci> quickCheck prop_sortSorts
+++ OK, passed 100 tests; 43 discarded.

See the complete QuickCheck property and its discarded-case report. section 9.5.1

How Learn Haskell by Example covers it

How deep it goes
Defines implication-based filtering and reports discarded cases, but defers generator redesign and coverage measurement to separate techniques.
Examples
Uses a sorting property requiring lists with at least two elements and reports 43 discarded cases.
What you can do after
Apply it via QuickCheck's `==>` operator to exclude irrelevant generated test cases.
How it connects
Connects QuickCheck, property testing, random test generation, and test coverage.

Also explained in

Compare how 8 books explain precondition →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Haskell by Example. The section links point to the parts of the book it draws on.