Implementing a booking aggregate with events
Lab: build a RoomDay aggregate with value objects and three invariants, an in-memory repository with optimistic version checks, and a domain event that updates a second aggregate; then let pytest and Hypothesis try to break every rule, and break the version check on purpose to watch a booking disappear.
Contentsand lesson path
On this page
- Goal and setup
- Step 1: Create the project
- Step 2: Value objects
- Step 3: The RoomDay aggregate and its events
- Step 4: Repository, second aggregate and application service
- Step 5: Predict, then run a busy morning
- Step 6: Tests that try to break each invariant
- Step 7: Break the version check on purpose
- Check your understanding
- Apply it: stretch tasks
- Review prompt
Lessons of Tactical Domain-Driven Design
- Entities, value objects and making illegal states unrepresentable Concept · 20 min
- Aggregates as consistency boundaries Concept · 25 min
- Shrinking an oversized order aggregate Worked example · 25 min
- Domain events, domain services and avoiding an anemic model Concept · 20 min
- Implementing a booking aggregate with events Lab · 30 min
- Aggregate design check Knowledge check · 6 questions
What you will learn
- Distinguish entities from value objects and implement immutable, self-validating value objects.
- Design aggregates around invariants, sized so that one transaction changes one aggregate.
- Coordinate behavior across aggregates with domain events and domain services without breaking encapsulation.
01. Goal and setup
In this lab you build Larkfield's booking model from lessons 1 to 4 as working code and then attack it. RoomDay holds every booking of one room on one day and protects three invariants: bookings stay inside opening hours (08:00 to 20:00), fit the room's seats, and never overlap. A repository refuses stale saves. Each booking or cancellation records an event that updates a second aggregate, MemberUsage, in its own transaction. Then tests try to break every rule: ordinary pytest tests for named situations, and property-based tests written with Hypothesis, a library that generates hundreds of inputs, looks for one that makes a test fail, and shrinks it to the smallest failing case.
The lab proves one principle from each lesson: a value object refuses bad values (lesson 1), only the root can change bookings and a version check keeps concurrent changes from losing work (lessons 2 and 3), and a second aggregate catches up through events even when an event arrives twice (lesson 4).
You need: Python 3.11 or newer (the outputs come from Python 3.12.13), pytest 9.2.0 and Hypothesis 6.170.17, installed into a virtual environment in step 1. Everything runs in memory; there is no database or network. The finished folder looks like this:
booking-lab/
├── values.py step 2: TimeRange and Headcount value objects
├── room_day.py step 3: the RoomDay aggregate, Booking entity, events
├── repository.py step 4: in-memory repository with a version check
├── usage.py step 4: the MemberUsage aggregate
├── service.py step 4: application service and event handler
├── demo.py step 5: a scripted morning at reception
├── conftest.py step 6: Hypothesis settings
├── test_room_day.py step 6: example-based tests
└── test_properties.py step 6: property-based tests02. Step 1: Create the project
Create the folder and a virtual environment, so the pinned versions do not touch anything else on your machine. If python3.12 is not installed, any python3 from 3.11 up works.
mkdir booking-lab
cd booking-lab
python3.12 -m venv .venv
source .venv/bin/activate
python -m pip install --quiet --disable-pip-version-check \
pytest==9.2.0 hypothesis==6.170.17
python --version && python -m pytest --versionPython 3.12.13
pytest 9.2.003. Step 2: Value objects
The value objects are the ones from lesson 1, plus Headcount, which refuses zero, negative numbers and anything that is not a whole number. bool is excluded on purpose, because in Python True counts as the integer 1. Check both refusals:
"""Value objects: immutable, compared by value, valid from the moment they exist."""
from dataclasses import dataclass
from datetime import time
@dataclass(frozen=True)
class TimeRange:
"""A half-open range [start, end) inside one day, on 15-minute marks."""
start: time
end: time
def __post_init__(self) -> None:
for moment in (self.start, self.end):
if moment.minute % 15 or moment.second or moment.microsecond:
raise ValueError(f"{moment:%H:%M:%S} is not on a 15-minute mark")
if self.start >= self.end:
raise ValueError(f"{self} is empty or backwards")
@property
def minutes(self) -> int:
start = self.start.hour * 60 + self.start.minute
return self.end.hour * 60 + self.end.minute - start
def overlaps(self, other: "TimeRange") -> bool:
return self.start < other.end and other.start < self.end
def __str__(self) -> str:
return f"{self.start:%H:%M}-{self.end:%H:%M}"
@dataclass(frozen=True)
class Headcount:
"""How many people a booking is for: a whole number, at least 1."""
people: int
def __post_init__(self) -> None:
if isinstance(self.people, bool) or not isinstance(self.people, int):
raise ValueError(f"headcount must be a whole number, not {self.people!r}")
if self.people < 1:
raise ValueError(f"headcount must be at least 1, not {self.people}")python - <<'EOF'
from datetime import time
from values import Headcount, TimeRange
print(TimeRange(time(9, 0), time(10, 30)).minutes, Headcount(3))
for make in (lambda: TimeRange(time(9, 0), time(9, 0)), lambda: Headcount(0)):
try:
make()
except ValueError as error:
print("refused:", error)
EOF90 Headcount(people=3)
refused: 09:00-09:00 is empty or backwards
refused: headcount must be at least 1, not 004. Step 3: The RoomDay aggregate and its events
RoomDay is the aggregate root. Its bookings dictionary is private (by convention: Python does not enforce it), and the only ways to change it are book, move and cancel, which check every invariant in _check before changing anything, so a refused command leaves no trace. Each change records an event whose id names that one occurrence, room/day/n, from a counter saved with the aggregate; lesson 4 explains why an id built from the booking id would break deduplication. The time comes in as now, so tests can pass a fixed clock. Events carry the minutes, so the usage handler never loads a RoomDay.
"""RoomDay aggregate: every booking of one room on one day, and their rules."""
from dataclasses import dataclass
from datetime import date, datetime, time
from values import Headcount, TimeRange
OPENS, CLOSES = time(8, 0), time(20, 0)
class BookingRefused(Exception):
"""The command would break a RoomDay invariant, so nothing changed."""
@dataclass(frozen=True)
class RoomEvent:
event_id: str # names one occurrence: room/day/n, the nth event of this RoomDay
occurred_at: datetime
room: str
day: date
booking_id: str
member_id: str
@dataclass(frozen=True)
class RoomBooked(RoomEvent):
minutes: int
@dataclass(frozen=True)
class BookingCancelled(RoomEvent):
minutes: int
@dataclass(frozen=True)
class BookingMoved(RoomEvent):
old_minutes: int
new_minutes: int
@dataclass(eq=False)
class Booking:
"""Entity inside the aggregate: only RoomDay creates, moves or removes one."""
booking_id: str
member_id: str
at: TimeRange
people: Headcount
def __eq__(self, other: object) -> bool:
return isinstance(other, Booking) and other.booking_id == self.booking_id
def __hash__(self) -> int:
return hash(self.booking_id)
class RoomDay:
"""Aggregate root. Invariants: inside opening hours, fits the room, no overlap."""
def __init__(self, room: str, day: date, seats: int) -> None:
self.room, self.day, self.seats = room, day, seats
self._bookings: dict[str, Booking] = {} # private by convention only
self._events: list[RoomEvent] = []
self._recorded = 0 # events ever recorded; saved with the aggregate
@property
def bookings(self) -> tuple[Booking, ...]:
return tuple(self._bookings.values())
def book(self, booking_id: str, member_id: str, at: TimeRange,
people: Headcount, now: datetime) -> None:
if booking_id in self._bookings:
raise BookingRefused(f"{booking_id} already exists")
self._check(at, people, ignore=None)
booking = Booking(booking_id, member_id, at, people)
self._bookings[booking_id] = booking
self._record(RoomBooked, booking, now, minutes=at.minutes)
def move(self, booking_id: str, at: TimeRange, now: datetime) -> None:
booking = self._find(booking_id)
if at == booking.at:
return # nothing changed, so nothing happened
self._check(at, booking.people, ignore=booking_id)
old_minutes, booking.at = booking.at.minutes, at
self._record(BookingMoved, booking, now, old_minutes=old_minutes,
new_minutes=at.minutes)
def cancel(self, booking_id: str, now: datetime) -> None:
booking = self._find(booking_id)
del self._bookings[booking_id]
self._record(BookingCancelled, booking, now, minutes=booking.at.minutes)
def pull_events(self) -> list[RoomEvent]:
events, self._events = self._events, []
return events
def _find(self, booking_id: str) -> Booking:
if booking_id not in self._bookings:
raise BookingRefused(f"no booking {booking_id} in {self.room}")
return self._bookings[booking_id]
def _check(self, at: TimeRange, people: Headcount, ignore: str | None) -> None:
if at.start < OPENS or at.end > CLOSES:
raise BookingRefused(f"{at} is outside opening hours")
if people.people > self.seats:
raise BookingRefused(f"{people.people} people, only {self.seats} seats")
for other in self._bookings.values():
if other.booking_id != ignore and at.overlaps(other.at):
raise BookingRefused(f"{at} overlaps {other.booking_id} at {other.at}")
def _record(self, kind, booking: Booking, now: datetime, **facts: int) -> None:
self._recorded += 1
event_id = f"{self.room}/{self.day}/{self._recorded}"
self._events.append(kind(event_id, now, self.room, self.day,
booking.booking_id, booking.member_id, **facts))python - <<'EOF'
from datetime import date, datetime, time
from room_day import BookingRefused, RoomDay
from values import Headcount, TimeRange
room = RoomDay("R2", date(2026, 12, 7), seats=8)
now = datetime(2026, 12, 1, 9, 0)
room.book("BK-1", "M-7", TimeRange(time(9, 0), time(10, 0)), Headcount(6), now)
try:
room.book("BK-2", "M-9", TimeRange(time(9, 45), time(11, 0)), Headcount(2), now)
except BookingRefused as rule:
print("refused:", rule)
print([b.booking_id for b in room.bookings], [e.event_id for e in room.pull_events()])
EOFrefused: 09:45-11:00 overlaps BK-1 at 09:00-10:00
['BK-1'] ['R2/2026-12-07/1']05. Step 4: Repository, second aggregate and application service
Three more files. repository.py stores a deep copy of each aggregate with a version number, so no two callers share one object, the way rows in a database work. save refuses a copy whose version is out of date. Any object can be stored, which the quick check below uses.
usage.py is the second aggregate. It remembers the ids of the events it has applied, so a redelivered event is counted once. service.py is the application service: load, call the root, take the events, save with the expected version, and publish only if the save succeeded. On a version conflict it reloads and runs the command again, up to three times. published stands in for an outbox or a message broker, and the handler runs straight after the save, a simplification of the asynchronous delivery described in lesson 4.
"""In-memory repository with an optimistic version check; one per aggregate type."""
import copy
class ConcurrencyConflict(Exception):
"""The aggregate was saved by someone else after this copy was loaded."""
class InMemoryRepository:
def __init__(self) -> None:
self._rows: dict[object, tuple[int, object]] = {}
def __contains__(self, key: object) -> bool:
return key in self._rows
def add(self, key: object, aggregate: object) -> None:
if key in self._rows:
raise KeyError(f"{key} already exists")
self._rows[key] = (1, copy.deepcopy(aggregate))
def get(self, key: object) -> tuple[object, int]:
version, aggregate = self._rows[key]
return copy.deepcopy(aggregate), version # callers never share an object
def save(self, key: object, aggregate: object, expected_version: int) -> None:
stored_version, _ = self._rows[key]
if stored_version != expected_version:
raise ConcurrencyConflict(
f"{key}: loaded v{expected_version}, stored v{stored_version}")
self._rows[key] = (stored_version + 1, copy.deepcopy(aggregate))"""MemberUsage aggregate: the room minutes one member booked in one month."""
from room_day import BookingCancelled, BookingMoved, RoomBooked, RoomEvent
class MemberUsage:
def __init__(self, member_id: str, month: str, allowance: int) -> None:
self.member_id, self.month, self.allowance = member_id, month, allowance
self.minutes = 0
self._counted: set[str] = set() # ids of events already applied
def apply(self, event: RoomEvent) -> None:
if event.event_id in self._counted:
return # the same occurrence delivered again: already counted
self._counted.add(event.event_id)
if isinstance(event, RoomBooked):
self.minutes += event.minutes
elif isinstance(event, BookingCancelled):
self.minutes -= event.minutes
elif isinstance(event, BookingMoved):
self.minutes += event.new_minutes - event.old_minutes
@property
def over_allowance(self) -> int:
return max(0, self.minutes - self.allowance)"""Application service: loads, calls the aggregate, saves, then publishes."""
from datetime import datetime, timezone
from repository import ConcurrencyConflict, InMemoryRepository
from usage import MemberUsage
ALLOWANCE = 600 # minutes a month included in every membership
class BookingService:
def __init__(self, rooms: InMemoryRepository, usage: InMemoryRepository,
clock=lambda: datetime.now(timezone.utc)) -> None:
self.rooms, self.usage, self.clock = rooms, usage, clock
self.published: list[object] = [] # stands in for an outbox or a broker
def book(self, room, day, booking_id, member_id, at, people) -> None:
key = f"{room}/{day}"
self._change(key, lambda rd: rd.book(booking_id, member_id, at, people,
now=self.clock()))
def move(self, room, day, booking_id, at) -> None:
key = f"{room}/{day}"
self._change(key, lambda rd: rd.move(booking_id, at, now=self.clock()))
def cancel(self, room, day, booking_id) -> None:
key = f"{room}/{day}"
self._change(key, lambda rd: rd.cancel(booking_id, now=self.clock()))
def _change(self, key, command, attempts: int = 3) -> None:
for attempt in range(1, attempts + 1):
room_day, version = self.rooms.get(key)
command(room_day) # BookingRefused leaves the stored RoomDay untouched
events = room_day.pull_events()
try:
self.rooms.save(key, room_day, expected_version=version)
except ConcurrencyConflict:
if attempt == attempts:
raise
continue # reload the new version and run the command again
self.publish(events) # only after the save succeeded
return
def publish(self, events: list) -> None:
for event in events:
self.published.append(event)
self.on_room_event(event)
def on_room_event(self, event) -> None:
"""Handler: applies the event to MemberUsage in its own transaction."""
month = f"{event.day:%Y-%m}"
key = f"{event.member_id}/{month}"
if key not in self.usage:
self.usage.add(key, MemberUsage(event.member_id, month, ALLOWANCE))
for _ in range(3):
usage, version = self.usage.get(key)
usage.apply(event)
try:
self.usage.save(key, usage, expected_version=version)
return
except ConcurrencyConflict:
continue
raise ConcurrencyConflict(f"{key}: gave up after 3 tries")python - <<'EOF'
from repository import ConcurrencyConflict, InMemoryRepository
repo = InMemoryRepository()
repo.add("R2/2026-12-07", ["anything"])
mine, my_version = repo.get("R2/2026-12-07")
theirs, their_version = repo.get("R2/2026-12-07")
repo.save("R2/2026-12-07", theirs, expected_version=their_version)
try:
repo.save("R2/2026-12-07", mine, expected_version=my_version)
except ConcurrencyConflict as conflict:
print("refused:", conflict)
EOFrefused: R2/2026-12-07: loaded v1, stored v206. Step 5: Predict, then run a busy morning
demo.py replays the 08:59 race from lesson 2. Desk A and desk B load R2 at the same version and book overlapping times; desk A saves first. Before you run it, predict: what happens to desk B's save, and what happens when desk B retries through the service? Then: which of BK-3, BK-4 and BK-5 succeed, and how many minutes does each member end with?
"""A scripted morning at Larkfield Works, run against the in-memory repositories."""
from datetime import date, datetime, time, timezone
from repository import ConcurrencyConflict, InMemoryRepository
from room_day import BookingRefused, RoomDay
from service import BookingService
from values import Headcount, TimeRange
DAY = date(2026, 12, 7)
KEY = f"R2/{DAY}"
NOW = datetime(2026, 12, 7, 7, 59, tzinfo=timezone.utc) # a fixed clock: same output
def at(start: str, end: str) -> TimeRange:
return TimeRange(time.fromisoformat(start), time.fromisoformat(end))
rooms, usage = InMemoryRepository(), InMemoryRepository()
rooms.add(KEY, RoomDay("R2", DAY, seats=8))
app = BookingService(rooms, usage, clock=lambda: NOW)
print("1. Two desks load R2 at version 1 and book overlapping times")
desk_a, version_a = rooms.get(KEY)
desk_b, version_b = rooms.get(KEY)
desk_a.book("BK-1", "M-7", at("09:00", "10:00"), Headcount(6), now=NOW)
desk_b.book("BK-2", "M-9", at("09:30", "10:30"), Headcount(4), now=NOW)
events_a = desk_a.pull_events()
rooms.save(KEY, desk_a, expected_version=version_a)
app.publish(events_a) # what BookingService does after a successful save
print(" desk A saved BK-1")
try:
rooms.save(KEY, desk_b, expected_version=version_b)
except ConcurrencyConflict as conflict:
print(" desk B refused:", conflict)
print("2. Desk B retries through the service, which reloads version 2")
try:
app.book("R2", DAY, "BK-2", "M-9", at("09:30", "10:30"), Headcount(4))
except BookingRefused as rule:
print(" refused:", rule)
print("3. More requests through the service")
app.book("R2", DAY, "BK-3", "M-9", at("10:00", "11:00"), Headcount(4))
print(" BK-3 booked straight after BK-1")
for booking_id, start, end, people in [("BK-4", "11:00", "12:00", 9),
("BK-5", "19:30", "20:30", 2)]:
try:
app.book("R2", DAY, booking_id, "M-7", at(start, end), Headcount(people))
except BookingRefused as rule:
print(f" {booking_id} refused:", rule)
app.cancel("R2", DAY, "BK-1")
app.book("R2", DAY, "BK-1", "M-7", at("11:00", "12:00"), Headcount(6))
print(" BK-1 cancelled, then booked again for 11:00-12:00")
room_day, version = rooms.get(KEY)
print("4. R2 is at version", version, "with", [str(b.at) for b in room_day.bookings])
for event in app.published:
print(f" published {event.event_id}: {type(event).__name__} {event.booking_id}")
for member in ("M-7", "M-9"):
member_usage, _ = usage.get(f"{member}/2026-12")
print(f" {member} has {member_usage.minutes} minutes booked in 2026-12")python demo.py1. Two desks load R2 at version 1 and book overlapping times
desk A saved BK-1
desk B refused: R2/2026-12-07: loaded v1, stored v2
2. Desk B retries through the service, which reloads version 2
refused: 09:30-10:30 overlaps BK-1 at 09:00-10:00
3. More requests through the service
BK-3 booked straight after BK-1
BK-4 refused: 9 people, only 8 seats
BK-5 refused: 19:30-20:30 is outside opening hours
BK-1 cancelled, then booked again for 11:00-12:00
4. R2 is at version 5 with ['10:00-11:00', '11:00-12:00']
published R2/2026-12-07/1: RoomBooked BK-1
published R2/2026-12-07/2: RoomBooked BK-3
published R2/2026-12-07/3: BookingCancelled BK-1
published R2/2026-12-07/4: RoomBooked BK-1
M-7 has 60 minutes booked in 2026-12
M-9 has 60 minutes booked in 2026-12Desk B's save is refused because its copy is stale, not because of the overlap: the repository never looks at bookings. The retry reloads version 2, the root runs the overlap rule and refuses. BK-3 starts when BK-1 ends, which is allowed because ranges are half-open. BK-4 breaks the seat rule and BK-5 the opening hours. After BK-1 is cancelled and booked again, M-7 has 60 minutes: three events, three ids, each counted once.
07. Step 6: Tests that try to break each invariant
Now the tests. conftest.py loads a Hypothesis profile with derandomize=True, which, according to Hypothesis's documentation, makes every run test the same cases until you change Hypothesis, Python or the test. That keeps this lab's outputs reproducible; in a real project you may prefer random runs that explore more.
test_room_day.py names situations: back-to-back bookings are allowed, refused commands change nothing, bad values and stale saves are refused, a redelivered event is counted once, a cancelled id booked again is counted, and a booking moved away and back gets a new event id each time. test_properties.py attacks the rules with generated input. The first property runs up to 30 random book, move and cancel commands, including times outside opening hours and groups too big for the room, and checks all three invariants after every command. The second runs scripts through the service while delivering every event twice, and checks that each member's usage equals the minutes of their remaining bookings. The third replays the two-desk race with random times and checks that every booking a desk was told about is still stored, with no overlap.
"""Hypothesis settings for the lab: a fixed seed, so every run finds the same cases."""
from hypothesis import settings
settings.register_profile("lab", max_examples=200, derandomize=True,
database=None, deadline=None)
settings.load_profile("lab")"""Example-based tests: one named situation per test."""
from datetime import date, datetime, time, timezone
import pytest
from repository import ConcurrencyConflict, InMemoryRepository
from room_day import BookingRefused, RoomDay
from service import BookingService
from usage import MemberUsage
from values import Headcount, TimeRange
DAY = date(2026, 12, 7)
NOW = datetime(2026, 12, 1, 9, 0, tzinfo=timezone.utc)
def at(start: str, end: str) -> TimeRange:
return TimeRange(time.fromisoformat(start), time.fromisoformat(end))
def test_back_to_back_bookings_are_allowed():
room = RoomDay("R2", DAY, seats=8)
room.book("BK-1", "M-7", at("09:00", "10:00"), Headcount(2), NOW)
room.book("BK-2", "M-9", at("10:00", "11:00"), Headcount(2), NOW)
assert len(room.bookings) == 2
@pytest.mark.parametrize("start, end, people", [
("09:30", "10:30", 2), # overlaps BK-1
("07:45", "08:30", 2), # starts before opening
("13:00", "14:00", 9), # more people than seats
])
def test_a_refused_command_changes_nothing(start, end, people):
room = RoomDay("R2", DAY, seats=8)
room.book("BK-1", "M-7", at("09:00", "10:00"), Headcount(2), NOW)
room.pull_events()
with pytest.raises(BookingRefused):
room.book("BK-2", "M-9", at(start, end), Headcount(people), NOW)
assert [b.booking_id for b in room.bookings] == ["BK-1"]
assert room.pull_events() == []
def test_value_objects_refuse_bad_input():
for make in (lambda: at("10:00", "09:00"), lambda: at("09:10", "10:00"),
lambda: Headcount(0)):
with pytest.raises(ValueError):
make()
def test_a_stale_save_is_refused():
repo = InMemoryRepository()
repo.add("R2", RoomDay("R2", DAY, seats=8))
first, first_version = repo.get("R2")
second, second_version = repo.get("R2")
repo.save("R2", first, expected_version=first_version)
with pytest.raises(ConcurrencyConflict):
repo.save("R2", second, expected_version=second_version)
def test_usage_counts_a_redelivered_event_once():
room = RoomDay("R2", DAY, seats=8)
room.book("BK-1", "M-7", at("09:00", "10:30"), Headcount(2), NOW)
[event] = room.pull_events()
usage = MemberUsage("M-7", "2026-12", allowance=60)
usage.apply(event)
usage.apply(event)
assert (usage.minutes, usage.over_allowance) == (90, 30)
def run_service(*commands):
rooms, usage = InMemoryRepository(), InMemoryRepository()
rooms.add(f"R2/{DAY}", RoomDay("R2", DAY, seats=8))
app = BookingService(rooms, usage, clock=lambda: NOW)
for name, *args in commands:
getattr(app, name)("R2", DAY, *args)
ids = [event.event_id for event in app.published]
return ids, usage.get(f"M-7/{DAY:%Y-%m}")[0].minutes
def test_a_cancelled_id_can_be_booked_again_and_is_counted():
ids, minutes = run_service(
("book", "BK-1", "M-7", at("09:00", "10:00"), Headcount(2)),
("cancel", "BK-1"),
("book", "BK-1", "M-7", at("09:00", "10:00"), Headcount(2)))
assert len(set(ids)) == 3 and minutes == 60
def test_moving_away_and_back_gives_each_move_its_own_event():
ids, minutes = run_service(
("book", "BK-1", "M-7", at("10:00", "11:00"), Headcount(2)),
("move", "BK-1", at("10:00", "12:00")),
("move", "BK-1", at("10:00", "11:00")))
assert len(set(ids)) == 3 and minutes == 60"""Property tests: Hypothesis invents command sequences that try to break the rules."""
from datetime import date, datetime, time, timezone
from hypothesis import given, strategies as st
from repository import ConcurrencyConflict, InMemoryRepository
from room_day import CLOSES, OPENS, BookingRefused, RoomDay
from service import BookingService
from values import Headcount, TimeRange
DAY, KEY, MEMBERS = date(2026, 12, 7), "R2/2026-12-07", ["M-1", "M-2", "M-3"]
NOW = datetime(2026, 12, 1, 9, 0, tzinfo=timezone.utc)
@st.composite
def time_ranges(draw) -> TimeRange:
"""Ranges from 06:00 to 22:00, so some fall outside opening hours."""
start = draw(st.integers(min_value=24, max_value=87)) # in quarter hours
end = min(start + draw(st.integers(min_value=1, max_value=16)), 88)
return TimeRange(time(start // 4, start % 4 * 15), time(end // 4, end % 4 * 15))
book = st.tuples(st.just("book"), time_ranges(), st.integers(1, 12),
st.sampled_from(MEMBERS))
cancel = st.tuples(st.just("cancel"), st.integers(min_value=0, max_value=30))
move = st.tuples(st.just("move"), st.integers(min_value=0, max_value=30), time_ranges())
scripts = st.lists(st.one_of(book, cancel, move), max_size=30)
def check_invariants(room: RoomDay) -> None:
for booking in room.bookings:
assert OPENS <= booking.at.start and booking.at.end <= CLOSES
assert booking.people.people <= room.seats
for i, first in enumerate(room.bookings):
for second in room.bookings[i + 1:]:
assert not first.at.overlaps(second.at), (first.at, second.at)
@given(scripts)
def test_no_script_breaks_the_room_day_invariants(script):
room = RoomDay("R2", DAY, seats=8)
for n, command in enumerate(script):
try:
if command[0] == "book":
_, wanted, people, member = command
room.book(f"BK-{n}", member, wanted, Headcount(people), NOW)
elif command[0] == "move":
room.move(f"BK-{command[1]}", command[2], NOW)
else:
room.cancel(f"BK-{command[1]}", NOW)
except BookingRefused:
pass
check_invariants(room)
class DeliverTwice(BookingService):
"""At-least-once delivery: every event reaches the handler twice."""
def on_room_event(self, event) -> None:
super().on_room_event(event)
super().on_room_event(event)
@given(scripts)
def test_usage_catches_up_with_bookings_despite_duplicates(script):
rooms, usage = InMemoryRepository(), InMemoryRepository()
rooms.add(KEY, RoomDay("R2", DAY, seats=8))
app = DeliverTwice(rooms, usage)
for n, command in enumerate(script):
try:
if command[0] == "book":
_, wanted, people, member = command
app.book("R2", DAY, f"BK-{n}", member, wanted, Headcount(people))
elif command[0] == "move":
app.move("R2", DAY, f"BK-{command[1]}", command[2])
else:
app.cancel("R2", DAY, f"BK-{command[1]}")
except BookingRefused:
pass
room, _ = rooms.get(KEY)
for member in MEMBERS:
booked = sum(b.at.minutes for b in room.bookings if b.member_id == member)
key = f"{member}/2026-12"
counted = usage.get(key)[0].minutes if key in usage else 0
assert counted == booked
@given(time_ranges(), time_ranges())
def test_two_desks_never_lose_or_overlap_a_booking(first, second):
rooms, usage = InMemoryRepository(), InMemoryRepository()
rooms.add(KEY, RoomDay("R2", DAY, seats=8))
app = BookingService(rooms, usage)
desk_a, version_a = rooms.get(KEY)
desk_b, version_b = rooms.get(KEY)
confirmed = []
try:
desk_a.book("BK-A", "M-1", first, Headcount(2), NOW)
rooms.save(KEY, desk_a, expected_version=version_a)
confirmed.append("BK-A")
except BookingRefused:
pass
try:
desk_b.book("BK-B", "M-2", second, Headcount(2), NOW)
try:
rooms.save(KEY, desk_b, expected_version=version_b)
except ConcurrencyConflict: # desk B retries through the service
app.book("R2", DAY, "BK-B", "M-2", second, Headcount(2))
confirmed.append("BK-B")
except BookingRefused:
pass
room, _ = rooms.get(KEY)
check_invariants(room)
assert sorted(b.booking_id for b in room.bookings) == confirmedpython -m pytest -q............ [100%]
12 passed in 7.85sTwelve tests pass. With up to 200 examples per property, the limit set in conftest.py, Hypothesis tried hundreds of command scripts and found none that broke a rule. That is evidence, not proof: it covers only inputs the strategies can generate, as practice question 1 shows.
08. Step 7: Break the version check on purpose
Passing tests prove little until you have seen them fail for the right reason. Open repository.py and change line 27, if stored_version != expected_version:, to the line shown by the grep below, so that save accepts every copy. Predict before running: when two desks race now, will Hypothesis find an overlap or something else?
grep -n BROKEN repository.py27: if False: # BROKEN ON PURPOSEpython -m pytest -q test_properties.py -k two_desks 2>&1 \
| grep -E 'Error|Failing|first=|second='E AssertionError: assert ['BK-B'] == ['BK-A', 'BK-B']
E Failing test case: test_two_desks_never_lose_or_overlap_a_booking(
E first=TimeRange(start=datetime.time(8, 0), end=datetime.time(8, 15)),
E second=TimeRange(start=datetime.time(8, 0), end=datetime.time(8, 15)),
test_properties.py:113: AssertionErrorpython -m pytest -q 2>&1 | tail -n 3FAILED test_properties.py::test_two_desks_never_lose_or_overlap_a_booking - A...
FAILED test_room_day.py::test_a_stale_save_is_refused - Failed: DID NOT RAISE...
2 failed, 10 passed in 19.41sHypothesis shrank its failing case to the simplest one: both desks booking 08:00 to 08:15. No overlap was stored. Desk B's copy was taken before desk A saved, so it did not contain BK-A, and saving it replaced the whole RoomDay. Desk A's member was told 'booked' and the booking silently vanished, a lost update. Without the version check, an aggregate stored as one unit loses work rather than breaking its rule; design A in lesson 2, which stored bookings one by one, broke the rule instead. The example-based stale-save test fails too. Change the line back and run the suite again:
python -m pytest -q 2>&1 | tail -n 112 passed in 3.94s09. Check your understanding
10. Apply it: stretch tasks
- Close the gap. Add a test that books the same live id twice and expects
BookingRefused. Delete the check and confirm that your test now fails. - Resize. Add
RoomDay.resize(booking_id, people)with aBookingResizedevent, add a 'resize' command to the property-test scripts, and predict which invariant a first version is most likely to break. - Transfer to your clinic. Do the skill's practice task: implement your clinic context with at least two aggregates, validated value objects and an event consumed by the second aggregate, with tests that try and fail to break each invariant. Use this lab's layout as a template.
11. Review prompt
Without looking back:
- Name the three invariants of
RoomDayand the line of code that enforces each. - Why does
service.pytake the events off the aggregate before saving but publish them only after? - Why did desk B's first save fail even though the repository knows nothing about overlaps?
- What does
derandomize=Truegive you, and what does it cost? - Why did removing the version check lose a booking instead of storing an overlap?
References
- Hypothesis: property-based testing for Python
- Hypothesis API reference: settings such as derandomize and deadline
- pytest documentation
- venv: creation of virtual environments (Python documentation)
- Effective Aggregate Design, parts I to III (Vaughn Vernon)
- Domain-Driven Design Reference (Eric Evans, 2015)
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.