SyntaxStudy
Sign Up
Python Property-Based Testing with Hypothesis
Python Advanced 5 min read

Property-Based Testing with Hypothesis

Hypothesis

Hypothesis generates thousands of random inputs to find edge cases your example-based tests miss.

Example
from hypothesis import given, strategies as st

@given(st.integers(), st.integers())
def test_addition_commutative(a, b):
    assert a + b == b + a

@given(st.lists(st.integers()))
def test_sort_is_idempotent(lst):
    assert sorted(sorted(lst)) == sorted(lst)

@given(st.text(min_size=1))
def test_upper_lower_roundtrip(s):
    assert s.upper().lower() == s.lower()
Pro Tip

Hypothesis remembers failing examples in its database and replays them on every subsequent run.