How do you test a state machine for forbidden transitions?
Question
An order workflow has 5 states (Pending, Paid, Shipped, Cancelled, Refunded) and 4 events (pay, ship, cancel, refund). Only 5 transitions are allowed:
Pending+pay->Paid,Pending+cancel->CancelledPaid+ship->Shipped,Paid+cancel->CancelledShipped+refund->Refunded
All other pairs must raise ValueError and leave state unchanged. A stale webhook cancelled a shipped order, and a double click refunded an order twice.
- Why did happy-path tests miss both bugs?
- Fix the transition rule and test all 20
(state, event)pairs.
class Order: def __init__(self, state="Pending"): self.state = state def apply(self, event): if event == "pay" and self.state == "Pending": self.state = "Paid" elif event == "ship" and self.state == "Paid": self.state = "Shipped" elif event == "cancel": self.state = "Cancelled" elif event == "refund": self.state = "Refunded" else: raise ValueError(f"bad: {self.state} + {event}")
Show hints (3)
- "CHECK MISSING GUARDS"
Look at
elif event == "cancel"andelif event == "refund"in the starter. Neither checksself.statefirst. - "COUNT EVERY CELL"
5 states times 4 events equals 20 cells. Only 5 are valid; the other 15 must raise
ValueError. - "USE TRANSITION TABLE"
Store allowed
(state, event) -> next_statepairs in one dict, then loop over every state and event to test valid and forbidden cells.
Show checked explanation
Happy-path tests only cover the 5 allowed arrows, so they miss unguarded cancel and refund branches. Drive Order from an explicit transition map. Then test all 20 cells of the 5x4 table against a separate spec oracle, asserting ValueError and unchanged order.state on all 15 forbidden pairs.
class Order: _T = {("Pending", "pay"): "Paid", ("Pending", "cancel"): "Cancelled", ("Paid", "ship"): "Shipped", ("Paid", "cancel"): "Cancelled", ("Shipped", "refund"): "Refunded"} def __init__(self, state="Pending"): self.state = state def apply(self, ev): if (self.state, ev) not in self._T: raise ValueError(self.state) self.state = self._T[(self.state, ev)] SPEC = {("Pending", "pay"): "Paid", ("Pending", "cancel"): "Cancelled", ("Paid", "ship"): "Shipped", ("Paid", "cancel"): "Cancelled", ("Shipped", "refund"): "Refunded"} for s in ("Pending", "Paid", "Shipped", "Cancelled", "Refunded"): for e in ("pay", "ship", "cancel", "refund"): o = Order(s) try: o.apply(e) assert (s, e) in SPEC and o.state == SPEC[(s, e)] except ValueError: assert (s, e) not in SPEC and o.state == s print(f"{len(SPEC)} valid, {20 - len(SPEC)} forbidden checked")
5 valid, 15 forbidden checked
Executed the solution on CPython 3.12.10, confirmed the starter passes all 5 valid transitions while allowing 7 illegal ones, and proved the solution's SPEC assertions catch mutated Order classes and state corruption on error. Checked by an editor other than the author.
Walkthrough
In the starter Order, cancel and refund forgot to check self.state. Every valid path (Pending -> Paid -> Shipped -> Refunded, Pending -> Cancelled, Pending -> Paid -> Cancelled) passes, yet the starter silently allows 7 illegal transitions, including Shipped + cancel, Refunded + refund, and Pending + refund.
A state transition table lists every state against every event (5 x 4 = 20 cells). Blank or error cells are just as important as valid ones:
| State | pay | ship | cancel | refund |
|---|---|---|---|---|
Pending | Paid | error | Cancelled | error |
Paid | error | Shipped | Cancelled | error |
Shipped | error | error | error | Refunded |
Cancelled | error | error | error | error |
Refunded | error | error | error | error |
Three end-to-end paths cover all 5 valid single transitions (0-switch coverage): Pending -> Paid -> Shipped -> Refunded, Pending -> Cancelled, and Pending -> Paid -> Cancelled. That reaches 100% valid-transition coverage and still misses all 15 forbidden cells.
To catch forbidden transitions, iterate over the full Cartesian product of STATES and EVENTS. For each of the 5 valid cells, assert the exact next state. For each of the 15 forbidden cells, assert that ValueError is raised and that order.state stays unchanged on stateful objects. Notice that Cancelled and Refunded are terminal states: all 4 events fail from both.
Moving the production rule itself into an explicit (state, event) -> next_state table turns missing if guards into an impossible bug class.
Common mistakes
- Testing only valid transitions (0-switch coverage). All 5 happy arrows pass even when
cancelandrefundaccept any state. - Asserting only that a forbidden event raises
ValueError, without checking thatorder.stateand side effects stayed unchanged. - Forgetting self-loops on terminal states (
Refunded + refund,Cancelled + cancel), where duplicate webhooks cause double payouts. - Reusing
Order._Tinside test expectations instead of writing a separateSPECoracle. If both share one dict, a wrong transition passes its own test.
Follow-up questions
- "How do you test multi-step bugs like
Pending -> Paid -> Cancelled -> pay?" Step up to 1-switch coverage (every valid pair of consecutive transitions) plus terminal-state escape tests. Here, afterPending -> Paid -> Cancelled, sendingpay,ship,cancel, andrefundconfirms the cancelled order cannot revive. - "What if the same webhook delivers
paytwice for an alreadyPaidorder?" Decide up front whether duplicate events are rejected (ValueError/ HTTP 409) or handled as idempotent no-ops using an idempotency key. Either way, assert that the charge runs once and state remainsPaid. - "What if two concurrent requests send
shipandcancelon the samePaidorder?" Unit table tests will not catch races. In the database, guard transitions with an atomicUPDATE orders SET state = $next WHERE id = $id AND state = $expected(or row lock) and test that exactly one request wins.
What a strong answer covers
Spots the unguarded cancel and refund branches, builds the full 5x4 table (5 valid, 15 forbidden), asserts both ValueError and unchanged state, and discusses terminal states, idempotency, and concurrent transitions.
Open in interactive practice deck →