Playwright Python Test Generation Instructions
Write resilient Playwright tests using role-based locators, web-first assertions, and clear pytest organisation.
Code Quality Standards
Locators
- •Prioritise user-facing, role-based locators for resilience and accessibility:
- •
get_by_role(),get_by_label(),get_by_text(),get_by_placeholder()
- •
- •Avoid fragile CSS selectors or XPath unless no role-based alternative exists
Assertions
- •Use auto-retrying web-first assertions via the
expectAPI:- •
expect(page).to_have_title(...)✅ - •
expect(locator).to_have_text(...)✅ - •
expect(locator).to_be_visible()— use only when testing visibility change specifically
- •
- •Prefer
expectover plainassertfor UI tests
Timeouts
- •Rely on Playwright's built-in auto-waiting mechanisms
- •Never add
time.sleep()or hardcoded waits - •Never increase default timeouts unless absolutely required and documented
Clarity
- •Use descriptive test titles:
def test_navigation_link_navigates_to_doc_page(): - •Add comments only to explain complex logic — not to describe simple actions like "click a button"
Test Structure
Imports
Every test file must begin with:
python
from playwright.sync_api import Page, expect
Fixtures
- •Use
page: Pagefixture as argument in test functions - •Place shared setup in standard Pytest fixtures
- •Navigation (
page.goto()) goes at the beginning of each test function
File Organisation
- •Location:
tests/directory (or follow existing project structure) - •Naming:
test_<feature-or-page>.py— required for Pytest discovery - •Scope: One test file per major application feature or page
Assertion Reference
| Scenario | Assertion |
|---|---|
| Element count | expect(locator).to_have_count(n) |
| Exact text | expect(locator).to_have_text("exact") |
| Partial text | expect(locator).to_contain_text("partial") |
| URL check | expect(page).to_have_url("https://...") |
| Title check | expect(page).to_have_title(re.compile("...")) |
| Visibility | expect(locator).to_be_visible() |
Example Test File
python
import re
import pytest
from playwright.sync_api import Page, expect
@pytest.fixture(scope="function", autouse=True)
def before_each_after_each(page: Page):
page.goto("https://example.com/")
def test_has_title(page: Page):
expect(page).to_have_title(re.compile("Example"))
def test_get_started_link(page: Page):
page.get_by_role("link", name="Get started").click()
expect(page.get_by_role("heading", name="Installation")).to_be_visible()
def test_navigation_link_works(page: Page):
page.get_by_role("navigation").get_by_role("link", name="Docs").click()
expect(page).to_have_url(re.compile(r"/docs"))
Test Execution Strategy
- •Execution: Run from terminal using
pytestorpytest tests/ - •Debug Failures: Analyse test failures, identify root causes
- •Trace Viewer: Use
--tracing=onflag for visual failure debugging - •Screenshots: Capture on failure with
page.screenshot(path="failure.png")