Step code and tz helpers
Test Blocks step code is Python with a small, fixed set of names. tz is the
one that reaches your test data, outputs, files, Salesforce, HTTP APIs, sign-in
helpers, and the device. This page lists every construct Test Blocks supports.
For how to write steps in the first place, read the
Test Blocks authoring guide.
Names available in step code
Which names a step can use depends on its Needs browser to run (or, on a mobile test, Needs device to run) switch.
| Step | Names |
|---|---|
| Needs browser to run on (web tests) | tz, page (Playwright page), expect (Playwright assertions) |
| Needs device to run on (mobile tests) | tz, device, driver, AppiumBy |
| The switch off (no browser or device) | tz only |
Every step can also use these built-ins: str, int, float, bool, dict,
list, tuple, set, len, all, any, sum, min, max, sorted,
enumerate, range, zip, isinstance, True, False, None, and the
exceptions Exception, ValueError, TypeError, KeyError, IndexError,
AssertionError, ZeroDivisionError, and RuntimeError.
What step code may not contain
A step is checked before it runs. It is rejected when it contains:
import,def,async def,class,lambda,global, ornonlocal;- any name not listed above (assign a local variable first to use it);
- an attribute that starts with
_; - an assignment to an attribute (
obj.name = …), or to anything reached fromtz,page,device, or another provided name. Item assignment on your own dicts and lists (row["status"] = "done") is fine; .format()on anything other than a plain string literal.
if, for, while, try/except, with, comprehensions, and f-strings are
all allowed. assert condition, "message" fails the step with your message.
Data and variables
| Construct | Returns or does |
|---|---|
tz.testdata (also tz.test_data) |
Attached test data. Read fields as attributes or keys: tz.testdata.account.name |
tz.environment |
The attached environment; current values under tz.environment.current |
tz.input |
Values passed in by a suite |
tz.output |
Outputs saved so far in this run, and outputs received from earlier tests |
tz.temp |
Temp values saved so far in this run |
tz.knowledge |
Attached knowledge bases |
tz.loop |
Inside For each: item, index (from 0), and iteration (from 1) |
tz.runtime |
Run facts such as the resolved time zone |
tz.setTemp(name, value) |
Keep a value for later steps in this run |
tz.setOutput(name, value) |
Publish a value with the run, for the next test in a suite |
tz.saveToFile(file, path, value) |
Merge value at path ("$.a.b", or "$" with a dict) into a JSON file published with the run; later steps read it as tz.output[<file name>] |
tz.pick(value, path, default=None, required=False) |
Read one field from a response or query result: tz.pick(result, "records[0].Id"). A missing field gives default, or fails the step when required=True |
tz.log(message) |
Write a line to the step's log. Known secrets are blanked |
record = tz.salesforce.lookupRecord("Account", "Name", tz.testdata.account.name)
tz.setTemp("account_id", record["Id"])
tz.setOutput("account_id", record["Id"])Dates and times
| Construct | Returns |
|---|---|
tz.date(days=0, months=0, years=0, fmt="%Y-%m-%d", zone="") |
Today, or a date moved from today, as text |
tz.now(days=0, hours=0, minutes=0, fmt="%Y-%m-%d %H:%M", zone="") |
The current date and time, or one moved from now, as text |
Both are worked out each time the step runs, so a saved step always uses the
current date. "Today" is in the browser's time zone unless zone names one
("America/New_York"). Months and years move first and keep the day where they
can (31 January plus one month is the last day of February), then days.
due = tz.date(30, fmt="%m/%d/%Y")Files
| Construct | Returns or does |
|---|---|
tz.read(name, kind=None) |
The contents of an attached file: CSV, TSV, and XLSX as a list of row dicts; JSON, YAML, and XML parsed; PDF and text as a string |
tz.file(name) |
The local path of an attached file, for uploads |
tz.files |
Every attached file, by name |
tz.download(page, locator, name="download") |
Click locator, capture the download, and save it as a run output. Pass device instead of page on a mobile test |
tz.verifyFile(name, kind, encrypted=None) |
Check that a downloaded file is the expected kind (and, optionally, encrypted) |
tz.saveFileOutput(name, path) |
Publish a file the step produced as a run output |
tz.setTemp("rows", tz.read("accounts.csv"))
page.get_by_label("Upload").set_input_files(tz.file("contract.pdf"))Browser helpers
These take a Playwright page or locator, so they work only on steps with
Needs browser to run on.
| Construct | Does |
|---|---|
tz.typeInto(locator, value) |
Replace a field's text the way a user does: clear it, then send real keystrokes. Lookup and search fields need real keystrokes to react |
tz.typeCode(boxes, code) |
Type a one-time code into a row of one-character boxes, one character per box |
tz.wait_for_page(page, timeout_ms=30000, url=None, visible=None, hidden=None, text=None) |
Wait until the page is ready: loaded, no spinner, no request in flight, nothing still moving, plus any condition you pass |
tz.click_opens_tab(locator, button="left") |
Click a control that opens a new tab and return that tab |
tz.switch_tab(page, url="") |
Bring forward the tab showing url |
tz.copy_text(page, text) |
Copy text the way the user did, so a later paste types it |
tz.assertPageText(page, text, present=True, timeout=5) |
Pass when text is on the page (frames included), or absent when present=False |
tz.compareScreen(page, reference, title) |
Compare the page with an image attached to the test; fail when they differ |
tz.checkVisual(page, feature, title) |
Fail unless the page shows the described feature (an icon, a colour, a layout) |
tz.compareValues(left, right, operator) |
Fail unless the two values compare: equals, not_equals, contains, not_contains, starts_with, ends_with |
Playwright's own page and expect APIs work as usual:
page.get_by_role("button", name="Save").click()
expect(page.get_by_text("Account was created")).to_be_visible()Salesforce: tz.salesforce
Calls run against the Salesforce org connected to the test's environment, through the API, so they work with Needs browser to run off. The step's proof labels such a step SOQL, Apex, or Advanced.
| Construct | Does |
|---|---|
soql(query) |
Run a SOQL query, every page of it. Returns {totalSize, done, records} |
soqlQuery(query) |
The rows only (or the count, for a bare COUNT() query) |
executeAnonymous(apex) |
Run Anonymous Apex. A compile error or exception fails the step |
rest(method, path, body=None, params=None, headers=None) |
Any Salesforce REST call. A path without /services/ is relative to the org's REST API version |
describe(object_name) |
Fields, relationships, and picklists of one object |
findObjects(text, custom_only=False, limit=…) |
Objects whose API name or label matches text, best first |
createRecord(object_name, fields) |
Create a record and read it back; fails if a field does not match |
updateRecord(object_name, record_id, fields) |
Change fields and read them back |
deleteRecord(object_name, record_id) |
Delete a record and confirm it is gone |
lookupRecord(object_name, field, value) |
The one record whose field equals value |
changeUserProfile(user, profile) |
Set a user's profile and read it back |
loginAs(page, user_url) |
Log the browser in as another user, and make API calls as that user too |
useBrowserSession(page) |
Make API calls as whoever the browser is logged in as |
restoreSession() |
Make API calls as the connected user again |
resetAuthSession(page) |
Put the browser and API calls back on the original user without logging out |
logout(page) |
Log the browser out of the org |
org(name_or_id) |
The same helpers against another connected org |
instanceUrl(), apiVersion() |
The org's instance URL and REST API version |
result = tz.salesforce.soql(
f"SELECT Id, StageName FROM Opportunity WHERE Name = '{tz.testdata.deal.name}'"
)
assert result["totalSize"] == 1, "expected exactly one opportunity"
assert result["records"][0]["StageName"] == "Closed Won"Values placed outside quotes in SOQL or Apex must be a number, true/false,
null, a date, or a record Id. Anything else is rejected; put text inside
quotes.
HTTP APIs: tz.api
| Construct | Does |
|---|---|
tz.api.request(method, url, params=None, body=None, body_mode="", headers=None, auth_type="", auth_value=None, expect_status=None, check_status=True, json_body=None) |
Send one request and return the parsed body |
tz.api.get, post, put, patch, delete, head, options |
Shortcuts for request with that method and the same keyword arguments |
body_mode:json,urlencoded,multipart,raw, orbinary.auth_type:basic,bearer,api_key,jwt,form_login,salesforce, orbrowser(reuse the browser session's cookies).- A relative
urlis resolved against the API base URL stored on the environment. - A response outside 2xx fails the step unless you pass
expect_statusorcheck_status=False.
order = tz.api.post(
"/orders",
json_body={"sku": tz.testdata.order.sku, "qty": 1},
auth_type="bearer",
auth_value=tz.environment.current.api_token,
expect_status=201,
)
tz.setOutput("order_id", tz.pick(order, "id", required=True))SQL databases: tz.sql
| Construct | Does |
|---|---|
tz.sql.query(connection_string, query, params=None, schema_name=None) |
Run a read-only SELECT or WITH query with named parameters |
tz.sql.describe(connection_string, table=None, schema=None) |
List tables, or the columns of one table |
Sign-in, MFA, and email
| Construct | Does |
|---|---|
tz.auth.login(name="", via=None) |
Sign in with the environment's login flow name (the only one when blank), by form replay or front door |
tz.auth.logout() |
Sign out, clear cookies and storage, and restore API calls |
tz.mfa.totp(name) |
A fresh authenticator code from the environment's TOTP authentication |
tz.email.otp(sender="", subject="", mailbox="", timeout=…, reuse=False) |
Wait for a new email and return its one-time code |
tz.email.latest(sender="", subject="", mailbox="", timeout=…) |
Wait for a new email and return it |
tz.email.fetch(sender="", subject="", mailbox="", max_results=…) |
List recent emails, newest first, without waiting |
tz.email.attachment(message_id, attachment_id, file_name, mailbox="") |
Download an attachment from a fetched email and return its path |
code = tz.email.otp(subject="Your verification code")
tz.typeCode(page.locator("input.otp-digit"), code)Security scans: tz.security
| Construct | Does |
|---|---|
tz.security.scan(target_url, tags, headers=None, open_api_spec=None) |
Scan a URL you name with the selected scanner templates |
tz.security.scanOpenApi(spec_path, tags, headers=None) |
Scan the endpoints described by an OpenAPI file |
tz.security.templates(tags) |
List the templates that match tags, without sending requests |
Device: tz.device
Available on steps with Needs device to run on. A locator is a resource-id, an accessibility id, or visible text.
| Construct | Does |
|---|---|
launch(package=""), close(package="") |
Bring an app to the foreground, or stop it; blank means the session's own app |
isForeground(package="") |
Whether the app owns the screen |
tap(locator), doubleTap(locator) |
Tap a control |
type(locator, text, clear=True) |
Type into a field |
find(locator), locate(locator) |
Resolve a control (locate searches the current screen) |
reveal(locator) |
Scroll until the control is on screen |
isVisible(locator), assertVisible(locator), text(locator) |
Read or check a control |
waitFor(locator, timeout, gone=False) |
Wait for a control to appear, or to leave |
assertText(text, present=True) |
Pass when text is on the screen, or absent |
scrollDown(fraction), scrollUp(fraction), dragTo(locator, target) |
Scroll and drag |
setSlider(locator, value) |
Set a slider to a value |
pressKey(key), back(), hideKeyboard() |
Hardware keys: enter, back, home, tab, search, delete |
upload(locator, file_path) |
Attach a test-data file through the control that opens the file picker |
download(locator, name), fetch(locator) |
Save a file from the app and bring it back as a run output |
useWebview(match), useNative(), context() |
Switch between the app's native controls and a webview |
setOrientation(orientation), orientation() |
Rotate to portrait or landscape |
setLocation(latitude, longitude, altitude), location() |
Set or read the device's GPS position |
compareScreen(reference, title), checkVisual(feature, title) |
Visual checks, as on the web |
wait(seconds) |
Pause for a fixed time |
tz.device.launch()
tz.device.tap("Sign in")
tz.device.type("username", tz.testdata.user.email)
tz.device.assertText("Welcome")Tokens in English steps
English instructions reference the same data with [$.…] tokens:
[$.testdata.…], [$.environment.…], [$.input.…] (also [$.params.…]),
[$.temp.…], [$.output.…] (also [$.outputs.…]), [$.loop.…], and
[$.knowledge.…]. See Use variables, not literals.