Definition
Property-based testing is a testing method in which the tester states a property, a rule that the output must satisfy for every valid input, and a tool checks the rule on many inputs built by a generator. A generator is a function that produces random inputs of a stated kind, such as lists of integers. When an input breaks the property, the tool reports it, usually after shrinking: searching for a smaller input that still breaks the property.
The idea
An example-based test checks one chosen input against one expected output: sorting [3, 1, 2] must give [1, 2, 3]. The author picks the inputs, so the tests cover what the author thought of, and the bugs the author did not think of stay untested. A property-based test states instead what must hold for every input. For a sort function the rule is: the output is in non-decreasing order, and the output holds exactly the same values as the input, each as many times. The tool then tries hundreds or thousands of generated lists against that rule. QuickCheck, a library for the Haskell language published by Claessen and Hughes in 2000 [489], made the method widely known; Hypothesis is a widely used library for it in Python §12.23.
The generator matters as much as the property, because the rule is checked only on the inputs that the generator produces. Call a set of inputs that the specification or the code treats in one way a semantic class: lists with a repeated value, the empty list, values at the edge of their range, malformed inputs. Equivalence partitioning §10.32 divides the inputs into such classes. If a bug lives in a class that the generator reaches once in a billion tries, a thousand tries almost certainly miss it. In one line: the property says what to check, and the generator decides where to look.
How it works
A property-based test is built and run in five steps.
State the property and its precondition. The property is a check on an input and the output computed from it. The precondition says which inputs the property claims to cover; for a sort, every finite list of values that can be compared.
Write the generator. Libraries supply generators for basic types and ways to combine them; Hypothesis calls them strategies. Build each semantic class that the specification names on purpose, as the next paragraph describes.
Run. The tool draws an input, runs the code on it and checks the property, many times over; Hypothesis tries 100 inputs per test by default.
Shrink. After a failure, the tool tries simpler versions of the failing input, such as shorter lists and smaller numbers, and keeps each one that still fails. The result is a small counterexample that is easier to understand.
Record for replay. The tool reports the failing input and what is needed to produce it again, such as the random seed, the starting value of the generator’s pseudorandom number sequence. Hypothesis also saves failing inputs in a local database and tries them first on the next run.
Rare classes are reached by construction, not by luck.
One generator per class, mixed together: empty lists, lists with forced repeats (draw a few values, then build the list from copies of them), lists of the largest allowed size, values at the limits of their type.
Small value ranges. Elements drawn from repeat often; elements drawn from all 32-bit integers almost never repeat.
Construction, not filtering. Generating broadly and discarding the inputs outside the class wastes nearly every draw when the class is rare. Hypothesis offers
assumefor filtering and fails a health check when a test discards too many inputs.Pinned examples. Critical inputs, such as the input of a past bug, are attached to the test so that every run includes them; Hypothesis offers the
@exampledecorator for this.Measurement. Label each input with its class and count the labels in every run. QuickCheck can be given a minimum share for a class, and it then fails a run that falls short.
Stateful tests. For code with internal state, such as a queue, generate sequences of operations, each starting from a fresh state, and after each operation compare the code with a simple model of the expected state. This is model-based testing §10.34 with generated sequences.
Worked example
The property for a function applied to a list has two parts. The output is in non-decreasing order. And the output contains every value as many times as does; that is, the output and are equal as multisets §14.13, collections in which a value may occur more than once. Take . The correct output passes both parts: , and on both sides the value 1 occurs once and the value 2 twice.
A faulty sort removes repeated values and returns . The first part passes, because . The second part fails: the value 2 occurs twice in but once in the output. The fault shows only on lists that contain a repeated value.
Compare two generators of lists of length 3. Generator draws each element independently and uniformly from all values of a 32-bit integer. The three elements are all different with probability : the second element must differ from the first, and the third from the first two. A repeat therefore occurs with probability . In a run of 100 lists, the chance that any list has a repeat is at most . Generator essentially never finds the fault.
Generator draws each element from . There are equally likely lists, and of them have three different elements, so a list has a repeat with probability . The chance that all 100 lists miss the fault is . Generator finds the fault in essentially every run. The property is the same in both cases; only the generator changed. Both calculations assume independent, uniform draws. Real libraries do not draw that way, which is why classes are built on purpose and counted rather than left to chance.
Stated precisely
Let be the function under test, the set of inputs the test covers, the precondition, and the property, which is true when output is acceptable for input . A property-based test is an attempt to refute the statement The tool checks this statement on a finite sample drawn by the generator. One with true and false disproves the statement, provided correctly expresses the specification. No number of passing inputs proves the statement, except when the sample is the whole of , which is exhaustive enumeration §10.33.
If each draw falls into a semantic class independently with probability , the chance that draws all miss is . Pushing that chance down to a target or below needs , where is the natural logarithm; the inequality turns around on division because is negative. For and : and , so , that is, at least 688 draws. The formula needs independence and a known . Neither is guaranteed for the generator of a real library, so the formula explains why class counts must be measured; it does not replace the measurement.
The two parts of the sort property together define the correct output. For values with a total order, in which any two values can be compared, exactly one list is both in non-decreasing order and equal to the input as a multiset. Either part alone is weaker: an empty output is always in order, and an output equal to the input always keeps every value.
Limits and common mistakes
A weak property passes wrong code. Checking order alone accepts a function that always returns an empty list.
A property that recomputes the expected output with a second copy of the same algorithm §14.1 shares that algorithm’s bugs. A useful property is simpler than the code it checks.
A precondition or filter that is too strict hides classes silently. A test that discards every list with a repeated value never sees the fault in the worked example. Keep exactly the precondition the specification states, and generate invalid inputs on purpose when the code must refuse them.
Shrinking keeps the failure, not necessarily its cause. A shrunk input can fail for a different reason than the original; examine both.
A random seed alone does not reproduce a failure that also depends on the library version, the generator code, the clock, the environment or state left by earlier tests. Record these, and reset state between generated inputs.
Passing generated inputs are finite evidence. Report the property, the generators, the class counts and the number of inputs, not only that the test passed.
A stable sort, which keeps equal items in their original order, needs a third property; the two parts above do not check stability.
Questions answered
What makes the generator reach rare but important semantic classes?
A generator reaches rare but important semantic classes only when it is designed to build them; uniform random draws over a large range of values almost never do. A semantic class is a set of inputs that the specification or the code handles in one way: lists with a repeated value, the empty list, values at the limits of their type, malformed inputs, a particular history of earlier operations. In property-based testing, where a tool checks a stated rule on many generated inputs, the generator alone decides which classes are tried.
Five design choices get the generator there.
List the classes from the specification and from the branches of the code.
Build each class with a generator of its own and mix the generators, instead of generating broadly and filtering, which discards nearly every draw when a class is rare.
Narrow the value ranges so that collisions are common: with elements from , a list of length 3 has a repeated value with probability ; with elements from all 32-bit integers, the probability is about .
Pin critical cases, such as the empty input and the inputs of past bugs, as fixed examples in every run.
Label each generated input with its class, count the labels in every run, and fail the run when a class falls below a stated share.
For code with internal state, the generator produces sequences of operations long enough to reach deep states, each starting from a fresh state. Keep the precondition separate from these choices, so that difficult valid inputs are never discarded silently.
Related entries: Test oracle (§10.5), Generation-based fuzzing (§10.11), Delta debugging (§10.39), Set versus multiset (§14.13), Equivalence partitioning (§10.32), Exhaustive enumeration (§10.33), Model-based testing (§10.34). Further reading: [44, 489].