| created | "2025-12-16T00:00:00.000Z" |
| modified | "2025-12-16T00:00:00.000Z" |
| reviewed | "2025-12-16T00:00:00.000Z" |
| name | hypothesis-testing |
| description | Property-based testing with Hypothesis for discovering edge cases and validating invariants.
Use when implementing comprehensive test coverage, testing complex logic with many inputs,
or validating mathematical properties and invariants across input domains.
Triggered by: hypothesis, property-based testing, @given, strategies, generative testing.
|
Hypothesis Property-Based Testing
Hypothesis is a powerful property-based testing library that automatically generates test cases to find edge cases and validate properties of your code.
Core Concept
Traditional example-based testing:
def test_addition():
assert add(2, 3) == 5
assert add(0, 0) == 0
assert add(-1, 1) == 0
Property-based testing with Hypothesis:
from hypothesis import given
import hypothesis.strategies as st
@given(st.integers(), st.integers())
def test_addition_commutative(a, b):
"""Addition is commutative for ALL integers."""
assert add(a, b) == add(b, a)
Hypothesis generates hundreds of test cases automatically, including edge cases you might not think of.
Installation
uv add --dev hypothesis pytest
uv add --dev hypothesis[numpy]
uv add --dev hypothesis[pandas]
uv add --dev hypothesis[django]
Configuration
pyproject.toml Configuration
[tool.pytest.ini_options]
addopts = [
"--hypothesis-show-statistics",
"--hypothesis-seed=0",
]
[tool.hypothesis]
max_examples = 200
deadline = 1000
verbosity = "normal"
derandomize = false
database = ".hypothesis/examples"
[tool.hypothesis.profiles.dev]
max_examples = 50
deadline = 1000
verbosity = "normal"
[tool.hypothesis.profiles.ci]
max_examples = 500
deadline = 5000
verbosity = "verbose"
[tool.hypothesis.profiles.debug]
max_examples = 10
deadline = null
verbosity = "debug"
Activate Profile
from hypothesis import settings, Verbosity
import os
if os.getenv("CI"):
settings.load_profile("ci")
else:
settings.load_profile("dev")
settings.register_profile("custom", max_examples=100, deadline=500)
settings.load_profile("custom")
Basic Usage
Simple Property Tests
from hypothesis import given, example
import hypothesis.strategies as st
@given(st.integers())
def test_absolute_value_non_negative(x):
"""abs(x) is always non-negative."""
assert abs(x) >= 0
@given(st.integers(), st.integers())
def test_addition_associative(a, b, c):
"""Addition is associative: (a + b) + c == a + (b + c)."""
assert (a + b) + c == a + (b + c)
@given(st.text())
def test_string_length(s):
"""Length of reversed string equals original."""
assert len(s[::-1]) == len(s)
@given(st.text(), st.text())
def test_string_concatenation(s1, s2):
"""String concatenation length is sum of lengths."""
result = s1 + s2
assert len(result) == len(s1) + len(s2)
@given(st.integers())
():
process(x)
Testing Functions
from hypothesis import given, assume
import hypothesis.strategies as st
def safe_divide(a: float, b: float) -> float:
"""Divide a by b, avoiding division by zero."""
if b == 0:
raise ValueError("Division by zero")
return a / b
@given(st.floats(allow_nan=False, allow_infinity=False),
st.floats(allow_nan=False, allow_infinity=False))
def test_safe_divide(a, b):
"""Test safe_divide with all valid floats."""
assume(b != 0)
result = safe_divide(a, b)
assert isinstance(result, float)
assert result * b == pytest.approx(a)
@given(st.floats())
def test_divide_by_zero_raises(a):
"""Division by zero raises ValueError."""
with pytest.raises(ValueError, match="Division by zero"):
safe_divide(a, 0)
Strategies
Built-in Strategies
import hypothesis.strategies as st
st.none()
st.booleans()
st.integers()
st.integers(min_value=0, max_value=100)
st.floats()
st.floats(min_value=0.0, max_value=1.0)
st.decimals()
st.fractions()
st.complex_numbers()
st.text()
st.text(alphabet="abc")
st.text(min_size=1, max_size=10)
st.binary()
st.characters()
st.lists(st.integers())
st.lists(st.text(), min_size=1, max_size=10)
st.tuples(st.integers(), st.text())
st.sets(st.integers())
st.frozensets(st.text())
st.dictionaries(keys=st.text(), values=st.integers())
st.uuids()
st.datetimes()
st.dates()
st.times()
st.timedeltas()
st.emails()
st.ip_addresses()
st.urls()
Composite Strategies
from hypothesis import given
from hypothesis.strategies import composite
import hypothesis.strategies as st
@composite
def users(draw):
"""Generate user objects."""
return {
"id": draw(st.integers(min_value=1)),
"name": draw(st.text(min_size=1, max_size=50)),
"email": draw(st.emails()),
"age": draw(st.integers(min_value=0, max_value=120)),
"active": draw(st.booleans())
}
@given(users())
def test_user_validation(user):
"""Test user validation with generated users."""
assert user["id"] > 0
assert len(user["name"]) > 0
assert "@" in user["email"]
assert 0 <= user["age"] <= 120
@composite
def http_requests(draw):
"""Generate HTTP request objects."""
method = draw(st.sampled_from([, , , ]))
path = draw(st.text(alphabet=, min_size=))
headers = draw(st.dictionaries(
keys=st.text(alphabet=, min_size=),
values=st.text()
))
body =
method [, ]:
body = draw(st.one_of(st.none(), st.text(), st.binary()))
{
: method,
: ,
: headers,
: body
}
():
response = handle_request(request)
response.status_code [, , , , ]
Data Classes and Models
from dataclasses import dataclass
from hypothesis import given
from hypothesis.strategies import builds
import hypothesis.strategies as st
@dataclass
class Point:
x: float
y: float
@given(builds(Point, x=st.floats(), y=st.floats()))
def test_point_distance(point):
"""Test distance calculation for points."""
origin = Point(0.0, 0.0)
distance = calculate_distance(origin, point)
assert distance >= 0
@dataclass
class User:
id: int
name: str
email: str
age: int
def valid_users():
return builds(
User,
id=st.integers(min_value=1),
name=st.text(min_size=1, max_size=100),
email=st.emails(),
age=st.integers(min_value=0, max_value=120)
)
@given(valid_users())
def ():
json_data = user.to_json()
restored = User.from_json(json_data)
restored == user
Strategy Combinators
import hypothesis.strategies as st
st.one_of(st.none(), st.integers(), st.text())
st.sampled_from(["admin", "user", "guest"])
st.just(42)
st.lists(
st.integers(min_value=0),
min_size=1,
max_size=10,
unique=True
)
st.dictionaries(
keys=st.text(min_size=1),
values=st.integers(),
min_size=1,
max_size=5
)
st.tuples(st.integers(), st.text(), st.booleans())
st.fixed_dictionaries({
"id": st.integers(min_value=1),
"name": st.text(),
"optional": st.one_of(st.none(), st.text())
})
json_strategy = st.recursive(
st.one_of(st.none(), st.booleans(), st.floats(), st.text()),
lambda children: st.lists(children) | st.dictionaries(st.text(), children),
max_leaves=10
)
Advanced Patterns
Stateful Testing
from hypothesis.stateful import RuleBasedStateMachine, rule, invariant
import hypothesis.strategies as st
class ShoppingCartMachine(RuleBasedStateMachine):
"""Test shopping cart with stateful operations."""
def __init__(self):
super().__init__()
self.cart = ShoppingCart()
self.items_added = []
@rule(item=st.text(min_size=1), quantity=st.integers(min_value=1, max_value=10))
def add_item(self, item, quantity):
"""Add item to cart."""
self.cart.add(item, quantity)
self.items_added.append((item, quantity))
@rule(item=st.text())
def remove_item(self, item):
"""Remove item from cart."""
try:
self.cart.remove(item)
self.items_added = [(i, q) for i, q in self.items_added if i != item]
except ValueError:
pass
@rule()
def ():
.cart.clear()
.items_added = []
():
expected_items = {item: qty item, qty .items_added}
actual_items = .cart.get_items()
expected_items == actual_items
():
.cart.get_total() >=
TestShoppingCart = ShoppingCartMachine.TestCase
Shrinking and Example Database
from hypothesis import given, settings, example
import hypothesis.strategies as st
@given(st.lists(st.integers()))
def test_list_processing(items):
"""Test list processing - Hypothesis will shrink failing examples."""
result = process_list(items)
assert result is not None
@given(st.lists(st.integers()))
@settings(max_examples=100, phases=["generate"])
def test_without_shrinking(items):
"""Test without shrinking for faster debugging."""
assert process_list(items) is not None
Targeted Property Testing
from hypothesis import given, target
import hypothesis.strategies as st
@given(st.lists(st.integers()))
def test_sort_with_targeting(items):
"""Guide Hypothesis toward larger lists."""
target(float(len(items)))
sorted_items = sorted(items)
assert all(sorted_items[i] <= sorted_items[i+1]
for i in range(len(sorted_items) - 1))
@given(st.floats(min_value=0.0, max_value=1.0))
def test_with_edge_targeting(probability):
"""Guide Hypothesis toward edge values (0.0 and 1.0)."""
target(abs(probability - 0.5))
result = simulate_with_probability(probability)
assert 0 <= result <= 1
Hypothesis with Async Code
import pytest
from hypothesis import given
import hypothesis.strategies as st
@pytest.mark.asyncio
@given(st.integers())
async def test_async_function(value):
"""Test async function with property-based testing."""
result = await async_process(value)
assert result is not None
@pytest.mark.asyncio
@given(st.lists(st.integers(), min_size=1))
async def test_async_batch_processing(items):
"""Test async batch processing."""
results = await process_batch(items)
assert len(results) == len(items)
assert all(r is not None for r in results)
When to Use Hypothesis vs Example-Based Tests
Use Hypothesis (Property-Based) When:
-
Testing mathematical properties
@given(st.integers(), st.integers())
def test_addition_commutative(a, b):
assert a + b == b + a
-
Testing invariants across many inputs
@given(st.lists(st.integers()))
def test_sort_idempotent(items):
sorted_once = sorted(items)
sorted_twice = sorted(sorted_once)
assert sorted_once == sorted_twice
-
Finding edge cases
@given(st.text())
def test_parse_input(text):
result = parse(text)
assert result is not None
-
Testing serialization round-trips
@given(st.from_type(MyData))
def test_serialization(data):
json_str = data.to_json()
restored = MyData.from_json(json_str)
assert restored == data
-
Testing APIs with many parameters
@given()
():
response = api_call(name, count, flag, option)
response.status [, ]
Use Example-Based Tests When:
-
Testing specific known edge cases
def test_empty_list():
assert process([]) == []
def test_single_item():
assert process([1]) == [1]
-
Testing exact business logic
def test_discount_calculation():
assert calculate_discount(100, 0.1) == 10
assert calculate_discount(50, 0.2) == 10
-
Testing error messages
def test_validation_error_message():
with pytest.raises(ValueError, match="Email must contain @"):
validate_email("invalid")
-
Testing integration with external systems
def test_api_integration():
response = api.get("/users/123")
assert response["name"] == "Test User"
-
Testing UI behavior
def test_button_click():
button.click()
assert button.text == "Clicked"
Hybrid Approach (Best Practice)
from hypothesis import given, example
import hypothesis.strategies as st
@given(st.integers())
@example(0)
@example(-1)
@example(2**31 - 1)
def test_absolute_value(x):
"""Test with both generated and explicit examples."""
result = abs(x)
assert result >= 0
assert result == abs(-x)
@given(st.lists(st.integers()))
@example([1, 2, 3])
@example([])
@example([42] * 1000)
def test_list_processing(items):
"""Test general property + specific known cases."""
result = process_list(items)
(result) == (items)
Best Practices
1. Start with Simple Properties
@given(st.integers())
def test_increment(x):
assert x + 1 > x
@given(st.integers(), st.integers())
def test_addition_properties(a, b):
assert a + b == b + a
assert (a + 1) + b == a + (1 + b)
2. Use assume() Sparingly
@given(st.integers(), st.integers())
def test_slow(a, b):
assume(a > 0)
assume(b > 0)
assume(a < 100)
assume(b < 100)
assert a + b < 200
@given(st.integers(min_value=1, max_value=99),
st.integers(min_value=1, max_value=99))
def test_fast(a, b):
assert a + b < 200
3. Test Invariants, Not Implementation
@given(st.lists(st.integers()))
def test_sort_implementation(items):
result = my_sort(items)
assert result.pivot_index == len(items) // 2
@given(st.lists(st.integers()))
def test_sort_properties(items):
result = my_sort(items)
assert len(result) == len(items)
assert sorted(result) == result
assert set(result) == set(items)
4. Use @example() for Regression Tests
@given(st.lists(st.integers()))
@example([])
@example([1, 1, 1])
@example([-2**31])
def test_with_regressions(items):
"""Property test + regression tests."""
result = process(items)
assert result is not None
5. Configure for Different Environments
from hypothesis import given, settings, Verbosity
@given(st.lists(st.integers()))
@settings(max_examples=50, deadline=500)
def test_dev(items):
assert process(items) is not None
@given(st.lists(st.integers()))
@settings(max_examples=500, deadline=5000, verbosity=Verbosity.verbose)
def test_ci(items):
assert process(items) is not None
Common Patterns
Testing Encoding/Decoding
@given(st.from_type(MyData))
def test_json_roundtrip(data):
"""JSON encoding/decoding preserves data."""
json_str = data.to_json()
restored = MyData.from_json(json_str)
assert restored == data
@given(st.binary())
def test_base64_roundtrip(data):
"""Base64 encoding/decoding preserves data."""
encoded = base64.b64encode(data)
decoded = base64.b64decode(encoded)
assert decoded == data
Testing Parsers
@given(st.text())
def test_parser_does_not_crash(text):
"""Parser handles any input without crashing."""
try:
result = parse(text)
assert isinstance(result, ParsedData)
except ParseError:
pass
Testing Database Operations
@given(st.lists(valid_users(), max_size=10))
def test_batch_insert(users):
"""Batch insert preserves all users."""
db.batch_insert(users)
for user in users:
retrieved = db.get_user(user.id)
assert retrieved == user
@given(valid_users())
def test_update_preserves_id(user):
"""Updating user preserves ID."""
db.save(user)
original_id = user.id
user.name = "Updated Name"
db.save(user)
assert user.id == original_id
CI Integration
name: Tests
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Install uv
uses: astral-sh/setup-uv@v2
- name: Set up Python
run: uv python install 3.12
- name: Install dependencies
run: uv sync --all-extras --dev
- name: Run hypothesis tests (CI profile)
run: |
uv run pytest \
--hypothesis-show-statistics \
--hypothesis-profile=ci \
--hypothesis-seed=${{ github.run_number }}
- name: Upload hypothesis database
uses:
Debugging Failing Tests
from hypothesis import given, settings, Verbosity, Phase
import hypothesis.strategies as st
@given(st.lists(st.integers()))
@settings(
verbosity=Verbosity.debug,
max_examples=10,
phases=[Phase.generate],
print_blob=True
)
def test_debug(items):
"""Debug failing test with full output."""
result = buggy_function(items)
assert result is not None
@given(st.lists(st.integers()))
@example([1, 2, -2147483648])
def test_reproduce_failure(items):
"""Reproduce and fix specific failure."""
result = process(items)
assert result is not None
Resources
Summary
Hypothesis provides property-based testing for Python:
- @given decorator: Generate test inputs automatically
- Strategies: Built-in and custom data generators
- Shrinking: Automatically minimize failing examples
- Stateful testing: Test complex state machines
- Example database: Store and replay failing cases
- Use for: Properties, invariants, round-trips, edge case discovery
- Combine with: Example-based tests for comprehensive coverage
- CI integration: Run with more examples in CI environments