event-sourcing-tests
Tests for an event-sourced system verify replay determinism, snapshot
equivalence, and version-evolution correctness - without them, the
event log silently drifts from the rebuilt state.
When to use
- Domain model is event-sourced (orders, accounts, inventory).
- Audit / compliance requirements demand event log as system of
record.
- Adding a new event type or changing payload schema -
retro-compat tests are mandatory.
How to use
- Write the aggregate's given-events / when-command / then-events test
first (see Worked example) - it is the base every other check builds on.
- Add a replay-determinism assertion: replay the same log twice and assert
identical state; this catches
time.now() / random-ID leaks at the source.
- When snapshots are introduced, assert snapshot-at-N equals replay-to-N -
see references/snapshot-versioning-projections.md.
- When an event type or payload schema changes, add versioned upcasters and a
mixed-version replay test - see the references (versioning + upcasting).
- For read models, add the projection tests below - determinism,
idempotent + out-of-order apply, rebuild + swap - and assert the
documented convergence window per
references/convergence-windows.md.
- Gate appends on optimistic concurrency (expected version) and suppress
external calls in replay mode - see the references (concurrency, replay mode).
Worked example - one event-sourced aggregate, end to end
The base test for any event-sourced aggregate is given-events /
when-command / then-events: seed the aggregate with its prior events,
handle one command, then assert the events it emits and the resulting
state. Per Fowler - Event Sourcing, replay = "rebuild application
state from scratch by replaying events in order."
def test_confirm_order_emits_order_confirmed():
# GIVEN - the aggregate's prior event history
history = [
OrderCreated(order_id="o1", customer="c1"),
ItemAdded(order_id="o1", sku="sku1", qty=2),
]
order = OrderAggregate.replay(history)
# WHEN - one command is handled
new_events = order.handle(ConfirmOrder(order_id="o1"))
# THEN - assert the emitted events, not only the final state
assert new_events == [OrderConfirmed(order_id="o1")]
# AND replay is deterministic: the same log rebuilds the same state
state_a = OrderAggregate.replay(history + new_events)
state_b = OrderAggregate.replay(history + new_events)
assert state_a == state_b
assert state_a.status == "confirmed"
assert state_a.line_items == [("sku1", 2)]
If handle emits events derived from time.now() or random IDs,
state_a == state_b fails - the test catches non-deterministic replay
before it drifts the log from the rebuilt state.
Once this base test is green, layer on the operational checks -
order independence within causality, snapshot equivalence, event
versioning + upcasting, projection rebuild, retroactive correction,
replay-mode side-effect suppression, and optimistic-concurrency
appends - in
references/snapshot-versioning-projections.md.
Projection rebuild (CQRS read models)
Per Fowler - CQRS, the read model is rebuilt from the write model's
event stream; test it like the aggregate - deterministic, idempotent,
rebuildable:
- Determinism -
apply_all(events) twice yields the same
materialized state; current-time / random-ID reads in apply break it.
- Per-event delta - each event type produces one well-defined change
(parameterize:
ProductPriceChanged → {"sku1.price": 120}, etc.).
- Idempotent apply - the same event applied twice leaves state
unchanged (track applied event IDs per projection).
- Out-of-order delivery - the projection buffers or versions when
Updated arrives before Created; if it assumes in-order (Kafka
per-partition), test that assumption end-to-end.
- Rebuild + zero-downtime swap - rebuild from a known event range
and compare to a fixture; at the swap point assert
new_proj.materialize() == old_proj.materialize() before switching
reads. Full swap mechanic + the read-your-writes guard (202 Accepted →
pending → active) are in
references/rebuild-swap-and-read-your-writes.md.
- Convergence window - async projections lag; document the window
("read model converges within 5s of write") and assert it with the
deadline + poll + assert pattern in
references/convergence-windows.md,
which also covers monotonic-read and bounded-staleness assertions.
Test each projection off one stream independently (search index,
materialized SQL view, OLAP cube) so a flawed one doesn't mask the others.
Anti-patterns
| Anti-pattern |
Why it fails |
Fix |
Replay calls time.now() / random IDs |
Non-deterministic |
Make replay deterministic (Worked example) |
| Skip snapshot equivalence test |
Snapshots silently diverge |
Assert snapshot-at-N == replay-to-N (references) |
| No upcasting plan; rewrite event store on schema change |
Audit loss; downtime |
Versioned upcasters (references) |
| Real email/HTTP calls during replay |
Duplicate side effects |
Replay-mode flag (references) |
| Append without expected version |
Lost updates from concurrent writers |
Optimistic concurrency (references) |
| Skip the convergence-window test |
"I changed it but the UI shows the old value" |
Assert the window (references/convergence-windows.md) |
| Treat the projection as always-current |
Subtle stale reads in prod |
Document + assert the window |
| No rebuild test for a projection |
Schema migration becomes risky |
Rebuild + swap tests (projection section) |
Limitations
- Event-store implementations vary widely (EventStoreDB, Kafka,
Postgres). Test against the actual store.
- Snapshot strategy choice (every N events, every X minutes) has
performance implications outside this skill's scope.
- Cross-aggregate transactions are not part of event sourcing -
use sagas (
saga-transaction-tests) for those.
References
- Fowler - Event Sourcing - pattern overview, replay, snapshots,
retroactive corrections, gateway considerations.
- Fowler - CQRS - command/query split, read-model framing, cautions.
- references/snapshot-versioning-projections.md -
the deep operational tests: order independence, snapshot equivalence,
versioning + upcasting, projection rebuild, retroactive correction,
replay-mode side effects, and optimistic-concurrency appends.
- references/rebuild-swap-and-read-your-writes.md -
zero-downtime swap + read-your-writes worked tests.
- references/convergence-windows.md -
convergence-window, monotonic-read, and bounded-staleness assertions.
saga-transaction-tests -
cross-aggregate transactions.
1---2name: event-sourcing-tests3description: "Use when an event-sourced aggregate gains or changes an event type, snapshots are added, or a CQRS read model is projected from events. Tests given-events/when-command/then-events, replay determinism, upcasting, snapshot equivalence, projections and eventual-consistency windows."4metadata:5 source: https://skillmd.com/skills/testland/event-sourcing-tests6 keywords: "event-sourcing, aggregate-replay, snapshot, upcasting, projection"7 version: "1.2.14"8---910# event-sourcing-tests1112Tests for an event-sourced system verify replay determinism, snapshot13equivalence, and version-evolution correctness - without them, the14event log silently drifts from the rebuilt state.1516## When to use1718- Domain model is event-sourced (orders, accounts, inventory).19- Audit / compliance requirements demand event log as system of20 record.21- Adding a new event type or changing payload schema - 22 retro-compat tests are mandatory.2324## How to use25261. Write the aggregate's given-events / when-command / then-events test27 first (see Worked example) - it is the base every other check builds on.282. Add a replay-determinism assertion: replay the same log twice and assert29 identical state; this catches `time.now()` / random-ID leaks at the source.303. When snapshots are introduced, assert snapshot-at-N equals replay-to-N -31 see [references/snapshot-versioning-projections.md](references/snapshot-versioning-projections.md).324. When an event type or payload schema changes, add versioned upcasters and a33 mixed-version replay test - see the references (versioning + upcasting).345. For read models, add the projection tests below - determinism,35 idempotent + out-of-order apply, rebuild + swap - and assert the36 documented convergence window per37 [references/convergence-windows.md](references/convergence-windows.md).386. Gate appends on optimistic concurrency (expected version) and suppress39 external calls in replay mode - see the references (concurrency, replay mode).4041## Worked example - one event-sourced aggregate, end to end4243The base test for any event-sourced aggregate is given-events /44when-command / then-events: seed the aggregate with its prior events,45handle one command, then assert the events it emits and the resulting46state. Per [Fowler - Event Sourcing], replay = "rebuild application47state from scratch by replaying events in order."4849```python50def test_confirm_order_emits_order_confirmed():51 # GIVEN - the aggregate's prior event history52 history = [53 OrderCreated(order_id="o1", customer="c1"),54 ItemAdded(order_id="o1", sku="sku1", qty=2),55 ]56 order = OrderAggregate.replay(history)5758 # WHEN - one command is handled59 new_events = order.handle(ConfirmOrder(order_id="o1"))6061 # THEN - assert the emitted events, not only the final state62 assert new_events == [OrderConfirmed(order_id="o1")]6364 # AND replay is deterministic: the same log rebuilds the same state65 state_a = OrderAggregate.replay(history + new_events)66 state_b = OrderAggregate.replay(history + new_events)67 assert state_a == state_b68 assert state_a.status == "confirmed"69 assert state_a.line_items == [("sku1", 2)]70```7172If `handle` emits events derived from `time.now()` or random IDs,73`state_a == state_b` fails - the test catches non-deterministic replay74before it drifts the log from the rebuilt state.7576Once this base test is green, layer on the operational checks -77order independence within causality, snapshot equivalence, event78versioning + upcasting, projection rebuild, retroactive correction,79replay-mode side-effect suppression, and optimistic-concurrency80appends - in81[references/snapshot-versioning-projections.md](references/snapshot-versioning-projections.md).8283## Projection rebuild (CQRS read models)8485Per [Fowler - CQRS], the read model is rebuilt from the write model's86event stream; test it like the aggregate - deterministic, idempotent,87rebuildable:88891. **Determinism** - `apply_all(events)` twice yields the same90 materialized state; current-time / random-ID reads in `apply` break it.912. **Per-event delta** - each event type produces one well-defined change92 (parameterize: `ProductPriceChanged` → `{"sku1.price": 120}`, etc.).933. **Idempotent apply** - the same event applied twice leaves state94 unchanged (track applied event IDs per projection).954. **Out-of-order delivery** - the projection buffers or versions when96 `Updated` arrives before `Created`; if it assumes in-order (Kafka97 per-partition), test that assumption end-to-end.985. **Rebuild + zero-downtime swap** - rebuild from a known event range99 and compare to a fixture; at the swap point assert100 `new_proj.materialize() == old_proj.materialize()` before switching101 reads. Full swap mechanic + the read-your-writes guard (202 Accepted →102 pending → active) are in103 [references/rebuild-swap-and-read-your-writes.md](references/rebuild-swap-and-read-your-writes.md).1046. **Convergence window** - async projections lag; document the window105 ("read model converges within 5s of write") and assert it with the106 deadline + poll + assert pattern in107 [references/convergence-windows.md](references/convergence-windows.md),108 which also covers monotonic-read and bounded-staleness assertions.109110Test each projection off one stream independently (search index,111materialized SQL view, OLAP cube) so a flawed one doesn't mask the others.112113## Anti-patterns114115| Anti-pattern | Why it fails | Fix |116|---|---|---|117| Replay calls `time.now()` / random IDs | Non-deterministic | Make replay deterministic (Worked example) |118| Skip snapshot equivalence test | Snapshots silently diverge | Assert snapshot-at-N == replay-to-N (references) |119| No upcasting plan; rewrite event store on schema change | Audit loss; downtime | Versioned upcasters (references) |120| Real email/HTTP calls during replay | Duplicate side effects | Replay-mode flag (references) |121| Append without expected version | Lost updates from concurrent writers | Optimistic concurrency (references) |122| Skip the convergence-window test | "I changed it but the UI shows the old value" | Assert the window (references/convergence-windows.md) |123| Treat the projection as always-current | Subtle stale reads in prod | Document + assert the window |124| No rebuild test for a projection | Schema migration becomes risky | Rebuild + swap tests (projection section) |125126## Limitations127128- Event-store implementations vary widely (EventStoreDB, Kafka,129 Postgres). Test against the actual store.130- Snapshot strategy choice (every N events, every X minutes) has131 performance implications outside this skill's scope.132- Cross-aggregate transactions are not part of event sourcing - 133 use sagas (`saga-transaction-tests`) for those.134135## References136137- [Fowler - Event Sourcing] - pattern overview, replay, snapshots,138 retroactive corrections, gateway considerations.139- [Fowler - CQRS] - command/query split, read-model framing, cautions.140- [references/snapshot-versioning-projections.md](references/snapshot-versioning-projections.md) -141 the deep operational tests: order independence, snapshot equivalence,142 versioning + upcasting, projection rebuild, retroactive correction,143 replay-mode side effects, and optimistic-concurrency appends.144- [references/rebuild-swap-and-read-your-writes.md](references/rebuild-swap-and-read-your-writes.md) -145 zero-downtime swap + read-your-writes worked tests.146- [references/convergence-windows.md](references/convergence-windows.md) -147 convergence-window, monotonic-read, and bounded-staleness assertions.148- `saga-transaction-tests` - 149 cross-aggregate transactions.150151[Fowler - Event Sourcing]: https://martinfowler.com/eaaDev/EventSourcing.html152[Fowler - CQRS]: https://martinfowler.com/bliki/CQRS.html