Programming Search⌘K

Conceptcore

Property-based testing

Also called property-based test, property test, QuickCheck-style testing, generative testing.

A property-based test states a rule that must hold for all inputs of a kind. A tool generates many inputs, checks the rule on each, and shrinks a failing input to a small one.

Applies to
core-languages

Idea

An example-based test checks one input and one expected output. The author picks the input, so the test checks only the cases that the author thought of. A property-based test states a rule that must hold for every input of some kind. A tool then generates many inputs and checks the rule on each of them. When the rule fails, the tool reports the input, the counterexample.1

The function pages below says how many pages a list of items needs. It has a bug: it drops the last page when that page is not full. Two example tests pass. The property "the pages hold all the items" fails on the first generated input.

def xorshift32(state):
    state ^= (state << 13) & 0xFFFFFFFF
    state ^= state >> 17
    state ^= (state << 5) & 0xFFFFFFFF
    return state


def pages(items, per_page):
    return items // per_page  # bug: drops the last page when it is not full


assert pages(100, 10) == 10
assert pages(0, 10) == 0
print("examples: pass")

state = 2463534242
for trial in range(1, 101):
    state = xorshift32(state)
    items = state % 1001
    state = xorshift32(state)
    per_page = 1 + state % 50
    if pages(items, per_page) * per_page < items:
        print(f"property: falsified on test {trial} by items={items}, per_page={per_page}")
        break
else:
    print("property: passed 100 tests")
Output
examples: pass
property: falsified on test 1 by items=967, per_page=7

The test does not need to know the right answer for 967 items on pages of 7. It only needs a rule that every right answer obeys. This is the main gain of the method. Claessen and Hughes call the question of whether a test passed the oracle problem, and a property is one answer to it.1

How it works

A property-based testing tool has four parts: properties, generators, a runner and a shrinker.

Properties. A property is a function from the generated inputs to true or false. In QuickCheck, a property is a Haskell function whose name starts with prop_, such as prop_RevRev xs = reverse (reverse xs) == xs.1 Some kinds of property occur again and again:

  • Round trip. Decoding undoes encoding: parse(format(x)) == x. Serializers, parsers and codecs have this property.
  • Invariant. The output always has some feature: a sorted list is ordered, a page count covers all items, a balanced tree stays balanced.
  • Oracle. The result equals the result of a second implementation, such as a slower one that is clearly correct. Claessen and Hughes name this as a common solution to the oracle problem.1
  • Algebraic law. An operation is associative, commutative or idempotent, or two operations distribute. QuickCheck's first example tests three laws of reverse.1
  • Conditional property. The rule holds only when a precondition holds. QuickCheck writes this x <= y ==> max x y == y and discards the inputs that fail the precondition.1

Generators. A generator makes a random value of a type. QuickCheck links generators to types through the type class Arbitrary, so a property over [Int] gets a generator for lists of integers without more code.1 A generator is a function from a source of random numbers to a value, and larger generators are built from smaller ones. QuickCheck also passes a size bound to each generator. It starts with small values and lets the size grow as the run goes on, which makes small counterexamples more likely.1

The runner. The runner calls the generator, checks the property, and stops at the first failure. QuickCheck runs 100 tests by default; the paper calls this number arbitrary.1 A run must be repeatable, or a failure seen once cannot be debugged. So the runner uses a pseudo-random generator with a seed, prints the seed, and can replay it. QuickCheck's Args has a field replay for this. Hypothesis also saves each failing input in a local database and tries it first on the next run.26

The shrinker. A random counterexample is often large. A shrinker tries smaller inputs and keeps one that still fails, until no smaller candidate fails. QuickCheck's documentation asks a shrinker to try at least the immediate parts of a value, the value with its parts shrunk, and simpler constructors.2 For an integer, the checker below tries the minimum first, then values that move toward the failing value in halving steps. The 2000 paper of QuickCheck does not describe shrinking. QuickCheck's library has it now through the method shrink of Arbitrary.12

The checker below has all four parts. It uses Marsaglia's xorshift generator with 32-bit state and the shifts 13, 17 and 5, seeded with 2463534242, the seed in his paper.3 The examples in each language use the same generator, so each prints the same lines.

SEED = 2463534242  # the seed in Marsaglia's xorshift paper


class Rng:
    """xorshift32: the same numbers in every language and on every run."""

    def __init__(self, seed):
        self.state = seed

    def next(self):
        y = self.state
        y ^= (y << 13) & 0xFFFFFFFF
        y ^= y >> 17
        y ^= (y << 5) & 0xFFFFFFFF
        self.state = y
        return y

    def between(self, lo, hi):
        return lo + self.next() % (hi - lo + 1)


def check(name, generate, holds, shrink, trials=100):
    rng = Rng(SEED)
    for trial in range(1, trials + 1):
        case = generate(rng)
        if holds(case):
            continue
        print(f"{name}: falsified on test {trial} by {case}")
        steps = 0
        while True:
            smaller = next((c for c in shrink(case) if not holds(c)), None)
            if smaller is None:
                break
            case, steps = smaller, steps + 1
        print(f"{name}: shrunk in {steps} steps to {case}")
        return
    print(f"{name}: passed {trials} tests")


def shrink_int(x, lo):
    """Candidates from the smallest up: lo, then x - d for d = (x - lo) / 2, / 4, ..., 1."""
    candidates = [lo] if x > lo else []
    d = (x - lo) // 2
    while d > 0:
        candidates.append(x - d)
        d //= 2
    return candidates


# Property 1, a round trip: parsing the decimal form gives the number back.
check(
    "round trip",
    lambda rng: rng.between(-(2**31), 2**31 - 1),
    lambda x: int(str(x)) == x,
    lambda x: [],
)


# Property 2, an invariant: the pages hold all the items.
def pages(items, per_page):
    return items // per_page  # bug: drops the last page when it is not full


check(
    "pages",
    lambda rng: (rng.between(0, 1000), rng.between(1, 50)),
    lambda c: pages(*c) * c[1] >= c[0],
    lambda c: [(n, c[1]) for n in shrink_int(c[0], 0)] + [(c[0], p) for p in shrink_int(c[1], 1)],
)
Output
round trip: passed 100 tests
pages: falsified on test 1 by (967, 7)
pages: shrunk in 13 steps to (1, 2)

The shrunk input (1, 2) explains the bug at once: one item on pages of two needs one page, and 1 // 2 is 0. The fix is the rounded-up quotient (items + per_page - 1) // per_page. The shrinker does not find the smallest input in every case. It finds an input that no single step can make smaller, a local minimum. With a shrinker that tried only the halves, this run stopped at (241, 2), because every even count passes.

In languages

