Property-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.
Overview
Hypothesis is a property-based testing library for Python. Instead of hand-writing test cases with specific inputs, you state properties that should hold for all valid inputs — “reversing twice returns the original”, “sorted output has the same length” — and Hypothesis generates hundreds of cases with type-aware generators called strategies. When something fails, it shrinks the input to the smallest counterexample that still breaks.
This recipe covers the practical API surface: builtin strategies, @composite, assume, stateful machines, @settings, and @example. For the broader theory behind choosing properties, see Implement Property-Based Testing and the complete guide to property-based testing.
When to Use
- Testing pure functions where you can state invariants (e.g., “sorting returns the same elements in order”)
- Finding edge cases in parsers, serializers, and data transformations
- Testing mathematical properties (associativity, commutativity, idempotency)
- Verifying round-trip properties (encode then decode returns the original)
- Fuzzing code that processes untrusted input (JSON parsing, URL parsing)
When NOT to Use
- Testing specific known scenarios — use
@pytest.mark.parametrizewith explicit cases - Testing side effects or stateful interactions — random inputs make order-dependent tests flaky
- Testing UI or integration flows — property-based testing shines on pure logic
- When test runtime matters — Hypothesis runs 100+ cases per test by default
Solution
Setup
pip install hypothesis pytest
Basic property test
from hypothesis import given
from hypothesis import strategies as st
def reverse_string(s: str) -> str:
return s[::-1]
@given(st.text())
def test_reverse_twice_returns_original(s):
assert reverse_string(reverse_string(s)) == s
@given(st.text())
def test_reverse_preserves_length(s):
assert len(reverse_string(s)) == len(s)
@given(st.text())
def test_reverse_first_becomes_last(s):
if s:
assert reverse_string(s)[0] == s[-1]
Integer strategies
@given(st.integers(min_value=0, max_value=100))
def test_square_is_non_negative(n):
assert n * n >= 0
@given(st.integers(), st.integers())
def test_addition_is_commutative(a, b):
assert a + b == b + a
@given(st.integers(min_value=1))
def test_division_then_multiplication(n):
assert (n * 10) // 10 == n
List strategies
@given(st.lists(st.integers(min_value=1, max_value=100), min_size=1))
def test_max_is_in_list(lst):
assert max(lst) in lst
@given(st.lists(st.integers()))
def test_sort_preserves_length(lst):
assert len(sorted(lst)) == len(lst)
@given(st.lists(st.integers()))
def test_sort_is_idempotent(lst):
assert sorted(sorted(lst)) == sorted(lst)
@given(st.lists(st.integers(), min_size=1))
def test_min_le_max(lst):
assert min(lst) <= max(lst)
Dictionary and JSON strategies
import json
@given(st.dictionaries(st.text(min_size=1), st.integers()))
def test_dict_items_roundtrip(d):
assert dict(d.items()) == d
@given(st.from_type(dict))
def test_json_roundtrip(d):
encoded = json.dumps(d)
decoded = json.loads(encoded)
assert decoded == d
Custom strategies with @composite
from hypothesis import strategies as st, composite
@composite
def valid_email(draw):
alphabet = st.characters(categories=("Ll", "Nd"))
local = draw(st.text(min_size=1, max_size=20, alphabet=alphabet))
domain = draw(st.text(min_size=1, max_size=10, alphabet=alphabet))
tld = draw(st.sampled_from(["com", "org", "net", "io"]))
return f"{local}@{domain}.{tld}"
@given(valid_email())
def test_email_validation(email):
assert "@" in email
assert "." in email.split("@")[1]
Using assume to filter inputs
import math
from hypothesis import given, assume
from hypothesis import strategies as st
@given(st.integers())
def test_division(n):
assume(n != 0)
# Float division isn't exact — compare with tolerance, not ==
assert math.isclose(100 / n * n, 100)
@given(st.lists(st.integers()))
def test_sorted_min_is_first(lst):
assume(len(lst) > 0)
assert min(lst) == sorted(lst)[0]
Stateful testing with RuleBasedStateMachine
from hypothesis.stateful import RuleBasedStateMachine, rule, invariant
from hypothesis import strategies as st
class StackMachine(RuleBasedStateMachine):
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
Controlling example count and shrinking
from hypothesis import given, settings
from hypothesis import strategies as st
@given(st.lists(st.integers()))
@settings(max_examples=500, deadline=1000)
def test_with_more_examples(lst):
assert sorted(lst) == sorted(lst, reverse=True)[::-1]
Using @example for specific cases
from hypothesis import given, example
from hypothesis import strategies as st
@given(st.lists(st.integers()))
@example([])
@example([1])
@example([1, 2, 3])
def test_sort_with_specific_cases(lst):
assert sorted(lst) == sorted(sorted(lst))
A runnable version of this test suite lives in the companion repo.
Variants
Testing with st.builds for dataclasses
from dataclasses import dataclass
from hypothesis import given
from hypothesis import strategies as st
@dataclass
class User:
id: int
name: str
email: str
@given(st.builds(User, id=st.integers(min_value=1), name=st.text(min_size=1), email=st.emails()))
def test_user_serialization(user):
data = {"id": user.id, "name": user.name, "email": user.email}
reconstructed = User(**data)
assert reconstructed == user
Testing pandas DataFrames
# Requires: pip install hypothesis[pandas] pandas
import pandas # noqa: F401 — needed by hypothesis.extra.pandas
from hypothesis import given
from hypothesis import strategies as st
from hypothesis.extra.pandas import data_frames, column
@given(data_frames([column("a", st.integers()), column("b", st.text())]))
def test_dataframe_shape(df):
assert len(df.columns) == 2
assert "a" in df.columns
assert "b" in df.columns
How It Works
A strategy describes a data type (st.text(), st.lists(st.integers())) and Hypothesis’s engine generates examples biased toward edge cases — empty strings, zeros, Unicode, huge lists — because it tracks which code branches each input exercises. On failure, the shrinker systematically simplifies the input (smaller numbers, shorter strings, fewer elements) until further simplification stops failing, which is why the reported counterexample is almost always minimal.
assume() is the input filter: it discards generated values that can’t satisfy your preconditions, so the generator keeps drawing until it finds valid ones. @settings tunes the run — max_examples controls how many cases run, deadline caps per-example time. And RuleBasedStateMachine swaps single inputs for sequences of operations, checking @invariants after every step — the tool for APIs with state.
Best Practices
Start with simple strategies (st.text(), st.integers()) and narrow with min_value/max_size as needed — a strategy that generates impossible data wastes examples on assume rejections.
Use assume() for preconditions instead of if guards inside the test body. A guard silently passes the example; assume tells the engine to discard it and draw a better one.
Pin known edge cases with @example — the empty list, the boundary value, the exact input that once crashed production. They run first, and they document intent better than a comment.
Keep property tests pure. No network, no database, no wall-clock dependence — generated inputs plus side effects produce flakiness that shrinking can’t explain away.
Use st.from_type(MyClass) or st.builds to generate domain objects from type hints instead of hand-rolling composites for every model. For custom types, st.register_type_strategy wires them into from_type globally.
Common Mistakes
Asserting exact equality on floats. 100 / n * n == 100 fails at n=3 — IEEE 754 makes the round trip 99.9999…. Use math.isclose or a tolerance, or keep the property on integers.
One test, many properties. When a @given checks five invariants and fails, the output tells you almost nothing. One property per test keeps failures diagnosable.
Filtering with if instead of assume. Guards skip the assertion but still count the example; too many and Hypothesis gives up with UnsatisfiedAssumption.
Ignoring the shrunk counterexample. The minimal failing input Hypothesis prints is the bug report — copy it into an @example so the regression stays pinned forever.
Troubleshooting
DeadlineExceededon CI: generated inputs hit a slow path. Raisedeadlinein@settings, shrink the strategy domain, or profile the worst case — it’s often a real performance bug.UnsatisfiedAssumption/FailedHealthCheck: yourassumefilters out too much. Generate valid data directly in the strategy (e.g.,min_size=1) instead of rejecting it afterwards.- Same failure every run: that’s the point — Hypothesis replays the seed it prints. Add
@examplewith the shrunk input, fix the bug, and the test stays pinned. - Tests are slow: drop
max_examplesin CI (@settings(max_examples=50)) and keep the high count in a nightly profile viaregister_profile.
Further Reading
- Hypothesis documentation — strategies, settings, stateful testing
- Hypothesis quickstart — official walkthrough of this exact workflow
Frequently Asked Questions
How does Hypothesis find edge cases?
Its engine tracks which branches of your code each generated input exercises and biases generation toward unexplored branches. That's how it surfaces empty strings, negative numbers, and Unicode you'd never write by hand.
What is shrinking?
When a test fails, Hypothesis simplifies the input — smaller numbers, shorter strings, fewer elements — until further simplification stops failing. [3, -1, 0, 42, 17] might shrink to [-1]: the minimal reproducer.
How do I reproduce a failing Hypothesis test?
Hypothesis prints the failing input after shrinking. Pin it with @example:
@example(s="\x00")
@given(st.text())
def test_with_reproducer(s):
...
Can I use Hypothesis with Django or Flask?
Yes, but only for pure logic — model methods, utility functions, validators. Don't use it for views that hit the database; use @pytest.mark.django_db with explicit cases there.
How do I limit test runtime?
@settings(max_examples=50, deadline=500) caps the generated cases and sets a per-example timeout in milliseconds. For suites, settings.register_profile("ci", max_examples=50) keeps local runs thorough and CI fast.
Related Resources
Pytest Fixtures and Parametrize
How to use pytest fixtures and @pytest.mark.parametrize to write data-driven tests with reusable setup logic across Python projects.
RecipeMeasure and Enforce Python Test Coverage with pytest-cov
Measure and enforce coverage with pytest-cov: branch coverage, HTML reports, exclusions, CI integration.
RecipeMock External APIs with responses Library
How to mock HTTP API calls in Python tests using the responses library, including status codes, headers, JSON bodies, and error simulation.
GuideProperty-Based Testing Guide
Property-based testing with Hypothesis (Python) and fast-check (TypeScript): generate cases, catch edge cases, and shrink failures to minimal bugs.
RecipeGenerate Test Data (Faker + Factories)
How to generate realistic, deterministic test data with Faker, factory-boy, and type-aware generators for reliable test suites in Python, JavaScript, and Java.
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.