Overview
The Run Python step lets you execute custom Python code within a test with full Playwright access. Use it for complex logic, validations, data processing, and API/UI cross‑checks.Note
- Do not use double braces
{{ }}inside this step. Instead,env,vars, andrandomare provided directly as in‑memory objects.env.NAMEis read‑only,vars.name(aliastestVars.name) contains values produced by earlier steps, andrandom.*provides generators.
Execution model
- Wrap code in
async def supatest_run_code(...): - Runs in the test’s browser context with Playwright available; always
awaitasync calls - Optional inputs come from selected variables; the function’s
returnvalue is saved to a named variable - Uses the step timeout; prefer explicit waits over fixed delays
print()output appears in Raw Logs; failures include stack traces when available
Capabilities and globals
Available during execution:- Playwright:
page,expect - Networking:
fetch(JSON/ArrayBuffer) - Supatest:
env,update_env(name, value),vars(aliastestVars),random
Special Supatest functions
AI-powered functions available in the runtime:ai_assertion(user_instruction): Performs AI-powered visual assertions on the current page. ReturnsTrueif assertion passes, raisesExceptionif it fails.ai_condition(condition_prompt): Evaluates a condition using AI to determine if it’s true or false. Returnsbool.ai_browser_action(user_prompt): Executes browser automation tasks using AI agent. Returns a dict withsuccess,is_done,execution_time, etc.
Utility functions
One-line helper functions available in global scope: Date & Time:now(): Current datetimetoday(): Current datetimestamp(): Unix timestamptimedelta(days=...): Create time deltasformat_date(date_obj, fmt="%d/%m/%Y"): Format dates
uuid(): Generate random UUIDmd5(text): MD5 hashsha256(text): SHA256 hashhmac_sha256(key, msg): HMAC signatureb64encode(text)/b64decode(text): Base64 operationsurlencode(text)/urldecode(text): URL encoding/decodingslugify(text): Convert text to slug
randint(min, max): Random integerchoice(list): Pick random itemsample(list, k): Pick k random items
Available libraries
Standard Library (always available):asyncio, json, re, csv, io, os, sys, tempfile, time, datetime, pathlib, urllib.parse, base64, hashlib, random, string, collections, itertools, functools, typing
Third-party (pre-imported):
playwright.async_api: Full Playwright async APIfaker: Faker class for generating test datapytest: Test framework utilities
aiofiles: Async file I/O operationsaiohttp: HTTP requests (useClientSessionfor async operations)ssl,certifi: SSL/TLS certificate handlingasyncpg: PostgreSQL database connectionsmotor: MongoDB database connections (import asmotor.motor_asyncio)beautifulsoup4: HTML parsing (import asbs4)pydantic: Data validation and parsing
Environment variables
env.KEYis a read‑only view of the selected environment at the start of the run.update_env(name, value)persists changes to existing variables in the selected environment (org‑scoped).- Missing or failed updates cause the test to fail.
- Raw Logs show per‑call queued updates and one final summary.
When to use
- Conditional validations, loops, data transforms
- Compare UI state with API responses
- Temporary workaround when no dedicated step exists
Usage (form + editor)
- Title: short, descriptive
- Code: write inside
async def supatest_run_code(...):with Monaco editor syntax highlighting - Variables (optional): select earlier variables to become function parameters
- Return variable (optional): name for
returnvalue to use in later steps - Timeout (optional): override default
AI code generation
- Prompt in plain English; code respects Playwright best practices
- Refine with follow‑ups; review and edit before running
Examples
Minimal examples you can adapt:Basic page interaction
API and UI comparison
Using env, vars, and random (no {{ }} required)
AI-powered assertions and actions
Using utility functions
Response Format
When you specify a Return variable name (e.g.,pythonResult), the value returned by your function is stored and can be accessed in subsequent steps.
Simple Values
"success"
Access in later steps: ${pythonResult} → "success"
Numbers
42
Access in later steps: ${pythonResult} → 42
Objects (Dictionaries)
- User ID:
${pythonResult.userId}→123 - Email:
${pythonResult.email}→"[email protected]" - Active status:
${pythonResult.active}→true
Arrays (Lists)
- First item:
${pythonResult[0]}→"apple" - Array length:
${pythonResult.length}→3
Complex Nested Data
- API user name:
${pythonResult.api.name} - UI display name:
${pythonResult.ui.displayName} - Verification result:
${pythonResult.match}
Download file and parse CSV
Note File downloads will not work when running tests in the interactive editor due to limitations with remote browsers. However, they will work when running tests in headless mode from the test details page or in plans.
Best practices
- Structure: single entry
supatest_run_code, return only what later steps need - Selectors: prefer stable attributes; avoid brittle position‑based locators
- Waits: use Playwright waits (visible/attached/navigation) instead of fixed timeouts
- Assertions: prefer
expect(...)over manual checks - Performance: keep code concise; minimize unnecessary DOM queries and network calls
Common issues and fixes
- Not wrapped in
supatest_run_code→ wrap all logic inasync def supatest_run_code(...): - Missing
await→ await Playwright and promise calls - Return value not saved → set a Return variable name and ensure you
returnit - Timeouts → add explicit waits or increase step timeout
- Unreliable selectors → use more specific, stable attributes (e.g., data‑testid)
Third Party Libraries
The runtime includes several third-party libraries for common tasks. See the Available libraries section above for the complete list.Setting up environment variables for database connections
Before using database connections in your Run Python steps, you need to configure the necessary credentials:- Add environment variables: Go to your Supatest environment settings and add the required connection strings and credentials (e.g.,
DATABASE_URLfor PostgreSQL,MONGODB_URLandMONGODB_DATABASEfor MongoDB). - Select the environment: Make sure the correct environment is selected before running your test, as the code will access these variables using
env.VARIABLE_NAMEorenv['VARIABLE_NAME']syntax. - Access in code: Use
env.DATABASE_URL,env.MONGODB_URL, etc. to access your configured credentials within the Run Python step.
Example: Query PostgreSQL with asyncpg
Example: Query MongoDB with motor
Example: Parse CSV from API using aiofiles + csv
Example: Stream parse a local CSV file using aiofiles
We will expand this list over time with additional approved Python libraries.

