Writing steps
Authoring UI tests as plain sentences. For engineers writing tests and integrators wiring the library into a test framework.
A test as a scenario
from prettyplay import PrettyPlay
def test_login():
t = PrettyPlay("login-flow")
t.step("open the login page")
t.step("enter the login and password")
t.step("click the «Sign in» button")
t.expect("the «Welcome back» message appears")
t.close()
Or with the context manager:
with PrettyPlay("login-flow") as t:
t.step("open the login page")
The site base URL
The root URL of the environment under test — configured once, read through the property:
with PrettyPlay("login-flow") as t:
t.step(f"open the page {t.site_base_url}/login")
- The value comes from
[tool.prettyplay.site] base_url(envPRETTYPLAY_SITE_BASE_URL, programmaticSiteConfig(base_url=...)) — an http/https URL with a host, kept verbatim, empty when unset - It is not wired into Playwright navigation: the URL the author renders into a sentence becomes part of the step address — staging and production keep separate cache entries
Step kinds
step(text)— performs what the sentence saysexpect(text)— verifies what the sentence says; a legitimately failed expectation fails the test as a product defect
Step parameters
step(text, tries=3)— the total number of executions of the step's code, the first execution included; for that step it replaces the time-bounded settle window of the polling settings with a count-bounded one — only pollable failures re-execute, afterpolling_delay, until the count is spent; the global polling settings stay untouched; absorbed retries appear assettle_retryrecords only, the step stays green — see Settle pollingstep(text, delay=1.5)— a quiet pause in seconds before the step's code runs: the declared seconds pass first — no event, no log record — then the started event fires with the ready render, then the code; a step never reached never pausesstep(text, _scope="pages/login")— the step scope: the shared cache namespace of one page object; keyword-only,None— unscoped; see The step scope- These parameters and
varsare keyword-only and accepted by both step kinds; invalid values (zero or negativetries, negativedelay, a malformed_scope) fail loudly at the call — before any page or LLM involvement
Templates and step memory
Use Jinja expressions to insert a value captured earlier in the same test.
The {% var name %} tag declares a result that generated step code must read
from the page and return as a nonblank string. A successful step publishes its
captures together after validation; an unsuccessful attempt publishes nothing.
t.step("Read the first item name into {% var name %}")
t.step("Open the item named {{ name }}")
t.expect("The page shows {{ name }}")
t.step("Enter {{ vars.code }}", vars={"code": "A1"})
vars is a separate namespace for call-local string inputs and is reserved as
a capture name. Captures last until this test ends, including across page
navigation. An expect may read captures but cannot declare one. Use Jinja's
raw block when a sentence must contain literal template markers.
Steps address the cache by their rendered sentence: {{ name }}
interpolations substitute the actual values from memory and vars, so the
same template with different values is a different step — no cross-value
replay. Active {% var name %} capture tags stay in the address verbatim —
Read {% var a %} and Read {% var x %} are different steps; a tag inside
an inactive branch contributes nothing. Case and internal whitespace are
significant — «Click Sign in» and «click sign in » are different steps; a
plain sentence and a template producing the exact same text share one step.
The instruction sent to the LLM keeps the tag-stripped render — unchanged.
See Step cache.
Step groups
with t.group("accept cookies, fill and submit the order form") as g:
g.step("accept the cookie banner")
g.step("fill the email field", delay=0.5)
g.step("submit the form")
g.expect("the status shows order confirmed", tries=2)
The group block is one coherent mini-scenario with a shared goal: inside,
steps use the ordinary authoring surface — retry count, start pause and vars
included. A failing group step on a non-strict run is diagnosed with the
whole group in view and the affected row is recovered automatically; group
membership changes no step's cache address — a group opened with _scope
addresses every step under that scope. See
Groups.
The step scope (_scope)
A scope is the shared cache namespace of one page object: the same step phrase under one scope is one cache entry for all tests — the first test generates it, the rest replay it without a model call. The integrator layer sets it, per step or once per group:
# per step on the facade, outside any group
t.step("open the dashboard", _scope="pages/dashboard")
# once per block — inherited by every step of the group
class LoginPage:
def __init__(self, t: PrettyPlay):
self._group = t.group("the user signs in", _scope="pages/login_page")
def login(self, user: str):
with self._group as g:
g.step("fill the login field with {{ vars.user }}", vars={"user": user})
g.step("click the sign-in button")
_scopeis keyword-only;None(the default) — unscoped, the step addresses exactly as before- Inside a group the scope is set once at creation — a per-step
_scopeon the group object is rejected with a loud error naming the remedy - Form: 1..N segments of
[A-Za-z0-9._-]+joined by exactly one/(e.g.pages/login_page); a segment equal to exactly..is invalid —.and...pass,..never does; an invalid value fails loudly at the call naming_scope, the received value and the allowed form — before anything renders or executes - The scope replaces exactly two things: the key part of the step address
and the file routing (
<cache root>/<scope>/); the same phrase as an action and as an assertion remains two entries - Scoped files survive every close-time sweep — cleanup concerns the test's unscoped steps only; budgets stay per test: the generating test pays, a reusing test pays nothing
- The scope never enters the rendered sentence or any LLM request
Stateful page actions — the escape hatch
Some actions stay out of generated code because they outlive a step on the
page shared by the whole test: network interception (page.route), the
clock (page.clock), add_init_script, tracing, HAR, CDP. They belong to
the author, executed explicitly through run_on_page:
with PrettyPlay("login-flow") as t:
t.step("open the login page")
def stub_the_api(page): # runs inside the driver worker thread, on the genuine page
page.route("**/api/config", lambda route: route.fulfill(json={"mode": "demo"}))
t.run_on_page(stub_the_api)
t.step("the dashboard renders in demo mode")
- The action receives the genuine sync
Pageand runs sequentially with every step — the same primitive step code crosses through (see Driver facade) - The action must use the page API only — calling back into the test
object (
t.step,t.get_screenshot, a nestedt.run_on_page) marshals into the same worker thread the action runs on; the worker rejects the re-entrant crossing with a loud error instead of a deadlock - Requires an opened page: call it after the first step — before that a
loud
PrettyplayErrorraises - The outcome returns as-is; an exception inside the action propagates untouched
Screenshots
Two author-facing abilities on the test object:
with PrettyPlay("login-flow") as t:
t.step("open the login page")
png = t.get_screenshot() # full-page PNG bytes of the current state
t.save_screenshot("artifacts/home.png") # write full-page PNG to an explicit path
- Both require an opened page: call them after the first step of the test
- Nothing is captured automatically on failures — attaching screenshots to reports is the author's decision
What the generated code looks like
The step sentence stays a plain sentence; the generated code is standard Playwright sync API running on the genuine page — see Driver facade:
from playwright.sync_api import expect
# «open the login page and sign in» — an action step ends at its action
page.goto("https://example.com/login")
page.get_by_label("Username").fill("user")
# the structural anchor first, the text anchor as the chained fallback
page.locator("#login-submit").or_(page.get_by_role("button", name="Sign in")).first.click()
# «the page shows a list of videos» — count forms, one check per meaning
items = page.get_by_role("listitem")
assert items.count() > 1
# «click «Delete» and accept the confirmation dialog»
with page.expect_event("dialog") as info:
page.get_by_role("button", name="Delete").click()
info.value.accept()
# «click «Open docs» — the documentation opens in a new tab»
with page.expect_popup() as popup_info:
page.get_by_role("link", name="Open docs").click()
popup = popup_info.value
popup.bring_to_front()
# «click «Pay» inside the embedded checkout frame»
checkout = page.frame_locator("#checkout")
checkout.get_by_role("button", name="Pay").click()
# «scroll down until the footer shows»
page.mouse.wheel(0, 600)
expect(page.get_by_text("Footer")).to_be_visible()
When a step is generated, the engine also captures the structural element
registry of the page — every interactive element with a runtime-verified
unique selector (a test-id, an id, a name, an aria-label, a class, a scoped
CSS or a structural XPath) — and sends it alongside the accessibility
snapshot. The generated code anchors through that selector first and keeps
the text or role+name locator only as the chained .or_() fallback, so a
reworded label no longer breaks the step; elements the registry cannot
anchor uniquely still locate by role+name. Set send_structure = false to
capture nothing and generate exactly as before.
Dialogs that no in-step capture claims are resolved by the driver's
resolver of last resort — accepted when the accept_dialogs browser
setting is on, explicitly dismissed when off — see
Configuration.
Addressing
The step's address is built from its rendered sentence (the addressing
text); a template rendered with different values is a different step. The
constructor arguments form the cache address: cache_key (mandatory) and
cache_path (optional subdirectory) — unless the step runs under a
_scope, which replaces the key part of the address (see
The step scope). Equal cache keys in the shared root
reuse one cached step across tests; a different language, step type or key is
a different step. User instructions (generation_prompt,
classification_prompt) take no part in the address — a cached step never
regenerates because the instructions changed. The attempt history and the
honest request inputs take no part in the address either. See
Step cache.
How a step is generated
On a cache miss the generation engine produces a candidate and executes it against the live page:
- The loop: request code (every request carries the packaged Playwright
skill as guidance) → the deterministic pre-flight check — syntax, the
fixed step form, name resolution; a violation consumes the attempt with
the outcome
preflight blockedand the code never reaches the browser → execute against the live page → on failure re-request with the grown attempt history and the fresh snapshot - Attempts are budgeted per step per test (default 3); exhaustion raises
IncurableStepErrorcarrying the classification verdict of the last candidate - A failed check of a candidate (an assertion that executed and did not hold)
stops the retries at once: the failure goes through the bounded-healing
decision table —
product_defectraisesProductDefectErrorwith the verdict,incurableraisesIncurableStepErrorwith it, and arotorfixableverdict grants exactly one healing-funded regeneration carrying the classification recommendation; a repeat failure of that regeneration is terminal with one final classification deciding the kind; one failed check is spent, never the whole budget - Other candidate failures (element not found, timeouts) retry with the fresh error and snapshot
- Only a success is stored in the cache — and only after it passes the
compliance gate (
generation_approve, default on), which judges both the user instructions and the step adequacy — whether the code accomplishes what the step sentence says for its step type: ahighfinding in either dimension fails the attempt and the retry carries the violation with the grown history,mediumandlowfindings pass with aWARNING, and a malformed verdict is re-asked once, then passes unchecked with aWARNING— the built-in engine gate owns it, and it never propagates fromstep/expect. See Configuration - Transient provider unavailability of a generation request is retried within
that request, up to
llm_request_attemptstotal sends. A permanent rejection or exhausted request raisesLLMUnavailableError.
A non-empty generation_prompt setting adds a USER INSTRUCTIONS block to
every generation and regeneration request — the project's code style guidance
(e.g. prefer data-test-id attributes), binding for the generated code while
the compliance gate is on; classification requests never carry
it. The instructions are not part of the cache address: changing them never
invalidates cached steps — replayed code is never re-gated, so changed
instructions need a manual cache purge to take effect.
The request context is honest end to end: every generation, healing and
steering request receives the step type (action or assertion), the prepared
instruction with its input bindings and result declarations, and the
verbatim per-step attempt history — every prior candidate with its outcome,
its URL before → after line, its complete code and complete error, the
original cached code anchored first. The cache write is guarded by the
compliance gate above, so a cached step contains the action the sentence
asks for, not a check of an already-achieved state. All of this is internal:
the authoring surface uses step() and expect() with optional vars;
cache addressing uses the rendered sentence (the addressing text).
What you see
Step sentences go to the logger prettyplay at info level — the suite output
reads as a plain-language scenario. A failed step renders one structured
message — the primary reason, the step and the full underlying error, the
verdict — identical in the runner output, the log and the on_step_failed
hook. Healing, cache writes and skipped writes are reported loudly through the
same logger.
Limitations
!!! warning Step sentences land in the repository cache, the logs and the LLM requests: never put secrets or personal data into a step.