Unit 2 of 8 · about 4 hours · implement
Property, metamorphic and differential testing with shrinking
Examples check the inputs you thought of. Properties check the inputs you did not, and shrinking hands you the smallest case that breaks your claim.
You'll be able to
- State a property, metamorphic relation or differential oracle for a small function and encode it with Hypothesis strategies.
- Read a shrunk counterexample and turn it into a minimal permanent regression case.
- Replay persisted failures from the example database and pin them with
@exampleinstead of opaque blobs.
Covers
Read
In this order, only the parts listed
0 of 4 done
- Hypothesis quickstartHypothesis documentation
Install Hypothesis through Write your first test; Running in a test suite; the
max_examplesdefault of 100; Filtering inside a test - Hypothesis strategies referenceHypothesis documentation
Primitives; Numeric (
integers); Strings (text); Collections (lists); Combinators - Hypothesis test settingsHypothesis documentation
Changing the number of test cases; Changing settings across your test suite with profiles
- Replaying failed Hypothesis testsHypothesis documentation
The Hypothesis database; Using
@exampleto run a specific input; Replaying test cases with@reproduce_failure; Prefer@exampleover the database for correctness
Focus on
- A property relates many inputs to expected structure: ordered output, round trips, idempotence. A metamorphic relation compares outputs across related inputs; a differential test compares two implementations on the same inputs.
- Given the same drawn data, the test must behave the same way. Randomness, clocks and global state inside the test break shrinking and replay, and Hypothesis reports the test as flaky.
- Shrinking minimizes the failing case automatically. The report shows the minimal input, not the first one found.
- The database replays past failures before generating new ones. Pin durable cases with
@example; a@reproduce_failureblob is opaque and version-fragile, so convert it promptly.
Common mistakes · 3
- Skipping unwanted inputs with a plain
ifandreturninside the test. Those examples count as passes, so coverage shrinks silently; constrain the strategy or callassume, and expect thefilter_too_muchhealth check when most inputs are rejected. - Keeping a
@reproduce_failureblob as the regression test. It is opaque and may stop replaying after upgrades, so rewrite it as@example. - Calling a nondeterministic property suite green. A flaky failure poisons the database, so fix determinism first.
Try it yourself
Closed-book, before checking anything
@given(st.integers(min_value=0)) test asserting with max_examples=200: it fails and reports , the minimal failure, in well under a second on a 12th Gen Intel Core i9-12900K with Python 3.14.4 and Hypothesis 6.169.0. Run it again and it replays from the .hypothesis database. Add derandomize=True, delete .hypothesis, rerun, and see the database stay empty. Then assert sorted(sorted(xs)) == sorted(xs) over st.lists(st.integers()) and count 200 examples.Quiz yourself
Answer first, then mark it. Missed ones go to Review.
0 got · 0 missed
1.Hypothesis tried a large integer first but reports . Why?Answer
Shrinking. After finding a failure it searches for the smallest input that still fails, so the report shows the minimal case.
2.When should a failing case live in @example rather than the database?Answer
For every durable regression. The database is a local directory that can go stale across versions, and
derandomize=True, which the built-inciprofile sets, turns it off, while@exampleruns on every machine in the explicit phase.3.Give a round-trip property for a serializer plus parser, and a metamorphic relation for a sort.Answer
Round trip:
parse(serialize(tree))equalstreefor every generated tree. Metamorphic:sorted(xs + ys)equalssorted(ys + xs), relating two runs without knowing the right answer.4.A property test fails only on some runs of identical code. What must you check?Answer
Determinism of draws plus outcome: unmanaged randomness, time, filesystem or global state. Only that sequence needs to be deterministic.
Practice
- Hypothesis quickstart failing test
Running in a test suite: the
assertexampleRun it, read the shrunk report, then convert the case to
@example. - Hypothesis rule-based state machines: DatabaseComparison
Rule-based state machines: the
DatabaseComparisonexample withadd_key,save,deleteandvalues_agreeRebuild it against a
dict-backed store of your own and run at least 50 examples.
You're done when
Your property suite fails on a seeded bug with a one-line minimal case, and every durable failure exists as @example with the database replay passing.
Only when you can do this without notes.
Leads to
Notes
Resources · 1 for this unit, 6 more in the section
- Hypothesis documentationHypothesis · required
Follow the Quick start and property-based testing guides, then generate operation histories and retain the minimized example for one real defect.
Also in this section
- The Missing Semester of Your CS EducationMIT · primary
Complete the 2026 lectures on the shell, command-line environment, development tools, debugging and profiling, Git, packaging and shipping code, and code quality. Apply every exercise to the same stage project.
- pytest documentationpytest · required
Use Get Started, fixtures, parametrization, monkeypatch, caplog and temporary paths to build behavior and failure-path tests without order dependence.
- The Art of DebuggingStas Bekman · support
Use the Unix, Python and compiled-code sections during a real seeded defect. Follow the evidence and tiny-reproducer workflow rather than reading the unfinished book front to back.
- Pro GitGit project · support
Use Chapters 2-3 and the sections on debugging, internals and recovery while constructing a history for bisect and recovering a deliberately displaced commit.
- Stas' Python Cookbook - debugging and testingStas Bekman · support
Use Part III and the packaging sections for debugger, traceback, pytest, logging, profiling and clean-environment recipes.
- AlgoMaster Python - mockingAlgoMaster · support
Use the Mocking lesson for
unittest.mock:MockversusMagicMock,patchtargets,autospecand the over-mocking trap. The pytest docs remain the reference for fixtures andmonkeypatch.