Property-Based Testing Guide
Property-based testing with Hypothesis (Python) and fast-check (TypeScript): generate cases, catch edge cases, and shrink failures to minimal bugs.
Introduction
You’ve written twelve unit tests for your parser. They’re all green. Then production feeds it a string with a Unicode combining character and everything burns. That’s the recurring problem with example-based tests: they only check the inputs you thought of, and the bugs that reach production are almost always in the inputs nobody thought of.
Property-based testing attacks that gap. Instead of enumerating examples, you state invariants — “reversing twice returns the original”, “sorted output stays sorted” — and the framework generates hundreds of random inputs, checks each one, and when something fails it shrinks the input down to the smallest case that still breaks. This guide walks through Hypothesis for Python and fast-check for TypeScript, the two most mature implementations of the QuickCheck idea. For the broader picture of where this fits in your test suite, see Software Testing Strategy.
When to Use It (and When Not To)
| Good fit | Poor fit |
|---|---|
| Pure functions (parse, serialize, sort, encode) | UI rendering, visual states |
| Data transformations with invariants | Side-effect-heavy code (I/O, network) |
| Serialization roundtrips | Functions with complex external preconditions |
| Stateful systems (queues, caches, stacks) | Code where the “property” is just re-stating the implementation |
| Code with a reference implementation to compare | Performance assertions (timing isn’t a property) |
Don’t use property tests as a replacement for example tests. Examples document expected behavior for humans; properties hunt the edge cases you forgot. You want both — properties find the bug, then the shrunk case becomes a permanent example test.
Core Concepts
Example-based vs. property-based testing
Example-based (traditional):
test_add(2, 3) == 5
test_add(0, 0) == 0
test_add(-1, 1) == 0
→ You think of edge cases manually. You miss some.
Property-based:
for all integers a, b:
add(a, b) == add(b, a) — commutativity
add(a, 0) == a — identity
add(add(a, b), c) == add(a, add(b, c)) — associativity
→ Framework generates hundreds of inputs. Finds edge cases you missed.
The property-based testing cycle
- Generate: Create random inputs within defined constraints
- Execute: Run the function under test with those inputs
- Verify: Check if the property holds
- Shrink: On failure, reduce the input to the minimal reproducing case
- Report: Present the shrunk counterexample
That last step is what makes PBT practical. A failing test on a 500-element list is useless for debugging; the same failure shrunk to [0, -1] tells you the bug immediately.
How to find properties
Three patterns cover most of the useful properties you’ll write:
- Roundtrip:
decode(encode(x)) == x— serializes, parses, encoders, compressors - Invariant: things that must always be true — sorted output is sorted, length is preserved, values stay in range
- Oracle: compare against a reference — your hand-rolled
sortagainst the built-insorted, your parser againstjson.loads - Metamorphic: when no oracle exists — transform the input predictably and check the output transforms predictably (
scale(x, 2)doubles every element)
If you can’t articulate an invariant, you probably don’t have a property yet — “returns the right answer” isn’t one.
Hypothesis (Python)
Installation
pip install hypothesis
# Or with pytest integration (recommended)
pip install hypothesis pytest
Hypothesis plugs into pytest: @given decorators run inside ordinary test functions, so there’s no separate runner and no new CI machinery. For a broader pytest setup, see Pytest in Production.
Basic properties
# tests/test_string_properties.py — Basic property tests
from hypothesis import given, strategies as st
@given(st.text())
def test_string_uppercase_is_uppercase(s):
"""Uppercase of any string contains no lowercase characters."""
assert s.upper().isupper() or not s
@given(st.text())
def test_string_reversal_is_inverse(s):
"""Reversing a string twice gives back the original."""
assert s[::-1][::-1] == s
@given(st.lists(st.integers()))
def test_list_sort_preserves_length(lst):
"""Sorting a list does not change its length."""
assert len(sorted(lst)) == len(lst)
@given(st.lists(st.integers()))
def test_list_sort_idempotent(lst):
"""Sorting an already sorted list gives the same list."""
sorted_lst = sorted(lst)
assert sorted(sorted_lst) == sorted_lst
@given(st.lists(st.integers()))
def test_list_max_is_in_list(lst):
"""The maximum of a list is always an element of the list."""
if lst:
assert max(lst) in lst
Notice what’s missing: no expected values. You assert relationships, not outputs — that’s the whole mental shift. The st.text() strategy generates everything from empty strings to emoji to control characters, which is exactly where parsers tend to break.
Composite strategies
Real code rarely accepts st.text() — it accepts users, orders, configs. @composite lets you build those domains from primitives:
# tests/test_user_properties.py — Composite strategies
import json
from hypothesis import given, strategies as st, composite
@composite
def valid_email(draw):
"""Generate valid email addresses."""
local = draw(st.text(min_size=1, max_size=20,
alphabet=st.characters(categories=("Ll", "Nd"))))
domain = draw(st.text(min_size=1, max_size=10,
alphabet=st.characters(categories=("Ll", "Nd"))))
tld = draw(st.sampled_from(["com", "org", "net", "io", "dev"]))
return f"{local}@{domain}.{tld}"
@composite
def user_strategy(draw):
"""Generate user objects with valid fields."""
return {
"id": draw(st.integers(min_value=1, max_value=1000000)),
"name": draw(st.text(min_size=1, max_size=50)),
"email": draw(valid_email()),
"age": draw(st.integers(min_value=0, max_value=150)),
"is_active": draw(st.booleans()),
}
@given(user_strategy())
def test_user_serialization_roundtrip(user):
"""Serializing and deserializing a user preserves all fields."""
serialized = json.dumps(user)
deserialized = json.loads(serialized)
assert deserialized == user
@given(user_strategy())
def test_user_email_contains_at(user):
"""Every generated user email contains @."""
assert "@" in user["email"]
Two things worth knowing here. categories=("Ll", "Nd") restricts generated characters to lowercase letters and digits — the modern spelling; the old whitelist_categories argument was removed in Hypothesis 6.x. And for structured objects, st.builds(User, name=..., age=...) often does the job without a hand-rolled composite — it calls the constructor with strategy-fed arguments.
Assumptions and conditional properties
# tests/test_conditional_properties.py — Filtering inputs
from hypothesis import given, strategies as st, assume
@given(st.lists(st.integers()))
def test_binary_search_finds_element(lst):
"""Binary search finds any element in a sorted list."""
assume(len(lst) > 0) # Skip empty lists
sorted_lst = sorted(lst)
target = sorted_lst[len(sorted_lst) // 2] # Pick middle element
def binary_search(arr, target):
lo, hi = 0, len(arr) - 1
while lo <= hi:
mid = (lo + hi) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
lo = mid + 1
else:
hi = mid - 1
return -1
result = binary_search(sorted_lst, target)
assert result != -1
assert sorted_lst[result] == target
assume discards inputs that don’t meet a precondition. Use it sparingly: if Hypothesis has to reject most generated inputs, the test gets slow and you’ll see UnsatisfiedAssumption failures. When you’re filtering a lot, build the constraint into the strategy instead — st.lists(st.integers(), min_size=1) beats assume(len(lst) > 0).
Stateful testing
# tests/test_stack_properties.py — Stateful property testing
from hypothesis.stateful import RuleBasedStateMachine, rule, invariant
from hypothesis import strategies as st
class StackMachine(RuleBasedStateMachine):
"""Test a stack implementation with stateful properties."""
def __init__(self):
super().__init__()
self.stack = []
@rule(value=st.integers())
def push(self, value):
self.stack.append(value)
@rule()
def pop(self):
if self.stack:
self.stack.pop()
@invariant()
def stack_size_non_negative(self):
assert len(self.stack) >= 0
TestStack = StackMachine.TestCase
RuleBasedStateMachine generates random sequences of operations — push, pop, push, push, pop — and checks invariants after every step. This is where PBT earns its keep on stateful systems: it finds the interleaving of operations that breaks your cache or queue, then shrinks that sequence to three steps.
Settings, profiles, and the example database
# tests/test_configured.py — Hypothesis settings
from hypothesis import given, strategies as st, settings, HealthCheck
@given(st.lists(st.integers(), min_size=1))
@settings(
max_examples=500, # Generate up to 500 test cases
deadline=2000, # 2 second timeout per test
suppress_health_check=[HealthCheck.too_slow],
print_blob=True, # Print the failing input as a blob
)
def test_large_list_processing(lst):
"""Process large lists within time budget."""
# result = process_list(lst) # your function under test
assert len(lst) >= 1
Two things that save real debugging time:
@example(x)inside@givenpins a known-tricky input to always run — the shrunk counterexample from last week’s bug becomes a permanent regression case.- Hypothesis persists every failing example in
.hypothesis/examples/and replays them on the next run, even across different seeds. Commit that directory (or at least don’t gitignore it blindly) — it’s your generated regression suite.
# conftest.py — separate CI vs dev effort
from hypothesis import settings
settings.register_profile("dev", max_examples=50)
settings.register_profile("ci", max_examples=1000, deadline=None)
settings.load_profile("dev") # HYPOTHESIS_PROFILE=ci in the pipeline
fast-check (TypeScript/JavaScript)
Installation
npm install -D fast-check vitest
fast-check plays the same role as Hypothesis in the JS ecosystem — it works with vitest, jest, and mocha, and its arbitraries map closely to Hypothesis strategies. The recipe Implement Property-Based Testing covers a minimal first test; below is the fuller picture.
Basic properties
// tests/properties/string.test.ts — Basic property tests with fast-check
import { describe, it, expect } from "vitest";
import fc from "fast-check";
describe("String properties", () => {
it("uppercase contains no lowercase characters", () => {
fc.assert(fc.property(fc.string(), (s) => {
expect(s.toUpperCase().match(/[a-z]/)).toBeNull();
}));
});
it("reversing twice returns the original", () => {
fc.assert(fc.property(fc.string(), (s) => {
expect(s.split("").reverse().reverse().join("")).toBe(s);
}));
});
it("concatenation length is sum of lengths", () => {
fc.assert(fc.property(fc.string(), fc.string(), (a, b) => {
expect((a + b).length).toBe(a.length + b.length);
}));
});
});
describe("Number properties", () => {
it("addition is commutative", () => {
fc.assert(fc.property(fc.integer(), fc.integer(), (a, b) => {
expect(a + b).toBe(b + a);
}));
});
it("addition is associative", () => {
fc.assert(fc.property(fc.integer(), fc.integer(), fc.integer(), (a, b, c) => {
expect((a + b) + c).toBe(a + (b + c));
}));
});
it("multiplication distributes over addition", () => {
fc.assert(fc.property(fc.integer(), fc.integer(), fc.integer(), (a, b, c) => {
expect(a * (b + c)).toBe(a * b + a * c);
}));
});
});
Custom arbitraries
// tests/properties/user.test.ts — Custom arbitraries
import { describe, it, expect } from "vitest";
import fc from "fast-check";
const validEmail = fc.tuple(
fc.string({ minLength: 1 }).map((s) => s.replace(/[^a-zA-Z0-9]/g, "a")),
fc.string({ minLength: 1 }).map((s) => s.replace(/[^a-zA-Z0-9]/g, "a")),
fc.constantFrom("com", "org", "net", "io", "dev")
).map(([local, domain, tld]) => `${local}@${domain}.${tld}`);
const userArbitrary = fc.record({
id: fc.integer({ min: 1, max: 1000000 }),
name: fc.string({ minLength: 1, maxLength: 50 }),
email: validEmail,
age: fc.integer({ min: 0, max: 150 }),
isActive: fc.boolean(),
});
describe("User properties", () => {
it("serialization roundtrip preserves data", () => {
fc.assert(fc.property(userArbitrary, (user) => {
const serialized = JSON.stringify(user);
const deserialized = JSON.parse(serialized);
expect(deserialized).toEqual(user);
}));
});
it("email contains @", () => {
fc.assert(fc.property(userArbitrary, (user) => {
expect(user.email).toContain("@");
}));
});
});
fc.record is the equivalent of @composite — it builds objects field by field. For domain-heavy code, build a small library of arbitraries (email, url, uuid, date ranges) once and reuse them across the suite rather than redefining them per test.
Stateful testing with fast-check
// tests/properties/stack.test.ts — Stateful property testing
import { describe, it, expect } from "vitest";
import fc from "fast-check";
type StackCommand =
| { type: "push"; value: number }
| { type: "pop" };
const stackCommands = fc.array(
fc.oneof(
fc.record({ type: fc.constant("push"), value: fc.integer() }),
fc.record({ type: fc.constant("pop") })
)
);
describe("Stack stateful properties", () => {
it("stack size is always non-negative", () => {
fc.assert(fc.property(stackCommands, (commands) => {
const stack: number[] = [];
for (const cmd of commands) {
if (cmd.type === "push") {
stack.push(cmd.value);
} else if (stack.length > 0) {
stack.pop();
}
expect(stack.length).toBeGreaterThanOrEqual(0);
}
}));
});
it("pop returns last pushed value (LIFO)", () => {
fc.assert(fc.property(stackCommands, (commands) => {
const stack: number[] = [];
for (const cmd of commands) {
if (cmd.type === "push") {
stack.push(cmd.value);
} else if (stack.length > 0) {
const top = stack[stack.length - 1];
expect(stack.pop()).toBe(top);
}
}
}));
});
});
The pattern is the same as RuleBasedStateMachine: generate command sequences, replay them, assert invariants after each step. fast-check also has fc.commands and Model/Run for a more formal model-based approach when the system under test is more complex than a stack.
Shrinking and debugging
// tests/properties/shrinking.test.ts — Understanding shrinking
import { describe, it, expect } from "vitest";
import fc from "fast-check";
describe("Shrinking behavior", () => {
it("finds minimal failing case", () => {
// This will fail and shrink to the minimal case
fc.assert(
fc.property(fc.array(fc.integer()), (arr) => {
// Property: sorted array has no element greater than the next
const sorted = [...arr].sort((a, b) => a - b);
for (let i = 0; i < sorted.length - 1; i++) {
expect(sorted[i]).toBeLessThanOrEqual(sorted[i + 1]);
}
}),
{ verbose: 2 } // Show shrinking steps
);
});
it("with custom seed for reproducibility", () => {
fc.assert(
fc.property(fc.integer(), (n) => {
expect(Math.abs(n)).toBeGreaterThanOrEqual(0);
}),
{ seed: 12345 } // Reproducible test runs
);
});
});
verbose: 2 shows each shrinking step — useful while you’re learning to read the output. { seed } freezes the RNG so a CI failure replays identically on your machine; fast-check prints the failing seed in its output, so copy-paste it to reproduce.
Practical Property Patterns
Roundtrip properties
# Python: serialize → deserialize → compare
@given(st.text())
def test_json_roundtrip(s):
"""JSON serialization is a roundtrip for strings."""
assert json.loads(json.dumps(s)) == s
@given(st.lists(st.integers()))
def test_sort_roundtrip(lst):
"""Sorting is idempotent."""
assert sorted(sorted(lst)) == sorted(lst)
// TypeScript: encode → decode → compare
it("base64 roundtrip", () => {
fc.assert(fc.property(fc.string(), (s) => {
const encoded = btoa(s);
const decoded = atob(encoded);
expect(decoded).toBe(s);
}));
});
Invariant properties
@given(st.lists(st.integers(), min_size=1))
def test_max_is_geq_all(lst):
"""The max of a list is >= all elements."""
m = max(lst)
for x in lst:
assert m >= x
@given(st.lists(st.integers(), min_size=1))
def test_sum_equals_max_times_count(lst):
"""Sum of a list of identical values equals value * count."""
value = lst[0]
assume(all(x == value for x in lst))
assert sum(lst) == value * len(lst)
Oracle properties
@given(st.lists(st.integers()))
def test_custom_sort_matches_builtin(lst):
"""Custom sort produces same result as Python's built-in sort."""
custom_sorted = my_custom_sort(lst[:]) # your implementation
builtin_sorted = sorted(lst)
assert custom_sorted == builtin_sorted
The oracle pattern is the strongest of the four — when a trusted reference exists (stdlib sorted, json.loads, a legacy implementation), any divergence between it and your code is a bug by definition.
Stateful properties with a model
from hypothesis.stateful import RuleBasedStateMachine, rule, invariant
class DictStateMachine(RuleBasedStateMachine):
def __init__(self):
super().__init__()
self.dict = {} # system under test
self.model = {} # trusted reference
@rule(key=st.text(), value=st.integers())
def set_value(self, key, value):
self.dict[key] = value
self.model[key] = value
@rule(key=st.text())
def get_value(self, key):
if key in self.model:
assert self.dict[key] == self.model[key]
@invariant()
def sizes_match(self):
assert len(self.dict) == len(self.model)
TestDict = DictStateMachine.TestCase
The model-based variant keeps a trivial “obviously correct” data structure next to the real one — every operation updates both, and invariants compare them. This is how you test databases, caches, and queues where the correct answer is “whatever the model says”.
CI Integration
GitHub Actions with Hypothesis
# .github/workflows/property-tests.yml
name: Property Tests
on: [push, pull_request]
jobs:
property-tests:
runs-on: ubuntu-latest
env:
HYPOTHESIS_PROFILE: ci
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.12"
- run: pip install hypothesis pytest
- run: pytest tests/ -v --hypothesis-show-statistics
GitHub Actions with fast-check
# .github/workflows/property-tests.yml
name: Property Tests
on: [push, pull_request]
jobs:
property-tests:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
cache: npm
- run: npm ci
- run: npx vitest run tests/properties/
Give property tests a bigger budget in CI than locally — max_examples=1000 overnight is cheap insurance. And never run them with a fixed seed only: the point of CI is exploring new input space every run. Pin seeds only to reproduce a specific failure.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
UnsatisfiedAssumption failures | assume rejecting most inputs | Build the constraint into the strategy (min_size, map, filter on the strategy) |
| Tests take minutes | max_examples too high or strategies generating huge data | Cap sizes (max_size), lower max_examples, check deadline |
| Failure won’t reproduce locally | Different seed between CI and dev | Copy the seed/<blob> from the failure output; @example it |
| Shrinker loops forever | Pathological input space | @settings(deadline=None) on that test, or simplify the strategy |
HealthCheck warnings | Slow strategies, large data, filtering | Read the warning; most have a suppress_health_check escape hatch as last resort |
| Property “passes” but tests nothing | Assertion too weak | Add a second clause — sorted result must be ordered, not just same length |
Best Practices
- Start with simple properties — commutativity, associativity, identity, roundtrips
- Set
max_exampleshigher for critical code — 1000 instead of the default 100 - Build constrained strategies over broad
assume— generation is faster than rejection - Pin failing cases with
@exampleor the example DB — never lose a counterexample - Combine with example-based tests — properties hunt edge cases, examples document intent
- Use stateful testing for stateful systems — databases, caches, queues, connection pools
- Read the shrunk case before fixing — the minimal input usually names the bug
- One property per test function — a failure should point at exactly one broken invariant
- Test your logic, not the language — verifying
sorted()works isn’t a useful property - Keep oracles close — a reference implementation in the test file beats re-checking by hand
Common Mistakes
- Properties too weak:
sort(lst)has the same length aslst— true but doesn’t test sorting. Add “output is ordered”. - Properties too strong:
add(a, b) > 0fails for negatives. Useadd(a, 0) == ainstead. - Re-stating the implementation: asserting
my_sort == my_sort_logic_copytests nothing — compare against an independent oracle. - Over-using
assume: filtering 95% of inputs means Hypothesis works hard to test little. Constrain the strategy instead. - Ignoring shrinking: the shrunk case is the most valuable output. Read it before reaching for the debugger.
- Huge strategies:
st.lists(st.integers())unbounded generates megabyte lists — capmax_sizefor unit tests. - Fixed seeds everywhere: pinning
seedin every test defeats the point — pin only to reproduce a failure, then unpin. - Testing too much per property: one property per test function. If it fails, you know exactly which invariant broke.
See Also
Frequently Asked Questions
What is property-based testing?
A testing approach where you define invariants (properties) that should hold for all valid inputs, and a framework generates hundreds of test cases automatically. When a test fails, the framework shrinks the input to the minimal reproducing case.
How is it different from fuzzing?
Fuzzing focuses on finding crashes and security issues by throwing random data at a program — usually at the binary or protocol level. Property-based testing verifies that specific invariants hold, with structured input generation, typed strategies, and shrinking for debugging. Think of PBT as fuzzing with an oracle and a memory.
What is shrinking?
When a property test fails with a complex input, the framework systematically simplifies the input — smaller lists, smaller strings, simpler structures — until it finds the smallest case that still fails. Instead of debugging a 500-element list, you get a 2-element list triggering the same bug.
When should I use property-based testing?
For pure functions, data transformations, serialization, parsers, and stateful systems — anywhere you can state an invariant. It's most valuable when a reference implementation exists (oracle properties) or the input space is too big to enumerate (text, nested JSON, numeric ranges).
What are the limitations?
Properties are hard to write for UI code, side-effect-heavy functions, and code with complex external preconditions. Runs take longer than unit tests — hundreds of iterations instead of one. And a weak property gives false confidence: "same length" passing tells you nothing about ordering. Use PBT alongside, not instead of, example-based tests.
Can I mix property tests and regular tests in one file?
Yes — @given functions are just pytest/vitest tests with extra machinery. Common pattern: example tests document the expected behavior, property tests sit next to them hunting edge cases, and any shrunk counterexample gets pinned with @example or added to the example tests permanently.
Related Resources
Test-Driven Development (TDD) — A Practical Workflow
Learn TDD step by step: write a failing test, make it pass, refactor. Red-Green-Refactor with real examples in Python, JavaScript, and Java.
GuideSoftware Testing Strategy Guide
A practical guide to building a layered testing strategy with unit, integration, contract, and end-to-end tests that your team will actually maintain.
GuidePytest in Production Guide
Pytest for production: advanced fixtures, custom markers, parametrization, xdist parallelism, plugins, and CI integration patterns.
RecipeProperty-Based Testing with Hypothesis
How to use Hypothesis for property-based testing in Python, generating hundreds of test cases automatically from strategies instead of writing them by hand.
RecipeImplement Property-Based Testing
How to write property-based tests with Hypothesis, fast-check, and jqwik that generate thousands of inputs to find edge cases traditional tests miss.