|
| 1 | +--- |
| 2 | +description: 'Best practices for property-based testing in Python using Hypothesis framework' |
| 3 | +applyTo: '**/test_*.py, **/*_test.py, **/tests/**/*.py' |
| 4 | +--- |
| 5 | + |
| 6 | +# Python Property Testing with Hypothesis |
| 7 | + |
| 8 | +Use property-based testing to discover edge cases automatically by testing universal properties instead of specific examples. |
| 9 | + |
| 10 | +## Installation |
| 11 | + |
| 12 | +```bash |
| 13 | +pip install "hypothesis[cli]" |
| 14 | +``` |
| 15 | + |
| 16 | +## Configuration |
| 17 | + |
| 18 | +```python |
| 19 | +# conftest.py |
| 20 | +from hypothesis import settings |
| 21 | +import os |
| 22 | + |
| 23 | +settings.register_profile("dev", max_examples=100) |
| 24 | +settings.register_profile("ci", max_examples=1000) |
| 25 | +settings.load_profile(os.getenv("HYPOTHESIS_PROFILE", "dev")) |
| 26 | +``` |
| 27 | + |
| 28 | +```ini |
| 29 | +# pytest.ini |
| 30 | +[pytest] |
| 31 | +markers = property: Property-based tests |
| 32 | +hypothesis-show-statistics = true |
| 33 | +``` |
| 34 | + |
| 35 | +## Common Property Patterns |
| 36 | + |
| 37 | +```python |
| 38 | +from hypothesis import given, strategies as st, example |
| 39 | + |
| 40 | +# Idempotency: f(f(x)) == f(x) |
| 41 | +@given(st.lists(st.integers())) |
| 42 | +def test_reverse_twice(xs): |
| 43 | + assert reverse(reverse(xs)) == xs |
| 44 | + |
| 45 | +# Round-trip: decode(encode(x)) == x |
| 46 | +@given(st.dictionaries(st.text(), st.integers())) |
| 47 | +def test_json_roundtrip(data): |
| 48 | + assert json.loads(json.dumps(data)) == data |
| 49 | + |
| 50 | +# Invariant: property always holds |
| 51 | +@given(st.lists(st.integers(), min_size=1)) |
| 52 | +def test_max_in_list(xs): |
| 53 | + assert max(xs) in xs |
| 54 | + |
| 55 | +# Oracle: compare with known implementation |
| 56 | +@given(st.lists(st.integers())) |
| 57 | +def test_sort_matches_builtin(xs): |
| 58 | + assert custom_sort(xs) == sorted(xs) |
| 59 | + |
| 60 | +# Commutativity: f(a, b) == f(b, a) |
| 61 | +@given(st.integers(), st.integers()) |
| 62 | +def test_addition_commutative(a, b): |
| 63 | + assert a + b == b + a |
| 64 | +``` |
| 65 | + |
| 66 | +## Strategies |
| 67 | + |
| 68 | +```python |
| 69 | +# Built-in strategies |
| 70 | +st.integers(min_value=0, max_value=100) |
| 71 | +st.text(min_size=1, max_size=100) |
| 72 | +st.lists(st.integers(), max_size=50) |
| 73 | +st.dictionaries(st.text(), st.integers()) |
| 74 | +st.dates(min_value=date(2000, 1, 1)) |
| 75 | +st.emails() |
| 76 | + |
| 77 | +# Composite strategies |
| 78 | +from hypothesis.strategies import composite |
| 79 | + |
| 80 | +@composite |
| 81 | +def user_strategy(draw): |
| 82 | + return User( |
| 83 | + username=draw(st.text(min_size=3)), |
| 84 | + age=draw(st.integers(min_value=18, max_value=120)), |
| 85 | + email=draw(st.emails()) |
| 86 | + ) |
| 87 | +``` |
| 88 | + |
| 89 | +## Stateful Testing |
| 90 | + |
| 91 | +```python |
| 92 | +from hypothesis.stateful import RuleBasedStateMachine, rule, invariant |
| 93 | + |
| 94 | +class StackMachine(RuleBasedStateMachine): |
| 95 | + def __init__(self): |
| 96 | + super().__init__() |
| 97 | + self.stack = [] |
| 98 | + |
| 99 | + @rule(value=st.integers()) |
| 100 | + def push(self, value): |
| 101 | + self.stack.append(value) |
| 102 | + |
| 103 | + @rule() |
| 104 | + def pop(self): |
| 105 | + if self.stack: |
| 106 | + self.stack.pop() |
| 107 | + |
| 108 | + @invariant() |
| 109 | + def size_non_negative(self): |
| 110 | + assert len(self.stack) >= 0 |
| 111 | + |
| 112 | +TestStack = StackMachine.TestCase |
| 113 | +``` |
| 114 | + |
| 115 | +## Migration from Example Tests |
| 116 | + |
| 117 | +```python |
| 118 | +# Keep critical edge cases |
| 119 | +@given(st.lists(st.integers())) |
| 120 | +@example([]) # Empty |
| 121 | +@example([1]) # Single |
| 122 | +@example([1, 1, 1]) # Duplicates |
| 123 | +def test_sort(xs): |
| 124 | + result = sort(xs) |
| 125 | + assert sorted(result) == sorted(xs) |
| 126 | +``` |
| 127 | + |
| 128 | +## Debugging |
| 129 | + |
| 130 | +```python |
| 131 | +from hypothesis import seed, note |
| 132 | + |
| 133 | +# Reproduce failure |
| 134 | +@seed(1234567890) # From failure output |
| 135 | +@given(st.integers()) |
| 136 | +def test_reproduce(x): |
| 137 | + note(f"Input: {x}") |
| 138 | + assert process(x) is not None |
| 139 | +``` |
| 140 | + |
| 141 | +## Settings |
| 142 | + |
| 143 | +```python |
| 144 | +from hypothesis import settings |
| 145 | +from datetime import timedelta |
| 146 | + |
| 147 | +@settings( |
| 148 | + max_examples=50, |
| 149 | + deadline=timedelta(milliseconds=100) |
| 150 | +) |
| 151 | +@given(st.lists(st.integers())) |
| 152 | +def test_with_settings(xs): |
| 153 | + assert process(xs) is not None |
| 154 | +``` |
| 155 | + |
| 156 | +## Best Practices |
| 157 | + |
| 158 | +**DO:** |
| 159 | +- Test universal properties, not specific examples |
| 160 | +- Use strategy constraints over `assume()` |
| 161 | +- Keep critical edge cases with `@example()` |
| 162 | +- Run CI with `max_examples=1000` |
| 163 | + |
| 164 | +**AVOID:** |
| 165 | +- Test implementation details |
| 166 | +- Use `random.random()` (breaks reproducibility) |
| 167 | +- Over-use `assume()` (prefer constraints) |
| 168 | + |
| 169 | +## Common Patterns |
| 170 | + |
| 171 | +```python |
| 172 | +# Prefer strategy constraints |
| 173 | +@given(st.integers().map(lambda x: x * 2)) |
| 174 | +def test_even(n): |
| 175 | + assert n % 2 == 0 |
| 176 | + |
| 177 | +# Avoid heavy filtering |
| 178 | +@given(st.integers()) |
| 179 | +def test_even_bad(n): |
| 180 | + assume(n % 2 == 0) # Not recommended |
| 181 | +``` |
| 182 | + |
| 183 | +## Resources |
| 184 | + |
| 185 | +- [Hypothesis Documentation](https://hypothesis.readthedocs.io/) |
| 186 | +- [Property-Based Testing Guide](https://fsharpforfunandprofit.com/posts/property-based-testing/) |
0 commit comments