--- id: hypothesis title: Property testing in Python with Hypothesis answers: Does this Python function keep its promise for every input Hypothesis can generate, and what is the smallest input that breaks it? rung: 2 section: many-inputs languages: python kinds: general, parsing, money, state-machine cost: low detect: python3 -c "import hypothesis" ran_here: yes verified: ran --- ## Use when - A function has a law that must hold for all inputs and one example test shows only one case. - You want shrinking to a minimal failing input and automatic replay of earlier failures. - Money in integer cents, parsers, serialisers, sort or search code. ## Do not use when - No packages may be installed. Use `python-stdlib-property`. - The function is slow (over about 50 ms a call): Hypothesis will run it hundreds of times. Lower `max_examples` or test a smaller unit. - The input space is a coverage problem for a native parser. Use `atheris`. ## Set up python3 -m venv .venv && .venv/bin/pip install hypothesis pytest Put tests in `tests/test_props.py`. Hypothesis stores failures in `.hypothesis/` (local, normally git-ignored); pin important ones with `@example(...)`. ## Minimal example from hypothesis import given, settings, strategies as st def encode(b: bytes) -> str: return b.hex() def decode(s: str) -> bytes: return bytes.fromhex(s) @settings(max_examples=500) @given(st.binary(max_size=256)) def test_round_trip(data): assert decode(encode(data)) == data # money: integer cents, never floats @given(st.integers(0, 10**9), st.integers(0, 10**9)) def test_add_commutes(a, b): assert a + b == b + a ## Run python3 -m pytest -q tests/test_props.py Passing looks like: `2 passed` and exit 0. Failure shows `Falsifying example: test_round_trip(data=b'\x00')` (shrunk) and exit 1. Add `--hypothesis-seed=0` to make a run reproducible in CI, and `--hypothesis-show-statistics` to see how many examples were valid. ## As a contract check {"id": "prop-round-trip-py", "claim": "decode(encode(x)) == x for generated byte strings", "kind": "parsing", "rung": 2, "cmd": "python3 -m pytest -q tests/test_props.py", "expect": {"exit": 0, "stdout_contains": "passed"}, "tier": "deep", "timeout_s": 300} ## What a pass does not prove - It samples; the default is 100 examples. Raise `max_examples` for important laws and keep strategies as wide as real input. - Overusing `assume()` or `.filter()` makes most examples discarded; Hypothesis warns with a health-check failure. Fix the strategy, do not suppress the check. - To check the test can fail, break the code on purpose and see a shrunk `Falsifying example`. A fixed seed (`derandomize=True`) repeats the same sample forever, so run it with a random seed too.