@property-based-testing

Write property-based tests with Hypothesis, proptest, or fast-check. Design non-tautological invariants, avoid filtered generator starvation, shrink counterexamples, and pin CI seeds.

Property-Based Testing

When to Use

  • Test parsers, serializers, encoders, interval/calendar math, state machines, or data transforms where hand-picked examples miss edge cases.
  • Catch subtle boundary bugs by generating structured inputs and shrinking failures to minimal counterexamples.
  • Harden CI against regressions discovered by fuzzing or property failures without introducing flaky test runs.

Prerequisites

Identify the language, test runner, and property-testing library (hypothesis in Python, proptest in Rust, or fast-check in TypeScript/JavaScript). Confirm the function's public contract, domain constraints (such as valid input ranges, NaN/infinity handling, or ordering guarantees), and runtime budget in CI.

Choose real invariants instead of tautologies

  1. Avoid re-implementing the production formula inside the test (which merely tests that two copies of the same bug agree). Pick independent mathematical or behavioral properties:
    • Round-trip / inverse: decode(encode(x)) == x for valid domain inputs, verifying canonical encoding rules when multiple representations exist.
    • Oracle / differential: compare an optimized or complex implementation against a simple, obviously correct reference model on bounded inputs (for example point-set coverage for interval merging).
    • Idempotence and canonical form: applying normalization, formatting, or merging twice produces the same output (f(f(x)) == f(x)) and satisfies structural postconditions (sorted, disjoint, escaped).
    • Metamorphic and order invariance: permuting input order, splitting batches, or scaling inputs transforms the output predictably.
    • Stateful model checking: run random sequences of commands (RuleBasedStateMachine / fc.commands) against both the system under test and a simple in-memory reference model.

Construct healthy generators and shrink cleanly

  • Build valid domain values directly with combinators (flatmap, composite, builds) instead of generating unconstrained inputs and discarding 90% with .filter(...) or assume(...), which slows execution and triggers health-check failures.
  • Keep generator ranges small enough that collisions, duplicates, empty collections, and boundary values occur frequently (for example small integer bounds for interval overlap tests rather than full 64-bit ranges where two intervals almost never intersect).
  • When shrinking exposes a bug, promote the shrunk minimal counterexample into an explicit @example(...) (Hypothesis) or named unit test so the regression runs deterministically on every commit.

Make CI deterministic and debuggable

  • Pin derandomize=True (or record seeds in CI logs / proptest-regressions) so pull-request checks remain reproducible while scheduled/local runs can explore broader random seeds with higher max_examples.
  • Keep tests pure and side-effect free: avoid shared mutable global state, wall-clock dependence, or network calls inside property loops.

Example

An interval-merging utility passes simple overlapping unit tests but silently drops data on nested intervals such as [(0, 2), (1, 1)].

Run the worked Hypothesis invariants and shrinking test to verify that a coverage-oracle property catches the nested-interval bug and that the fixed implementation satisfies oracle, canonical-form, idempotence, and reversal invariants with a pinned @example.

Limitations

  • Property-based testing finds bugs within the domain your generators actually produce; biased or overly narrow strategies can still miss failure modes (such as Unicode normalization, huge allocations, or concurrency races).
  • Exhaustive formal verification and timing/load characteristics are outside the scope of randomized property testing.

Safety and Side Effects

Run property suites against in-memory data or isolated disposable fixtures. Never point randomized generators at production databases, paid external APIs, or destructive filesystem paths. Keep generated example databases (.hypothesis/ or proptest-regressions/) aligned with repository ignore/commit conventions.