Express Invariants as Property-Based Tests
Core idea
A property is a condition expected to hold across a defined input domain. Instead of checking only chosen examples, generate multiple inputs and verify the invariant. A bounded exhaustive loop is a useful standard-library demonstration, not a complete property-testing engine. Hypothesis uses strategies to generate cases and can shrink a failing example.
from itertools import productfrom collections import Counterdef arrange(xs): return sorted(xs)checked = 0for xs in product(range(3), repeat=3): ys = arrange(xs) assert all(a <= b for a,b in zip(ys,ys[1:])) assert Counter(xs) == Counter(ys) checked += 1print(checked)Ordering alone could accept an empty output; preserving multiplicity closes that gap for the tested domain.
Expected output:
27Find a reproducible counterexample
from itertools import productfrom collections import Counterdef wrong(xs): return sorted(set(xs))for xs in product(range(2), repeat=2): if Counter(xs) != Counter(wrong(xs)): print(xs) breakThe first enumerated counterexample shows duplicates were discarded; it is not a claim about Hypothesis shrinking.
Expected output:
(0, 0)Common mistake
A weak property can pass a broken implementation. Document the domain and combine invariants with explicit boundary cases. The loops use assert for tests, not production validation; run without -O.
Practice
In an environment with Hypothesis installed, use @given(st.lists(st.integers())) from hypothesis and hypothesis.strategies (imported as st) to check sorted order and Counter equality. Record the version, any failing example and reproduction instructions. Try empty and repeated lists explicitly. Hypothesis execution is not locally verified here.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Property-based tests
Check your understanding of property-based tests.
What is printed?
from itertools import productprint(len(list(product(range(2),repeat=3))))What is printed?
from collections import Counterprint(Counter([1,1,2])==Counter([1,2]))What is a property?
What does shrinking attempt?