State Transition Testing: Diagram, Table and a Login Lockout Example
State transition testing checks how a system moves between states when events happen, and what it does with events that should be refused. Learn to build the diagram and state table, derive valid and invalid tests, choose 0-switch or 1-switch coverage, and automate it with pytest.
- State transition testing is a black-box technique for anything whose behaviour depends on what happened before: logins, orders, subscriptions, workflows.
- Model the system as states, events, transitions and actions, then test every valid transition and the important invalid ones.
- A state table shows the invalid transitions a diagram hides; those cells are where many bugs live.
- In our demo, all 9 single-step tests passed on buggy code. Only a 1-switch test, which chains two transitions, caught the bug.
Enter a wrong password once and you get “try again”. Do it three times and the account locks, so even the right password fails. The same input, a password, gives different results depending on history. That is exactly the kind of behaviour state transition testing was designed for. Instead of testing inputs in isolation, you test sequences of events and the states they lead to.
In this guide we model a login lockout, build its diagram and state table, derive tests, and run them with pytest 9.2.0 on Python 3.13.6. We also plant a realistic bug to show which level of coverage finds it.
What is state transition testing?
State transition testing is a test design technique from the ISTQB black-box family. You describe the system as a finite state machine: a limited set of states, plus rules that say which event moves it from one state to another. Test cases are then derived from that model rather than from individual input fields. It sits alongside equivalence partitioning, boundary value analysis and decision table testing, and our overview of test design techniques shows how they fit together.
When to use it
- The same input should give different results depending on history, such as a password after three failures.
- The product has a lifecycle: order placed, paid, shipped, delivered, returned.
- There are rules about what is not allowed, such as refunding an unpaid order or cancelling a delivered one.
- The requirements already include a status field or a workflow diagram.
It is less useful for stateless logic, such as a tax calculation where the output depends only on the current inputs. There, partitions and boundaries are a better fit.
The four building blocks
| Term | Meaning | Login example |
|---|---|---|
| State | A condition the system stays in until something happens | Logged out, Logged in, Locked |
| Event | Something that happens to the system | Correct password, wrong password, logout, admin unlock |
| Transition | A move from one state to another caused by an event | Logged out to Locked on the third wrong password |
| Action | What the system does during the transition | Show “account locked”, reset the failure counter |
Some transitions also have a guard condition, a rule that must be true for the transition to happen. In our example, a wrong password only locks the account when it is the third failure in a row.
The example: a login lockout
Requirements, written the way a product owner might:
- A correct password logs the user in and resets the failure count.
- A wrong password shows an error. The third wrong password in a row locks the account.
- A locked account rejects every login attempt, even with the correct password.
- Only an admin unlock returns a locked account to logged out.
- You can only log out while logged in.
The state diagram
Drawn as text, the model has three states and six transitions:
correct password
[LOGGED_OUT] -----------------------> [LOGGED_IN]
| ^ ^ <----------------------- |
| | | logout | (login while logged in:
| | | | "already", no change)
| | +--- wrong password (1st, 2nd): stays LOGGED_OUT
| |
| +------- admin unlock
|
+--- wrong password (3rd) ---> [LOCKED] --- any password: stays LOCKED
Draw this with your team before writing tests. Most of the value of the technique comes from the conversation it forces: what happens if an admin unlocks an account that is not locked? Does a successful login really reset the counter? Those questions become test cases.
The state table
A diagram only shows the arrows that exist. A state table lists every combination of state and event, so missing behaviour stands out. A dash marks an invalid transition, which the system should refuse safely:
| State / Event | Correct password | Wrong password | Logout | Admin unlock |
|---|---|---|---|---|
| LOGGED_OUT (0-1 fails) | LOGGED_IN | LOGGED_OUT, count + 1 | – | – |
| LOGGED_OUT (2 fails) | LOGGED_IN | LOCKED | – | – |
| LOGGED_IN | “already”, no change | “already”, no change | LOGGED_OUT | – |
| LOCKED | LOCKED | LOCKED | – | LOGGED_OUT, count 0 |
The table has 16 cells, and six of them are dashes. Each dash is a question for the requirements: should logout while logged out raise an error, be ignored, or log a warning? Our implementation raises an error, and the tests check that.
Tip: invalid transitions are where the security bugs hide. Unlocking an account that was never locked, or refunding an order that was never paid, are both “dash” cells that attackers love to try.
Deriving test cases
Each valid transition becomes at least one test, written as start state, event, expected end state and expected output:
| ID | Start state | Event | Expected result | End state |
|---|---|---|---|---|
| T1 | LOGGED_OUT | correct password | ok | LOGGED_IN |
| T2 | LOGGED_OUT | wrong password | wrong | LOGGED_OUT |
| T3 | LOGGED_OUT, 2 fails | wrong password | locked | LOCKED |
| T4 | LOGGED_IN | logout | none | LOGGED_OUT |
| T5 | LOCKED | admin unlock | none | LOGGED_OUT |
| T6 | LOCKED | correct password | locked | LOCKED |
| N1-N3 | various | logout or unlock where invalid | error | unchanged |
0-switch vs 1-switch coverage
Coverage levels say how many transitions in a row each test exercises:
- All states: every state is visited at least once. The weakest level.
- 0-switch (all transitions): every valid transition is executed at least once, one step at a time. This is the usual minimum.
- 1-switch: every valid pair of consecutive transitions is executed. It catches bugs where one transition leaves hidden data behind that breaks the next.
- Invalid transitions: every dash in the table is attempted, to confirm it is refused.
Higher switch levels grow quickly, so teams usually aim for 0-switch plus invalid transitions, and add 1-switch paths for the risky parts, such as anything involving counters, timers or money.
Automating the tests with pytest
Our implementation stores a state and a failure counter. The tests are data-driven: each row lists the events that set up the start state, then the event under test and the expected result.
VALID = [
([], ("login", "s3cret"), "ok", "LOGGED_IN"),
([], ("login", "bad"), "wrong", "LOGGED_OUT"),
([("login", "bad")] * 2, ("login", "bad"), "locked", "LOCKED"),
([("login", "s3cret")], ("logout",), None, "LOGGED_OUT"),
([("login", "bad")] * 3, ("unlock",), None, "LOGGED_OUT"),
]
INVALID = [([], ("logout",)), ([], ("unlock",)), ([("login", "s3cret")], ("unlock",))]
@pytest.mark.parametrize("pre,action,result,end", VALID)
def test_valid_transitions(pre, action, result, end):
acc = Account("s3cret")
run(acc, pre)
name, *args = action
assert getattr(acc, name)(*args) == result
assert acc.state == end
@pytest.mark.parametrize("pre,action", INVALID)
def test_invalid_transitions(pre, action):
acc = Account("s3cret")
run(acc, pre)
with pytest.raises(RuntimeError):
getattr(acc, action[0])()
def test_counter_resets_after_success(): # a 1-switch path
acc = Account("s3cret")
run(acc, [("login", "bad"), ("login", "bad"), ("login", "s3cret"), ("logout",)])
assert acc.login("bad") == "wrong"
assert acc.state == "LOGGED_OUT"
Plus one test that a locked account rejects the correct password. On the correct implementation, all 10 tests passed in under half a second. The table-to-parametrize mapping is the key idea: each row of the state table becomes a row of test data. Our pytest parametrize guide covers the decorator in depth.
The bug only 1-switch coverage caught
We then planted a realistic bug: on a successful login, the code changed the state but forgot to reset the failure counter. A user who fails twice, logs in, logs out and then mistypes once would be locked out immediately.
FAILED test_bug.py::test_counter_resets_after_success - AssertionError: assert 'locked' == 'wrong'
1 failed, 9 passed in 0.22s
Every single-transition test still passed, because each one starts from a fresh account where the counter is zero anyway. Only the 1-switch path, which chains failures, a success, a logout and another failure, exposed the leftover state. This is the strongest argument for adding a few multi-step paths around anything that keeps a count.
More real-world examples
- E-commerce order: Placed, Paid, Shipped, Delivered, Cancelled, Refunded. Test that a delivered order cannot be cancelled and that a refund only follows payment.
- Subscription: Trial, Active, Past due, Cancelled. Test what happens when a payment fails during a trial.
- Bug tracker: the bug life cycle is a state machine; test that a closed bug can be reopened but a rejected one follows its own path.
- Media player: Stopped, Playing, Paused. Test pressing pause while stopped.
Limitations
- It only works when the behaviour can be reduced to a manageable number of states. A text editor has effectively infinite states.
- The model can be wrong. If the diagram misses a state, the tests miss it too, so review the model with developers.
- Higher switch coverage grows the test count fast, so pick multi-step paths by risk rather than covering them all.
- It does not test the data inside each step; combine it with partitions and boundaries for that.
Step-by-step checklist
- List the states from the requirements, UI labels or a status column in the database.
- List the events, including timeouts and admin actions.
- Draw the diagram and review it with a developer and the product owner.
- Build the state table and decide what each dash should do.
- Write one test per valid transition, then one per important invalid transition.
- Add 1-switch paths around counters, timers, retries and payments.
- Automate with data-driven tests so new transitions are one new row.
Final thoughts
State transition testing turns “it depends on what happened before” into a clear model you can review and test. Draw the diagram, fill in the state table, test every valid transition and the risky invalid ones, and add a few chained paths where state can leak between steps. Our planted counter bug passed every single-step test and failed the first 1-switch path, which is a pattern you will see again in real projects.
Frequently asked questions
What is state transition testing in simple words?
It is a black-box technique that tests how a system moves between states when events happen, such as a login moving to locked after three wrong passwords, and checks that disallowed moves are refused.
What is the difference between a state diagram and a state table?
A diagram shows states as boxes and valid transitions as arrows. A table lists every state and event combination, so it also shows invalid transitions that a diagram leaves out.
What is 0-switch and 1-switch coverage?
0-switch coverage executes every valid transition once on its own. 1-switch coverage executes every valid pair of consecutive transitions, which finds bugs caused by state left over from the previous step.
Is state transition testing black-box or white-box?
It is a black-box technique. Tests come from the specified behaviour and states, not from reading the code, although developers can use the same model for unit tests.
When should I not use state transition testing?
Skip it for stateless logic where outputs depend only on current inputs, and for systems with too many states to model. Use partitions, boundaries or decision tables there.
Keep learning
Need help with testing, WordPress or SEO?
We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.