Testing and QA · Intermediate · 22 min
Find edge cases with property-based testing in Hypothesis
By Padding · Updated 18 Nov 2026
Debian (python:3.15-slim) · Python 3.15 · Hypothesis 6.170 · pytest 9.2.0 · uv 0.13
You will use Hypothesis with pytest to state round-trip, invariant, oracle and stateful properties for a small room-booking module, and let it find, shrink and pin three planted bugs before you fix them.
On this page
An example-based test checks the cases you thought of. The bugs that reach users are usually in the cases you did not: a name with a strange character in it, two meetings that touch end to start, a slot freed and booked again. Property-based testing turns that around. You describe what must always be true, and a library generates hundreds of inputs looking for one that breaks the rule. When it finds one, it shrinks it to the smallest input that still fails, so the report reads like a test you could have written by hand.
Hypothesis is the property-based testing library for Python, and it plugs into pytest with no extra configuration. In this tutorial you build a small meeting-room booking module in three parts and test each with a different kind of property:
- a round trip: saving a booking to a line of text and reading it back gives the same booking;
- an invariant and an oracle: inserting into a sorted schedule keeps it sorted, and a fast overlap check agrees with a slow, obviously correct one;
- a state machine: any sequence of bookings and cancellations leaves the calendar consistent with a simple model.
Each part has a bug planted in it. You watch Hypothesis find it, read the shrunk example, pin it, and fix the code.
Step 1 · Create the project and install Hypothesis
Make a throwaway project and add pytest and Hypothesis as development dependencies. The ranges allow patch releases and nothing newer, so a new minor version cannot change behaviour under you:
mkdir -p ~/hypothesis-demo
cd ~/hypothesis-demo
uv init --no-package
uv add --dev "pytest>=9.2,<9.3" "hypothesis>=6.170,<6.171"
rm main.py
echo ".hypothesis/" >> .gitignoreThe last line keeps Hypothesis's local example database out of version control. You will meet that folder in a later step.
Check it worked
uv run python -c "import hypothesis; print(hypothesis.__version__)"The command prints 6.170.17, or a later 6.170 release.
Step 2 · Write a round-trip property
The booking module stores each booking as one line of text, with fields separated by |, so bookings can go into a log file or a text message. Create codec.py:
cat > codec.py <<'PY'
from dataclasses import dataclass
@dataclass(frozen=True)
class Booking:
room: str
start: int # minutes after midnight
length: int # minutes
guest: str
def to_line(booking):
return f"{booking.room}|{booking.start}|{booking.length}|{booking.guest}"
def from_line(line):
room, start, length, guest = line.split("|")
return Booking(room, int(start), int(length), guest)
PYThe property is simple to say: whatever booking you write out, reading the line back gives the same booking. Create test_codec.py:
cat > test_codec.py <<'PY'
from hypothesis import given, strategies as st
from codec import Booking, from_line, to_line
names = st.text(min_size=1, max_size=40) | st.text(
alphabet="Ade |,", min_size=1, max_size=10
)
bookings = st.builds(
Booking,
room=st.sampled_from(["Baobab", "Iroko", "Mahogany"]),
start=st.integers(min_value=0, max_value=24 * 60 - 1),
length=st.integers(min_value=15, max_value=240),
guest=names,
)
@given(bookings)
def test_line_round_trip(booking):
assert from_line(to_line(booking)) == booking
PYEach strategy describes a set of values Hypothesis may generate:
st.sampled_frompicks one item from a list, here the three room names.st.integerswith bounds gives whole numbers in a range. Hypothesis favours the edges of the range, so0and the maximum turn up far more often than chance.st.textgives strings drawn from the whole of Unicode: accented letters, scripts such as Ge'ez or Arabic, emoji, control characters. Names likeỌláolúwaorNnamdi Ọ̀kọ̀are ordinary input to it.a | bmeans "either strategy". Unicode is huge, so any single character such as|comes up rarely in plain text. The second, narrow strategy leans on the characters your format treats as special, which is where a text format breaks.st.buildscallsBookingwith a value from each strategy, so the test receives finished objects.
@given(bookings) tells pytest to run the test function many times, 100 by default, with a different booking each time. Run it:
uv run pytest test_codec.pyCheck it worked
The test fails with ValueError: too many values to unpack (expected 4, got 5). Under it, pytest shows a section headed Failing test case: that names one booking with guest='|'. A guest whose name contains the separator produces five fields instead of four.
Step 3 · Read the shrunk example and pin it
Look closely at the failing case. It is something like this:
Failing test case: test_line_round_trip(
# The test always failed when commented parts were varied together.
booking=Booking(
room='Baobab', # or any other generated value
start=0, # or any other generated value
length=15, # or any other generated value
guest='|',
),
)Hypothesis did not stop at the first failing booking, which probably had a long, messy name. It shrank it: shorter strings, smaller numbers, the first room in the list, until any further simplification made the test pass. Every value here is the simplest its strategy allows (start at its minimum 0, length at its minimum 15) except the one that matters. The comments say so outright: the room, start and length can be anything, and the guest name | is the cause. When you read a shrunk example, look for the value that is not at its simplest. That is usually the bug.
Hypothesis also saved this failure in the .hypothesis/ folder in your project. On the next run it replays saved failures first, so a bug you found once does not slip away on a lucky run. That database is local to your machine, which is why you kept it out of Git. To keep a case forever and share it with your team, pin it in the test with @example.
Fix the code first. The guest is the last field, so splitting at most three times leaves any extra | inside the guest's name:
cat > codec.py <<'PY'
from dataclasses import dataclass
@dataclass(frozen=True)
class Booking:
room: str
start: int # minutes after midnight
length: int # minutes
guest: str
def to_line(booking):
return f"{booking.room}|{booking.start}|{booking.length}|{booking.guest}"
def from_line(line):
# The guest is the last field, so split at most three times:
# any "|" left over belongs to the guest's name.
room, start, length, guest = line.split("|", 3)
return Booking(room, int(start), int(length), guest)
PYThen rewrite the test with two pinned examples: the separator case Hypothesis found, and a name with Yoruba diacritics, the kind of text a booking form in Lagos or Ibadan really receives:
cat > test_codec.py <<'PY'
from hypothesis import example, given, strategies as st
from codec import Booking, from_line, to_line
names = st.text(min_size=1, max_size=40) | st.text(
alphabet="Ade |,", min_size=1, max_size=10
)
bookings = st.builds(
Booking,
room=st.sampled_from(["Baobab", "Iroko", "Mahogany"]),
start=st.integers(min_value=0, max_value=24 * 60 - 1),
length=st.integers(min_value=15, max_value=240),
guest=names,
)
@given(bookings)
@example(Booking("Baobab", 0, 15, "|"))
@example(Booking("Iroko", 540, 60, "Ọláolúwa Adébáyọ̀"))
def test_line_round_trip(booking):
assert from_line(to_line(booking)) == booking
PY
uv run pytest test_codec.pyEach @example runs on every test run, before any generated input, whatever the settings. Pinned examples turn a one-off discovery into a regression test that also documents the edge case for the next reader.
Check it worked
pytest reports 1 passed. If you put the old line.split("|") back, the | example fails at once, without waiting for Hypothesis to find it again.
Step 4 · Check an invariant and compare with an oracle
The second part of the module works with time slots, written as (start, end) pairs in minutes, with the end exclusive: a meeting from 600 to 660 frees the room at 660. Create slots.py with an overlap check and a helper that inserts a slot into a schedule kept in start order:
cat > slots.py <<'PY'
def overlaps(a, b):
"""True when two (start, end) slots share at least one minute."""
a_start, a_end = a
b_start, b_end = b
return a_start <= b_end and b_start <= a_end
def insert_slot(schedule, slot):
"""Return a new schedule with slot added, kept in start order."""
for i, existing in enumerate(schedule):
if slot < existing:
return schedule[:i] + [slot] + schedule[i:]
return schedule + [slot]
PYTwo kinds of property fit here. An invariant is something an operation must preserve: after insert_slot, the schedule is still sorted, is one item longer and contains the new slot. An oracle is a second implementation you trust because it is too simple to be wrong, even if it is too slow for production: two slots overlap exactly when the sets of minutes they cover have something in common.
Random slots across a whole day rarely sit exactly end to start, and that is where overlap code goes wrong. A composite strategy lets you draw values that depend on each other. @st.composite turns a function into a strategy, and draw takes a value from another strategy inside it. Create test_slots.py:
cat > test_slots.py <<'PY'
from hypothesis import given, strategies as st
from slots import insert_slot, overlaps
@st.composite
def slots(draw):
start = draw(st.integers(min_value=0, max_value=22 * 60))
length = draw(st.integers(min_value=15, max_value=120))
return (start, start + length)
@st.composite
def nearby_pairs(draw):
"""A slot, and a second slot that starts near where the first ends."""
first = draw(slots())
gap = draw(st.integers(min_value=-180, max_value=60))
length = draw(st.integers(min_value=15, max_value=120))
start = max(0, first[1] + gap)
return first, (start, start + length)
def overlaps_slow(a, b):
"""Obviously correct and slow: compare the actual minutes."""
return bool(set(range(*a)) & set(range(*b)))
@given(nearby_pairs())
def test_overlaps_matches_slow_version(pair):
a, b = pair
assert overlaps(a, b) == overlaps_slow(a, b)
@given(nearby_pairs())
def test_overlaps_is_symmetric(pair):
a, b = pair
assert overlaps(a, b) == overlaps(b, a)
@given(st.lists(slots(), max_size=20), slots())
def test_insert_keeps_schedule_sorted(schedule, slot):
schedule = sorted(schedule)
result = insert_slot(schedule, slot)
assert result == sorted(result)
assert len(result) == len(schedule) + 1
assert slot in result
PYRun it:
uv run pytest test_slots.pyst.lists(slots(), max_size=20) builds lists of up to 20 slots, including the empty list, which Hypothesis tries early because it is the simplest. The sorted-schedule invariant and the symmetry check pass. The oracle test fails, with something like pair=((0, 15), (15, 30)): the second slot starts at the exact minute the first ends. The fast version says they overlap, the slow version says they do not, and the slow version is right, because the end is exclusive. In a booking app this bug refuses a perfectly good back-to-back meeting.
Fix the comparison so that touching slots do not count:
cat > slots.py <<'PY'
def overlaps(a, b):
"""True when two (start, end) slots share at least one minute.
End times are exclusive: a slot that ends at 600 and one that
starts at 600 sit back to back and do not overlap.
"""
a_start, a_end = a
b_start, b_end = b
return a_start < b_end and b_start < a_end
def insert_slot(schedule, slot):
"""Return a new schedule with slot added, kept in start order."""
for i, existing in enumerate(schedule):
if slot < existing:
return schedule[:i] + [slot] + schedule[i:]
return schedule + [slot]
PY
uv run pytest test_slots.pyCheck it worked
The first run shows 1 failed, 2 passed, and the failing pair has a second slot that starts at the first slot's end. After the fix, pytest reports 3 passed.
Step 5 · Tune settings, deadlines and profiles
Hypothesis's defaults suit a quick local run: 100 examples per test and a deadline of 200 milliseconds for each example. A test that takes longer than its deadline fails with DeadlineExceeded, which catches accidental slowness, such as a quadratic loop that only bites on long lists. You change these per test with @settings, for example on a test that reads files or talks to a database:
from hypothesis import given, settings
@settings(max_examples=300, deadline=None)
@given(bookings)
def test_saves_and_loads_from_disk(booking):
...deadline=None switches the deadline off for that test only. Use it for tests whose timing depends on the disk or the network, not to hide a slow function.
For the whole suite, register named profiles in conftest.py. A small one keeps local runs fast, which matters on a modest laptop or when you run tests often while you work. A larger one gives CI more time to search:
cat > conftest.py <<'PY'
from datetime import timedelta
from hypothesis import settings
settings.register_profile("dev", max_examples=50)
settings.register_profile(
"ci",
max_examples=1000,
deadline=timedelta(milliseconds=500),
print_blob=True,
)
settings.load_profile("dev")
PY
uv run pytest -qload_profile("dev") makes dev the default. The ci profile runs 20 times as many examples, allows a slower shared CI machine more time per example, and with print_blob=True prints a @reproduce_failure line on failure, so you can replay exactly what CI saw on your own machine. Choose a profile on the command line and ask for statistics to see what Hypothesis did:
uv run pytest -q --hypothesis-profile=ci --hypothesis-show-statisticsCheck it worked
The plain run reports 4 passed. The ci run also passes, and its statistics block lists each test with a line like 1000 passing, 0 failing, and 0 invalid test cases and a reason such as Stopped because settings.max_examples=1000. In your CI workflow, use the same command with --hypothesis-profile=ci.
Step 6 · Model the booking calendar as a state machine
Some bugs need a sequence of actions, not one input. The third part of the module is a calendar for one room that accepts or refuses bookings and lets you cancel them. To make availability checks fast, it keeps a set of busy hours next to the bookings themselves, a cache that must stay in step. Create roomcal.py:
cat > roomcal.py <<'PY'
class RoomCalendar:
"""Bookings for one meeting room. Times are whole hours, 0 to 24."""
def __init__(self):
self._bookings = {} # reference -> (start, end)
self._busy = set() # hours already taken, for fast checks
self._next_ref = 1
def book(self, start, end):
hours = set(range(start, end))
if hours & self._busy:
return None
ref = self._next_ref
self._next_ref += 1
self._bookings[ref] = (start, end)
self._busy |= hours
return ref
def cancel(self, ref):
del self._bookings[ref]
def bookings(self):
return sorted(self._bookings.values())
PYA stateful test describes the actions a user can take as rules, and checks after every action that the real object agrees with a model, here a plain dictionary of what should be booked. Hypothesis then generates whole sequences of actions. Create test_roomcal.py:
cat > test_roomcal.py <<'PY'
from hypothesis import strategies as st
from hypothesis.stateful import (
Bundle,
RuleBasedStateMachine,
consumes,
invariant,
multiple,
rule,
)
from roomcal import RoomCalendar
from slots import overlaps
class CalendarMachine(RuleBasedStateMachine):
refs = Bundle("refs")
def __init__(self):
super().__init__()
self.calendar = RoomCalendar()
self.model = {} # what the calendar should hold: ref -> slot
@rule(
target=refs,
start=st.integers(min_value=8, max_value=17),
hours=st.integers(min_value=1, max_value=2),
)
def book(self, start, hours):
slot = (start, start + hours)
should_accept = not any(overlaps(slot, s) for s in self.model.values())
ref = self.calendar.book(*slot)
assert (ref is not None) == should_accept
if ref is None:
return multiple()
self.model[ref] = slot
return ref
@rule(ref=consumes(refs))
def cancel(self, ref):
self.calendar.cancel(ref)
del self.model[ref]
@invariant()
def matches_model(self):
assert self.calendar.bookings() == sorted(self.model.values())
@invariant()
def no_double_bookings(self):
held = self.calendar.bookings()
for i, a in enumerate(held):
for b in held[i + 1:]:
assert not overlaps(a, b)
TestCalendar = CalendarMachine.TestCase
PYRun it:
uv run pytest test_roomcal.pyHow the pieces fit:
- A
Bundleis a pool of values that rules produce and other rules use.bookhastarget=refs, so each reference it returns goes into the pool. When a booking is refused there is no reference, andreturn multiple()adds nothing. canceltakes a reference withconsumes(refs), which also removes it from the pool, so the machine never cancels the same booking twice. Until a booking exists, Hypothesis cannot runcancelat all.- Each
@invariantruns after every step. Together with the assertion insidebook, they compare the calendar with the model. - The working hours 8 to 18 and lengths of one or two hours are a deliberately small space, so bookings collide often. A wide space would mostly produce bookings that never meet.
CalendarMachine.TestCaseis the object pytest collects and runs.
Check it worked
The test fails, and the failing case is written as a short program, something like this, with the invariant calls between steps left out here:
state = CalendarMachine()
refs_0 = state.book(hours=1, start=8)
state.cancel(ref=refs_0)
state.book(hours=1, start=8)
state.teardown()Book a slot, cancel it, book the same slot again: the calendar refuses, although the room is free. cancel removes the booking but leaves its hours in the busy set. No single-input test finds this, and an example-based test only finds it if someone thought to write that exact sequence. Hypothesis shrank whatever long sequence first failed down to these three steps.
Step 7 · Fix the calendar and run the whole suite
Make cancel release the hours as well as the booking:
cat > roomcal.py <<'PY'
class RoomCalendar:
"""Bookings for one meeting room. Times are whole hours, 0 to 24."""
def __init__(self):
self._bookings = {} # reference -> (start, end)
self._busy = set() # hours already taken, for fast checks
self._next_ref = 1
def book(self, start, end):
hours = set(range(start, end))
if hours & self._busy:
return None
ref = self._next_ref
self._next_ref += 1
self._bookings[ref] = (start, end)
self._busy |= hours
return ref
def cancel(self, ref):
start, end = self._bookings.pop(ref)
self._busy -= set(range(start, end))
def bookings(self):
return sorted(self._bookings.values())
PY
uv run pytest -qA state machine run is one example per sequence, and each sequence has up to 50 steps by default (stateful_step_count). The dev profile's 50 examples are enough here because the space is small. For a bigger model, set more examples or longer sequences on the test case itself, for example TestCalendar.settings = settings(max_examples=200, stateful_step_count=30).
Before you trust a green property test, check it can fail. Put one of the bugs back for a moment, run the suite, see it go red, and restore the fix. A property that never fails may be generating inputs that never reach the code you care about, and --hypothesis-show-statistics helps you see that.
Check it worked
uv run pytest -q --hypothesis-profile=ciBoth runs report 5 passed: the round trip, three slot properties and the calendar machine.
Step 8 · Clean up
Remove the demo project when you are done. Python and uv stay installed:
cd ~
rm -rf ~/hypothesis-demoCheck it worked
ls ~/hypothesis-demo reports that the folder does not exist.
Next steps
- Refresh the pytest basics this tutorial builds on: write and run tests in Python with pytest.
- Decide which example-based tests to keep next to your properties: write unit tests that stay useful.
- Apply the same ideas in JavaScript and TypeScript: write property-based tests in TypeScript with fast-check.
Related tutorials
- Write unit tests that stay useful as the code changesYou will replace a brittle pytest suite with behaviour tests that catch a real boundary bug and stay green when the code under them is rewritten.
- Write property-based tests in TypeScript with fast-checkYou will use fast-check and Vitest to find a rounding bug in a TypeScript money module, replay the failure from its seed, fix it, and model-test a shopping cart with generated command sequences.
- Write negative tests for an API: bad input, auth and limitsYou will build a pytest and httpx suite that attacks a small FastAPI ordering API with missing and extra fields, wrong types, boundary values, long and multilingual text, bad tokens, another user's data, rate limits and reused idempotency keys, and proves every error comes back in one RFC 9457 format.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials