1. Home
  2. Blog
  3. Software Testing

Software Testing

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.

9 min read
State transition testing with a diagram, state table and login lockout example

Key takeaways

  • 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

  1. List the states from the requirements, UI labels or a status column in the database.
  2. List the events, including timeouts and admin actions.
  3. Draw the diagram and review it with a developer and the product owner.
  4. Build the state table and decide what each dash should do.
  5. Write one test per valid transition, then one per important invalid transition.
  6. Add 1-switch paths around counters, timers, retries and payments.
  7. 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

Work with Stack Quora

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.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

Levenshtein Distance: Formula, Worked Table and Python Code

Levenshtein distance explained: the edit operations, the dynamic programming table for kitten and sitting, Python code with two-row memory, normalised…

Read article →
Software Development

URL Encoding Explained: Spaces, Plus Signs and UTF-8

URL encoding explained with tested Python and JavaScript code: percent encoding, reserved characters, %20 vs plus, UTF-8 bytes, encodeURI vs…

Read article →
DevOps

Gitignore: Patterns, Negation and Fixing Tracked Files

A tested gitignore guide: pattern rules, leading and trailing slashes, negation with !, the ignored parent folder trap, git check-ignore…

Read article →
Software Testing

Acceptance Criteria: Given When Then Examples and Checklist

How to write acceptance criteria testers can run: rule-based and Given When Then formats, a worked discount code example turned…

Read article →
Software Testing

State Transition Testing: Diagram, Table and Example

State transition testing explained with a login lockout example: states, events, the diagram, the state table, valid and invalid transitions,…

Read article →
Databases & SQL

Second Highest Salary in SQL: 5 Tested Ways and the Tie Trap

Find the second highest salary in SQL five ways: MAX subquery, LIMIT OFFSET, DENSE_RANK, a correlated subquery and per department,…

Read article →
Databases & SQL

SQL ROW_NUMBER: Top N per Group, Dedupe and Pagination

SQL ROW_NUMBER explained with tested queries: PARTITION BY, top N per group, deleting duplicates, pagination, the tie trap and how…

Read article →
Software Development

JavaScript Set: Union, Intersection and Removing Duplicates

JavaScript Set explained with tested examples: add, has, delete, deduplicating arrays, the new union and intersection methods, equality rules and…

Read article →
Test Automation

Python Unittest: Assert Methods, setUp and Mocks With Examples

A practical Python unittest tutorial: TestCase, assert methods, setUp and tearDown, subTest, skips, expected failures and mock, with a test…

Read article →
Software Development

Python Map and Filter: Examples vs List Comprehensions

Python map and filter explained with tested examples: lazy map objects, multiple iterables, filter(None), chaining, and a timed comparison with…

Read article →
Artificial Intelligence

Jaccard Similarity: Formula, Python, MinHash

Jaccard similarity measures overlap between two sets as intersection over union. Work the formula, compute it in Python for words…

Read article →
Software Development

Unix Timestamp Explained: Seconds vs ms

A Unix timestamp counts seconds since 1 January 1970 UTC. Learn seconds vs milliseconds, converting in Python, JavaScript and SQL,…

Read article →
DevOps

Git Hooks: Pre-commit and Commit-msg Examples

Git hooks run scripts at key moments such as commit and push. See tested pre-commit, commit-msg and prepare-commit-msg hooks, sharing…

Read article →
Test Automation

API Testing in Python: Pytest + Requests Suite

Build an API testing suite in Python with pytest and requests: fixtures, status codes, headers, JSON schema validation, CRUD flows,…

Read article →
Software Testing

Test Design Techniques: 9 Methods + Examples

Test design techniques help you write fewer tests that catch more bugs. Learn 9 black-box, white-box and experience-based methods with…

Read article →
Databases & SQL

SQL Temporary Table: Create, Use and Drop It

SQL temporary tables store interim results for one session. Learn syntax for SQL Server, PostgreSQL, MySQL, Oracle and SQLite, session…

Read article →
Databases & SQL

SQL CROSS JOIN: Every Combination + Examples

SQL CROSS JOIN returns every combination of rows from two tables. See the row math, product variants, calendar grids that…

Read article →
Software Development

