Property-based testing: say what is always true, let the machine hunt
An example test checks the inputs you thought of. A property states a rule for every input and a generator goes looking for the one that breaks it
Gelila writes a property for Ojaline's price_cart: raising the quantity of any line never lowers the total. Hypothesis generates 100 random carts and the property passes every time. What can she conclude?
You have already met the idea twice. The property-based testing lesson shows a generator finding a failure and shrinking it, and the legacy function project used @given to find a year that never advanced. This chapter is the craft behind those two moments: how to choose properties, how to build generators that reach the edges, what to do when one fails, and how to test a sequence of calls and not one input.
What a property is
An example test has the shape for this input, expect this output. A property has a different shape: for every input in this set, this statement is true. The statement does not name an answer. It describes a relationship between the input and the output that any correct implementation must keep.
Take vat_on in checkout/money.py. An example test says vat_on(1_000_000) == 75_000. A property says: the VAT is never negative; it is within half a kobo of 7.5% of the net; more net never means less VAT. None of those names a result. All three hold for ₦10,000, for 1 kobo and for ₦10 billion, and a Hypothesis test runs them on a few hundred of those amounts.
The tool does two jobs. A generator, which Hypothesis calls a strategy, draws inputs: st.integers(min_value=0, max_value=10**12) draws kobo amounts. A runner calls your test with each draw (100 by default, set with max_examples) and, when one fails, shrinks it. Shrinking tries simpler inputs, smaller numbers and shorter lists, and keeps each one that still fails, until nothing simpler does. You read the end of that search, not the long random input that started it.
// example tests: every amount divides evenly
expect(split(100, 4)).toEqual([25, 25, 25, 25]);
expect(split(90, 3)).toEqual([30, 30, 30]);
function split(total, n) {
if (total < n) return []; // never reached by the examples
...
}// a property holds for every input, not one you picked
fc.assert(fc.property(fc.nat(10_000_000), fc.integer({ min: 1, max: 12 }), (total, n) => {
const s = split(total, n);
return s.length === n
&& s.every(Number.isInteger)
&& s.reduce((a, b) => a + b, 0) === total
&& Math.max(...s) - Math.min(...s) <= 1;
})); // on a failure the library shrinks to the smallest input Run the sim through to the failure and watch three things. The example tests all pass, because they use amounts that divide evenly. The generator finds the failing input within a few draws. The shrinker then walks it down step by step. The sim splits an amount between people, a different function from Ojaline’s, but the loop is the one you run in the lab.
Where properties come from
The hard part is never the tool. It is thinking of the statement. Five families cover most of what you will write for money and pricing code, and you can scan any function for them.
| Family | The statement | Ojaline example |
|---|---|---|
| Round trip | Undo what you did and you get the input back | parse(format(kobo)) == kobo |
| Bounds | The output stays in a range | VAT is at least 0; a discount is at most 10% |
| Monotone | More of the input never gives less (or more) of the output | More net never means less VAT; a promo never raises the total |
| Accounting identity | The parts add up to the whole, to the kobo | total == net + vat + delivery_fee |
| Model | A slow, obvious version agrees with the real one | A plain counter agrees with the stock table after any sequence of calls |
The families are checks against a specification, not against the code. That is why they survive refactoring: you can rewrite vat_on completely and every property stays true. It is also why they are hard to write at the start. An example is a copy of one answer. A property is a piece of the specification, and you have to know it.
John Hughes’s paper in the Reading list is a catalogue of how to find these and how to tell a strong one from a weak one. The strength question matters, because a weak property passes bad code. The property VAT is never negative passes an implementation that returns 0 for every amount. It is still worth keeping, since it guards one rule, but it is one rule among several. The lesson’s card on the lopsided split makes the same point: a property that says only that the shares add up lets one person take everything. Test your properties against a deliberately broken version, as the break at the end of the lab does, and trust only the ones that go red.
Strategies: the generator is half the test
@given(kobo) hands your function a number from the strategy named kobo. What the strategy can produce decides what the test can find, so choosing it is a design decision and not a detail.
kobo = st.integers(min_value=0, max_value=10**12) # up to ₦10 billion
lines = st.builds(Line, unit_price_kobo=st.integers(1, 5_000_000), qty=st.integers(1, 50))
carts = st.lists(lines, min_size=1, max_size=6)
Three things to know about them.
The ranges are the preconditions. qty runs from 1 because line_total raises ValueError below 1, and the API’s request model refuses it too. A test that fed qty=0 would test the error, which is a different property: a bad quantity is refused. State the precondition in the strategy, and write the refusal as its own test, as choosing cases did with the unhappy path. Say in a comment what your ranges leave out, because a property is only as wide as its generator.
st.builds and st.lists compose. Start from the smallest strategies, integers and sampled values, and build the domain objects from them. When the construction has rules, such as a cart whose lines are for different products, write a function and decorate it with @st.composite. Resist filtering with .filter(...) for anything that rejects most draws. Hypothesis gives up and reports a health check failure when too many draws are thrown away, and the fix is to build the valid object directly.
The default generator does not know your edges. Hypothesis favours the edges of the ranges you give it: zero, the maximum, small values. It has no idea that ₦10,000 is a tier edge in pricing.py. If a bug lives at a rule edge that is not an edge of the type, the generator may never visit it. The lab shows this in numbers: a property that is false passes on a first run.
The tool has run-time knobs you will use immediately. @settings(max_examples=1000) raises the count for one test. --hypothesis-seed=0 on the pytest command line fixes the random draw so a failure reproduces on someone else’s machine. --hypothesis-show-statistics prints how many draws ran, how many were rejected as invalid and how long they took. Hypothesis also has a default deadline of 200 ms per example, which turns a slow draw into a failure called flaky or deadline exceeded. Leave it on for pure code. Switch it off with deadline=None for tests that open a database, as the state machine below does.
When a property fails
A failure means one of two things, and your first job is to say which.
- The code is wrong. The property states a rule from the specification and the code breaks it. Fix the code.
- The property is wrong. It states a rule the specification never promised. Restate it, and write down what you decided.
The second case is not a nuisance. It is often the most useful thing the test does. In the lab you will write the property Chaltu’s finance team asked for, more quantity never lowers the total, run it on random carts and see it pass. Then you will point the generator at the discount edges and see it fail. A cart of 49 units at ₦200 costs ₦12,035. Add one unit and the subtotal reaches ₦10,000, the 5% tier starts, and the total falls to ₦11,712.50. The code is doing what the pricing rule says. The property was an intuition about how prices behave, and the rule has a cliff in it. Nobody wrote that cliff down, and the property found it.
What you do next is a product decision and not a testing one, which is why the chapter’s Decide asks it. You can keep the cliff and weaken the property to hold only inside a tier. You can change the rule so the discount applies only to the units above the edge, which removes the cliff. Both are defensible. Writing the failure down as a test is not optional.
Shrinking is best effort
Read a shrunk example as a small failure, not the smallest. Hypothesis tries simpler inputs in a fixed order and stops at a local minimum. When failures are scattered, as they are for a float parser that loses a kobo on some amounts and not others, different runs end at different inputs. The lab’s float parser failed at 201 on one run and at 262_625_047_443 on another. Either one is enough to find the bug, and neither one is the smallest. Use the shrunk example as the first thing you read. Then try the smaller ones you can think of by hand.
Keep the counterexample
Hypothesis saves each failing input in a local database, the .hypothesis/examples folder, and replays it first on the next run. That folder is ignored by git in this lab and is local to one machine. It does not survive a clean checkout, so it does not protect CI. A counterexample that matters needs to live in the test file, where @example pins it:
@example(amount=29) # the float parser lost a kobo here: int(0.29 * 100) is 28
@given(kobo)
def test_format_then_parse_returns_the_same_kobo(amount):
...
@example runs that input on every run before any generated one, in every checkout. It is a regression test with a name and a comment. This is how a property-based suite and an example-based suite cooperate: the generator finds, the example remembers. When Hypothesis prints a git apply .hypothesis/patches/... line after a failure, it is offering to write the @example lines for you. Read the patch before you apply it, and add the comment yourself.
Properties for money
Money code is the best place to start, for three reasons. It is pure, so no database or clock is needed. It has a specification, usually written in a policy page. And the cost of a wrong answer is paid on every order near the wrong input, for months, in amounts too small for anyone to notice. A one-kobo error is invisible on a receipt and ruinous on a reconciliation.
Three habits help.
Work in integers, and say so. All amounts in the lab are integer kobo, and the strategies draw integers. Do not draw floats and compare with a tolerance. A tolerance hides the very error you are looking for. The lesson on money and floating point shows why.
Check the rounding rule, not only the answer. The VAT rule is 7.5% of the net, rounded half up to the kobo. The property that checks it is the half-kobo bound: abs(vat * 10_000 - net * 750) <= 5_000. It says the rounded answer is never more than half a kobo from the exact one. It would catch a switch to rounding down, which can be a whole kobo out. It does not tell half up from half even, so add one example that lands exactly on a half (₦0.20 gives 1.5 kobo, which rounds to 2).
Check the identities that finance checks. The parts of a quote add up, always. net == subtotal - tier_discount - promo_discount and total == net + vat + delivery_fee. If these ever fail, a reconciliation will find it later and with much less to go on. A later chapter, Testing money, builds on this with a reconciliation script and evidence for an auditor.
State machines: when the bug needs a sequence
Everything so far was a pure function of one input. Some bugs need a history: reserve three units, release two, reserve five, and the count is wrong. A property over one input cannot reach that. A state machine test can.
You write four pieces for Hypothesis’s RuleBasedStateMachine (its docs call this stateful testing):
- Rules: the operations, each a method decorated with
@rule, with generated arguments. Hypothesis picks which rule to run next, and with what arguments, at random. - A model: a plain Python value, such as an integer, that says what should be true. It must be simpler than the real thing, so it is obviously right.
- An invariant: a method decorated with
@invariant()that compares the real system with the model. It runs after every step. - A start state:
@initialize()runs once at the start of each sequence and builds a fresh system. Hypothesis creates a new machine for each sequence, so no sequence sees another’s state.
When an invariant fails, Hypothesis shrinks the sequence the way it shrinks a number: fewer steps, smaller arguments. You get the shortest list of calls that reproduces the failure, which reads like a bug report. In the lab, the shrunk sequence is two steps long.
Stock is a good fit. checkout/inventory.py reserves and releases units, and the rule is the count never goes negative and equals the start minus what is currently held. The model is one integer, held. A test of one call cannot check this. A machine can check it after every step, across any order of calls, with a count of units that Hypothesis varies.
One limit to state clearly. This machine runs one operation at a time, so it cannot see a race between two threads. Whether two requests can take the last unit together is a question for the next chapter, Testing time, randomness and concurrency, and it uses real threads. A model test and a concurrency test answer different questions.
What property-based tests cost
They are not free, and the costs decide where to use them.
Writing the property takes thought. An example takes a minute. A property takes the time to understand the specification. That cost is the benefit too, because you learn the rule while you write it. It is the reason to start with the code whose rules matter most.
Failures can be slow to read. A failing run prints a counterexample, and sometimes a long assertion. Name the properties for the behaviour (test_a_promo_never_raises_the_price), and keep the assertion to one statement so the output says which rule broke.
Runs can differ. With a random generator, a bug that the generator finds one time in 500 shows up in one run and not in the next. That is flakiness of a kind, and the cure is the saved example, a fixed seed in CI where you need exact repeatability, and max_examples high enough for the edges you care about. A suite that is green on 100 draws is not the same as one that is green on 1,000, and CI is a good place to run the larger one (@settings(max_examples=...), or a settings profile loaded by a flag).
Speed. Each property runs your code 100 times or more. For pure functions this is milliseconds. For a test that opens a database file for each draw, as the state machine does, keep the count modest (50 examples of 30 steps here) and move the test under the integration folder if it gets slow. The shape of a suite explains why.
Where properties earn their cost: pure code with a written rule (money, pricing, dates, parsers, serialisers); anything with an inverse; anything with a simple model; and any code a human has tested with ten examples and called done. Where they do not: code whose rule is do what the screen says (an HTML page), and code that is mostly wiring.
You will write properties for checkout/money.py and checkout/pricing.py, read a shrunk counterexample, keep it as an @example, find a rule nobody wrote down, and then test checkout/inventory.py with a state machine. Work from labs/testing. Hypothesis is already in the lab’s requirements.txt (6.141.1, checked on Python 3.9.6). Start with:
export PYTHONDONTWRITEBYTECODE=1
mkdir -p tests/propertiesThe folder is tests/properties, not tests/unit, on purpose: the lab’s mutation run executes everything in tests/unit to collect statistics, and a Hypothesis test there crashes that step. Pytest runs tests/properties as part of the whole suite, and later chapters and the project use the same folder name.
1. Three properties for VAT.
Create tests/properties/test_money_properties.py:
from hypothesis import given, strategies as st
from checkout.money import format_naira, vat_on
kobo = st.integers(min_value=0, max_value=10**12) # up to N10 billion
@given(kobo)
def test_vat_is_never_negative(net):
assert vat_on(net) >= 0
@given(kobo)
def test_vat_is_within_half_a_kobo_of_7_5_percent(net):
# vat * 10_000 and net * 750 are both in units of 1/10_000 kobo
assert abs(vat_on(net) * 10_000 - net * 750) <= 5_000
@given(kobo, kobo)
def test_more_net_never_means_less_vat(a, b):
low, high = sorted((a, b))
assert vat_on(low) <= vat_on(high).venv/bin/pytest tests/properties -p no:randomly -q3 passed. Each test ran 100 generated amounts. Nothing is shown about what was generated, so run it once with --hypothesis-show-statistics to see the counts: 100 passing examples, 0 failing, 0 invalid. A green property run says no failure was found. It does not say none exists.2. A round trip that fails.
The lab has format_naira and no parser, so write one in the test file. Write it the way a hurried colleague would, with a float. Append to tests/properties/test_money_properties.py:
def parse_naira(text):
return int(float(text[1:].replace(",", "")) * 100)
@given(kobo)
def test_format_then_parse_returns_the_same_kobo(amount):
assert parse_naira(format_naira(amount)) == amount.venv/bin/pytest tests/properties -p no:randomly -q1 failed, 3 passed. The three VAT properties still pass. The round trip fails with a shrunk example. On the run this chapter was written from it was:
E AssertionError: assert 200 == 201
E + where 200 = parse_naira('N2.01')
E Falsifying example: test_format_then_parse_returns_the_same_kobo(
E amount=201,
E )Your number will differ: another run of the same test ended at 262_625_047_443. The float 2.01 times 100 is 200.99999999999997, and int cuts it down to 200. A shrunk example is a small failure and not always the smallest. 29 is smaller than both, and it fails for the same reason.
3. Fix the parser, keep the counterexample.
Replace parse_naira with an integer parser and pin the case with @example. The top of the file becomes from hypothesis import example, given, strategies as st, and the parser and test become:
def parse_naira(text):
whole, kobo_part = text[1:].replace(",", "").split(".")
return int(whole) * 100 + int(kobo_part)
@example(amount=29) # the float parser lost a kobo here: int(0.29 * 100) is 28
@given(kobo)
def test_format_then_parse_returns_the_same_kobo(amount):
assert parse_naira(format_naira(amount)) == amount.venv/bin/pytest tests/properties -p no:randomly -q4 passed. The @example(amount=29) case runs first on every run, in every checkout, whatever the generator draws. To see it earn its place, put the float parser back for a moment: the failure now names 29 on a fresh clone with no .hypothesis folder. Restore the integer parser.4. Pricing properties, and a rule nobody wrote down.
Create tests/properties/test_pricing_properties.py:
from datetime import datetime, timezone
from hypothesis import given, settings, strategies as st
from checkout.pricing import Line, discount_bp, price_cart
NOW = datetime(2026, 12, 15, 12, 0, tzinfo=timezone.utc) # inside the HARMATTAN window
lines = st.builds(Line, unit_price_kobo=st.integers(1, 5_000_000), qty=st.integers(1, 50))
carts = st.lists(lines, min_size=1, max_size=6)
km = st.integers(0, 100)
@given(carts, km)
def test_the_quote_parts_add_up(cart, distance):
q = price_cart(cart, distance, NOW, "HARMATTAN")
assert q.net == q.subtotal - q.tier_discount - q.promo_discount
assert q.total == q.net + q.vat + q.delivery_fee
@given(carts, km)
def test_a_promo_never_raises_the_price(cart, distance):
with_promo = price_cart(cart, distance, NOW, "HARMATTAN")
without = price_cart(cart, distance, NOW)
assert with_promo.total <= without.total
@given(carts, km, st.integers(min_value=0))
def test_raising_a_quantity_never_lowers_the_total(cart, distance, which):
i = which % len(cart)
bigger = list(cart)
bigger[i] = Line(cart[i].unit_price_kobo, cart[i].qty + 1)
assert price_cart(bigger, distance, NOW).total >= price_cart(cart, distance, NOW).total.venv/bin/pytest tests/properties/test_pricing_properties.py -p no:randomly -q3 passed. The last one is the finance question, and it passes. Do not trust it yet. Random carts rarely land within 5% under a discount edge, so the generator never tested the one place the rule could fail.Now aim the generator at the edges. Append:
# Prices that divide a tier edge exactly, so a short cart can land on it.
edge_prices = st.sampled_from([20_000, 25_000, 40_000, 50_000, 100_000, 250_000])
one_line = st.builds(Line, unit_price_kobo=edge_prices, qty=st.integers(1, 200))
@settings(max_examples=1000)
@given(one_line, km)
def test_quantity_up_on_edge_prices(line, distance):
more = Line(line.unit_price_kobo, line.qty + 1)
assert price_cart([more], distance, NOW).total >= price_cart([line], distance, NOW).total.venv/bin/pytest tests/properties/test_pricing_properties.py -p no:randomly -q1 failed, 3 passed. The new test fails with a counterexample at a tier edge. One run ended at the example below; another shrank to Line(unit_price_kobo=20000, qty=49), the same cliff at 50 units:
E assert 1171250 >= 1198125
E Falsifying example: test_quantity_up_on_edge_prices(
E line=Line(unit_price_kobo=25000, qty=39),
E distance=0, # or any other generated value
E )39 units at ₦250 is a subtotal of ₦9,750 and a total of ₦11,981.25. The fortieth unit makes ₦10,000, the 5% tier starts, and the total drops to ₦11,712.50. The code follows the pricing rule. The property was the intuition. In eight runs from a clean .hypothesis folder this test failed every time at 1,000 examples. The version without the edge-shaped strategy passed on one run of 5,000 random carts, and of thirteen runs of the default 100 examples, twelve stayed green and one found the cliff by luck, which is no reason to trust it.
You now have a decision, taken in the Decide below. For the lab, assume the product owner keeps the cliff and wants the property to say what holds. Change the body of test_quantity_up_on_edge_prices and add a comment saying so:
def test_quantity_up_on_edge_prices(line, distance):
more = Line(line.unit_price_kobo, line.qty + 1)
before, after = price_cart([line], distance, NOW), price_cart([more], distance, NOW)
if discount_bp(after.subtotal) == discount_bp(before.subtotal): # the tier edge itself is a different question
assert after.total >= before.total.venv/bin/pytest tests/properties/test_pricing_properties.py -p no:randomly -q4 passed. Within a tier the rule holds on every draw. Across a tier edge the test says nothing, and the cliff is now written down in the file. Add @example(line=Line(25_000, 39), distance=0) above @given if you want the cliff pinned as a case that runs every time.5. A state machine for stock.
Create tests/properties/test_stock_machine.py:
import tempfile
from pathlib import Path
from hypothesis import settings, strategies as st
from hypothesis.stateful import RuleBasedStateMachine, initialize, invariant, rule
from checkout.db import Database
from checkout.inventory import release_all, reserve
START = 20
class StockMachine(RuleBasedStateMachine):
@initialize()
def open_database(self):
self.tmp = tempfile.TemporaryDirectory()
self.db = Database(str(Path(self.tmp.name) / "machine.sqlite"))
self.pid = self.db.add_product("shea-co", "Test soap", 100_000, "published", START)["id"]
self.held = 0 # the model: units reserved and not yet released
def teardown(self):
self.tmp.cleanup()
@rule(qty=st.integers(1, 8))
def reserve_some(self, qty):
took = reserve(self.db, self.pid, qty)
assert took == (START - self.held >= qty)
if took:
self.held += qty
@rule(qty=st.integers(1, 8))
def release_some(self, qty):
if qty <= self.held: # only release what this model holds
release_all(self.db, [{"product_id": self.pid, "qty": qty}])
self.held -= qty
@invariant()
def stock_matches_the_model_and_is_never_negative(self):
on_hand = self.db.stock_of(self.pid)
assert on_hand >= 0
assert on_hand == START - self.held
TestStock = StockMachine.TestCase
TestStock.settings = settings(max_examples=50, stateful_step_count=30, deadline=None).venv/bin/pytest tests/properties -q9 passed: three VAT properties, the round trip, four pricing properties and the machine, in about 2.5 seconds. Fifty sequences of up to thirty reserves and releases ran against a fresh sqlite file each, and the stock count matched the model after every step. Run .venv/bin/pytest tests -q for the whole suite: 32 passed, 1 skipped, 1 deselected on a machine without Chromium.The machine only reserves quantities from 1 to 8 because a negative quantity is not an input the API sends. Leave it that way, and say so in your notes: it is a precondition you chose.
6. Put the lab back, after the break below. Later chapters count tests from the starter state, and a leftover tests/properties folder changes their numbers. When you have finished the break and reverted checkout/inventory.py:
rm -rf tests/properties .hypothesis
.venv/bin/pytest -q23 passed, 1 skipped, 1 deselected, the starter state.Break it. A property is only worth keeping if it goes red on a wrong answer. In checkout/inventory.py, make release_all give back one unit too few:
db.give_stock(line["product_id"], line["qty"] - 1)Run .venv/bin/pytest tests/properties/test_stock_machine.py -q -p no:randomly. It fails, and the shrunk sequence is two steps long. The block below is trimmed: the real output also shows state = StockMachine(), a state.stock_matches_the_model_and_is_never_negative() call after every step (the invariant), state.teardown() and an Explanation block of file and line numbers. Only the rule calls matter:
E assert 19 == (20 - 0)
E Falsifying example:
E state.open_database()
E state.reserve_some(qty=1)
E state.release_some(qty=1)Reserve one, release one, and one unit has vanished: that reads like a bug report. Would your example tests have found it? Check git diff to see that only this line changed, then revert it with git checkout checkout/inventory.py.
Chaltu shows finance the result from the lab: at a discount edge a customer can pay less for buying one more unit. For ₦250 items, 39 units cost ₦11,981.25 and 40 cost ₦11,712.50. Gelila, who owns the pricing rules, says the cliff is the intended reward for reaching ₦10,000, and that the rule has been live for two years. Finance says a cliff invites a buyer to pad a basket, and a seller to split orders. What should the team do?
- PAPER Claessen and Hughes, QuickCheck: a lightweight tool for random testing of Haskell programs (ICFP, 2000) Koen Claessen, John Hughes, 2000
The paper that started the idea. Properties as executable specifications and generators for the test data are the two ideas this chapter uses. The publisher blocks automated fetches, so open it in a browser. Read: The introduction and the sections on properties and test-data generators; skip the Haskell type-class detail.
- DOC Hypothesis documentation
The reference for everything in the lab: strategies, settings (max_examples, deadline), replaying failures and the @example decorator. Read the tutorial pages on strategies and settings first.
- DOC Hypothesis documentation: Stateful tests
The page for RuleBasedStateMachine, with rules, invariants, initialize and bundles, which pass values from one rule to another. Read it before you write a machine for a second system.
- POST MacIver, In praise of property-based testing (Increment, 2019) David MacIver, 2019
A short argument from the author of Hypothesis that properties make a clearer specification than examples, with advice on converting a few existing tests first. A good thing to send a sceptical colleague.
- POST MacIver, What is Hypothesis? David MacIver
The library's own introduction: you describe a range of scenarios and it generates the examples, runs inside an existing test runner and saves failing cases so a bug stays reproducible. It calls the reduction step simplification.
- PAPER Hughes, How to Specify It! A Guide to Writing Properties of Pure Functions (TFP, 2019) John Hughes, 2019
The best guide to the hard step, choosing a property that fails on a wrong implementation. Springer may ask for a login redirect; the DOI resolves to the same chapter. Read: The catalogue of five kinds of property and the comparison of how many bugs each finds; skip the Haskell-specific notation.
- PAPER MacIver, Hatfield-Dodds and many others, Hypothesis: A new approach to property-based testing (JOSS, 2019) David R. MacIver, Zac Hatfield-Dodds, 2019
A short account of how Hypothesis generates test cases and reduces failing ones. Read it for why shrinking works on any strategy and not only on numbers. Read: The whole paper; it is short.
All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.