A terminal UI is the part of a CLI most likely to go untested. It feels visual and interactive, so it gets checked by hand — until a refactor quietly breaks the Enter key, or a Textual upgrade changes focus behaviour, and nobody notices until a user does. Textual was designed with testing in mind: App.run_test() runs an app headless at a chosen screen size, and the Pilot it yields presses keys, clicks widgets and waits for the app to settle, while your test inspects widgets directly. Combined with plain unit tests for logic and snapshot tests for appearance, that gives a TUI the same safety net as the rest of the CLI. This guide builds that net for a small fuzzy-picker app. It belongs to the building terminal UIs with Textual topic.
Prerequisites
- Textual 1.0+ and pytest, plus an async test plugin:
pytest-asynciowithasyncio_mode = "auto"in your pytest configuration, or anyio's pytest plugin. - Optional:
pytest-textual-snapshotfor visual snapshot tests. - An app built along the lines of building your first Textual app.
Decide what to test where
The most effective TUI testing strategy is mostly not TUI testing. Filtering, sorting, formatting and validation belong in plain functions that the app calls; they are tested with ordinary fast unit tests. Pilot tests then cover what only a running app can show — that keys do what they should, focus moves correctly, screens appear and dismiss, and the app returns the right result. Snapshot tests catch visual regressions in layout and styling.
The app under test
A picker: type to filter a list of names, move with the arrow keys, press Enter to choose or Escape to cancel. It is the kind of component a CLI uses as mytool checkout $(mytool pick-branch). The ranking logic lives in its own module:
# src/picker/logic.py
from __future__ import annotations
def rank(query: str, names: list[str]) -> list[str]:
"""Case-insensitive filter: prefix matches first, then substring matches, alphabetical within each."""
q = query.strip().lower()
if not q:
return sorted(names)
prefix = sorted(n for n in names if n.lower().startswith(q))
inner = sorted(n for n in names if q in n.lower() and n not in prefix)
return prefix + inner
# src/picker/app.py
from __future__ import annotations
from textual import events
from textual.app import App, ComposeResult
from textual.widgets import Footer, Input, OptionList
from picker.logic import rank
class Picker(App[str | None]):
"""Type to filter, arrows to move, Enter to choose, Escape to give up."""
BINDINGS = [("escape", "give_up", "Cancel")]
def __init__(self, names: list[str]) -> None:
super().__init__()
self.names = names
def compose(self) -> ComposeResult:
yield Input(placeholder="type to filter")
yield OptionList(*rank("", self.names))
yield Footer()
def on_input_changed(self, event: Input.Changed) -> None:
options = self.query_one(OptionList)
options.clear_options()
options.add_options(rank(event.value, self.names))
if options.option_count:
options.highlighted = 0
def on_input_submitted(self) -> None:
options = self.query_one(OptionList)
if options.highlighted is not None:
self.exit(str(options.get_option_at_index(options.highlighted).prompt))
def on_key(self, event: events.Key) -> None:
"""Let arrow keys move through the list while typing in the input."""
if event.key in ("down", "up") and self.focused is self.query_one(Input):
options = self.query_one(OptionList)
if event.key == "down":
options.action_cursor_down()
else:
options.action_cursor_up()
event.prevent_default()
def action_give_up(self) -> None:
self.exit(None)
App[str | None] declares the return type: self.exit(value) ends the app, and run() — or app.return_value in tests — gives the caller that value.
The recipe: unit tests for the logic
# tests/test_logic.py
from picker.logic import rank
NAMES = ["web", "webhooks", "api", "billing-web", "worker"]
def test_empty_query_lists_everything_sorted():
assert rank("", NAMES) == sorted(NAMES)
def test_prefix_matches_come_first():
assert rank("web", NAMES) == ["web", "webhooks", "billing-web"]
def test_case_insensitive():
assert rank("API", NAMES) == ["api"]
These run in milliseconds and pin the behaviour users care most about — which names appear, in what order — without starting the app at all.
The recipe: Pilot tests for interaction
# tests/test_picker.py
from textual.widgets import Input, OptionList
from picker.app import Picker
NAMES = ["web", "webhooks", "api", "billing-web", "worker"]
async def test_typing_filters_the_list():
app = Picker(NAMES)
async with app.run_test() as pilot:
await pilot.press(*"hook")
options = app.query_one(OptionList)
assert options.option_count == 1
assert app.query_one(Input).value == "hook"
async def test_enter_returns_the_highlighted_name():
app = Picker(NAMES)
async with app.run_test() as pilot:
await pilot.press(*"web", "down", "enter")
assert app.return_value == "webhooks"
async def test_escape_returns_none():
app = Picker(NAMES)
async with app.run_test() as pilot:
await pilot.press("escape")
assert app.return_value is None
async def test_no_matches_then_enter_does_nothing():
app = Picker(NAMES)
async with app.run_test() as pilot:
await pilot.press(*"zzz", "enter")
assert app.is_running
await pilot.press("escape")
assert app.return_value is None
What these tests show:
async with app.run_test() as pilotstarts the app headless with a default size of 80×24 (passsize=(w, h)for layout-sensitive tests) and shuts it down cleanly when the block ends.pilot.press(*"hook")types characters one key at a time, exactly as a user would, so theInput.Changedmessages fire and the list refilters. Special keys use their names:"enter","escape","down","ctrl+c".- Queries inspect state directly.
app.query_one(OptionList).option_countasserts on the widget rather than on rendered text, which is more robust than matching characters on screen. app.return_valueis available after the block exits, which is how to test what a picker returns.app.is_runningconfirms the app did not exit — the edge case of pressing Enter with no matches, which should do nothing rather than return an empty string or crash.
Pilot methods await until the app has processed the input. When an action triggers further work — a message handled by another widget, a screen push — call await pilot.pause() before asserting, which lets pending messages drain.
Workers, timers and time
Apps that load data in background workers or refresh on a timer need two extra techniques. Wait for workers explicitly with await app.workers.wait_for_complete() rather than sleeping. And make intervals configurable, so a test can pass a long interval (or disable the timer) and trigger refreshes itself by pressing the refresh key — the approach used in the job-monitor test in building your first Textual app. Inject the data source too: a fake that returns fixed data makes every run identical.
Snapshot tests for appearance
Logic and interaction tests will not notice that a border disappeared or a column overlaps its neighbour. pytest-textual-snapshot renders the app to an SVG screenshot and compares it with a stored one:
# tests/test_snapshots.py
from pathlib import Path
APP = Path(__file__).parent / "snapshot_apps" / "picker_app.py"
def test_picker_initial(snap_compare):
assert snap_compare(APP, terminal_size=(60, 12))
def test_picker_filtered(snap_compare):
assert snap_compare(APP, press=["w", "e", "b"], terminal_size=(60, 12))
snap_compare takes a path to a small script that creates the app (or an app instance), optional key presses to run first, and a terminal size. A snapshot test fails until a reference exists, so record the first ones with pytest --snapshot-update and commit the generated files; from then on any visual difference fails the test and produces an HTML report showing old and new side by side. Update snapshots the same way — deliberately, reviewing the diff — whenever a visual change is intended. Keep snapshot tests few — a handful of key screens — because every intentional styling change requires reviewing and updating them.
UX considerations
Tests protect the user experience in specific ways for TUIs:
- Escape hatches must always work. Test that Escape,
qor Ctrl+C leave the app from every screen; a TUI you cannot exit is the worst possible failure. - Keyboard-only use. Pilot tests that drive everything with keys prove the app is fully usable without a mouse, which matters over SSH and for accessibility.
- Empty and error states. No matches, no data, a failed load — test that each shows something sensible rather than an empty screen or a traceback.
- Stable results for pickers. When the TUI returns a value to a shell pipeline, test the exact value, since scripts will depend on it.
Testing the behaviour in CI
Headless tests need no terminal, so they run in any CI job on any operating system:
Two practical notes. Pin Textual in the lockfile and upgrade deliberately; Textual evolves quickly, and a routine upgrade is exactly when these tests earn their keep. And run snapshot tests on one platform only (usually Linux), because font-independent as they are, minor rendering differences between platforms can still produce noisy diffs; logic and Pilot tests can run everywhere in the matrix described in testing a CLI across Python versions with GitHub Actions.
Conclusion
Test a Textual TUI in three layers: plain unit tests for the logic you have extracted from widgets, Pilot tests that drive the running app headless with real key presses and assert on widget state and return values, and a few snapshot tests that catch visual regressions. Wait for workers and messages explicitly instead of sleeping, inject data sources and intervals, test the exits and empty states, and run it all in CI like any other suite. The interactive part of your CLI then gets the same confidence as the rest.
Frequently asked questions
Do Pilot tests run in parallel with pytest-xdist?
Yes. Each test starts its own app instance headless, so they are independent. Snapshot tests work with xdist too.
How do I test mouse interactions?
await pilot.click("#selector") clicks a widget by CSS selector, and pilot.hover(...) moves the pointer. Offsets let you click specific positions within a widget.
My test passes locally but fails in CI with a timeout. Why?
Usually a worker or timer that never completes under the test's conditions — a real network call, or an interval so short the app never settles. Inject fakes for I/O and make intervals configurable; wait_for_complete() then returns promptly.
Should I test the Typer command that launches the TUI?
Test its non-interactive paths with CliRunner: that it refuses to start without a terminal and points at the scriptable alternative. The app itself is covered by Pilot tests; starting a full-screen app through CliRunner adds little.