JavaScript Date: Format, Parse, Timezone Bugs

JavaScript Date explained with tested Node.js code: zero-based months, the date-only UTC parsing trap, toISOString, getTimezoneOffset, Intl formatting, date math…

Read article →
Software Development

Python Requests: GET, POST, Timeouts, Retries

Python requests explained with code tested against a local API: GET with params, POST json vs data, headers and auth,…

Read article →
Artificial Intelligence

TF-IDF Explained: Formula and Worked Example

TF-IDF scores a word by how often it appears in a document and how rare it is across all documents….

Read article →
DevOps

Git Tag: Create, Push and Delete Release Tags

Git tag explained with tested commands: annotated vs lightweight tags, listing and sorting, pushing with follow-tags, deleting local and remote…

Read article →
Test Automation

Pytest Coverage: pytest-cov and Branch Gaps

Measure pytest coverage with pytest-cov: term-missing reports, branch coverage, HTML reports, pyproject settings and a fail-under gate for CI, with…

Read article →
Software Testing

Error Guessing in Testing: Checklist + Demo

Error guessing uses tester experience to predict where code breaks. Get a ready checklist of risky inputs, a step by…

Read article →
Databases & SQL

SQL LAG and LEAD: Compare Rows, 5 Examples

SQL LAG and LEAD read values from the previous or next row without a self join. Five tested examples: change,…

Read article →
Databases & SQL

SQL STRING_AGG: Combine Rows Into One String

SQL STRING_AGG joins values from many rows into one string per group. See syntax for PostgreSQL, SQL Server, MySQL GROUP_CONCAT,…

Read article →
Artificial Intelligence

BM25 Explained: How Keyword Search Ranks Results, With Python Code and Hybrid Search

BM25 explained with a pure Python implementation we ran: the formula, IDF, term saturation, the k1 and b parameters, why…

Read article →
DevOps

Git Bisect Explained: Find the Commit That Broke Your Code, Manually or Automatically

Git bisect explained with a tested repository: find the one bad commit among 41 in 5 test runs, automate it…

Read article →
Test Automation

pytest Markers Explained: Custom Marks, skip, skipif, xfail and -m Filters

pytest markers explained with a tested suite: register custom marks, run only smoke tests with -m, combine filters with and,…

Read article →
Software Testing

Positive vs Negative Testing: Differences, 24 Real Test Cases and a Checklist

Positive vs negative testing explained with a real signup form: 6 positive and 18 negative test cases run in pytest,…

Read article →
Artificial Intelligence

Cosine Similarity Explained: Formula, Worked Example and Python Code

Cosine similarity explained simply: the formula, a worked example by hand, pure Python and NumPy code, cosine vs Euclidean distance…

Read article →
DevOps

Git Squash Commits: 4 Easy Ways, Tested Step by Step (rebase -i, reset, merge)

Git squash commits explained with 4 tested methods: interactive rebase, reset –soft, merge –squash and fixup with autosquash. Before-and-after logs,…

Read article →
Test Automation

pytest parametrize Explained: 7 Patterns with Tested Examples

pytest parametrize explained with 7 tested patterns: basic cases, readable ids, stacked decorators, pytest.param with xfail and skip, indirect fixtures…

Read article →
Software Testing

Retesting vs Regression Testing: 8 Key Differences with a Real Bug Fix Example

Retesting vs regression testing explained with a real bug fix run in pytest: retesting confirmed the fix, the regression run…

Read article →
Artificial Intelligence

RAG Chunking Strategies Explained: Fixed, Overlap, Sentence, Recursive and Headings, Measured

RAG chunking strategies compared on one document with tiktoken 0.14: fixed-size, overlap, sentence packing, recursive splitting and heading-based chunks, measuring…

Read article →
DevOps

Git Stash Explained: Save, Apply, Pop and Untracked Files, Tested

Git stash explained with commands we ran on Git 2.56: push with a message, untracked files, list and show, apply…

Read article →
Test Automation

Test Doubles Explained: Dummy, Stub, Spy, Mock and Fake, with Tested Python Code

Test doubles explained with one Python example run in pytest 9.2: dummy, stub, spy, mock and fake, when to use…

Read article →