Section 10.7

Property-based testing

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.

  1. 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.

  2. 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.

  3. 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.

  4. 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.

  5. 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.

Worked example

The property for a function sort\mathrm{sort} applied to a list xx has two parts. The output is in non-decreasing order. And the output contains every value as many times as xx does; that is, the output and xx are equal as multisets §14.13, collections in which a value may occur more than once. Take x=[2,1,2]x = [2, 1, 2]. The correct output [1,2,2][1, 2, 2] passes both parts: 1≤2≤21 \le 2 \le 2, and on both sides the value 1 occurs once and the value 2 twice.

A faulty sort removes repeated values and returns [1,2][1, 2]. The first part passes, because 1≤21 \le 2. The second part fails: the value 2 occurs twice in xx 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 G1G_1 draws each element independently and uniformly from all 232=4,294,967,2962^{32} = 4{,}294{,}967{,}296 values of a 32-bit integer. The three elements are all different with probability (1−1/232)×(1−2/232)(1 - 1/2^{32}) \times (1 - 2/2^{32}): the second element must differ from the first, and the third from the first two. A repeat therefore occurs with probability 1−(1−1/232)(1−2/232)≈3/232≈7.0×10−101 - (1 - 1/2^{32})(1 - 2/2^{32}) \approx 3 / 2^{32} \approx 7.0 \times 10^{-10}. In a run of 100 lists, the chance that any list has a repeat is at most 100×7.0×10−10=7.0×10−8100 \times 7.0 \times 10^{-10} = 7.0 \times 10^{-8}. Generator G1G_1 essentially never finds the fault.

Generator G2G_2 draws each element from {0,1,2}\{0, 1, 2\}. There are 33=273^3 = 27 equally likely lists, and 3×2×1=63 \times 2 \times 1 = 6 of them have three different elements, so a list has a repeat with probability 1−6/27=21/27≈0.781 - 6/27 = 21/27 \approx 0.78. The chance that all 100 lists miss the fault is (6/27)100≈4.8×10−66(6/27)^{100} \approx 4.8 \times 10^{-66}. Generator G2G_2 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 ff be the function under test, DD the set of inputs the test covers, pre(x)\mathrm{pre}(x) the precondition, and P(x,y)P(x, y) the property, which is true when output yy is acceptable for input xx. A property-based test is an attempt to refute the statement for every x∈D:pre(x)⇒P(x,f(x)).\text{for every } x \in D:\ \mathrm{pre}(x) \Longrightarrow P\bigl(x, f(x)\bigr). The tool checks this statement on a finite sample x1,…,xnx_1, \dots, x_n drawn by the generator. One xix_i with pre(xi)\mathrm{pre}(x_i) true and P(xi,f(xi))P(x_i, f(x_i)) false disproves the statement, provided PP correctly expresses the specification. No number of passing inputs proves the statement, except when the sample is the whole of DD, which is exhaustive enumeration §10.33.

If each draw falls into a semantic class CC independently with probability pp, the chance that nn draws all miss CC is (1−p)n(1 - p)^n. Pushing that chance down to a target δ\delta or below needs n≥lnδ/ln(1−p)n \ge \ln \delta / \ln(1 - p), where ln\ln is the natural logarithm; the inequality turns around on division because ln(1−p)\ln(1 - p) is negative. For p=0.01p = 0.01 and δ=0.001\delta = 0.001: ln0.001≈−6.908\ln 0.001 \approx -6.908 and ln0.99≈−0.01005\ln 0.99 \approx -0.01005, so n≥687.3n \ge 687.3, that is, at least 688 draws. The formula needs independence and a known pp. 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.

  1. List the classes from the specification and from the branches of the code.

  2. 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.

  3. Narrow the value ranges so that collisions are common: with elements from {0,1,2}\{0, 1, 2\}, a list of length 3 has a repeated value with probability 21/27≈0.7821/27 \approx 0.78; with elements from all 32-bit integers, the probability is about 7×10−107 \times 10^{-10}.

  4. Pin critical cases, such as the empty input and the inputs of past bugs, as fixed examples in every run.

  5. 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].