LanguageVerdictNote
PythonLibrary
C++Idiom
JavaLibrary
CIdiom
C#Library
JavaScriptLibrary
TypeScriptLibrary
GoStandard library
RustLibrary
KotlinLibraryThe Kotlin standard library has no property checker. Alternative: Jqwik, which runs property-based tests on the JVM with a focus on Java and Kotlin.
SQLDoes not applyA query has no test runner.
BashIdiomBash has no property checker. Alternative: A loop over $RANDOM, seeded by an assignment to RANDOM.
PowerShellIdiomPowerShell has no property checker in the language or its core modules. Alternative: A loop over Get-Random with -SetSeed, which gives the same numbers for the same seed.
HTMLDoes not applyMarkup has no functions to test.
CSSDoes not applyStyle rules have no functions to test.
Regular expressionsDoes not applyA pattern is tested through the language that uses it.

The example files run the same checker in each language. The table gives the verdict for each tier 1 language. A verdict of library means that a mature property testing library exists; the examples use only the standard library.

Language Verdict Form
Python library Hypothesis: @given with strategies5
JavaScript library fast-check7
TypeScript library fast-check, with typed arbitraries7
Java library jqwik, a test engine for the JVM8
C idiom a loop over a seeded generator, as in the example
C++ idiom a loop over a seeded generator; a generic checker with templates and lambdas
C# library FsCheck, which runs properties from F#, C# or VB10
Go stdlib testing/quick.Check, with a seeded Config.Rand; it does not shrink11
Rust library proptest, in the QuickCheck family9
Kotlin library jqwik, which supports Java and Kotlin8
PowerShell idiom a loop over Get-Random -SetSeed12
Bash idiom a loop over $RANDOM, seeded by an assignment13
SQL n/a a query has no test runner
Regex n/a a pattern is tested through the language that uses it
HTML/CSS n/a markup and style rules have no functions to test

Go is the only tier 1 language with a property checker in its standard library. testing/quick.Check calls a function that returns a Boolean with random arguments made by reflection, and it takes a *rand.Rand in its Config. The package is frozen and accepts no more features.11 Its documentation describes no shrinking. Hypothesis uses one internal representation for all generated data, so it can shrink any input with no shrinker from the user.5 Proptest also defines generation and shrinking for each value rather than for each type.9

PythonGitHub
import functools
import unittest

SEED = 2463534242  # the seed in Marsaglia's xorshift paper


class Rng:
    def __init__(self, seed):
        self.state = seed

    def next(self):
        y = self.state
        y ^= (y << 13) & 0xFFFFFFFF
        y ^= y >> 17
        y ^= (y << 5) & 0xFFFFFFFF
        self.state = y
        return y

    def between(self, lo, hi):
        return lo + self.next() % (hi - lo + 1)


def shrink_int(x, lo):
    candidates = [lo] if x > lo else []
    d = (x - lo) // 2
    while d > 0:
        candidates.append(x - d)
        d //= 2
    return candidates


def for_all(generate, shrink, trials=100, seed=SEED):
    """Runs the test body on generated cases; reports the shrunk failure."""

    def decorate(body):
        def fails(self, case):
            try:
                body(self, *case)
            except AssertionError:
                return True
            return False

        @functools.wraps(body)
        def run(self):
            rng = Rng(seed)
            for _ in range(trials):
                case = generate(rng)
                if fails(self, case):
                    while (smaller := next((c for c in shrink(case) if fails(self, c)), None)) is not None:
                        case = smaller
                    self.fail(f"falsified by {case} (seed {seed})")

        return run

    return decorate


def page_cases(rng):
    return rng.between(0, 1000), rng.between(1, 50)


def shrink_pages(case):
    items, per_page = case
    return [(n, per_page) for n in shrink_int(items, 0)] + [(items, p) for p in shrink_int(per_page, 1)]


def buggy_pages(items, per_page):
    return items // per_page


