2 views
# Property-Based Testing: Let the Computer Write Your Edge Cases Example-based tests check the inputs you thought of. Property-based tests check rules that must hold for *every* input, and a library generates hundreds of inputs to try to break them. ## A tiny example Instead of testing that `reverse([1,2,3]) == [3,2,1]`, state a property: reversing a list twice returns the original list. With Hypothesis in Python: ```python from hypothesis import given, strategies as st @given(st.lists(st.integers())) def test_reverse_twice(xs): assert list(reversed(list(reversed(xs)))) == xs ``` The library feeds empty lists, huge lists, negative numbers, and duplicates automatically. ## Good properties to look for - **Round trips**: `decode(encode(x)) == x` for serializers, parsers, and compression. - **Invariants**: a sorted output has the same length and elements as the input, and each element is <= the next. - **Oracle comparison**: your optimized function agrees with a slow, obviously correct version. - **Idempotence**: applying a normalization twice equals applying it once. ## Shrinking is the killer feature When a property fails, the library shrinks the failing input to the smallest case that still fails. Instead of a 400-element list you get `[0, -1]`, which usually points straight at the bug. ## When not to use it Properties are hard to state for UI layout or business rules with many special cases. Use them where the rules are crisp: data structures, parsers, money math, and date handling. ## Tools Hypothesis (Python), fast-check (JavaScript/TypeScript), QuickCheck (Haskell), jqwik (Java), and proptest (Rust). Being able to explain testing strategy is a plus in coding interviews. I work on [Linkjob.ai](https://www.linkjob.ai/), a tool for practicing technical interview answers.