Skip to content

Lesson 5 of 9 · 25m

Property-Based Testing with Hypothesis

Generate hostile inputs automatically, state invariants instead of examples, and shrink failures into reproducible regression tests.

Example-based tests answer: "does the code work for inputs I thought of?" Property-based testing answers: "does the invariant hold for inputs I did not think of?" That difference matters because production users are much more creative than test authors.

Start with invariants, not randomness

A property is a rule that should always hold. For a money parser:

from hypothesis import given
from hypothesis import strategies as st

@given(st.integers(min_value=0, max_value=1_000_000))
def test_cents_round_trip(cents):
    assert parse_money(format_money(cents)) == cents

You are not testing randomness. You are testing that formatting and parsing are inverse operations across a huge input space. Good properties include round trips, ordering, idempotence, length preservation, and commutativity.

Hypothesis shrinks the counterexample

When a property fails, Hypothesis searches for a smaller failing input. You may see:

Falsifying example: test_slug_never_empty(title=' ')

That single minimized case is gold. Copy it into a normal regression test after fixing the bug:

def test_slug_for_single_space_is_not_empty():
    assert slugify(" ") != ""

The generated test explores; the example test preserves the lesson.

Strategies are executable input models

Do not generate arbitrary text when the input has structure. Model the structure:

emails = st.builds(
    lambda local, domain: f"{local}@{domain}",
    local=st.text(alphabet="abcdefghijklmnopqrstuvwxyz0123456789", min_size=1, max_size=20),
    domain=st.sampled_from(["example.com", "mail.example.org"]),
)

Better strategies produce more interesting failures. If all inputs are valid, you never test rejection paths. If all inputs are noise, you mostly test the parser's garbage handling and miss realistic edge cases.

Useful properties in business code

  • Serialization: deserialize(serialize(x)) == x.
  • Sorting: output is ordered and contains the same elements.
  • State machines: illegal transitions never mutate state.
  • Idempotency: applying an operation twice equals applying it once.
  • Sanitizers: output never contains forbidden control characters. Do not force property tests onto code with no clear invariant. CRUD glue sometimes needs integration coverage more than clever generation.

Field notes

  • Install with pip install hypothesis; pytest discovers @given tests without special plugins.
  • Use @settings(max_examples=50, deadline=None) sparingly for slow cases, and explain why in a comment.
  • Hypothesis persists failing examples in .hypothesis/; do not treat that cache as a substitute for regression tests.
  • Never weaken the property just to make generation easier — write a better strategy.
  • Deterministic seeds in CI are useful for reproducing rare flakes: record the seed printed in failure output.

Was this lesson helpful?

Sign in to rate