def pages(items, per_page):
    return -(-items // per_page)  # floor division of the negation rounds up


class PagesTest(unittest.TestCase):
    @for_all(page_cases, shrink_pages)
    def test_pages_hold_all_items(self, items, per_page):
        self.assertGreaterEqual(pages(items, per_page) * per_page, items)

    @for_all(page_cases, shrink_pages)
    def test_one_page_fewer_is_not_enough(self, items, per_page):
        self.assertLess((pages(items, per_page) - 1) * per_page, items)

    def test_the_property_catches_the_bug(self):
        @for_all(page_cases, shrink_pages)
        def check(self, items, per_page):
            self.assertGreaterEqual(buggy_pages(items, per_page) * per_page, items)

        with self.assertRaisesRegex(AssertionError, r"falsified by \(1, 2\)"):
            check(self)


if __name__ == "__main__":
    unittest.main(verbosity=2)
Error output
test_one_page_fewer_is_not_enough (test_main.PagesTest.test_one_page_fewer_is_not_enough) ... ok
test_pages_hold_all_items (test_main.PagesTest.test_pages_hold_all_items) ... ok
test_the_property_catches_the_bug (test_main.PagesTest.test_the_property_catches_the_bug) ... ok

----------------------------------------------------------------------
Ran 3 tests in $TIME

OK
  • Verdict: library. Hypothesis is a property testing library for Python. Its decorator @given takes strategies, which are generators passed as values.
  • for_all is a decorator that turns a test method with parameters into a method with none, so unittest can run it. Each case runs the body, and an AssertionError counts as a failure.
  • The shrinker calls the body again on each candidate. It keeps the first candidate that still fails, until none does, and the final message names the small case and the seed.
  • -(-items // per_page) rounds up, because floor division of a negative number rounds toward minus infinity. Python integers do not overflow, so the sum items + per_page - 1 is also safe here; in C and Rust it is not (see their examples).
  • The third test checks the checker. It runs the property on the buggy version and expects the failure message with the case (1, 2).
#include <charconv>
#include <cstdint>
#include <limits>
#include <optional>
#include <print>
#include <string>
#include <utility>
#include <vector>

// xorshift32 with Marsaglia's seed: the same numbers on every run.
struct Rng {
    std::uint32_t state = 2463534242u;

    std::uint32_t next() {
        state ^= state << 13;
        state ^= state >> 17;
        state ^= state << 5;
        return state;
    }

    std::int64_t between(std::int64_t lo, std::int64_t hi) {
        return lo + static_cast<std::int64_t>(next() % static_cast<std::uint64_t>(hi - lo + 1));
    }
};

// Runs a property on 100 generated cases and shrinks the first failure.
template <typename Generate, typename Holds, typename Shrink, typename Show>
void check(const char* name, Generate generate, Holds holds, Shrink shrink, Show show) {
    Rng rng;
    for (int trial = 1; trial <= 100; ++trial) {
        auto c = generate(rng);
        if (holds(c)) {
            continue;
        }
        std::println("{}: falsified on test {} by {}", name, trial, show(c));
        int steps = 0;
        for (bool shrunk = true; shrunk;) {
            shrunk = false;
            for (const auto& smaller : shrink(c)) {
                if (!holds(smaller)) {
                    c = smaller;
                    shrunk = true;
                    ++steps;
                    break;
                }
            }
        }
        std::println("{}: shrunk in {} steps to {}", name, steps, show(c));
        return;
    }
    std::println("{}: passed 100 tests", name);
}

// Gives lo, then x - d for d = (x - lo) / 2, / 4, ..., 1.
std::vector<int> shrink_int(int x, int lo) {
    std::vector<int> out;
    if (x > lo) {
        out.push_back(lo);
    }
    for (int d = (x - lo) / 2; d > 0; d /= 2) {
        out.push_back(x - d);
    }
    return out;
}

int pages(int items, int per_page) {
    return items / per_page;  // bug: drops the last page when it is not full
}

int main() {
    using Limits = std::numeric_limits<std::int32_t>;
    check(
        "round trip",
        [](Rng& rng) { return static_cast<std::int32_t>(rng.between(Limits::min(), Limits::max())); },
        [](std::int32_t x) {
            std::string text = std::to_string(x);
            std::int32_t back = 0;
            auto [end, error] = std::from_chars(text.data(), text.data() + text.size(), back);
            return error == std::errc{} && back == x;
        },
        [](std::int32_t) { return std::vector<std::int32_t>{}; },
        [](std::int32_t x) { return std::to_string(x); });

    using Pair = std::pair<int, int>;
    check(
        "pages",
        [](Rng& rng) {
            int items = static_cast<int>(rng.between(0, 1000));
            int per_page = static_cast<int>(rng.between(1, 50));
            return Pair{items, per_page};
        },
        [](const Pair& p) { return pages(p.first, p.second) * p.second >= p.first; },
        [](const Pair& p) {
            std::vector<Pair> out;
            for (int n : shrink_int(p.first, 0)) out.emplace_back(n, p.second);
            for (int n : shrink_int(p.second, 1)) out.emplace_back(p.first, n);
            return out;
        },
        [](const Pair& p) { return std::format("({}, {})", p.first, p.second); });
}
Output
round trip: passed 100 tests
pages: falsified on test 1 by (967, 7)
pages: shrunk in 13 steps to (1, 2)
  • Verdict: idiom. The C++ standard library has <random> with seeded engines, but no property checker.
  • check is a function template. Each lambda has its own type, so the template takes the generator, the property, the shrinker and the printer with no std::function and no heap allocation.
  • std::from_chars parses with no locale and no exceptions. It returns an error code, and the round trip tests it with the value.
  • The engines in <random>, such as std::mt19937, give the same sequence for a seed on every platform. The distributions, such as std::uniform_int_distribution, do not have a fixed algorithm, so the example uses its own between.
JavaGitHub
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
import java.util.function.Predicate;

public class Main {
    /** xorshift32 with Marsaglia's seed: the same numbers on every run. */
    static final class Rng {
        private int state = (int) 2463534242L; // Java has no unsigned int

        int next() {
            state ^= state << 13;
            state ^= state >>> 17; // >>> shifts in zeros, as on an unsigned value
            state ^= state << 5;
            return state;
        }

        long between(long lo, long hi) {
            return lo + Long.remainderUnsigned(Integer.toUnsignedLong(next()), hi - lo + 1);
        }
    }

    record Pair(int items, int perPage) {
        @Override
        public String toString() {
            return "(" + items + ", " + perPage + ")";
        }
    }

    /** Runs a property on 100 generated cases and shrinks the first failure. */
    static <T> void check(String name, Function<Rng, T> generate, Predicate<T> holds, Function<T, List<T>> shrink) {
        Rng rng = new Rng();
        for (int trial = 1; trial <= 100; trial++) {
            T c = generate.apply(rng);
            if (holds.test(c)) {
                continue;
            }
            System.out.println(name + ": falsified on test " + trial + " by " + c);
            int steps = 0;
            boolean shrunk = true;
            while (shrunk) {
                shrunk = false;
                for (T smaller : shrink.apply(c)) {
                    if (!holds.test(smaller)) {
                        c = smaller;
                        shrunk = true;
                        steps++;
                        break;
                    }
                }
            }
            System.out.println(name + ": shrunk in " + steps + " steps to " + c);
            return;
        }
        System.out.println(name + ": passed 100 tests");
    }

    /** Gives lo, then x - d for d = (x - lo) / 2, / 4, ..., 1. */
    static List<Integer> shrinkInt(int x, int lo) {
        List<Integer> out = new ArrayList<>();
        if (x > lo) {
            out.add(lo);
        }
        for (int d = (x - lo) / 2; d > 0; d /= 2) {
            out.add(x - d);
        }
        return out;
    }

    static int pages(int items, int perPage) {
        return items / perPage; // bug: drops the last page when it is not full
    }

    public static void main(String[] args) {
        check("round trip",
            rng -> (int) rng.between(Integer.MIN_VALUE, Integer.MAX_VALUE),
            x -> Integer.parseInt(Integer.toString(x)) == x,
            x -> List.of());

        check("pages",
            rng -> new Pair((int) rng.between(0, 1000), (int) rng.between(1, 50)),
            p -> pages(p.items(), p.perPage()) * p.perPage() >= p.items(),
            p -> {
                List<Pair> out = new ArrayList<>();
                for (int n : shrinkInt(p.items(), 0)) {
                    out.add(new Pair(n, p.perPage()));
                }
                for (int n : shrinkInt(p.perPage(), 1)) {
                    out.add(new Pair(p.items(), n));
                }
                return out;
            });
    }
}
Output
round trip: passed 100 tests
pages: falsified on test 1 by (967, 7)
pages: shrunk in 13 steps to (1, 2)
  • Verdict: library. jqwik is a property testing library for the JVM, with a focus on Java and Kotlin.
  • Java has no unsigned int. The state is stored in an int with the same bits, >>> shifts in zeros, and Integer.toUnsignedLong and Long.remainderUnsigned read the bits as an unsigned number.
  • Function and Predicate are the standard functional interfaces, and the lambdas implement them. The generic method check boxes the int cases as Integer.
  • A record gives the pair equals, hashCode and accessors. The program overrides toString so that the output matches the other languages.
#include <inttypes.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>

/* xorshift32 with Marsaglia's seed: the same numbers on every run. */
static uint32_t state = 2463534242u;

static uint32_t next(void) {
    state ^= state << 13;
    state ^= state >> 17;
    state ^= state << 5;
    return state;
}

static int64_t between(int64_t lo, int64_t hi) {
    return lo + (int64_t)(next() % (uint64_t)(hi - lo + 1));
}

/* Property 1, a round trip: parsing the decimal form gives the number back. */
static bool round_trip(int32_t x) {
    char text[16];
    snprintf(text, sizeof text, "%" PRId32, x);
    return strtol(text, NULL, 10) == x;
}

/* Property 2, an invariant: the pages hold all the items. */
static int pages(int items, int per_page) {
    return items / per_page; /* bug: drops the last page when it is not full */
}

static bool pages_hold_items(int items, int per_page) {
    return pages(items, per_page) * per_page >= items;
}

/* Candidates from the smallest up: lo, then x - d for d = (x - lo) / 2, / 4, ..., 1. */
static int shrink_int(int x, int lo, int out[]) {
    int n = 0;
    if (x > lo) {
        out[n++] = lo;
    }
    for (int d = (x - lo) / 2; d > 0; d /= 2) {
        out[n++] = x - d;
    }
    return n;
}

int main(void) {
    state = 2463534242u;
    bool passed = true;
    for (int trial = 1; trial <= 100 && passed; trial++) {
        int32_t x = (int32_t)between(INT32_MIN, INT32_MAX);
        if (!round_trip(x)) {
            printf("round trip: falsified on test %d by %" PRId32 "\n", trial, x);
            passed = false;
        }
    }
    if (passed) {
        printf("round trip: passed 100 tests\n");
    }

    state = 2463534242u;
    for (int trial = 1; trial <= 100; trial++) {
        int items = (int)between(0, 1000);
        int per_page = (int)between(1, 50);
        if (pages_hold_items(items, per_page)) {
            continue;
        }
        printf("pages: falsified on test %d by (%d, %d)\n", trial, items, per_page);
        int steps = 0;
        bool shrunk = true;
        while (shrunk) {
            shrunk = false;
            int candidates[40];
            int n = shrink_int(items, 0, candidates);
            for (int i = 0; i < n && !shrunk; i++) {
                if (!pages_hold_items(candidates[i], per_page)) {
                    items = candidates[i];
                    shrunk = true;
                }
            }
            n = shrink_int(per_page, 1, candidates);
            for (int i = 0; i < n && !shrunk; i++) {
                if (!pages_hold_items(items, candidates[i])) {
                    per_page = candidates[i];
                    shrunk = true;
                }
            }
            steps += shrunk;
        }
        printf("pages: shrunk in %d steps to (%d, %d)\n", steps, items, per_page);
        return 0;
    }
    printf("pages: passed 100 tests\n");
    return 0;
}
Output
round trip: passed 100 tests
pages: falsified on test 1 by (967, 7)
pages: shrunk in 13 steps to (1, 2)

The first fix rounds up with (items + per_page - 1) / per_page. In uint32_t, the sum wraps near the top of the range, and the program goes on with a wrong count. The generator takes a value near UINT32_MAX on one test in four, because a uniform choice almost never comes close.

This code runs but gives a wrong answer on purpose.

#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>

static uint32_t state = 2463534242u;

static uint32_t next(void) {
    state ^= state << 13;
    state ^= state >> 17;
    state ^= state << 5;
    return state;
}

/* One test in four takes a value near the maximum; a uniform choice almost never does. */
static uint32_t edgy_u32(void) {
    if (next() % 4 == 0) {
        return UINT32_MAX - next() % 4;
    }
    return next();
}

/* The fix for the last page: the rounded-up quotient. */
static uint32_t pages(uint32_t items, uint32_t per_page) {
    return (items + per_page - 1) / per_page; /* wraps when items is near UINT32_MAX */
}

static bool pages_hold_items(uint32_t items, uint32_t per_page) {
    return (uint64_t)pages(items, per_page) * per_page >= items;
}

/* Candidates from the smallest up: lo, then x - d for d = (x - lo) / 2, / 4, ..., 1. */
static int shrink_u32(uint32_t x, uint32_t lo, uint32_t out[]) {
    int n = 0;
    if (x > lo) {
        out[n++] = lo;
    }
    for (uint32_t d = (x - lo) / 2; d > 0; d /= 2) {
        out[n++] = x - d;
    }
    return n;
}

int main(void) {
    for (int trial = 1; trial <= 100; trial++) {
        uint32_t items = edgy_u32();
        uint32_t per_page = 1 + next() % 50;
        if (pages_hold_items(items, per_page)) {
            continue;
        }
        printf("falsified on test %d by (%u, %u)\n", trial, items, per_page);
        int steps = 0;
        bool shrunk = true;
        while (shrunk) {
            shrunk = false;
            uint32_t candidates[40];
            int n = shrink_u32(items, 0, candidates);
            for (int i = 0; i < n && !shrunk; i++) {
                if (!pages_hold_items(candidates[i], per_page)) {
                    items = candidates[i];
                    shrunk = true;
                }
            }
            n = shrink_u32(per_page, 1, candidates);
            for (int i = 0; i < n && !shrunk; i++) {
                if (!pages_hold_items(items, candidates[i])) {
                    per_page = candidates[i];
                    shrunk = true;
                }
            }
            steps += shrunk;
        }
        printf("shrunk in %d steps to (%u, %u): pages = %u\n", steps, items, per_page, pages(items, per_page));
        return 0;
    }
    printf("passed 100 tests\n");
    return 0;
}
Output
falsified on test 6 by (4294967294, 5)
shrunk in 2 steps to (4294967292, 5): pages = 0
  • Verdict: idiom. The C standard library has no property checker. The example writes one as a loop over a seeded generator.
  • C has no closures and no generic functions. The checker for pairs is written out by hand, and a general checker would take function pointers and void * cases.
  • uint32_t arithmetic wraps by rule, so xorshift32 needs no masks. The same wrap hides the overflow in the wrong block: pages returns 0 for 4294967292 items, and no error occurs. Rust panics on the same code in a debug build.
  • Signed overflow in C is undefined behavior, so pages(items, per_page) * per_page must stay small. The generator keeps items under 1001 for this reason.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;

// xorshift32 with Marsaglia's seed: the same numbers on every run.
sealed class Rng
{
    private uint state = 2463534242;

    public uint Next()
    {
        state ^= state << 13;
        state ^= state >> 17;
        state ^= state << 5;
        return state;
    }

    public long Between(long lo, long hi) => lo + (long)(Next() % (ulong)(hi - lo + 1));
}

static class Program
{
    // Runs a property on 100 generated cases and shrinks the first failure.
    static void Check<T>(string name, Func<Rng, T> generate, Func<T, bool> holds, Func<T, IEnumerable<T>> shrink)
    {
        var rng = new Rng();
        for (int trial = 1; trial <= 100; trial++)
        {
            T c = generate(rng);
            if (holds(c))
            {
                continue;
            }
            Console.WriteLine($"{name}: falsified on test {trial} by {c}");
            int steps = 0;
            // The list pattern matches when a smaller case still fails.
            while (shrink(c).Where(x => !holds(x)).Take(1).ToList() is [var smaller])
            {
                c = smaller;
                steps++;
            }
            Console.WriteLine($"{name}: shrunk in {steps} steps to {c}");
            return;
        }
        Console.WriteLine($"{name}: passed 100 tests");
    }

    // Gives lo, then x - d for d = (x - lo) / 2, / 4, ..., 1.
    static IEnumerable<int> ShrinkInt(int x, int lo)
    {
        if (x > lo)
        {
            yield return lo;
        }
        for (int d = (x - lo) / 2; d > 0; d /= 2)
        {
            yield return x - d;
        }
    }

    static int Pages(int items, int perPage) => items / perPage; // bug: drops the last page when it is not full

    static void Main()
    {
        Check(
            "round trip",
            rng => (int)rng.Between(int.MinValue, int.MaxValue),
            x => int.Parse(x.ToString(CultureInfo.InvariantCulture), CultureInfo.InvariantCulture) == x,
            x => Enumerable.Empty<int>());

        Check(
            "pages",
            rng => (Items: (int)rng.Between(0, 1000), PerPage: (int)rng.Between(1, 50)),
            c => Pages(c.Items, c.PerPage) * c.PerPage >= c.Items,
            c => ShrinkInt(c.Items, 0).Select(n => (Items: n, c.PerPage))
                .Concat(ShrinkInt(c.PerPage, 1).Select(p => (c.Items, PerPage: p))));
    }
}
Output
round trip: passed 100 tests
pages: falsified on test 1 by (967, 7)
pages: shrunk in 13 steps to (1, 2)
  • Verdict: library. FsCheck runs property-based tests from F#, C# and VB, and it shrinks a failing case to a minimal one.
  • uint is a 32-bit unsigned type, so xorshift32 needs no masks. Arithmetic is unchecked by default and wraps.
  • Check<T> takes delegates of the types Func<Rng, T>, Func<T, bool> and Func<T, IEnumerable<T>>. A named value tuple (Items, PerPage) prints as (1, 2).
  • ShrinkInt is an iterator with yield return, so the candidates are made one at a time and the loop stops at the first that fails.
  • int.Parse and ToString use the culture of the thread unless they get CultureInfo.InvariantCulture. A round trip test with the default culture can pass on one machine and fail on another.
JavaScriptGitHub
// xorshift32 with Marsaglia's seed: the same numbers on every run.
class Rng {
  #state = 2463534242;

  next() {
    let y = this.#state;
    y ^= y << 13; // the bit operators work on 32-bit signed integers
    y ^= y >>> 17;
    y ^= y << 5;
    this.#state = y >>> 0; // back to an unsigned value
    return this.#state;
  }

  between(lo, hi) {
    return lo + (this.next() % (hi - lo + 1));
  }
}

// Runs a property on 100 generated cases and shrinks the first failure.
function check(name, generate, holds, shrink) {
  const rng = new Rng();
  for (let trial = 1; trial <= 100; trial++) {
    let c = generate(rng);
    if (holds(c)) continue;
    console.log(`${name}: falsified on test ${trial} by (${c.join(", ")})`);
    let steps = 0;
    for (let smaller; (smaller = shrink(c).find((s) => !holds(s))) !== undefined; steps++) {
      c = smaller;
    }
    console.log(`${name}: shrunk in ${steps} steps to (${c.join(", ")})`);
    return;
  }
  console.log(`${name}: passed 100 tests`);
}

// Gives lo, then x - d for d = (x - lo) / 2, / 4, ..., 1.
function shrinkInt(x, lo) {
  const out = x > lo ? [lo] : [];
  for (let d = Math.trunc((x - lo) / 2); d > 0; d = Math.trunc(d / 2)) {
    out.push(x - d);
  }
  return out;
}

function pages(items, perPage) {
  return Math.trunc(items / perPage); // bug: drops the last page when it is not full
}

check(
  "round trip",
  (rng) => [rng.between(-(2 ** 31), 2 ** 31 - 1)],
  ([x]) => Number.parseInt(String(x), 10) === x,
  () => [],
);

check(
  "pages",
  (rng) => [rng.between(0, 1000), rng.between(1, 50)],
  ([items, perPage]) => pages(items, perPage) * perPage >= items,
  ([items, perPage]) => [
    ...shrinkInt(items, 0).map((n) => [n, perPage]),
    ...shrinkInt(perPage, 1).map((p) => [items, p]),
  ],
);
Output
round trip: passed 100 tests
pages: falsified on test 1 by (967, 7)
pages: shrunk in 13 steps to (1, 2)
  • Verdict: library. fast-check is a property testing library for JavaScript and TypeScript.
  • JavaScript numbers are 64-bit floats, and the bit operators convert them to 32-bit integers. << and ^ give a signed result, so >>> is the only shift that treats the state as unsigned, and >>> 0 turns the result back into a value from 0 to 2^32 - 1.
  • check takes four functions: a generator, the property, a shrinker and a printer. Closures over per_page and items build the shrink candidates for a pair.
  • Math.trunc gives integer division for non-negative numbers. The round trip works on the full 32-bit range because a double holds every 32-bit integer exactly.

The classic mistake in a port of xorshift32 to JavaScript is the signed shift >> and a state that stays signed. The remainder of a negative number is negative, so the generator for page sizes gives values below 1.

This code runs but gives a wrong answer on purpose.

// The same xorshift32, but with >> and no >>> 0 at the end.
let state = 2463534242;
function next() {
  state ^= state << 13; // ^ turns state into a signed 32-bit integer
  state ^= state >> 17; // >> copies the sign bit
  state ^= state << 5;
  return state;
}

const perPage = [];
for (let i = 0; i < 8; i++) {
  next(); // skip the value for items
  perPage.push(1 + (next() % 50));
}
console.log(perPage.join(" "));
Output
-37 38 -26 8 26 49 -36 -6

With a page size of -37, the property divides by a negative number, and every result after it means nothing. Write >>> for the right shift and end with >>> 0, as in the checker above.

TypeScriptGitHub
// xorshift32 with Marsaglia's seed: the same numbers on every run.
class Rng {
  private state = 2463534242;

  next(): number {
    let y = this.state;
    y ^= y << 13;
    y ^= y >>> 17;
    y ^= y << 5;
    this.state = y >>> 0;
    return this.state;
  }

  between(lo: number, hi: number): number {
    return lo + (this.next() % (hi - lo + 1));
  }
}

type Property<T> = {
  name: string;
  generate: (rng: Rng) => T;
  holds: (value: T) => boolean;
  shrink: (value: T) => T[];
  show: (value: T) => string;
};

// Runs a property on 100 generated cases and shrinks the first failure.
function check<T>(p: Property<T>): void {
  const rng = new Rng();
  for (let trial = 1; trial <= 100; trial++) {
    let c = p.generate(rng);
    if (p.holds(c)) continue;
    console.log(`${p.name}: falsified on test ${trial} by ${p.show(c)}`);
    let steps = 0;
    for (let s = p.shrink(c).find((x) => !p.holds(x)); s !== undefined; s = p.shrink(c).find((x) => !p.holds(x))) {
      c = s;
      steps++;
    }
    console.log(`${p.name}: shrunk in ${steps} steps to ${p.show(c)}`);
    return;
  }
  console.log(`${p.name}: passed 100 tests`);
}

// Gives lo, then x - d for d = (x - lo) / 2, / 4, ..., 1.
function shrinkInt(x: number, lo: number): number[] {
  const out = x > lo ? [lo] : [];
  for (let d = Math.trunc((x - lo) / 2); d > 0; d = Math.trunc(d / 2)) {
    out.push(x - d);
  }
  return out;
}

function pages(items: number, perPage: number): number {
  return Math.trunc(items / perPage); // bug: drops the last page when it is not full
}

check<number>({
  name: "round trip",
  generate: (rng) => rng.between(-(2 ** 31), 2 ** 31 - 1),
  holds: (x) => Number.parseInt(String(x), 10) === x,
  shrink: () => [],
  show: String,
});

check<[items: number, perPage: number]>({
  name: "pages",
  generate: (rng) => [rng.between(0, 1000), rng.between(1, 50)],
  holds: ([items, perPage]) => pages(items, perPage) * perPage >= items,
  shrink: ([items, perPage]) => [
    ...shrinkInt(items, 0).map((n): [number, number] => [n, perPage]),
    ...shrinkInt(perPage, 1).map((p): [number, number] => [items, p]),
  ],
  show: ([items, perPage]) => `(${items}, ${perPage})`,
});
Output
round trip: passed 100 tests
pages: falsified on test 1 by (967, 7)
pages: shrunk in 13 steps to (1, 2)
  • Verdict: library. fast-check is a property testing library for JavaScript and TypeScript.
  • Property<T> ties the four functions to one type, so a shrinker that returns the wrong kind of value does not type-check. The pair is a labelled tuple [items: number, perPage: number].
  • Each call states its type argument, check<number> and check<[items: number, perPage: number]>. The type annotations are erased before the program runs, so the run behaves as the JavaScript example does.
  • The arithmetic is the same as in JavaScript: >>> and >>> 0 keep the state unsigned.
package main

import (
	"fmt"
	"math"
	"strconv"
)

// Rng is xorshift32 with Marsaglia's seed: the same numbers on every run.
type Rng struct{ state uint32 }

func (r *Rng) Next() uint32 {
	r.state ^= r.state << 13
	r.state ^= r.state >> 17
	r.state ^= r.state << 5
	return r.state
}

func (r *Rng) Between(lo, hi int64) int64 {
	return lo + int64(uint64(r.Next())%uint64(hi-lo+1))
}

// Check runs a property on 100 generated cases and shrinks the first failure.
func Check[T any](name string, generate func(*Rng) T, holds func(T) bool, shrink func(T) []T) {
	rng := &Rng{state: 2463534242}
	for trial := 1; trial <= 100; trial++ {
		c := generate(rng)
		if holds(c) {
			continue
		}
		fmt.Printf("%s: falsified on test %d by %v\n", name, trial, c)
		steps := 0
		for shrunk := true; shrunk; {
			shrunk = false
			for _, smaller := range shrink(c) {
				if !holds(smaller) {
					c, shrunk = smaller, true
					steps++
					break
				}
			}
		}
		fmt.Printf("%s: shrunk in %d steps to %v\n", name, steps, c)
		return
	}
	fmt.Printf("%s: passed 100 tests\n", name)
}

// ShrinkInt gives lo, then x - d for d = (x - lo) / 2, / 4, ..., 1.
func ShrinkInt(x, lo int) []int {
	var out []int
	if x > lo {
		out = append(out, lo)
	}
	for d := (x - lo) / 2; d > 0; d /= 2 {
		out = append(out, x-d)
	}
	return out
}

func pages(items, perPage int) int {
	return items / perPage // bug: drops the last page when it is not full
}

type pair struct{ items, perPage int }

func (p pair) String() string { return fmt.Sprintf("(%d, %d)", p.items, p.perPage) }

func main() {
	Check("round trip",
		func(r *Rng) int32 { return int32(r.Between(math.MinInt32, math.MaxInt32)) },
		func(x int32) bool {
			back, err := strconv.ParseInt(strconv.FormatInt(int64(x), 10), 10, 32)
			return err == nil && int32(back) == x
		},
		func(int32) []int32 { return nil })

	Check("pages",
		func(r *Rng) pair { return pair{int(r.Between(0, 1000)), int(r.Between(1, 50))} },
		func(p pair) bool { return pages(p.items, p.perPage)*p.perPage >= p.items },
		func(p pair) []pair {
			var out []pair
			for _, n := range ShrinkInt(p.items, 0) {
				out = append(out, pair{n, p.perPage})
			}
			for _, n := range ShrinkInt(p.perPage, 1) {
				out = append(out, pair{p.items, n})
			}
			return out
		})
}
Output
round trip: passed 100 tests
pages: falsified on test 1 by (967, 7)
pages: shrunk in 13 steps to (1, 2)

The standard library has a property checker, testing/quick. A seeded Config.Rand makes the run repeatable.

package main

import (
	"fmt"
	"math/rand"
	"testing/quick"
)

func pages(items, perPage uint16) int {
	return int(items) / int(perPage) // bug: drops the last page when it is not full
}

func main() {
	holds := func(items uint16, perPage uint8) bool {
		per := uint16(perPage%50) + 1
		return pages(items, per)*int(per) >= int(items)
	}
	config := &quick.Config{MaxCount: 100, Rand: rand.New(rand.NewSource(1))}
	if err := quick.Check(holds, config); err != nil {
		fmt.Println(err)
		ce := err.(*quick.CheckError)
		fmt.Printf("test %d, arguments %v\n", ce.Count, ce.In)
	} else {
		fmt.Println("passed")
	}
}
Output
#1: failed on input 0xfd52, 0x4f
test 1, arguments [64850 79]
  • Verdict: stdlib. testing/quick.Check generates the arguments of a function by reflection and calls it until it returns false. The package is frozen.
  • quick.Check reports the first failing input as it is, 64850 items on pages of 79. It has no shrinker, so the hand-written Check above gives a smaller case, (1, 2).
  • Check[T any] is a generic function. Go has no tuples, so the pair is a struct with a String method, which %v calls.
  • Go has unsigned integers, so the state is a uint32 and the shifts and the overflow behave as in C. Unsigned arithmetic in Go wraps; it is not undefined.
  • In a test file, the same calls go in a func TestPages(t *testing.T). Go's native fuzzing, go test -fuzz, is a different tool with a corpus and coverage feedback; see Fuzz testing.
RustGitHub
use std::fmt::Debug;

/// xorshift32 with Marsaglia's seed: the same numbers on every run.
struct Rng(u32);

impl Rng {
    fn next(&mut self) -> u32 {
        self.0 ^= self.0 << 13;
        self.0 ^= self.0 >> 17;
        self.0 ^= self.0 << 5;
        self.0
    }

    fn between(&mut self, lo: i64, hi: i64) -> i64 {
        lo + (self.next() as u64 % (hi - lo + 1) as u64) as i64
    }
}

/// Runs a property on 100 generated cases and shrinks the first failure.
fn check<T: Debug>(
    name: &str,
    generate: impl Fn(&mut Rng) -> T,
    holds: impl Fn(&T) -> bool,
    shrink: impl Fn(&T) -> Vec<T>,
) {
    let mut rng = Rng(2463534242);
    for trial in 1..=100 {
        let mut case = generate(&mut rng);
        if holds(&case) {
            continue;
        }
        println!("{name}: falsified on test {trial} by {case:?}");
        let mut steps = 0;
        while let Some(smaller) = shrink(&case).into_iter().find(|c| !holds(c)) {
            case = smaller;
            steps += 1;
        }
        println!("{name}: shrunk in {steps} steps to {case:?}");
        return;
    }
    println!("{name}: passed 100 tests");
}

/// Gives lo, then x - d for d = (x - lo) / 2, / 4, ..., 1.
fn shrink_int(x: u32, lo: u32) -> Vec<u32> {
    let mut out = Vec::new();
    if x > lo {
        out.push(lo);
    }
    let mut d = (x - lo) / 2;
    while d > 0 {
        out.push(x - d);
        d /= 2;
    }
    out
}

fn pages(items: u32, per_page: u32) -> u32 {
    items / per_page // bug: drops the last page when it is not full
}

fn main() {
    check(
        "round trip",
        |rng| rng.between(i32::MIN as i64, i32::MAX as i64) as i32,
        |x| x.to_string().parse::<i32>() == Ok(*x),
        |_| Vec::new(),
    );

    check(
        "pages",
        |rng| (rng.between(0, 1000) as u32, rng.between(1, 50) as u32),
        |&(items, per_page)| pages(items, per_page) * per_page >= items,
        |&(items, per_page)| {
            let mut out: Vec<(u32, u32)> = shrink_int(items, 0).into_iter().map(|n| (n, per_page)).collect();
            out.extend(shrink_int(per_page, 1).into_iter().map(|p| (items, p)));
            out
        },
    );
}
Output
round trip: passed 100 tests
pages: falsified on test 1 by (967, 7)
pages: shrunk in 13 steps to (1, 2)

The first fix for the bug rounds up with (items + per_page - 1) / per_page. Near the top of the u32 range the sum overflows. A uniform generator almost never comes close to the top, so this generator takes a value near u32::MAX on one test in four.

This code panics, on purpose.

struct Rng(u32);

impl Rng {
    fn next(&mut self) -> u32 {
        self.0 ^= self.0 << 13;
        self.0 ^= self.0 >> 17;
        self.0 ^= self.0 << 5;
        self.0
    }

    /// One test in four takes a value near the maximum.
    fn edgy_u32(&mut self) -> u32 {
        if self.next() % 4 == 0 { u32::MAX - self.next() % 4 } else { self.next() }
    }
}

fn pages(items: u32, per_page: u32) -> u32 {
    (items + per_page - 1) / per_page // a debug build panics when the sum overflows
}

fn main() {
    let mut rng = Rng(2463534242);
    for _ in 0..100 {
        let (items, per_page) = (rng.edgy_u32(), 1 + rng.next() % 50);
        assert!(u64::from(pages(items, per_page)) * u64::from(per_page) >= u64::from(items));
    }
    println!("passed 100 tests");
}

A debug build panics with attempt to add with overflow, and the property test has found a second bug. div_ceil rounds up with no intermediate sum. The second assertion checks that the count is not too large.

struct Rng(u32);

impl Rng {
    fn next(&mut self) -> u32 {
        self.0 ^= self.0 << 13;
        self.0 ^= self.0 >> 17;
        self.0 ^= self.0 << 5;
        self.0
    }

    /// One test in four takes a value near the maximum.
    fn edgy_u32(&mut self) -> u32 {
        if self.next() % 4 == 0 { u32::MAX - self.next() % 4 } else { self.next() }
    }
}

fn pages(items: u32, per_page: u32) -> u32 {
    items.div_ceil(per_page) // rounds up with no intermediate sum
}

fn main() {
    let mut rng = Rng(2463534242);
    let mut near_max = 0;
    for _ in 0..100 {
        let (items, per_page) = (rng.edgy_u32(), 1 + rng.next() % 50);
        let n = pages(items, per_page);
        assert!(u64::from(n) * u64::from(per_page) >= u64::from(items), "pages too few");
        assert!(n == 0 || u64::from(n - 1) * u64::from(per_page) < u64::from(items), "pages too many");
        near_max += (items > u32::MAX - 4) as u32;
    }
    println!("passed 100 tests, {near_max} of them near u32::MAX");
}
Output
passed 100 tests, 28 of them near u32::MAX
  • Verdict: library. proptest is a property testing library in the QuickCheck family. Its strategies generate and shrink each value.
  • check takes three closures through impl Fn. The bound T: Debug lets it print any case with {:?}, so a tuple prints as (1, 2).
  • while let Some(smaller) = ... .find(...) is the whole shrink loop: it stops when no candidate fails.
  • Arithmetic overflow panics in a debug build, and a release build wraps. The C example shows the same bug with no panic.
  • The property computes pages * per_page in u64, so the check itself cannot overflow.
  • Type-driven and value-driven generators. QuickCheck finds the generator from the type of the property through Arbitrary.1 Hypothesis and proptest pass generators as values, called strategies. The proptest book says that generation and shrinking for each value, not for each type, is more flexible and composes better.9
  • Integrated shrinking. In QuickCheck, the generator and the shrinker are separate methods of Arbitrary, and a type with invariants needs a shrinker that keeps them.2 Hypothesis keeps one internal representation for all test data and shrinks that, so the user writes no shrinker.5
  • Explicit examples. Hypothesis's @example adds fixed inputs that run on each run before the generated ones. They do not shrink.6 This joins example-based tests and properties in one test.
  • Stateful or model-based testing. The tool generates a sequence of operations on an object and compares each result with a small model. FsCheck calls this model-based testing.10
  • Fuzz testing. A fuzzer also runs a program on many generated inputs, but it looks for crashes and hangs, not for the failure of a stated rule. Coverage-guided fuzzers steer the inputs with feedback from the program. See Fuzz testing.
  • Exhaustive testing of small inputs. For a small domain, a test can check every input up to some size instead of a random sample. The checker then needs no seed and no shrinker.

Pitfalls

The generator never makes the input that fails

A property can only fail on an input that the generator makes. Code that pads a column of text often assumes that str.upper keeps the length of a string. A generator of ASCII letters supports the assumption.

This code runs but gives a wrong answer on purpose.

def xorshift32(state):
    state ^= (state << 13) & 0xFFFFFFFF
    state ^= state >> 17
    state ^= (state << 5) & 0xFFFFFFFF
    return state


ALPHABET = "abcdefABCDEF"
state = 2463534242
for trial in range(1, 101):
    state = xorshift32(state)
    length = state % 9
    chars = []
    for _ in range(length):
        state = xorshift32(state)
        chars.append(ALPHABET[state % len(ALPHABET)])
    s = "".join(chars)
    if len(s.upper()) != len(s):
        print(f"falsified on test {trial} by {s!r}")
        break
else:
    print("passed 100 tests")
Output
passed 100 tests

With letters outside ASCII in the alphabet, the same loop finds a string whose upper case is longer. The German letter ß becomes SS.

def xorshift32(state):
    state ^= (state << 13) & 0xFFFFFFFF
    state ^= state >> 17
    state ^= (state << 5) & 0xFFFFFFFF
    return state


ALPHABET = "abcABCéÉßΣ"
state = 2463534242
for trial in range(1, 101):
    state = xorshift32(state)
    length = state % 9
    chars = []
    for _ in range(length):
        state = xorshift32(state)
        chars.append(ALPHABET[state % len(ALPHABET)])
    s = "".join(chars)
    if len(s.upper()) != len(s):
        print(f"falsified on test {trial} by {s!r}")
        print(f"{s.upper()!r} has {len(s.upper())} characters")
        break
else:
    print("passed 100 tests")
Output
falsified on test 5 by 'ΣBßΣécba'
'ΣBSSΣÉCBA' has 9 characters

Measure what the generator makes. QuickCheck has the combinators classify and collect to show the distribution of the test data.1 Add the known edge cases as explicit examples: zero, the minimum and maximum of a type, the empty string, characters outside ASCII.

A precondition throws most inputs away

A conditional property discards each input that fails its precondition. When the precondition is rare, the property runs on few inputs, and those few are biased toward the cases that meet the precondition by chance. Claessen and Hughes found that a property of insertion into ordered lists ran mostly on lists of length 0 and 1, because a random long list is rarely ordered.1

This code runs but gives a wrong answer on purpose.

def xorshift32(state):
    state ^= (state << 13) & 0xFFFFFFFF
    state ^= state >> 17
    state ^= (state << 5) & 0xFFFFFFFF
    return state


def is_ordered(xs):
    return all(a <= b for a, b in zip(xs, xs[1:]))


state = 2463534242
kept = {}
for _ in range(100):
    state = xorshift32(state)
    xs = []
    for _ in range(state % 7):
        state = xorshift32(state)
        xs.append(state % 10)
    if not is_ordered(xs):
        continue  # the precondition fails: discard the input
    kept[len(xs)] = kept.get(len(xs), 0) + 1
print("kept", sum(kept.values()), "of 100; by length:", dict(sorted(kept.items())))
Output
kept 44 of 100; by length: {0: 16, 1: 14, 2: 10, 3: 4}

Fewer than half of the inputs met the precondition, and none of them was longer than three. The fix is a generator that makes only valid inputs. QuickCheck's paper replaces the precondition with a generator of ordered lists.1 Here, sorting the generated list makes every input valid, and all lengths occur.

def xorshift32(state):
    state ^= (state << 13) & 0xFFFFFFFF
    state ^= state >> 17
    state ^= (state << 5) & 0xFFFFFFFF
    return state


state = 2463534242
kept = {}
for _ in range(100):
    state = xorshift32(state)
    xs = []
    for _ in range(state % 7):
        state = xorshift32(state)
        xs.append(state % 10)
    xs.sort()  # generate ordered lists directly
    kept[len(xs)] = kept.get(len(xs), 0) + 1
print("kept", sum(kept.values()), "of 100; by length:", dict(sorted(kept.items())))
Output
kept 100 of 100; by length: {0: 16, 1: 14, 2: 15, 3: 17, 4: 9, 5: 13, 6: 16}

The property restates the code

A property that computes the expected value in the same way as the code under test passes whenever the code runs. It cannot find a bug in the logic, because the bug is in both places.

This code runs but gives a wrong answer on purpose.

def xorshift32(state):
    state ^= (state << 13) & 0xFFFFFFFF
    state ^= state >> 17
    state ^= (state << 5) & 0xFFFFFFFF
    return state


def pages(items, per_page):
    return items // per_page  # the same bug as before


state = 2463534242
for trial in range(1, 101):
    state = xorshift32(state)
    items = state % 1001
    state = xorshift32(state)
    per_page = 1 + state % 50
    assert pages(items, per_page) == items // per_page  # restates the code
print("passed 100 tests")
Output
passed 100 tests

State what a right answer must satisfy, not how to compute it. For pages, there are two rules: the pages hold all the items (pages * per_page >= items), and one page fewer does not ((pages - 1) * per_page < items). Together they define the rounded-up quotient without computing it.

A seed that the run does not show

A failure from an unseeded run may not occur again. Print the seed of each run, and let the test accept a seed from outside. Do not depend on a library generator to give the same numbers forever. Python guarantees only that random() gives the same sequence for the same seed. Most other functions of the random module may change between Python versions.4 The examples on this page carry their own xorshift generator for this reason.

Cost

  • Time per test. A property runs its body many times, 100 by default in QuickCheck, plus the shrinking steps after a failure.1 A property over a function that takes milliseconds makes a test that takes seconds. The count is a parameter in QuickCheck, so a run can trade time for coverage.1
  • Thought per test. A good property needs a rule about the code, which takes more thought than one input and one output.
  • Generators. A generator for a domain type is code, and it can be wrong in the ways shown in Pitfalls. QuickCheck reduces the cost through type classes, and Hypothesis through composable strategies.15
  • Flakiness. A run that is not seeded can fail on one run and pass on the next. A seeded run with a saved database of failures gives a test that fails in the same way until the bug is fixed.6

History

  • 2000. Koen Claessen and John Hughes presented QuickCheck at ICFP 2000. It tested properties written as Haskell functions on random inputs from generators chosen by type. The paper compares random testing with partition testing and argues that random testing at a fine grain gives good coverage.1
  • 2003. George Marsaglia described the xorshift generators, which need only shifts and exclusive-or operations.3
  • 2006. Arts, Hughes, Johansson and Wiger described tests of telecoms software with Quviq QuickCheck, a version for Erlang.5
  • 2019. David MacIver, Zac Hatfield-Dodds and others described Hypothesis for Python in the Journal of Open Source Software. Hypothesis shrinks a single internal representation of the test data.5

References

  1. Koen Claessen and John Hughes, QuickCheck, A Lightweight Tool for Random Testing of Haskell Programs, ICFP 2000, pages 268 to 279, 2.1 A Simple Example; 2.3 Conditional Laws; 2.4 Monitoring Test Data; 3.1 Arbitrary; 3.2 Generators for User-Defined Types (sized); 6.1 On Random Testing; 6.2 Correctness Criteria
  2. QuickCheck package documentation, module Test.QuickCheck, the module description (minimal counterexample); class Arbitrary, shrink; data Args, replay
  3. George Marsaglia, Xorshift RNGs, Journal of Statistical Software 8(14), 2003, section 3, the 32-bit generator with the shifts 13, 17, 5 and the seed 2463534242
  4. The Python Standard Library, random, Python 3.14, Notes on Reproducibility
  5. David R. MacIver, Zac Hatfield-Dodds and others, Hypothesis, A new approach to property-based testing, Journal of Open Source Software 4(43), 1891, 2019, Summary; Hypothesis for Software Testing Research
  6. Hypothesis documentation, Replaying failed tests, The Hypothesis database; Using @example to run a specific input
  7. fast-check documentation, the home page (property-based testing for JavaScript and TypeScript)
  8. jqwik, Property-Based Testing in Java, the home page (the JVM, Java and Kotlin)
  9. The proptest book, Introduction
  10. FsCheck documentation, the home page (F#, C# and VB; minimal counterexample)
  11. Go standard library, package testing/quick, package overview (frozen); func Check; type Config
  12. PowerShell documentation, Get-Random, the parameter -SetSeed
  13. Bash Reference Manual, 5.2 Bash Variables, RANDOM

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/STCBBZ/text.yaml