download

How do you test a state machine for forbidden transitions?

Testing~8 minReviewed 2 Dec 2026Free · No sign-in

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 -> Cancelled
  • Paid + ship -> Shipped, Paid + cancel -> Cancelled
  • Shipped + 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.

  1. Why did happy-path tests miss both bugs?
  2. Fix the transition rule and test all 20 (state, event) pairs.
"CODE · PYTHON"
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)
  1. "CHECK MISSING GUARDS"

    Look at elif event == "cancel" and elif event == "refund" in the starter. Neither checks self.state first.

  2. "COUNT EVERY CELL"

    5 states times 4 events equals 20 cells. Only 5 are valid; the other 15 must raise ValueError.

  3. "USE TRANSITION TABLE"

    Store allowed (state, event) -> next_state pairs 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.

"SOLUTION · PYTHON"
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")
"OUTPUT"
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:

Statepayshipcancelrefund
PendingPaiderrorCancellederror
PaiderrorShippedCancellederror
ShippederrorerrorerrorRefunded
Cancellederrorerrorerrorerror
Refundederrorerrorerrorerror

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 cancel and refund accept any state.
  • Asserting only that a forbidden event raises ValueError, without checking that order.state and side effects stayed unchanged.
  • Forgetting self-loops on terminal states (Refunded + refund, Cancelled + cancel), where duplicate webhooks cause double payouts.
  • Reusing Order._T inside test expectations instead of writing a separate SPEC oracle. 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, after Pending -> Paid -> Cancelled, sending pay, ship, cancel, and refund confirms the cancelled order cannot revive.
  • "What if the same webhook delivers pay twice for an already Paid order?" 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 remains Paid.
  • "What if two concurrent requests send ship and cancel on the same Paid order?" Unit table tests will not catch races. In the database, guard transitions with an atomic UPDATE 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 →

Original OfferVibe question. ISTQB CTFL v4.0 Syllabus · pytest parametrize.
© 2026 OfferVibe · Text CC BY-NC-SA 4.0 · code MITFree to share and adapt with credit, not for commercial use. Code samples are free for any use.