Playwright Python Cheat Sheet (pytest-playwright, 2026)

Everything from this course on one page, for quick revision and for the moment you forget the exact name of an option. Each block shows the Python syntax you need most often, with a link to the lesson that explains it. The examples use the SQA Tools practice sites, and the complete test at the end was run with Playwright 1.65 and pytest-playwright 0.10.

📖 What You’ll Learn: install and project commands, pytest-playwright command-line options, locators, actions, assertions and timeouts, waiting for events, fixtures and context options, devices, storage state, network routes and HAR, API requests, frames, dialogs, tabs, downloads, tracing and debugging, parallel runs, reports and a CI snippet.


📦 Install and Project

⌨️ Terminal

python -m venv .venv
.venv\Scripts\activate                      # macOS/Linux: source .venv/bin/activate
pip install pytest-playwright               # playwright + pytest + pytest-base-url
playwright install --with-deps chromium     # or: playwright install (all browsers)
playwright codegen https://sqatools.in/dummy-ecommerce-website/
# pytest.ini
[pytest]
addopts = --base-url https://sqatools.in --strict-markers -ra
markers =
    smoke: quick checks

Lessons: 2, 6, 7.


⌨️ pytest-playwright Options

Option Example
Browser(s) --browser firefox --browser webkit
Branded browser --browser-channel chrome / msedge
Watch it --headed --slowmo 500
Device --device "Pixel 7"
Base URL --base-url https://qa.example.com
Artifacts --tracing retain-on-failure --screenshot only-on-failure --video retain-on-failure --output test-results
Select -k login, -m smoke, --lf, -x, path::test_name
Parallel -n auto (pytest-xdist)
Retries --reruns 2 (pytest-rerunfailures)
Reports --html=report.html --self-contained-html, --alluredir=allure-results, --junitxml=junit.xml

🎯 Locators

page.get_by_role("button", name="Log in", exact=True)
page.get_by_label("Email")
page.get_by_placeholder("Search for t-shirts")
page.get_by_text("Coupon SAVE10 applied.")
page.get_by_test_id("cart-count")                  # data-testid
page.locator("#price-min")                         # CSS
page.locator("xpath=//table//tr[2]")               # XPath (last resort)

cards = page.get_by_test_id("product-card")
cards.filter(has_text="Wireless Earbuds").get_by_role("button", name="Add to cart")
cards.first, cards.last, cards.nth(2), cards.count(), cards.all()
page.frame_locator("#sampleIframe").get_by_role("link")

Lessons: 31, 32.


🖱️ Actions

page.goto("/dummy-ecommerce-website/#/login")      # relative to base_url
locator.click(); locator.dblclick(); locator.hover()
locator.fill("testuser"); locator.clear(); locator.press("Enter")
locator.press_sequentially("earbuds", delay=50)
locator.check(); locator.uncheck(); locator.set_checked(True)
locator.select_option("price-asc"); locator.select_option(label="Price: low to high")
locator.set_input_files("report.pdf")
locator.drag_to(target)
locator.tap()                                      # needs has_touch
page.keyboard.press("Control+A"); page.mouse.wheel(0, 500)

Lesson: 33.


✅ Assertions (auto-retrying)

from playwright.sync_api import expect

expect(page).to_have_url(re.compile(r"#/cart$"))
expect(page).to_have_title(re.compile("SQA Tools"))
expect(locator).to_be_visible() / to_be_hidden() / to_be_enabled() / to_be_checked()
expect(locator).to_have_text("−₹500") / to_contain_text("applied")
expect(locator).to_have_text(["A", "B"])           # list: count + order + text
expect(locator).to_have_value("2") / to_have_count(3) / to_have_attribute("aria-expanded", "true")
expect(locator).not_to_be_empty()
expect(locator).to_have_text("x", timeout=10_000)  # one assertion
expect.set_options(timeout=7_000)                  # all assertions
expect(api_response).to_be_ok()

Lessons: 37, 38.


⏳ Waiting for Events

with page.expect_response("**/api/products*") as info:
    page.get_by_role("button", name="Reload").click()
data = info.value.json()

with page.expect_request("**/echo") as req: ...
with page.expect_download() as dl: ...; dl.value.save_as("file.csv")
with page.expect_popup() as popup: ...; new_page = popup.value
page.on("dialog", lambda d: d.accept())
page.on("console", lambda m: print(m.type, m.text))
page.wait_for_url(re.compile("dashboard"))
locator.wait_for(state="visible")

🧩 Fixtures and Context Options

import pytest

@pytest.fixture(scope="session")
def browser_context_args(browser_context_args, playwright):
    return {**browser_context_args,
            **{k: v for k, v in playwright.devices["Pixel 7"].items() if k != "default_browser_type"},
            "locale": "en-IN", "timezone_id": "Asia/Kolkata",
            "geolocation": {"latitude": 18.52, "longitude": 73.85}, "permissions": ["geolocation"],
            "color_scheme": "dark"}

@pytest.fixture(scope="session")
def browser_type_launch_args(browser_type_launch_args):
    return {**browser_type_launch_args, "slow_mo": 100}

@pytest.mark.skip_browser("webkit")
@pytest.mark.only_browser("chromium")
@pytest.mark.browser_context_args(locale="hi-IN")

Lessons: 41, 42, 43, 50.


🔐 Login Once (storage state)

context.storage_state(path=".auth/user.json")                 # after logging in
browser.new_context(storage_state=".auth/user.json")          # start logged in
context.set_storage_state(".auth/user.json")                  # switch an existing context
context.add_init_script("sessionStorage.setItem('k', 'v')")   # sessionStorage is not saved

Lesson: 51.


🌐 Network

page.route("**/api/products*", lambda r: r.fulfill(json={"data": []}))
page.route("**/api/**", lambda r: r.fulfill(status=500))
page.route("**/*.{png,jpg}", lambda r: r.abort())
page.route(API, handler, times=1); page.unroute(API)

def handler(route):
    response = route.fetch()
    body = response.json(); body["data"][0]["price"] = 1
    route.fulfill(response=response, json=body)

page.route_from_har("api.har", url="**/api/**", update=True)    # record
page.route_from_har("api.har", url="**/api/**")                 # replay

Lessons: 52, 53.


🔌 API Testing

api = playwright.request.new_context(base_url="https://sqatools.in/wp-json/sqa-api/v1/",
                                     extra_http_headers={"X-API-Key": "sqa-key-12345"})
r = api.get("products", params={"category": "books"})
r.status, r.ok, r.json(), r.headers["content-type"]
api.post("objects", data={"name": "x"})        # JSON body
api.put(...); api.patch(...); api.delete("objects/ID")
api.dispose()
page.request.post(...)                          # shares the browser's cookies

Lessons: 54, 55.


🐞 Debug, Trace, Report

⌨️ Terminal

pytest -k coupon --headed --slowmo 500
$env:PWDEBUG = "1"; pytest -k coupon          # Inspector (PowerShell); bash: PWDEBUG=1 pytest -k coupon
pytest --lf -x --pdb
$env:DEBUG = "pw:api"; pytest -k coupon -s     # log every API call
pytest --tracing retain-on-failure
playwright show-trace test-results/<test>/trace.zip
python -m playwright trace open test-results/<test>/trace.zip
python -m playwright cli open https://sqatools.in/ --browser firefox
page.pause()                                    # Inspector at this line (headed)
context.tracing.start(screenshots=True, snapshots=True, sources=True)
context.tracing.stop(path="trace.zip")

Lessons: 61, 62, 63, 64, 70.


🚀 CI (GitHub Actions)

- uses: actions/checkout@v7
- uses: actions/setup-python@v7
  with: { python-version: "3.13", cache: pip }
- run: pip install -r requirements.txt
- run: playwright install --with-deps chromium
- run: pytest -n auto --tracing retain-on-failure --junitxml=reports/junit.xml
- uses: actions/upload-artifact@v7
  if: failure()
  with: { name: test-results, path: test-results/ }

Docker image: mcr.microsoft.com/playwright/python:v1.65.2-noble (match your Playwright version). Lessons: 66, 67, 68.


🧪 One Test That Uses Most of It

📄 pytest.ini

[pytest]
addopts = --base-url https://sqatools.in

📄 tests/test_cheat_sheet.py

import re

import pytest
from playwright.sync_api import Page, expect

SHOP = "/dummy-ecommerce-website/"


@pytest.mark.parametrize("code, discount", [("SAVE10", "−₹500"), ("FLAT200", "−₹200")], ids=["save10", "flat200"])
def test_coupon_flow(page: Page, code, discount):
    page.goto(SHOP + "#/login")                                            # relative URL
    page.get_by_test_id("login-username").fill("testuser")                 # test-id locator
    page.get_by_test_id("login-password").fill("Test@123")
    page.get_by_role("button", name="Log in", exact=True).click()          # role locator, exact name
    expect(page.get_by_test_id("account-button")).to_contain_text("Hi, Test")

    page.get_by_test_id("search-input").fill("earbuds")
    page.get_by_test_id("search-button").click()
    card = page.get_by_test_id("product-card").filter(has_text="Wireless Earbuds")
    card.get_by_role("button", name="Add to cart").click()                 # chained, filtered locator
    expect(page.get_by_test_id("cart-count")).to_have_text("1")

    page.get_by_test_id("cart-link").click()
    expect(page).to_have_url(re.compile(r"#/cart$"))
    page.get_by_test_id("coupon-input").fill(code)
    page.get_by_test_id("apply-coupon").click()
    expect(page.get_by_test_id("coupon-message")).to_have_text(f"Coupon {code} applied.")
    expect(page.get_by_test_id("coupon-discount")).to_have_text(discount)

⌨️ Terminal

pytest -v --tracing retain-on-failure

🖥️ Output

============================= test session starts =============================
platform win32 -- Python 3.15.1, pytest-9.2.0, pluggy-1.7.0 -- C:\Users\you\playwright-python\.venv\Scripts\python.exe
cachedir: .pytest_cache
baseurl: https://sqatools.in
rootdir: C:\Users\you\playwright-python
configfile: pytest.ini
plugins: allure-pytest-2.16.2, base-url-2.1.0, bdd-9.0.1, html-4.2.0, metadata-3.1.1, playwright-0.10.0, rerunfailures-16.7, xdist-3.8.0
collecting ... collected 2 items

tests/test_cheat_sheet.py::test_coupon_flow[chromium-save10] PASSED      [ 50%]
tests/test_cheat_sheet.py::test_coupon_flow[chromium-flat200] PASSED     [100%]

============================== 2 passed in 6.54s ==============================

🏋️ Practice Exercises

Try each exercise on your own first, then open the answer to compare. The answers use the same practice sites and project layout as the lesson.

Exercise 1: Without looking above, write the locator for the “Add to cart” button inside the product card that contains “Wireless Earbuds”.

Show answer
page.get_by_test_id("product-card").filter(has_text="Wireless Earbuds").get_by_role("button", name="Add to cart")

Exercise 2: Write the one-line command that runs the smoke tests in Firefox and WebKit in parallel and keeps traces only for failures.

Show answer
pytest -m smoke --browser firefox --browser webkit -n auto --tracing retain-on-failure

Exercise 3: Which three lines make every test in a folder start logged in from .auth/user.json?

Show answer
@pytest.fixture(scope="session")
def browser_context_args(browser_context_args):
    return {**browser_context_args, "storage_state": ".auth/user.json"}

Put it in that folder’s conftest.py (and create the file in a session fixture or a setup script first).

Exercise 4: Mock **/api/products* with an empty list and assert the page shows “0 products”.

Show answer
page.route("**/api/products*", lambda r: r.fulfill(json={"data": [], "meta": {"total": 0}}))
page.goto("/shop")
expect(page.get_by_test_id("status")).to_have_text("0 products")

🧠 MCQ Quiz: Playwright Python Cheat Sheet

10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.

  1. Which command opens Codegen for a URL?
  2. Which option keeps a screenshot only for failed tests?
  3. What does exact=True change in get_by_role(..., name="Log in", exact=True)?
  4. How do you assert three list items in order?
  5. Which call starts every new context logged in?
  6. How do you fail a network request on purpose?
  7. Which client sends API requests without a browser?
  8. How do you open a trace from the terminal as text?
  9. Which Docker image tag matches Playwright 1.65.2?
  10. Which plugin adds --reruns?

Want a longer, timed test? Take the Playwright Python mock interviews (13 modules, 20 MCQs each).


❓ Frequently Asked Questions

🤔 Can I download this cheat sheet as a PDF?

Use your browser’s Print → Save as PDF on this page; the code blocks and tables print cleanly.

🤔 Is there a cheat sheet for Playwright with TypeScript?

Yes, the Playwright TypeScript cheat sheet covers the same ground for Playwright Test.

🤔 Which versions does this cheat sheet use?

Playwright for Python 1.65, pytest-playwright 0.10, pytest 9 and Python 3.10 or newer. The API is stable across recent versions; check the release notes when upgrading.

🤔 Where do I practise these commands?

On the SQA Tools practice apps (shop, bank, booking), the practice API and the automation practice page, all used throughout this course.

🤔 What should I learn after this course?

Build one of the Module 14 projects end to end in your own repository, add CI, and then explore the AI-assisted workflows in Module 13 with your team’s application.


🏁 Summary

  • Install with pytest-playwright and playwright install; configure base URL and markers in pytest.ini.
  • Prefer role, label and test-id locators; chain and filter; assert with retrying expect.
  • Use fixtures for context options, devices and logged-in state; routes and HAR for the network; APIRequestContext for APIs.
  • Debug with headed runs, PWDEBUG, traces and the trace CLI; report with pytest-html, Allure and JUnit.
  • Run in parallel with xdist and in CI with pinned versions and failure artifacts.

🎬 Watch the Playwright tutorial series on YouTube!

Subscribe to SqaToolsByDY • Practice on the SQA Tools Automation Practice Page

pytest Interview Questions and Answers for Automation Testers (2026)

pytest is the backbone of almost every Python test automation framework, so interviews for Playwright, Selenium and API roles all include pytest questions. This page covers the questions that come up most, from discovery rules and assert rewriting to fixture scopes, conftest.py, parametrization, markers, hooks, plugins and CI, each with a short answer and code where it helps. A runnable example at the end shows fixture order and scopes in action, because “explain what this prints” is a favourite interview task.

📖 What You’ll Learn: how to answer questions on test discovery and naming, assert rewriting, fixtures, yield teardown and scopes, autouse, conftest.py, fixture overriding, parametrize, ids and pytest.param, parametrized fixtures, markers, skip and xfail, configuration files and addopts, command-line selection, hooks such as pytest_addoption and pytest_runtest_makereport, plugins, output capture, tmp_path, monkeypatch, caplog, parallel runs, and reading fixture order.


🔍 Basics and Discovery

  1. Why pytest instead of unittest?

Plain functions and assert instead of classes and self.assertEqual; powerful fixtures with dependency injection and scopes; parametrization; markers; a large plugin ecosystem (pytest-playwright, xdist, html, rerunfailures). pytest also runs existing unittest tests. (Lesson 24)

  1. How does pytest find tests?

By default it collects files named test_*.py or *_test.py, functions named test_*, and methods named test_* in classes named Test* without an __init__. testpaths, python_files, python_classes and python_functions in the config change these rules.

  1. What is assertion rewriting?

pytest rewrites assert statements in test modules (and conftest/plugins) at import time so a failure shows the compared values, for example assert 3 == 4 explains both sides and diffs for lists and dicts. That is why plain assert is enough.

  1. How do you check that code raises an exception?

with pytest.raises(ValueError, match="must be positive"):
    set_price(-1)

match is a regular expression searched in the message; excinfo.value gives the exception object.

  1. How do you compare floating point numbers?

assert total == pytest.approx(10.3) (relative tolerance 1e-6 by default), or use Decimal for money.


🧩 Fixtures

  1. What is a fixture?

A function decorated with @pytest.fixture that provides a resource or state to tests that list it as an argument. pytest resolves dependencies between fixtures automatically (dependency injection). (Lesson 25)

  1. How does teardown work in fixtures?

Code after yield runs after the test, whether it passed or failed:

@pytest.fixture
def temp_user(api):
    user = api.create_user()
    yield user
    api.delete_user(user["id"])

request.addfinalizer(fn) is the older alternative.

  1. What scopes exist, and when do you use each?

function (default, fresh per test), class, module, package, session. Use wider scopes for expensive, read-only resources (a browser, an API client, a login state), and function scope for anything a test can change (a page, a cart).

  1. Can a function-scoped fixture use a session-scoped one? And the reverse?

Yes; a fixture may depend on fixtures with the same or wider scope. The reverse raises a ScopeMismatch error, because a session fixture would outlive the function fixture it depends on.

  1. What does autouse=True do?

The fixture runs for every test in its scope without being requested. Use it sparingly, for cross-cutting concerns such as attaching logs or setting timeouts.

  1. What is conftest.py?

A file whose fixtures and hooks are available to all tests in its directory and below, without imports. Layer them: shared fixtures at tests/, UI fixtures in tests/ui/, and so on. (Lesson 26)

  1. How can you override a fixture?

Define a fixture with the same name closer to the test (a sub-folder conftest, the test module or class). It can request the original by the same name, for example def browser_context_args(browser_context_args): return {**browser_context_args, ...}.

  1. What is the factory-as-fixture pattern?

The fixture yields a function that creates objects on demand and remembers them for clean-up, so one test can create several. (Lesson 58)

  1. Which built-in fixtures do you know?

tmp_path and tmp_path_factory (temporary folders), monkeypatch (patch attributes, environment variables, sys.path), capsys/capfd (captured output), caplog (log records), request (information about the requesting test), pytestconfig, record_property.

  1. How do you get information about the current test inside a fixture?

Through request: request.node.name, request.node.get_closest_marker("slow"), request.param in parametrized fixtures, request.getfixturevalue("name") for dynamic fixtures, request.config for options.


🎛️ Parametrization

  1. How do you run one test with several inputs?

@pytest.mark.parametrize("a, b, total", [(1, 2, 3), (2, 2, 4)])
def test_add(a, b, total):
    assert a + b == total

Each tuple becomes its own test. (Lesson 27)

  1. How do you name parametrized cases and mark one of them?

pytest.param(..., id="negative", marks=pytest.mark.xfail(reason="bug 123")), or ids=[...] / ids=function on the decorator.

  1. What happens when you stack two parametrize decorators?

pytest runs the cross product: 3 values × 4 values = 12 tests.

  1. What is a parametrized fixture?

@pytest.fixture(params=["admin", "viewer"]): every test that uses it runs once per parameter, available as request.param. Good for running many tests under several setups. (Lesson 45)

  1. What is pytest_generate_tests?

A hook that can call metafunc.parametrize(...) at collection time, for example to build cases from a command-line option or a file.


🏷️ Markers and Selection

  1. What are markers and how do you register them?

Labels on tests (@pytest.mark.smoke). Register them under markers in the config, and use --strict-markers so typos fail. Select with -m "smoke and not slow". (Lesson 28)

  1. skip vs skipif vs xfail?

skip always skips with a reason; skipif(condition, reason=...) skips conditionally (OS, version, environment); xfail runs the test but expects failure (known bug), and strict=True turns an unexpected pass into a failure.

  1. How do you run a single test or a subset?

A node id (pytest tests/test_cart.py::test_coupon[save10]), -k "coupon and not flat200" (name expression), -m smoke (markers), --lf (last failed), --ff (failed first), -x (stop at first failure), --maxfail=3.


⚙️ Configuration, Hooks and Plugins

  1. Where can pytest configuration live?

pytest.ini, pyproject.toml ([tool.pytest.ini_options]), tox.ini or setup.cfg. Only one file is used: the first found walking up from the arguments, with pytest.ini taking precedence. (Lesson 29)

  1. What is addopts?

Options added to every run, such as --strict-markers -ra --base-url=.... PYTEST_ADDOPTS adds more from the environment, and -o addopts="" clears it for one run.

  1. How do you add a custom command-line option?

def pytest_addoption(parser):
    parser.addoption("--env", default="qa", choices=["qa", "staging"])

in the root conftest.py or a plugin, then read it with request.config.getoption("--env"). (Lesson 30)

  1. Which hooks have you used?

pytest_addoption, pytest_configure, pytest_collection_modifyitems (add markers, reorder, skip), pytest_runtest_makereport (attach screenshots, record outcomes), pytest_report_header, pytest_sessionstart/finish.

  1. How do you take a screenshot only when a UI test fails?

A wrapper hook records the call outcome on the item; a fixture or the hook itself uses the open page:

@pytest.hookimpl(wrapper=True)
def pytest_runtest_makereport(item, call):
    report = yield
    if report.when == "call" and report.failed and "page" in item.funcargs:
        item.funcargs["page"].screenshot(path=f"failures/{item.name}.png")
    return report

pytest-playwright also offers --screenshot only-on-failure. (Lesson 63)

  1. Name plugins you use in a Playwright project.

pytest-playwright, pytest-base-url, pytest-xdist (parallel), pytest-rerunfailures (retries), pytest-html and allure-pytest (reports), pytest-bdd (Gherkin), pytest-asyncio (async tests), pytest-dotenv or python-dotenv (configuration).

  1. How do you write your own plugin?

Put hooks and fixtures in a module and register it with -p module_name, pytest_plugins = ["module"] in the root conftest, or an entry point in pyproject.toml ([project.entry-points.pytest11]) to share it as a package.


🛠️ Running and Output

  1. Why don’t I see my print() output?

pytest captures stdout and shows it only for failing tests. Use -s (or --capture=no) to see it live, or -rP to show passed tests’ output in the summary.

  1. How do you see the slowest tests?

--durations=10 lists the ten slowest setup, call and teardown phases.

  1. How do you use temporary files safely?

tmp_path gives each test its own pathlib.Path folder, cleaned up automatically after a few runs. tmp_path_factory creates folders for wider-scoped fixtures.

  1. How do you set an environment variable for one test?

monkeypatch.setenv("API_URL", "http://localhost"); it is restored after the test. monkeypatch.setattr(module, "name", value) patches attributes.

  1. How do you check that something was logged?

def test_logs_warning(caplog):
    caplog.set_level("WARNING")
    process_order(-1)
    assert "invalid order" in caplog.text

  1. How do you run tests in parallel and what breaks?

pytest -n auto with pytest-xdist. Session fixtures run once per worker, shared data and accounts collide, --pdb does not work in workers, and exactly-once setup needs a file lock. (Lesson 65)

  1. How do you retry flaky tests?

pytest-rerunfailures: --reruns 2 --reruns-delay 1, or @pytest.mark.flaky(reruns=2) per test, ideally with --only-rerun for infrastructure errors. Fix root causes; retries are a safety net. (Lesson 44)

  1. What exit codes does pytest use?

0 all passed, 1 some tests failed, 2 interrupted, 3 internal error, 4 usage error, 5 no tests collected. CI relies on them; exit code 5 often means a wrong path or marker expression.

  1. How do you produce JUnit XML for CI?

--junitxml=reports/junit.xml; record_property adds per-test properties (use junit_family = xunit1 for those). (Lesson 60)

  1. Explain the order in which fixtures run.

Higher-scoped fixtures are set up first (session, then module, then function); autouse fixtures run before requested ones of the same scope; dependencies run before the fixtures that need them; teardown happens in reverse order. The demo below proves it.


🧪 “What Does This Print?”

A classic interview task: predict the output, then run it.

📄 test_order.py

import pytest

log = []


@pytest.fixture(scope="session")
def session_res():
    log.append("session setup")
    yield
    log.append("session teardown")


@pytest.fixture(scope="module")
def module_res(session_res):
    log.append("module setup")
    yield
    log.append("module teardown")


@pytest.fixture(autouse=True)
def every_test():
    log.append("  autouse setup")
    yield
    log.append("  autouse teardown")


@pytest.fixture
def item(module_res):
    log.append("  item setup")
    yield "item"
    log.append("  item teardown")


@pytest.mark.parametrize("n", [1, 2], ids=["first", "second"])
def test_uses_item(item, n):
    log.append(f"    test {n}")


def test_last():
    print("\n" + "\n".join(log))

⌨️ Terminal

pytest test_order.py -q -s

🖥️ Output

..
session setup
module setup
  autouse setup
  item setup
    test 1
  item teardown
  autouse teardown
  autouse setup
  item setup
    test 2
  item teardown
  autouse teardown
  autouse setup
.
3 passed in 0.01s

Read it top to bottom: the session and module fixtures were set up once, before the first test that needed them; the autouse fixture wrapped every test, including test_last, which requested nothing; item was set up and torn down around each parametrized case; and the module and session teardowns have not happened yet when test_last prints, because they run after the last test of their scope.


🏋️ Practice Exercises

Try each exercise on your own first, then open the answer to compare. The answers use the same practice sites and project layout as the lesson.

Exercise 1: Write a fixture api_token (session scope) that logs in once, and a function-scoped fixture client that uses it. What happens if you make api_token function-scoped and client session-scoped?

Show answer
@pytest.fixture(scope="session")
def api_token(api):
    return api.login("admin", "admin@123")


@pytest.fixture
def client(api, api_token):
    return ApiClient(api, token=api_token)

The reverse (a session-scoped client depending on a function-scoped api_token) raises ScopeMismatch: a fixture can only depend on fixtures with the same or wider scope.

Exercise 2: Run only tests marked smoke whose names contain login but not locked, stopping at the first failure. Write the command.

Show answer
pytest -m smoke -k "login and not locked" -x

Exercise 3: A teammate’s xfail test started passing and nobody noticed. How do you make that impossible?

Show answer

Use @pytest.mark.xfail(reason="bug 123", strict=True) (or set xfail_strict = true in the config). An unexpected pass then fails the run, so the team removes the marker when the bug is fixed.

Exercise 4: Write a test that uses monkeypatch to set TEST_ENV=staging and checks that load_settings().env == "staging".

Show answer
def test_env_from_variable(monkeypatch):
    monkeypatch.setenv("TEST_ENV", "staging")
    assert load_settings().env == "staging"

monkeypatch restores the original environment after the test.


🧠 MCQ Quiz: pytest Interview Questions

10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.

  1. Which file names does pytest collect by default?
  2. What runs the code after yield in a fixture?
  3. What error do you get when a session fixture depends on a function fixture?
  4. What does pytest.param(..., marks=pytest.mark.xfail) affect?
  5. Where must pytest_addoption be defined?
  6. What does -k "cart and not coupon" select?
  7. Which built-in fixture gives each test its own temporary folder?
  8. What does exit code 5 mean?
  9. In which order are fixtures of different scopes set up?
  10. How do you see print output from passing tests?

Want a longer, timed test? Take the Playwright Python mock interviews (13 modules, 20 MCQs each).


❓ Frequently Asked Questions

🤔 How deep should my pytest knowledge be for an automation role?

Be fluent with fixtures (scopes, yield, conftest, overriding), parametrization, markers and configuration, and be able to explain one or two hooks you used in a real framework. Plugin authoring is a bonus for senior roles.

🤔 What is the most common pytest mistake interviewers look for?

Tests that depend on each other or on shared mutable state, and fixtures with the wrong scope (for example a session-scoped page). Mention isolation and scope choices explicitly in your answers.

🤔 Should I know unittest as well?

Know the differences and that pytest runs unittest tests. Most modern Python test frameworks use pytest style.

🤔 How do I practise these questions?

Take the pytest module mock interview and the Python pytest MCQ test, and rebuild one fixture-heavy example from Module 3 without looking.

🤔 What about the “what does this print” questions?

Practise with the fixture-order demo above: change scopes, add autouse, and predict the output before running it.


🏁 Summary

  • Discovery rules, assertion rewriting, pytest.raises and pytest.approx are the basics.
  • Fixtures: yield teardown, scopes and the scope rule, autouse, conftest layering, overriding and factory fixtures.
  • Parametrize with ids and per-case marks; stack for cross products; parametrized fixtures for setups.
  • Markers with strict registration, skip/skipif/xfail(strict), and selection with node ids, -k, -m, --lf.
  • Configuration and hooks (addoption, collection, makereport), plugins, output, built-in fixtures, parallel runs and fixture order.

🎬 Watch the Playwright tutorial series on YouTube!

Subscribe to SqaToolsByDY • Practice on the SQA Tools Automation Practice Page

Playwright Python Interview Questions and Answers (2026)

This page collects the Playwright with Python questions that come up in QA automation and SDET interviews, from fresher level to experienced, with short answers you can say out loud and code where it helps. Every answer links to the lesson where the topic is explained in depth, so you can revise quickly and then go deeper. Use it the night before an interview, and use the module mock interviews to test yourself under time pressure.

📖 What You’ll Learn: how to answer questions on Playwright architecture and the sync and async APIs, browsers, contexts and pages, locators and strict mode, auto-waiting and web-first assertions, pytest-playwright fixtures and options, configuration and test data, authentication and storage state, network mocking and HAR, API testing, page objects and framework design, debugging, traces and reports, parallel runs and CI, plus scenario questions with model answers.


🎯 How to Use This Page

  • Freshers: focus on the Basics, Locators and Waits sections and be ready to write a small test live.
  • 2–5 years: expect framework, fixtures, data, authentication and CI questions, and “how would you test…” scenarios.
  • Senior: expect trade-offs: flakiness strategy, parallelism, hybrid API + UI design, reporting and team practices.

Answer in three parts: what it is, how you use it (one line of code if possible), why it matters. Interviewers listen for the “why”.


🧱 Basics

  1. What is Playwright, and why use it with Python?

Playwright is an open-source browser automation library from Microsoft that drives Chromium, Firefox and WebKit through one API. With Python you combine it with pytest (via pytest-playwright) for fixtures, parametrization and plugins. Key strengths: auto-waiting, web-first assertions, isolated browser contexts, network interception, tracing and fast, reliable execution. (Lesson 1)

  1. What is the difference between the sync and async APIs?

Same classes and methods; the sync API (playwright.sync_api) blocks on each call and is the default for tests, the async API (playwright.async_api) needs await and an asyncio loop and is used inside async applications or for concurrency within one process. pytest-playwright is sync; pytest-playwright-asyncio provides async fixtures. (Lesson 69)

  1. Explain Browser, BrowserContext and Page.

A Browser is a launched browser process. A BrowserContext is an isolated, incognito-like session inside it (own cookies, storage, permissions). A Page is a tab in a context. pytest-playwright launches the browser once per session and creates a fresh context and page for each test, which is why tests are isolated and still fast. (Lesson 41)

  1. Which browsers does Playwright support, and how do you run tests in Firefox?

Chromium (Chrome, Edge), Firefox and WebKit (Safari engine), on Windows, macOS and Linux. pytest --browser firefox; repeat --browser for several; --browser-channel chrome or msedge uses the installed branded browser. (Lesson 49)

  1. How do you install Playwright for Python?

pip install pytest-playwright (installs playwright and pytest), then playwright install to download the browsers (--with-deps on Linux/CI for system libraries). (Lesson 2)

  1. What does Codegen do?

playwright codegen <url> opens a browser and records your actions as Python code with recommended locators. Use it to explore an app and find locators, then refactor the code into proper tests with assertions. (Lesson 7)


🎯 Locators and Actions

  1. Which locators does Playwright recommend, and why?

User-facing ones: get_by_role (with name), get_by_label, get_by_placeholder, get_by_text, get_by_alt_text, get_by_title, and get_by_test_id for stable test hooks. They follow how users and assistive technology see the page and survive markup changes better than CSS or XPath. (Lesson 31)

  1. What is strict mode?

Actions on a locator must match exactly one element; if several match, Playwright raises a “strict mode violation” listing the matches instead of guessing. Fix it by making the locator more specific (filter, exact=True, a parent scope) or by choosing explicitly with .first/.nth() when any match is fine. (Lesson 61)

  1. Is a locator evaluated when you create it?

No. Locators are lazy descriptions; they are resolved each time you act or assert, with auto-waiting. That is why you can define them once in page objects. (Lesson 56)

  1. How do you narrow a locator to one item in a list?

Chain and filter: page.get_by_test_id("product-card").filter(has_text="Wireless Earbuds").get_by_role("button", name="Add to cart"). filter(has=...) filters by a child locator, has_not_text excludes.

  1. When would you still use CSS or XPath?

When no user-facing attribute exists and you cannot add a test id, for example legacy markup or complex table structures. Keep them short and anchored to stable attributes, never to auto-generated classes or long absolute paths. (Lesson 32)

  1. fill() vs type() vs press_sequentially()?

fill() sets the value in one step (fast, clears first). press_sequentially() types character by character, firing key events, for inputs with per-key behaviour such as autocomplete. keyboard.type() types at the focused element. (Lesson 33)

  1. How do you handle dialogs, iframes and new tabs?

Dialogs: page.on("dialog", lambda d: d.accept()) before triggering them. Iframes: page.frame_locator("#frame").get_by_role(...) (or locator.content_frame). New tabs: with context.expect_page() as info: click() then info.value. (Lesson 34)

  1. How do you upload and download files?

Upload: locator.set_input_files("file.pdf"). Download: with page.expect_download() as info: click(), then info.value.save_as(path) and read suggested_filename. (Lesson 36)


⏱️ Waits and Assertions

  1. What is auto-waiting?

Before an action Playwright waits until the element is attached, visible, stable, enabled and receives events (actionability checks), up to the timeout. You almost never need manual waits. (Lesson 38)

  1. What are web-first assertions?

expect(locator).to_have_text(...), to_be_visible(), to_have_count() and friends retry until the condition is met or the timeout (5 s default) expires. A plain assert locator.inner_text() == ... reads once and is a common source of flakiness. (Lesson 37)

  1. Why is time.sleep() bad in Playwright tests?

It waits a fixed time: too short on slow runs (flaky) and too long on fast ones (slow suites). Use auto-waiting actions and expect; for special cases wait for an event (expect_response, wait_for_url). (Lesson 44)

  1. How do you change timeouts?

expect(locator).to_be_visible(timeout=10_000) for one assertion, expect.set_options(timeout=...) globally for assertions, page.set_default_timeout() / set_default_navigation_timeout() for actions, or --timeout style options in your fixtures. Raise them only where the app is slow by design.

  1. How do you assert a list of items?

expect(page.get_by_test_id("product")).to_have_text(["A", "B", "C"]) checks count, order and text in one retrying assertion; to_contain_text([...]) checks substrings. (Lesson 55)


🧪 pytest-playwright

  1. Which fixtures does pytest-playwright provide?

playwright, browser_type, browser, browser_name, context, page, new_context, browser_type_launch_args, browser_context_args, connect_options, plus base_url from pytest-base-url. Override browser_context_args to add context options for all tests. (Lesson 41)

  1. Which command-line options do you use most?

--headed, --slowmo, --browser, --browser-channel, --device, --base-url, --tracing, --screenshot, --video, --output. (Lesson 5)

  1. How do you run one test on mobile emulation?

pytest --device "iPhone 15" --browser webkit, or override browser_context_args with playwright.devices["Pixel 7"] for a folder of tests. (Lesson 50)

  1. How do you skip a test for one browser?

@pytest.mark.skip_browser("webkit") or @pytest.mark.only_browser("chromium"), always with a reason in the code review. (Lesson 43)


🗂️ Data, Configuration and Environments

  1. How do you make tests data-driven?

@pytest.mark.parametrize with pytest.param(..., id=...), data from JSON/CSV/Excel loaded once with a helper, or parametrized fixtures for setups such as user roles. (Lessons 45, 46)

  1. How do you keep credentials out of the code?

Environment variables, loaded from a git-ignored .env with python-dotenv locally and from CI secrets in pipelines, collected in one validated settings object with secrets hidden from repr. (Lesson 47)

  1. How do you run the same suite against QA and staging?

Relative page.goto() with base_url, a custom --env option (pytest_addoption) that loads per-environment config, and markers that block destructive tests on read-only environments. (Lesson 48)


🔐 Authentication and Network

  1. How do you avoid logging in through the UI in every test?

Log in once in a session fixture and save context.storage_state(path=...); create each test’s context with storage_state=. Each test is still isolated. Note that sessionStorage is not saved. (Lesson 51)

  1. How do you mock an API response?

page.route("**/api/products*", lambda route: route.fulfill(json={...})) registered before the request. route.abort() simulates network failure; route.fetch() plus fulfill(response=..., json=...) modifies a real response. (Lesson 52)

  1. How do you wait for and inspect a specific request or response?

with page.expect_response("**/api/orders") as info: click() then info.value.json(); for requests expect_request and request.post_data_json.

  1. What is a HAR file and how does Playwright use it?

An HTTP archive of requests and responses. page.route_from_har(path, url=..., update=True) records; without update it replays, so tests get realistic data offline. (Lesson 53)


🔌 API Testing

  1. How do you test APIs with Playwright Python?

playwright.request.new_context(base_url=...) gives an APIRequestContext with get, post, put, patch, delete; check status, json(), headers, or expect(response).to_be_ok(). End the base URL with / and use paths without a leading slash. (Lesson 54)

  1. What is the difference between page.request and a new request context?

page.request shares the browser context’s cookies (log in by API, continue in the UI); a new request context has its own isolated cookie jar. (Lesson 55)


🏗️ Framework Design

  1. How do you structure a Playwright Python framework?

pages/ (page objects and components), api/ (clients), config/ (settings), data/, tests/ split by layer, layered conftest.py files, settings in pyproject.toml with strict markers, pinned requirements. (Lesson 57)

  1. Explain the Page Object Model and one common mistake.

One class per page with locators defined once and intent-named actions that return the next page; tests keep the assertions. Common mistakes: god classes, sleeps inside page methods, returning raw strings instead of locators. (Lesson 56)

  1. Which design patterns do you use besides POM?

Factories for unique valid test data, builders for complex payloads, the factory-as-fixture pattern with clean-up, a facade for user journeys, and strategies for interchangeable login methods. (Lesson 58)

  1. How do you use BDD with Playwright Python?

pytest-bdd: Gherkin feature files bound with scenarios(), steps with @given/@when/@then and parsers.parse, target_fixture to share state, tags as markers. (Lesson 59)


🐞 Debugging, Reporting, CI

  1. How do you debug a failing test?

Read the full error (call log, actual value, aria snapshot), run it alone headed with --slowmo, step through with PWDEBUG=1 or page.pause(), inspect code with --pdb, and open the trace. (Lesson 61)

  1. What is the Trace Viewer?

A recording of actions with DOM snapshots, screenshots, console, network and source. Record with --tracing retain-on-failure, open with playwright show-trace or trace.playwright.dev, or inspect in a terminal with python -m playwright trace. (Lesson 62)

  1. Which reports do you use?

pytest-html for a single shareable file (with screenshots attached by a pytest_runtest_makereport hook), Allure for steps, history and quality gates, JUnit XML for CI dashboards. (Lessons 63, 64)

  1. How do you run tests in parallel?

pytest-xdist: pytest -n auto; each worker has its own browser and session fixtures, so data must be unique per worker and one-time setup needs a file lock. (Lesson 65)

  1. How do you run Playwright Python in CI?

Install pinned requirements, playwright install --with-deps, run pytest with traces on failure and JUnit output, upload test-results/ as an artifact, pass credentials as secrets; or use the mcr.microsoft.com/playwright/python image. (Lessons 66, 68)


💡 Scenario Questions

  1. A test passes locally but fails in CI. How do you investigate?

Get the trace and screenshot from the CI artifacts; compare with a local trace. Typical causes: timing (missing web-first assertion), different viewport or headless behaviour, environment data, missing fonts or locale, parallel runs sharing data, network to third parties. Reproduce with the same browser, --headed off, and -n setting.

  1. Your suite takes 60 minutes. How do you make it faster?

Measure first (--durations). Then: log in once with storage state, create data via API or seeded state instead of UI steps, mock slow third parties, parallelise with xdist and CI sharding, run a smoke subset per commit and the full suite nightly, and delete redundant UI tests that duplicate API coverage.

  1. How do you deal with flaky tests?

Treat flakiness as a bug: find the cause with traces (timing, shared state, test data, environment), fix it with proper waits, isolation or mocks; quarantine with a marker and a ticket while fixing; use retries (pytest-rerunfailures) only as a temporary safety net and track how often they happen. (Lesson 44)

  1. How would you automate a checkout with a payment step?

Use a test payment mode (sandbox cards), seed the cart via API or storage for most tests, cover each payment method and failure (declined card, terms not accepted), verify money as numbers, check side effects (cart emptied, order exists), and keep one full UI journey as a smoke test. (Project 2)


🧑‍💻 A Live-Coding Warm-Up

Interviewers often ask for a small test on the spot. Practise this one until you can type it in two minutes:

📄 tests/test_live.py

from playwright.sync_api import Page, expect


def test_locked_user_sees_error(page: Page):
    page.goto("https://sqatools.in/dummy-ecommerce-website/#/login")
    page.get_by_test_id("login-username").fill("lockeduser")
    page.get_by_test_id("login-password").fill("Test@123")
    page.get_by_role("button", name="Log in", exact=True).click()
    expect(page.get_by_test_id("login-error")).to_have_text("This account is locked. Please contact support.")

⌨️ Terminal

pytest -q

🖥️ Output

.                                                                        [100%]
1 passed in 3.26s

While typing, say what you do and why: “role locator with an exact name, because ‘Log in’ also appears in the page heading; a web-first assertion, so no sleeps”.


🏋️ Practice Exercises

Try each exercise on your own first, then open the answer to compare. The answers use the same practice sites and project layout as the lesson.

Exercise 1: Answer in under a minute: “Why are Playwright tests usually less flaky than Selenium tests?”

Show answer

Three built-in reasons: actions auto-wait for elements to be actionable; assertions are web-first and retry until the expected state appears; and each test runs in a fresh browser context, so state does not leak between tests. Flakiness still happens with bad test design (fixed sleeps, shared data, fragile locators), so those rules still apply.

Exercise 2: Write the code that mocks **/api/user to return {"name": "Test", "plan": "pro"} and checks the page shows “Pro plan”.

Show answer
def test_pro_plan_badge(page):
    page.route("**/api/user", lambda route: route.fulfill(json={"name": "Test", "plan": "pro"}))
    page.goto("/account")
    expect(page.get_by_text("Pro plan")).to_be_visible()

The route is registered before goto, so the first request is already intercepted.

Exercise 3: The interviewer asks: “How do you share a logged-in state across 300 tests without making them depend on each other?” Give a structured answer.

Show answer

Log in once per run (per xdist worker) in a session-scoped fixture, assert the login worked, and save context.storage_state() to a git-ignored file. Every test then gets a new context created with that state, so it starts logged in but isolated. Tests that need a guest opt out with a marker. If the app keeps its session in sessionStorage, restore it with an init script.

Exercise 4: Explain, with code, how you would assert that a table has exactly three rows with the texts “Alpha”, “Beta”, “Gamma” in order.

Show answer
expect(page.locator("table#results tbody tr")).to_have_text(["Alpha", "Beta", "Gamma"])

One retrying assertion checks the count, the order and each row’s text (use to_contain_text if rows contain more text).


🧠 MCQ Quiz: Playwright Python Interview Questions

10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.

  1. What does a BrowserContext provide?
  2. Which locator is generally preferred?
  3. What happens when a locator matches two elements and you call click()?
  4. Why prefer expect(locator).to_have_text() over assert locator.inner_text() ==?
  5. How do you reuse a login across tests?
  6. Which API mocks a network response?
  7. What does page.request share with the browser context?
  8. Which plugin runs Playwright Python tests in parallel?
  9. What is the best first step when a test fails only in CI?
  10. Which is a sound flaky-test strategy?

Want a longer, timed test? Take the Playwright Python mock interviews (13 modules, 20 MCQs each).


❓ Frequently Asked Questions

🤔 How should I prepare for a Playwright Python interview in one week?

Day 1–2: Modules 1, 4 and 5 (setup, locators, assertions). Day 3: fixtures and data (Modules 6, 7). Day 4: auth, network and API (Modules 8, 9). Day 5: framework design (Module 10). Day 6: debugging and CI (Modules 11, 12). Day 7: the mock interviews and one project.

🤔 Do interviewers expect Selenium knowledge too?

Often. Be ready to compare: Playwright’s auto-waiting, contexts, network control and tracing versus Selenium’s WebDriver protocol, explicit waits and wider legacy ecosystem. Explain when you would choose each.

🤔 Will I be asked to write code live?

Frequently: a small test, a page object, a fixture or a parametrized test. Practise the warm-up above and the practice questions of the lessons out loud.

🤔 Where can I test myself with timed questions?

In the Playwright Python mock interviews: 13 module tests with 200-question banks, 20 random questions in 20 minutes each.

🤔 What should I put in my CV?

Concrete outcomes: “Built a Playwright Python + pytest framework with 400 tests running in 12 minutes in GitHub Actions; cut flaky failures by 80% with storage-state logins and API data setup.” Link a public practice repository (for example one of the projects from Module 14).


🏁 Summary

  • Know the building blocks: browsers, contexts, pages, locators, strict mode, auto-waiting and web-first assertions.
  • Be fluent with pytest-playwright fixtures and options, data-driven tests, environments and secrets.
  • Explain storage-state logins, network mocking, HAR and API testing with short code examples.
  • Describe a framework (structure, POM, patterns, BDD) and the debugging, reporting, parallel and CI story.
  • Answer scenario questions with a method: evidence first, root cause, prevention, then speed.

🎬 Watch the Playwright tutorial series on YouTube!

Subscribe to SqaToolsByDY • Practice on the SQA Tools Automation Practice Page

“Project 4: Banking App Test Suite with Playwright Python (Data-Driven, Auth, Reports)”

Banking applications are where test automation has to be precise: two-step logins, account lockouts, transfer limits, fees and balances that must be correct to the paisa. This project tests SQA Bank, the practice net-banking site on SQA Tools, with Playwright Python. You will automate a login with a captcha and an OTP the honest way, test lockout rules, log in once per run even though the bank keeps its session in sessionStorage, drive transfers between accounts and to beneficiaries, check every limit and fee rule with data-driven tests, verify balances with Decimal, download the statement CSV and check its arithmetic, and produce an HTML report.

📖 What You’ll Learn: test design for a banking app, solving a test captcha and OTP in a fixture, field-level and page-level login errors, lockout after failed attempts, logging in once with storage_state plus restored sessionStorage, page helpers for transfers, exact money with Decimal, receipt and reference checks, data-driven transfer validation (zero amount, beneficiary limit, IMPS maximum, RTGS minimum, insufficient balance), fees on the review screen, downloading and validating a CSV statement, and an HTML report.


🏦 The Application and the Rules

SQA Bank is a client-side practice bank. Its test data is printed on the login page:

Item Value
Customer 100001 / Bank@123 (Asha Verma); 100099 is locked
Login customer ID + password + a math captcha, then a 6-digit OTP (123456)
Lockout 3 wrong passwords lock net banking
Transaction PIN 1234
Accounts Savings …0001 (₹2,45,000.50) and Current …0001 (₹8,75,500.00)
Transfer rules IMPS max ₹5,00,000 (fee ₹5), RTGS min ₹2,00,000 (fee ₹25), NEFT free, per-beneficiary limits

Every account, balance and transaction lives in the browser’s storage, so each new browser context starts from the same data: perfect for repeatable tests.

📌 Note: About the captcha. A real captcha exists to stop bots, and you should never try to defeat one on a production site. Test environments either disable it, use a fixed test answer, or (as here) a trivial practice question. In your own projects, ask developers for a test bypass instead of automating real captchas.


🗂️ Project Layout

bank-tests/
├── pytest.ini
├── conftest.py            login helpers, login-once fixtures, report screenshots
├── bank.py                page helpers: login, transfer, money parsing
└── tests/
    ├── test_login.py
    ├── test_transfers.py
    └── test_statement.py

📄 pytest.ini

[pytest]
addopts = --base-url https://sqatools.in -ra
pythonpath = .
testpaths = tests

🧰 bank.py: Helpers and Exact Money

Money is never a float in banking tests: 0.1 + 0.2 != 0.3 in binary floating point. Decimal keeps paise exact.

📄 bank.py

import re
from decimal import Decimal

from playwright.sync_api import Page, expect

APP = "/dummy-banking-website/"
CUSTOMER, PASSWORD, OTP, PIN = "100001", "Bank@123", "123456", "1234"
SAVINGS, CURRENT = "501000100001", "502000100001"


def money(text: str) -> Decimal:
    """'₹2,45,000.50' -> Decimal('245000.50')."""
    return Decimal(re.sub(r"[^\d.]", "", text))


def solve_captcha(page: Page) -> str:
    a, b = map(int, re.findall(r"\d+", page.get_by_test_id("captcha-question").inner_text()))
    return str(a + b)


def submit_credentials(page: Page, customer=CUSTOMER, password=PASSWORD, captcha: str | None = None):
    page.get_by_test_id("login-cid").fill(customer)
    page.get_by_test_id("login-password").fill(password)
    page.get_by_test_id("login-captcha").fill(captcha if captcha is not None else solve_captcha(page))
    page.get_by_test_id("login-button").click()


def login(page: Page, customer=CUSTOMER, password=PASSWORD):
    page.goto(APP)
    submit_credentials(page, customer, password)
    page.get_by_test_id("login-otp").fill(OTP)
    page.get_by_test_id("otp-submit").click()
    expect(page).to_have_url(re.compile(r"#/dashboard$"))


def balance(page: Page, account: str) -> Decimal:
    page.get_by_test_id("nav-dashboard").click()
    return money(page.get_by_test_id(f"balance-{account}").inner_text())


def start_transfer(page: Page, tab: str, amount: str, from_index: int = 0, to_index: int = 1,
                   beneficiary: str | None = None, mode: str | None = None):
    page.get_by_test_id("nav-transfer").click()
    page.get_by_test_id(f"tr-tab-{tab}").click()
    page.get_by_test_id("tr-from").select_option(index=from_index)
    if tab == "own":
        page.get_by_test_id("tr-to").select_option(index=to_index)
    if beneficiary:
        page.get_by_test_id("tr-bene").select_option(label=beneficiary)
    if mode:
        page.get_by_test_id(f"tr-mode-{mode.lower()}").check()
    page.get_by_test_id("tr-amount").fill(amount)
    page.get_by_test_id("tr-continue").click()


def confirm_with_pin(page: Page, pin: str = PIN):
    page.get_by_test_id("review-confirm").click()
    page.locator("#vf-code").fill(pin)
    page.get_by_test_id("verify-submit").click()
    expect(page.get_by_test_id("receipt")).to_be_visible(timeout=10_000)   # the bank "processes" for ~1 s

🔐 Login Tests

📄 tests/test_login.py

import pytest
from playwright.sync_api import Page, expect

from bank import APP, OTP, login, submit_credentials


def test_valid_login_shows_dashboard(page: Page):
    login(page)
    expect(page.get_by_test_id("user-bar")).to_contain_text("Welcome, Asha Verma")
    expect(page.get_by_test_id("account-tile").first).to_be_visible()


@pytest.mark.parametrize("customer, password, captcha, field, message", [
    pytest.param("12ab", "Bank@123", None, "login-cid", "Customer ID must be 6 digits.", id="bad-customer-id"),
    pytest.param("100001", "", None, "login-password", "Password is required.", id="no-password"),
    pytest.param("100001", "Bank@123", "999", "login-captcha", "Incorrect answer. Try the new question.", id="wrong-captcha"),
])
def test_field_errors(page: Page, customer, password, captcha, field, message):
    page.goto(APP)
    submit_credentials(page, customer, password, captcha)
    expect(page.locator(f"#{field}-err")).to_have_text(message)


def test_wrong_otp(page: Page):
    page.goto(APP)
    submit_credentials(page)
    page.get_by_test_id("login-otp").fill("000000")
    page.get_by_test_id("otp-submit").click()
    expect(page.locator("#login-otp-err")).to_have_text("Incorrect OTP. Please try again.")
    assert OTP != "000000"


def test_three_wrong_passwords_lock_access(page: Page):
    page.goto(APP)
    message = page.get_by_test_id("login-message")
    submit_credentials(page, password="wrong-1")
    expect(message).to_have_text("Invalid customer ID or password. 2 attempts left before your access is locked.")
    submit_credentials(page, password="wrong-2")
    expect(message).to_contain_text("1 attempt left")
    submit_credentials(page, password="wrong-3")
    expect(message).to_contain_text("locked after too many failed attempts")
    submit_credentials(page)                                               # even the right password is refused now
    expect(message).to_contain_text("locked after too many failed attempts")


def test_locked_customer(page: Page):
    page.goto(APP)
    submit_credentials(page, customer="100099")
    expect(page.get_by_test_id("login-message")).to_contain_text("locked after too many failed attempts")

⌨️ Terminal

pytest tests/test_login.py -v

🖥️ Output

============================= test session starts =============================
platform win32 -- Python 3.15.1, pytest-9.2.0, pluggy-1.7.0 -- C:\Users\you\playwright-python\.venv\Scripts\python.exe
cachedir: .pytest_cache
baseurl: https://sqatools.in
rootdir: C:\Users\you\playwright-python
configfile: pytest.ini
plugins: allure-pytest-2.16.2, base-url-2.1.0, bdd-9.0.1, html-4.2.0, metadata-3.1.1, playwright-0.10.0, rerunfailures-16.7, xdist-3.8.0
collecting ... collected 7 items

tests/test_login.py::test_valid_login_shows_dashboard[chromium] PASSED   [ 14%]
tests/test_login.py::test_field_errors[chromium-bad-customer-id] PASSED  [ 28%]
tests/test_login.py::test_field_errors[chromium-no-password] PASSED      [ 42%]
tests/test_login.py::test_field_errors[chromium-wrong-captcha] PASSED    [ 57%]
tests/test_login.py::test_wrong_otp[chromium] PASSED                     [ 71%]
tests/test_login.py::test_three_wrong_passwords_lock_access[chromium] PASSED [ 85%]
tests/test_login.py::test_locked_customer[chromium] PASSED               [100%]

============================= 7 passed in 15.26s ==============================

The lockout test changes data (the failure counter) in its own browser context, so it cannot affect other tests: the next test’s context starts with a fresh bank.


⚡ Log In Once per Run

Every transfer test needs a logged-in user, and the full login (captcha + OTP) takes several seconds. Lesson 51’s storage state helps, with one catch: SQA Bank keeps the session in sessionStorage, which storage_state() does not save (the accounts in localStorage are saved). The fixture below saves both and restores sessionStorage with an init script:

📄 conftest.py

import base64
import json

import pytest
import pytest_html
from playwright.sync_api import Browser, BrowserContext, Page

from bank import APP, login


@pytest.fixture(scope="session")
def bank_state(browser: Browser, base_url):
    """Log in once; keep localStorage (accounts) and sessionStorage (the login session)."""
    context = browser.new_context(base_url=base_url)
    page = context.new_page()
    login(page)
    state = {"storage": context.storage_state(), "session": page.evaluate("JSON.stringify(sessionStorage)")}
    context.close()
    return state


@pytest.fixture
def bank(browser: Browser, base_url, bank_state) -> Page:
    context: BrowserContext = browser.new_context(base_url=base_url, storage_state=bank_state["storage"])
    context.add_init_script(f"""
        if (location.hostname === 'sqatools.in' && !sessionStorage.getItem('sbSession')) {{
            const saved = JSON.parse({json.dumps(bank_state["session"])});
            for (const [k, v] of Object.entries(saved)) sessionStorage.setItem(k, v);
        }}""")
    page = context.new_page()
    page.goto(APP + "#/dashboard")
    yield page
    context.close()


@pytest.hookimpl(wrapper=True)
def pytest_runtest_makereport(item, call):
    """Attach a screenshot to the HTML report for failed tests (Lesson 63)."""
    report = yield
    if report.when == "call" and report.failed:
        page = item.funcargs.get("bank") or item.funcargs.get("page")
        if page is not None and not page.is_closed():
            extras = getattr(report, "extras", [])
            extras.append(pytest_html.extras.png(base64.b64encode(page.screenshot()).decode(), name="screenshot"))
            report.extras = extras
    return report

Each test gets a new context from the saved state: logged in, with the original balances, and isolated from every other test.


💸 Transfer Tests

📄 tests/test_transfers.py

import re
from decimal import Decimal

import pytest
from playwright.sync_api import Page, expect

from bank import CURRENT, SAVINGS, balance, confirm_with_pin, money, start_transfer


def test_own_account_transfer_moves_exact_amount(bank: Page):
    savings_before, current_before = balance(bank, SAVINGS), balance(bank, CURRENT)
    start_transfer(bank, "own", "1500.25")
    expect(bank.get_by_test_id("review-total-debit")).to_have_text("₹1,500.25")
    confirm_with_pin(bank)

    expect(bank.get_by_test_id("receipt-status")).to_have_text("Transfer successful")
    expect(bank.get_by_test_id("receipt-ref")).to_have_text(re.compile(r"^INT\d{14}$"))
    assert balance(bank, SAVINGS) == savings_before - Decimal("1500.25")
    assert balance(bank, CURRENT) == current_before + Decimal("1500.25")


def test_imps_fee_is_charged(bank: Page):
    savings_before = balance(bank, SAVINGS)
    start_transfer(bank, "bene", "1000", beneficiary="Priya · Demo National Bank · XXXX9012", mode="IMPS")
    expect(bank.get_by_test_id("review-charges")).to_contain_text("₹5")
    expect(bank.get_by_test_id("review-total-debit")).to_have_text("₹1,005.00")
    confirm_with_pin(bank)
    assert balance(bank, SAVINGS) == savings_before - Decimal("1005")


def test_wrong_pin_keeps_money(bank: Page):
    before = balance(bank, SAVINGS)
    start_transfer(bank, "own", "100")
    bank.get_by_test_id("review-confirm").click()
    bank.locator("#vf-code").fill("0000")
    bank.get_by_test_id("verify-submit").click()
    expect(bank.locator("#vf-code-err")).to_contain_text("Incorrect PIN")
    bank.get_by_test_id("verify-cancel").click()
    assert balance(bank, SAVINGS) == before


LANDLORD = "Landlord · Practice Bank of India · XXXX5544"
RAHUL = "Rahul · SQA Bank · XXXX0002"


@pytest.mark.parametrize("kwargs, where, message", [
    pytest.param(dict(amount="0", beneficiary=LANDLORD, mode="NEFT"), "#tr-amount-err",
                 "Enter an amount greater than zero.", id="zero"),
    pytest.param(dict(amount="250000", beneficiary=RAHUL), "#tr-amount-err",
                 "Amount exceeds the limit for this beneficiary (₹2,00,000.00).", id="beneficiary-limit"),
    pytest.param(dict(amount="600000", beneficiary=LANDLORD, mode="IMPS", from_index=1), "#tr-msg",
                 "IMPS transfers are limited to ₹5,00,000.00 per transaction. Use NEFT or RTGS.", id="imps-max"),
    pytest.param(dict(amount="50000", beneficiary=LANDLORD, mode="RTGS"), "#tr-msg",
                 "RTGS needs a minimum of ₹2,00,000.00. Use NEFT or IMPS for smaller amounts.", id="rtgs-min"),
    pytest.param(dict(amount="300000", beneficiary=LANDLORD, mode="NEFT"), "#tr-msg",
                 "Insufficient balance. Available: ₹2,45,000.50, required: ₹3,00,000.00.", id="insufficient"),
])
def test_transfer_rules(bank: Page, kwargs, where, message):
    start_transfer(bank, "bene", **kwargs)
    expect(bank.locator(where)).to_have_text(message)
    expect(bank.get_by_test_id("transfer-review")).to_have_count(0)        # never reaches the review step

⌨️ Terminal

pytest tests/test_transfers.py -v

🖥️ Output

============================= test session starts =============================
platform win32 -- Python 3.15.1, pytest-9.2.0, pluggy-1.7.0 -- C:\Users\you\playwright-python\.venv\Scripts\python.exe
cachedir: .pytest_cache
baseurl: https://sqatools.in
rootdir: C:\Users\you\playwright-python
configfile: pytest.ini
plugins: allure-pytest-2.16.2, base-url-2.1.0, bdd-9.0.1, html-4.2.0, metadata-3.1.1, playwright-0.10.0, rerunfailures-16.7, xdist-3.8.0
collecting ... collected 8 items

tests/test_transfers.py::test_own_account_transfer_moves_exact_amount[chromium] PASSED [ 12%]
tests/test_transfers.py::test_imps_fee_is_charged[chromium] PASSED       [ 25%]
tests/test_transfers.py::test_wrong_pin_keeps_money[chromium] PASSED     [ 37%]
tests/test_transfers.py::test_transfer_rules[chromium-zero] PASSED       [ 50%]
tests/test_transfers.py::test_transfer_rules[chromium-beneficiary-limit] PASSED [ 62%]
tests/test_transfers.py::test_transfer_rules[chromium-imps-max] PASSED   [ 75%]
tests/test_transfers.py::test_transfer_rules[chromium-rtgs-min] PASSED   [ 87%]
tests/test_transfers.py::test_transfer_rules[chromium-insufficient] PASSED [100%]

============================= 8 passed in 23.74s ==============================

Highlights:

  • 1500.25 (with paise) and Decimal comparisons catch rounding bugs that whole-rupee amounts would hide.
  • The IMPS test checks the fee on the review screen and in the balance afterwards: ₹1,000 + ₹5.
  • The wrong-PIN test checks a side effect: the money did not move.
  • Five business rules live in one parametrized test; each id says which rule it covers, and the last assertion makes sure an invalid transfer never reaches the review step.

📄 Statement CSV: Download and Validate

A bank statement must be internally consistent: going down the list (newest first), each row’s balance equals the next row’s balance plus a credit or minus a debit. Download the CSV after a transfer and check every row:

📄 tests/test_statement.py

import csv
from decimal import Decimal

from playwright.sync_api import Page, expect

from bank import confirm_with_pin, start_transfer


def download_statement(page: Page, tmp_path) -> list[dict]:
    page.get_by_test_id("nav-accounts").click()
    with page.expect_download() as info:
        page.get_by_test_id("download-csv").click()
    download = info.value
    target = tmp_path / download.suggested_filename
    download.save_as(target)
    print(f"\ndownloaded {download.suggested_filename}")
    with open(target, encoding="utf-8", newline="") as f:
        return list(csv.DictReader(f))


def test_statement_contains_new_transfer(bank: Page, tmp_path):
    start_transfer(bank, "own", "2500")
    confirm_with_pin(bank)
    reference = bank.get_by_test_id("receipt-ref").inner_text()

    rows = download_statement(bank, tmp_path)
    newest = rows[0]
    assert newest["Reference"] == reference
    assert newest["Type"] == "DR" and Decimal(newest["Amount"]) == Decimal("2500.00")


def test_statement_balances_are_consistent(bank: Page, tmp_path):
    rows = download_statement(bank, tmp_path)
    assert len(rows) > 3
    for newer, older in zip(rows, rows[1:]):
        amount = Decimal(newer["Amount"])
        expected = Decimal(older["Balance"]) + (amount if newer["Type"] == "CR" else -amount)
        assert Decimal(newer["Balance"]) == expected, f"row {newer['Reference']}: {newer['Balance']} != {expected}"
    print(f"checked {len(rows) - 1} balance steps")

⌨️ Terminal

pytest tests/test_statement.py -v -s

🖥️ Output

============================= test session starts =============================
platform win32 -- Python 3.15.1, pytest-9.2.0, pluggy-1.7.0 -- C:\Users\you\playwright-python\.venv\Scripts\python.exe
cachedir: .pytest_cache
baseurl: https://sqatools.in
rootdir: C:\Users\you\playwright-python
configfile: pytest.ini
plugins: allure-pytest-2.16.2, base-url-2.1.0, bdd-9.0.1, html-4.2.0, metadata-3.1.1, playwright-0.10.0, rerunfailures-16.7, xdist-3.8.0
collecting ... collected 2 items

tests/test_statement.py::test_statement_contains_new_transfer[chromium] 
downloaded statement_501000100001_2026-10-25_to_2026-11-24.csv
PASSED
tests/test_statement.py::test_statement_balances_are_consistent[chromium] 
downloaded statement_501000100001_2026-10-25_to_2026-11-24.csv
checked 11 balance steps
PASSED

============================== 2 passed in 8.84s ==============================

page.expect_download() waits for the file, download.suggested_filename keeps the bank’s name for it, and save_as() stores it in pytest’s per-test tmp_path. The consistency check is the kind of data validation that is impossible by eye and trivial in code.


📊 The Whole Suite with a Report

⌨️ Terminal

pytest -n 4 -q --html=reports/bank-report.html --self-contained-html

🖥️ Output

bringing up nodes...
bringing up nodes...

.................                                                        [100%]
- Generated html report: file:///C:/Users/you/playwright-python/reports/bank-report.html -
17 passed in 18.46s

All tests run in parallel: each one gets its own browser context and therefore its own copy of the bank’s data. Failed tests would carry a screenshot in the report thanks to the hook in conftest.py.


🧠 What This Project Practised

Skill Lessons
Two-step login with captcha and OTP in helpers 31-33, 42
Lockout rules and field vs page messages 37, 45
Login once with storage state + restored sessionStorage 51
Decimal money checks and data-driven business rules 45, 46
Downloads and CSV validation 36, 46
Parallel runs and HTML reports with screenshots 63, 65

🏋️ Practice Exercises

Try each exercise on your own first, then open the answer to compare. The answers use the same practice sites and project layout as the lesson.

Exercise 1: Add a test for a scheduled transfer: choosing “Later” with a date 100 days ahead must show “You can schedule up to 90 days ahead.” (The radio has test id tr-when-later, the date field tr-date.)

Show answer
from datetime import date, timedelta


def test_schedule_too_far(bank):
    bank.get_by_test_id("nav-transfer").click()
    bank.get_by_test_id("tr-tab-own").click()
    bank.get_by_test_id("tr-to").select_option(index=1)
    bank.get_by_test_id("tr-amount").fill("100")
    bank.get_by_test_id("tr-when-later").check()
    bank.get_by_test_id("tr-date").fill((date.today() + timedelta(days=100)).isoformat())
    bank.get_by_test_id("tr-continue").click()
    expect(bank.locator("#tr-date-err")).to_have_text("You can schedule up to 90 days ahead.")

Exercise 2: Why does test_three_wrong_passwords_lock_access not lock the account for the other tests?

Show answer

The failure counter and the lock are stored in the browser’s localStorage of that test’s own context. pytest-playwright creates a fresh context for every test, and the bank fixture creates contexts from the state saved right after a successful login, so every other test starts with an unlocked account.

Exercise 3: Write a test that a transfer to Rahul (an SQA Bank customer) is an internal transfer with no charges. What do you assert on the review screen?

Show answer
def test_internal_to_rahul(bank):
    start_transfer(bank, "bene", "500", beneficiary="Rahul · SQA Bank · XXXX0002")
    expect(bank.get_by_test_id("review-mode")).to_have_text("Within SQA Bank")
    expect(bank.get_by_test_id("review-charges")).to_have_text("Free")

Rahul only offers the internal mode, so no mode radio needs to be chosen.

Exercise 4: The statement check failed with row X: 1000.10 != 1000.1. Is this a bug?

Show answer

Not in the bank: it means the test compared strings or floats somewhere. Decimal("1000.10") == Decimal("1000.1") is True, so make sure both sides are converted with Decimal(...) before comparing, as in the lesson.


🧠 MCQ Quiz: Project 4: Banking App Test Suite

10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.

  1. Why use Decimal for money in tests?
  2. What is the right attitude to captchas in test automation?
  3. Why does the login-once fixture save sessionStorage separately?
  4. How does the bank fixture keep tests isolated?
  5. What does the wrong-PIN test check besides the error message?
  6. Which locator receives page-level transfer errors such as “Insufficient balance”?
  7. How does the suite capture the downloaded CSV?
  8. What does the statement consistency test verify?
  9. Why is 1500.25 used instead of 1500 in the transfer test?
  10. Why can this suite run with -n 4?

Want a longer, timed test? Take the Playwright Python mock interviews (13 modules, 20 MCQs each).


❓ Frequently Asked Questions

🤔 How do real banks let testers handle OTPs?

Test environments use fixed OTPs, an OTP API for testers, or a test SMS inbox that tests can read. Never automate a personal phone or real customer accounts.

🤔 Should a test suite ever run transfers on production?

No. Production checks for banking apps are read-only smoke tests with dedicated monitoring accounts, if any. Money-moving tests belong in test environments.

🤔 Why keep page helpers in functions instead of page-object classes?

For a project of this size, a module of clear functions is easy to read. Project 2 shows the class-based page-object style; both are valid, and you can move these helpers into classes as the suite grows.

🤔 How do I test the session timeout?

Use Playwright’s clock control (page.clock.install() and page.clock.fast_forward(...)) to move time forward instead of waiting, then check the logout message.

🤔 Can I reuse the login-once trick for my app?

Yes, whenever an app stores its session in sessionStorage. Save JSON.stringify(sessionStorage) after logging in and restore it with an init script that runs before the app’s scripts (Lesson 51).


🏁 Summary

  • A banking suite needs exact rules: lockout, limits, fees and balances to the paisa (Decimal).
  • Captcha and OTP are handled through the test environment’s practice values, in reusable helpers.
  • Logging in once uses storage state plus restored sessionStorage, while each test still gets a fresh context.
  • Data-driven tests cover every transfer rule and check side effects such as unchanged balances.
  • The statement CSV is downloaded and validated row by row, and the suite runs in parallel with an HTML report.

🎬 Watch the Playwright tutorial series on YouTube!

Subscribe to SqaToolsByDY • Practice on the SQA Tools Automation Practice Page

“Project 3: API + UI Hybrid Test Framework with GitHub Actions CI (Playwright Python)”

Real products are tested at two levels: the API that holds the business rules and the UI that people use. This project builds one framework that does both, with Playwright Python. The API side is a typed client for the SQA Tools practice API with JSON Schema contract tests and role checks; the UI side is a page object for the practice site’s request console; and hybrid tests create data through one layer and verify it through the other. Finally, a GitHub Actions workflow runs API tests without browsers and UI tests with them, in parallel jobs with a results summary.

📖 What You’ll Learn: designing layers (API client, schemas, page objects, fixtures, tests), a typed API client with logging, fetching and caching JSON Schemas, contract tests with jsonschema, role-based authorization tests, a factory fixture that cleans up, a page object for a JSON request console, hybrid API-to-UI and UI-to-API tests, markers to select layers, running layers in parallel, and a two-job GitHub Actions pipeline with a job summary.


🧭 What We Are Building

Layer Target Tests
API SQA Tools practice API (/wp-json/sqa-api/v1) contract (JSON Schema), CRUD, validation, roles
UI The practice page’s custom request console (method, path, body, Send, response panel) the console shows correct status and JSON
Hybrid both API creates → UI reads; UI creates → API verifies and cleans up
api-ui-hybrid/
├── pytest.ini
├── requirements.txt
├── conftest.py                  fixtures for every layer
├── framework/
│   ├── api_client.py            typed client for the practice API
│   └── contracts.py             JSON Schema fetch + validate
├── pages/
│   └── api_console.py           page object for the request console
├── tests/
│   ├── api/test_objects.py
│   ├── api/test_auth.py
│   ├── ui/test_console.py
│   └── hybrid/test_round_trips.py
└── .github/workflows/ci.yml

📄 requirements.txt

playwright==1.65.2
pytest==9.2.0
pytest-playwright==0.10.0
pytest-base-url==2.1.0
pytest-xdist==3.8.0
jsonschema==4.26.0

📄 pytest.ini

[pytest]
addopts = --base-url https://sqatools.in --strict-markers -ra
pythonpath = .
testpaths = tests
markers =
    api: API tests (no browser)
    ui: UI tests
    hybrid: tests that use both layers

🔌 The API Client

One method per business action, typed return values, and a log line per call. Tests never build URLs themselves:

📄 framework/api_client.py

import logging
from dataclasses import dataclass

from playwright.sync_api import APIRequestContext, APIResponse

log = logging.getLogger("api")


@dataclass
class ApiError(Exception):
    status: int
    body: dict

    def __str__(self):
        return f"HTTP {self.status}: {self.body}"


class PracticeApi:
    def __init__(self, request: APIRequestContext, token: str | None = None):
        self.request = request
        self.headers = {"Authorization": f"Bearer {token}"} if token else {}

    def _check(self, response: APIResponse, *expected: int) -> dict:
        log.info("%s -> %s", response.url.split("/v1/")[-1], response.status)
        body = response.json() if response.body() else {}
        if response.status not in expected:
            raise ApiError(response.status, body)
        return body

    # --- auth -----------------------------------------------------------
    def login(self, username: str, password: str) -> "PracticeApi":
        body = self._check(self.request.post("auth/login", data={"username": username, "password": password}), 200)
        return PracticeApi(self.request, body["access_token"])

    # --- temporary objects (no auth) ------------------------------------
    def create_object(self, name: str, data: dict) -> dict:
        return self._check(self.request.post("objects", data={"name": name, "data": data}), 201)

    def get_object(self, object_id: str) -> dict:
        return self._check(self.request.get(f"objects/{object_id}"), 200)

    def object_exists(self, object_id: str) -> bool:
        return self.request.get(f"objects/{object_id}").status == 200

    def delete_object(self, object_id: str) -> None:
        self._check(self.request.delete(f"objects/{object_id}"), 200, 204, 404)

    # --- bearer-protected objects ---------------------------------------
    def create_token_object(self, name: str) -> dict:
        return self._check(self.request.post("token/objects", data={"name": name, "data": {}}, headers=self.headers), 201)

    # --- read-only data ---------------------------------------------------
    def product(self, product_id: int) -> dict:
        return self._check(self.request.get(f"products/{product_id}"), 200)["data"]

📄 framework/contracts.py

from functools import cache

from jsonschema import Draft7Validator, FormatChecker

_request = None


def use(request):
    """Give the module an APIRequestContext (set once by a session fixture)."""
    global _request
    _request = request


@cache
def schema(name: str) -> dict:
    response = _request.get(f"schema/{name}")
    assert response.ok, f"schema {name}: HTTP {response.status}"
    return response.json()


def assert_matches(instance: dict, name: str) -> None:
    validator = Draft7Validator(schema(name), format_checker=FormatChecker())
    errors = sorted(validator.iter_errors(instance), key=lambda e: list(e.path))
    assert not errors, "\n".join(f"{'/'.join(map(str, e.path)) or '<root>'}: {e.message}" for e in errors)

The schemas come from the API itself (/schema/object, /schema/product …), so the contract tests check that responses match what the service promises, and a schema change shows up in the next run.


🧩 Fixtures for Every Layer

📄 conftest.py

import uuid
from pathlib import Path

import pytest
from playwright.sync_api import Page, Playwright

from framework import contracts
from framework.api_client import PracticeApi

API_URL = "https://sqatools.in/wp-json/sqa-api/v1/"


@pytest.fixture(scope="session")
def api(playwright: Playwright) -> PracticeApi:
    request = playwright.request.new_context(base_url=API_URL)
    contracts.use(request)
    yield PracticeApi(request)
    request.dispose()


@pytest.fixture
def unique_name(worker_id) -> str:
    return f"hybrid-{worker_id}-{uuid.uuid4().hex[:8]}"


@pytest.fixture
def created_objects(api):
    """Collects IDs of objects a test created (through any layer) and deletes them afterwards."""
    ids: list[str] = []
    yield ids
    for object_id in ids:
        api.delete_object(object_id)


@pytest.fixture
def console(page: Page):
    from pages.api_console import ApiConsolePage          # UI layer, written in the next section
    return ApiConsolePage(page).open()


def pytest_collection_modifyitems(items):
    for item in items:                                   # tests/api/... -> @api, tests/ui/... -> @ui, ...
        layer = Path(item.path).parent.name
        if layer in ("api", "ui", "hybrid"):
            item.add_marker(layer)

The last hook marks each test by its folder, so pytest -m api and pytest -m "ui or hybrid" select layers without decorating every test.


🧪 API Tests: Contracts, CRUD, Validation

📄 tests/api/test_objects.py

import pytest

from framework.api_client import ApiError
from framework.contracts import assert_matches


def test_created_object_matches_contract(api, unique_name, created_objects):
    obj = api.create_object(unique_name, {"price": 999})
    created_objects.append(obj["id"])
    assert_matches(obj, "object")
    assert obj["name"] == unique_name and obj["version"] == 1


def test_product_matches_contract(api):
    product = api.product(101)
    assert_matches(product, "product")


def test_contract_catches_a_broken_response(api):
    broken = {"id": "x", "name": "", "data": {}, "version": 0}          # wrong values, missing fields
    with pytest.raises(AssertionError) as info:
        assert_matches(broken, "object")
    print("\n" + str(info.value))


def test_deleted_object_is_gone(api, unique_name):
    obj = api.create_object(unique_name, {})
    api.delete_object(obj["id"])
    assert not api.object_exists(obj["id"])


def test_missing_name_is_rejected(api):
    with pytest.raises(ApiError) as info:
        api.create_object("", {})
    print(f"\n{info.value}")
    assert info.value.status in (400, 422)

📄 tests/api/test_auth.py

import pytest

from framework.api_client import ApiError


@pytest.fixture(scope="module")
def viewer(api):
    return api.login("viewer", "viewer@123")


def test_admin_can_create(api, unique_name):
    admin = api.login("admin", "admin@123")
    created = admin.create_token_object(unique_name)
    assert created["name"] == unique_name


def test_viewer_cannot_create(viewer, unique_name):
    with pytest.raises(ApiError) as info:
        viewer.create_token_object(unique_name)
    assert info.value.status == 403


def test_wrong_password(api):
    with pytest.raises(ApiError) as info:
        api.login("admin", "nope")
    assert info.value.status == 401

⌨️ Terminal

pytest -m api -v -s

🖥️ Output

============================= test session starts =============================
platform win32 -- Python 3.15.1, pytest-9.2.0, pluggy-1.7.0 -- C:\Users\you\playwright-python\.venv\Scripts\python.exe
cachedir: .pytest_cache
baseurl: https://sqatools.in
rootdir: C:\Users\you\playwright-python
configfile: pytest.ini
testpaths: tests
plugins: allure-pytest-2.16.2, base-url-2.1.0, bdd-9.0.1, html-4.2.0, metadata-3.1.1, playwright-0.10.0, rerunfailures-16.7, xdist-3.8.0
collecting ... collected 8 items

tests/api/test_auth.py::test_admin_can_create PASSED
tests/api/test_auth.py::test_viewer_cannot_create PASSED
tests/api/test_auth.py::test_wrong_password PASSED
tests/api/test_objects.py::test_created_object_matches_contract PASSED
tests/api/test_objects.py::test_product_matches_contract PASSED
tests/api/test_objects.py::test_contract_catches_a_broken_response 
<root>: 'created_at' is a required property
<root>: 'updated_at' is a required property
<root>: 'expires_at' is a required property
<root>: 'ttl_seconds' is a required property
id: 'x' does not match '^[A-Za-z0-9_-]{3,40}$'
name: '' should be non-empty
version: 0 is less than the minimum of 1
PASSED
tests/api/test_objects.py::test_deleted_object_is_gone PASSED
tests/api/test_objects.py::test_missing_name_is_rejected 
HTTP 422: {'error': {'status': 422, 'code': 'validation_failed', 'message': '1 field(s) failed validation.', 'details': [{'field': 'name', 'message': 'name is required: text of 1 to 100 characters.'}]}}
PASSED

============================== 8 passed in 6.31s ==============================

test_contract_catches_a_broken_response proves the contract check works by feeding it an invalid object: a check that never fails is not a check. Note how ApiError carries the status and body, so failures explain themselves.


🖥️ The UI Layer: a Page Object for the Request Console

The practice page has a custom request console: choose a method, type a path, add a body, press Send, and the response status and JSON appear.

📄 pages/api_console.py

import json

from playwright.sync_api import Page


class ApiConsolePage:
    URL = "/api-testing-practice/"

    def __init__(self, page: Page):
        self.page = page
        self.method = page.locator("#ap-method")
        self.path = page.locator("#ap-path")
        self.body = page.locator("#ap-body")
        self.json_header = page.locator("#ap-json")
        self.send_button = page.locator("#ap-send")
        self.status = page.get_by_test_id("res-status")
        self.response_body = page.get_by_test_id("res-body")

    def open(self):
        self.page.goto(self.URL)
        self.path.wait_for()
        return self

    def send(self, method: str, path: str, body: dict | None = None):
        self.method.select_option(method)
        self.path.fill(path)
        self.body.fill(json.dumps(body) if body is not None else "")
        if body is not None:
            self.json_header.click()                        # adds Content-Type: application/json
        previous = self.response_body.inner_text() if self.response_body.count() else None
        self.send_button.click()
        self.page.wait_for_function(
            "prev => { const el = document.querySelector('[data-testid=res-body]'); return el && el.textContent !== prev; }",
            arg=previous)
        return self

    def json(self) -> dict:
        return json.loads(self.response_body.inner_text())

send() waits until the response panel shows a new body, the console’s equivalent of waiting for the next page.

📄 tests/ui/test_console.py

from playwright.sync_api import expect


def test_console_shows_a_product(console):
    console.send("GET", "/products/101")
    expect(console.status).to_have_text("200")
    assert console.json()["data"]["name"] == "Wireless Mouse"


def test_console_shows_not_found(console):
    console.send("GET", "/products/99999")
    expect(console.status).to_have_text("404")
    assert console.json()["error"]["code"] == "not_found"

⌨️ Terminal

pytest -m ui -v

🖥️ Output

============================= test session starts =============================
platform win32 -- Python 3.15.1, pytest-9.2.0, pluggy-1.7.0 -- C:\Users\you\playwright-python\.venv\Scripts\python.exe
cachedir: .pytest_cache
baseurl: https://sqatools.in
rootdir: C:\Users\you\playwright-python
configfile: pytest.ini
testpaths: tests
plugins: allure-pytest-2.16.2, base-url-2.1.0, bdd-9.0.1, html-4.2.0, metadata-3.1.1, playwright-0.10.0, rerunfailures-16.7, xdist-3.8.0
collecting ... collected 10 items / 8 deselected / 2 selected

tests/ui/test_console.py::test_console_shows_a_product[chromium] PASSED  [ 50%]
tests/ui/test_console.py::test_console_shows_not_found[chromium] PASSED  [100%]

======================= 2 passed, 8 deselected in 6.15s =======================

🔁 Hybrid Tests: Cross-Layer Round Trips

📄 tests/hybrid/test_round_trips.py

from playwright.sync_api import expect


def test_created_by_api_is_visible_in_ui(api, console, unique_name, created_objects):
    obj = api.create_object(unique_name, {"source": "api"})              # arrange through the API
    created_objects.append(obj["id"])

    console.send("GET", f"/objects/{obj['id']}")                         # act and assert through the UI
    expect(console.status).to_have_text("200")
    shown = console.json()
    assert shown["name"] == unique_name and shown["data"] == {"source": "api"}


def test_created_in_ui_is_stored_in_api(api, console, unique_name, created_objects):
    console.send("POST", "/objects", body={"name": unique_name, "data": {"source": "ui"}})   # act through the UI
    expect(console.status).to_have_text("201")
    object_id = console.json()["id"]
    created_objects.append(object_id)                                    # cleaned up through the API

    stored = api.get_object(object_id)                                   # assert through the API
    assert stored["name"] == unique_name and stored["data"] == {"source": "ui"}


def test_ui_update_increments_version(api, console, unique_name, created_objects):
    obj = api.create_object(unique_name, {"qty": 1})
    created_objects.append(obj["id"])
    console.send("PATCH", f"/objects/{obj['id']}", body={"data": {"qty": 2}})
    expect(console.status).to_have_text("200")
    assert api.get_object(obj["id"])["version"] == 2

⌨️ Terminal

pytest -m hybrid -v

🖥️ Output

============================= test session starts =============================
platform win32 -- Python 3.15.1, pytest-9.2.0, pluggy-1.7.0 -- C:\Users\you\playwright-python\.venv\Scripts\python.exe
cachedir: .pytest_cache
baseurl: https://sqatools.in
rootdir: C:\Users\you\playwright-python
configfile: pytest.ini
testpaths: tests
plugins: allure-pytest-2.16.2, base-url-2.1.0, bdd-9.0.1, html-4.2.0, metadata-3.1.1, playwright-0.10.0, rerunfailures-16.7, xdist-3.8.0
collecting ... collected 13 items / 10 deselected / 3 selected

tests/hybrid/test_round_trips.py::test_created_by_api_is_visible_in_ui[chromium] PASSED [ 33%]
tests/hybrid/test_round_trips.py::test_created_in_ui_is_stored_in_api[chromium] PASSED [ 66%]
tests/hybrid/test_round_trips.py::test_ui_update_increments_version[chromium] PASSED [100%]

====================== 3 passed, 10 deselected in 11.19s ======================

Each hybrid test crosses the boundary in one direction, so a failure tells you which layer is wrong: if the API stores correct data but the UI shows something else, it is a UI bug; if the UI says 201 but the API cannot find the object, it is a backend bug.


⚡ All Layers in Parallel

⌨️ Terminal

pytest -n 4 -q

🖥️ Output

bringing up nodes...
bringing up nodes...

.............                                                            [100%]
13 passed in 10.64s

Every test uses unique names (with the worker id) and cleans up what it created, so all layers run safely in parallel.


🚀 The CI Pipeline

Two jobs: API tests need no browser, so they start in seconds; UI and hybrid tests install Chromium. Both publish a summary.

📄 .github/workflows/ci.yml

name: API + UI tests

on:
  push:
    branches: [main]
  pull_request:
  schedule:
    - cron: "0 21 * * *"          # 02:30 IST nightly

concurrency:
  group: tests-${{ github.ref }}
  cancel-in-progress: true

jobs:
  api:
    runs-on: ubuntu-latest
    timeout-minutes: 15
    steps:
      - uses: actions/checkout@v7
      - uses: actions/setup-python@v7
        with:
          python-version: "3.13"
          cache: pip
      - run: pip install -r requirements.txt
      - run: pytest -m api -n 4 --junitxml=reports/api.xml
      - if: always()
        uses: actions/upload-artifact@v7
        with:
          name: api-results
          path: reports/

  ui:
    runs-on: ubuntu-latest
    timeout-minutes: 30
    steps:
      - uses: actions/checkout@v7
      - uses: actions/setup-python@v7
        with:
          python-version: "3.13"
          cache: pip
      - run: pip install -r requirements.txt
      - run: playwright install --with-deps chromium
      - run: pytest -m "ui or hybrid" -n 4 --tracing retain-on-failure --junitxml=reports/ui.xml
      - if: failure()
        uses: actions/upload-artifact@v7
        with:
          name: ui-traces
          path: test-results/
      - if: always()
        uses: actions/upload-artifact@v7
        with:
          name: ui-results
          path: reports/

📄 check_ci.py

import yaml

wf = yaml.safe_load(open(".github/workflows/ci.yml", encoding="utf-8"))
for name, job in wf["jobs"].items():
    runs = [s["run"] for s in job["steps"] if "run" in s]
    installs_browsers = any("playwright install" in r for r in runs)
    print(f"{name:4} browsers={installs_browsers!s:5} test step: {runs[-1]}")

⌨️ Terminal

python check_ci.py

🖥️ Output

api  browsers=False test step: pytest -m api -n 4 --junitxml=reports/api.xml
ui   browsers=True  test step: pytest -m "ui or hybrid" -n 4 --tracing retain-on-failure --junitxml=reports/ui.xml

The API job never downloads a browser, which keeps it fast and cheap; the UI job keeps traces only when something failed. Add the job-summary script from Lesson 66 to both jobs for a results table on the run page.


🏋️ Practice Exercises

Try each exercise on your own first, then open the answer to compare. The answers use the same practice sites and project layout as the lesson.

Exercise 1: Add a contract test for /people/1 against the user schema. Which client method do you add?

Show answer
def person(self, person_id: int) -> dict:
    return self._check(self.request.get(f"people/{person_id}"), 200)["data"]
def test_person_matches_contract(api):
    assert_matches(api.person(1), "user")

(Remember: list endpoints use /people, never a path ending in /users, on this site.)

Exercise 2: Write a hybrid test: create an object through the UI console, delete it through the API, then check the UI console shows 404 for it.

Show answer
def test_api_delete_visible_in_ui(api, console, unique_name):
    console.send("POST", "/objects", body={"name": unique_name, "data": {}})
    object_id = console.json()["id"]
    api.delete_object(object_id)
    console.send("GET", f"/objects/{object_id}")
    expect(console.status).to_have_text("404")

Exercise 3: Your UI job fails but the API job passes. The failing hybrid test says the API returned the right data. Where is the bug most likely, and which artifact do you open first?

Show answer

In the UI layer (the console rendering or the page object), because the API side was verified directly. Open the trace from the ui-traces artifact: check the request the console sent (Network tab) and what the response panel showed at the failing step.

Exercise 4: Make the API client log the HTTP method as well as the path and status. Why can _check not read the method from the response, and how do you add it?

Show answer

APIResponse knows the URL and status but not the request method. Pass the method in from each call and include it in the log:

def _check(self, response, *expected, method="GET"):
    log.info("%s %s -> %s", method, response.url.split("/v1/")[-1], response.status)
    ...

def create_object(self, name, data):
    return self._check(self.request.post("objects", data={"name": name, "data": data}), 201, method="POST")

🧠 MCQ Quiz: Project 3: API + UI Hybrid Framework with CI

10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.

  1. Why split tests into api, ui and hybrid layers?
  2. Where do the JSON Schemas in this project come from?
  3. Why does the project include a test that feeds an invalid object to assert_matches?
  4. What does ApiError give a failing test?
  5. How does ApiConsolePage.send() know the response arrived?
  6. What does a hybrid test that creates through the UI and verifies through the API catch?
  7. How are layer markers applied?
  8. Why can all layers run with -n 4?
  9. Why does the API CI job not run playwright install?
  10. Which artifact does the UI job upload only when tests fail?

Want a longer, timed test? Take the Playwright Python mock interviews (13 modules, 20 MCQs each).


❓ Frequently Asked Questions

🤔 Why test the API console page instead of a normal web app?

Because it is a real UI on top of the same API, which makes cross-layer checks easy to see and to run against a public practice site. The same pattern applies to any app: create through the API, verify in the UI, and vice versa.

🤔 Can I validate responses without fetching schemas over the network?

Yes: store the schemas as JSON files in the repository and load them in contracts.schema(). Fetching them from the service detects contract changes automatically; storing them detects unexpected changes in the service. Many teams do both.

🤔 Where would a database check fit?

As a third layer with its own client and fixtures (for example db.fetch_order(id)), used in hybrid tests exactly like the API client here. Keep credentials in CI secrets.

🤔 How do I add an authenticated UI flow?

Log in through the API, save storage state or cookies (Lessons 51, 55), and give the UI fixtures a logged-in context. The console here also has “Add auth” buttons for its own requests.

🤔 Should the API tests use the browser’s page.request?

Not for pure API tests: a standalone playwright.request.new_context() needs no browser. Use page.request when an API step must share cookies with the UI session.


🏁 Summary

  • A typed API client with self-explaining errors, JSON Schema contracts from the service itself, and role checks form the API layer.
  • A page object for the request console forms the UI layer; send() synchronises on a new response.
  • Hybrid tests cross the layers in both directions and point to the failing layer.
  • Folder-based markers select layers; unique names and clean-up allow parallel runs.
  • GitHub Actions runs API tests without browsers and UI tests with traces on failure, in separate jobs.

🎬 Watch the Playwright tutorial series on YouTube!

Subscribe to SqaToolsByDY • Practice on the SQA Tools Automation Practice Page

“Project 2: E-commerce End-to-End Test Framework with Page Objects (Playwright Python)”

This project builds a real test framework, not a script. The target is SQA Shop, the SQA Tools practice store, with search, cart, coupons, a four-step checkout (contact, delivery, payment, review), several payment methods, order confirmation and order tracking. You will design page objects for every screen, add fixtures that create carts instantly, cover happy paths and error paths across payment methods, verify money calculations, run the suite in parallel and produce a report. It uses most of Modules 4 to 12 together, and every test shown was run against the live practice site.

📖 What You’ll Learn: designing a framework for a multi-step checkout, the folder layout, a shared Header component, page objects for search results, cart, checkout steps, order confirmation and tracking, step methods that synchronise on the next step, a cart builder and fixtures that seed state, tests for cart behaviour, coupons, guest and member checkout, card, UPI and cash on delivery, validation and declined payments, money arithmetic, order tracking, parallel runs and an HTML report.


🛒 The Application Under Test

SQA Shop is a single-page store with 108 products. The checkout is the interesting part:

Step What happens Rules worth testing
Cart quantities, remove, save for later, coupons SAVE10 (10%, max ₹500, min ₹999) and FLAT200 (min ₹1,499) caps and minimums
1 Contact email and mobile required, formats
2 Delivery address (or a “fill dummy address” button), standard or express speed pincodes starting with 9 are not serviceable
3 Payment card (4111 1111 1111 1111 ok, 4000 0000 0000 0002 declined), UPI (success@upi / failure@upi), net banking, cash on delivery declines appear only when placing the order
4 Review summary, terms checkbox, Place order terms required
Order confirmation with order ID, amount, status, delivery date; tracking by order ID + email data must match

🗂️ Framework Layout

shop-framework/
├── pytest.ini
├── conftest.py               fixtures: shop, cart builder, member state
├── framework/
│   ├── money.py              "₹13,299" -> 13299
│   └── cart_builder.py       seeds carts without clicking
├── pages/
│   ├── base.py               BasePage + Header component
│   ├── search.py             SearchResults
│   ├── cart.py               CartPage
│   ├── checkout.py           CheckoutPage with one method per step
│   └── order.py              OrderPage, TrackOrderPage
└── tests/
    ├── test_cart.py
    ├── test_checkout.py
    ├── test_checkout_errors.py
    └── test_orders.py

📄 pytest.ini

[pytest]
addopts = --base-url https://sqatools.in --screenshot only-on-failure --tracing retain-on-failure
pythonpath = .
testpaths = tests
markers =
    smoke: fast, critical checks

🧰 Framework Helpers

📄 framework/money.py

import re


def money(text: str) -> int:
    """'₹13,299' -> 13299, '−₹500' -> 500, 'Free' -> 0."""
    digits = re.sub(r"[^\d]", "", text)
    return int(digits) if digits else 0

📄 framework/cart_builder.py

import json
from dataclasses import dataclass, field

EARBUDS, HANDBOOK, TSHIRT = "EL-013", "DG-010", "CL-001"


@dataclass
class CartBuilder:
    lines: list[dict] = field(default_factory=list)

    def add(self, product_id: str, qty: int = 1, size: str = ""):
        self.lines.append({"id": product_id, "size": size, "color": "", "qty": qty})
        return self

    def init_script(self) -> str:
        data = json.dumps(json.dumps(self.lines))
        return (f"if (!sessionStorage.getItem('seeded')) {{ localStorage.setItem('spCart', {data}); "
                f"sessionStorage.setItem('seeded', '1'); }}")

📄 Page Objects

Base page and header

📄 pages/base.py

from playwright.sync_api import Page

SHOP = "/dummy-ecommerce-website/"


class Header:
    def __init__(self, page: Page):
        self.page = page
        self.search_input = page.get_by_test_id("search-input")
        self.search_button = page.get_by_test_id("search-button")
        self.cart_count = page.get_by_test_id("cart-count")
        self.account = page.get_by_test_id("account-button")

    def search(self, term: str):
        self.search_input.fill(term)
        self.search_button.click()
        from pages.search import SearchResults
        results = SearchResults(self.page)
        results.cards.first.wait_for()
        return results


class BasePage:
    route = ""

    def __init__(self, page: Page):
        self.page = page
        self.header = Header(page)

    def open(self):
        self.page.goto(SHOP + self.route)
        return self

Search results and cart

📄 pages/search.py

from pages.base import BasePage


class SearchResults(BasePage):
    def __init__(self, page):
        super().__init__(page)
        self.cards = page.get_by_test_id("product-card")

    def add_to_cart(self, name: str):
        before = int(self.header.cart_count.inner_text())
        card = self.cards.filter(has_text=name).first
        card.get_by_role("button", name="Add to cart").click()
        self.header.cart_count.filter(has_text=str(before + 1)).wait_for()   # synchronise on the badge
        return self

📄 pages/cart.py

from playwright.sync_api import Page

from pages.base import BasePage


class CartPage(BasePage):
    route = "#/cart"

    def __init__(self, page: Page):
        super().__init__(page)
        self.title = page.get_by_test_id("cart-title")
        self.item_names = page.get_by_test_id("cart-item-name")
        self.coupon_input = page.get_by_test_id("coupon-input")
        self.coupon_message = page.get_by_test_id("coupon-message")
        self.coupon_discount = page.get_by_test_id("coupon-discount")
        self.total = page.get_by_test_id("order-total")
        self.checkout_button = page.get_by_test_id("checkout-button")

    def quantity(self, product_id: str):
        return self.page.get_by_test_id(f"cart-qty-{product_id}")

    def increase(self, product_id: str):
        self.page.get_by_test_id(f"cart-plus-{product_id}").click()
        return self

    def remove(self, product_id: str):
        self.page.get_by_test_id(f"remove-{product_id}").click()
        return self

    def apply_coupon(self, code: str):
        self.coupon_input.fill(code)
        self.page.get_by_test_id("apply-coupon").click()
        return self

    def checkout(self):
        self.checkout_button.click()
        from pages.checkout import CheckoutPage
        return CheckoutPage(self.page).wait_for_step("contact")

Checkout: one method per step

📄 pages/checkout.py

from playwright.sync_api import Page

from pages.base import BasePage

CARD_OK, CARD_DECLINED = "4111 1111 1111 1111", "4000 0000 0000 0002"


class CheckoutPage(BasePage):
    route = "#/checkout"

    def __init__(self, page: Page):
        super().__init__(page)
        self.continue_button = page.get_by_test_id("step-continue")
        self.delivery_fee = page.get_by_test_id("delivery-fee")
        self.total = page.get_by_test_id("order-total")
        self.place_error = page.get_by_test_id("place-error")

    def wait_for_step(self, name: str):
        self.page.get_by_test_id(f"step-{name}").wait_for()
        return self

    def error_for(self, field_id: str):
        return self.page.locator(f"#{field_id}-err")

    # step 1
    def contact(self, email: str = "guest@example.com", phone: str = "9876543210"):
        self.page.get_by_test_id("checkout-email").fill(email)
        self.page.get_by_test_id("checkout-phone").fill(phone)
        self.continue_button.click()
        return self

    # step 2
    def delivery(self, pincode: str | None = None, express: bool = False):
        self.page.get_by_test_id("fill-dummy-address").click()
        if pincode:
            self.page.get_by_test_id("ad-pin").fill(pincode)
        self.page.get_by_test_id("speed-express" if express else "speed-standard").check()
        self.continue_button.click()
        return self

    # step 3
    def pay_by_card(self, number: str = CARD_OK):
        self.page.get_by_test_id("pay-card").check()
        self.page.get_by_test_id("card-name").fill("Test User")
        self.page.get_by_test_id("card-number").fill(number)
        self.page.get_by_test_id("card-expiry").fill("12/30")
        self.page.get_by_test_id("card-cvv").fill("123")
        return self._to_review()

    def pay_by_upi(self, upi: str = "success@upi"):
        self.page.get_by_test_id("pay-upi").check()
        self.page.get_by_test_id("upi-id").fill(upi)
        return self._to_review()

    def pay_cash_on_delivery(self):
        self.page.get_by_test_id("pay-cod").check()
        return self._to_review()

    def _to_review(self):
        self.continue_button.click()
        return self.wait_for_step("review")

    # step 4
    def place_order(self, accept_terms: bool = True):
        if accept_terms:
            self.page.get_by_test_id("accept-terms").check()
        self.page.get_by_test_id("place-order").click()
        return self

    def confirmed_order(self):
        from pages.order import OrderPage
        order = OrderPage(self.page)
        order.confirmation.wait_for(timeout=10_000)        # the store shows a 2-second "placing order" overlay
        return order

Order confirmation and tracking

📄 pages/order.py

from pages.base import BasePage


class OrderPage(BasePage):
    def __init__(self, page):
        super().__init__(page)
        self.confirmation = page.get_by_test_id("order-confirmation")
        self.title = page.get_by_test_id("confirm-title")
        self.order_id = page.get_by_test_id("order-id")
        self.paid = page.get_by_test_id("order-paid")
        self.status = page.get_by_test_id("order-status")
        self.eta = page.get_by_test_id("delivery-eta")


class TrackOrderPage(BasePage):
    route = "#/orders"

    def track(self, order_id: str, email: str):
        self.page.get_by_test_id("track-order-id").fill(order_id)
        self.page.get_by_test_id("track-email").fill(email)
        self.page.get_by_test_id("track-button").click()
        return OrderPage(self.page)

🧩 Fixtures

📄 conftest.py

import json

import pytest
from playwright.sync_api import BrowserContext, Page

from framework.cart_builder import CartBuilder
from pages.base import BasePage
from pages.cart import CartPage


@pytest.fixture
def shop(page: Page) -> BasePage:
    return BasePage(page).open()


@pytest.fixture
def cart_with(context: BrowserContext, page: Page):
    """cart_with(CartBuilder().add(...)) -> an open CartPage with those items, no clicking needed."""
    def _cart(builder: CartBuilder) -> CartPage:
        context.add_init_script(builder.init_script())
        return CartPage(page).open()
    return _cart


@pytest.fixture
def member(context: BrowserContext):
    """Log in as the remembered demo user before any page script runs (Lesson 58, StoredLogin)."""
    context.add_init_script(f"localStorage.setItem('spUser', {json.dumps(json.dumps('testuser'))});")

✅ Cart Tests

📄 tests/test_cart.py

import pytest
from playwright.sync_api import expect

from framework.cart_builder import EARBUDS, HANDBOOK, CartBuilder
from framework.money import money
from pages.cart import CartPage


@pytest.mark.smoke
def test_add_from_search(shop):
    shop.header.search("earbuds").add_to_cart("Wireless Earbuds")
    expect(shop.header.cart_count).to_have_text("1")
    cart = CartPage(shop.page).open()
    expect(cart.item_names).to_have_text(["Wireless Earbuds"])


def test_quantity_updates_total(cart_with):
    cart = cart_with(CartBuilder().add(EARBUDS))
    one = money(cart.total.inner_text())
    cart.increase(EARBUDS)
    expect(cart.quantity(EARBUDS)).to_have_value("2")
    expect(cart.header.cart_count).to_have_text("2")
    assert money(cart.total.inner_text()) == 2 * one


def test_remove_line(cart_with):
    cart = cart_with(CartBuilder().add(EARBUDS).add(HANDBOOK))
    cart.remove(HANDBOOK)
    expect(cart.item_names).to_have_text(["Wireless Earbuds"])


@pytest.mark.parametrize("builder, code, message, discount", [
    pytest.param(CartBuilder().add(EARBUDS), "SAVE10", "Coupon SAVE10 applied.", "−₹500", id="save10-capped"),
    pytest.param(CartBuilder().add(EARBUDS), "FLAT200", "Coupon FLAT200 applied.", "−₹200", id="flat200"),
    pytest.param(CartBuilder().add(HANDBOOK), "SAVE10", "Add ₹500 more to use SAVE10.", None, id="save10-below-min"),
    pytest.param(CartBuilder().add(HANDBOOK, qty=3), "FLAT200", "Add ₹2 more to use FLAT200.", None, id="flat200-just-below"),
])
def test_coupons(cart_with, builder, code, message, discount):
    cart = cart_with(builder).apply_coupon(code)
    expect(cart.coupon_message).to_have_text(message)
    if discount:
        expect(cart.coupon_discount).to_have_text(discount)
    else:
        expect(cart.coupon_discount).to_have_count(0)

⌨️ Terminal

pytest tests/test_cart.py -v

🖥️ Output

============================= test session starts =============================
platform win32 -- Python 3.15.1, pytest-9.2.0, pluggy-1.7.0 -- C:\Users\you\playwright-python\.venv\Scripts\python.exe
cachedir: .pytest_cache
baseurl: https://sqatools.in
rootdir: C:\Users\you\playwright-python
configfile: pytest.ini
plugins: allure-pytest-2.16.2, base-url-2.1.0, bdd-9.0.1, html-4.2.0, metadata-3.1.1, playwright-0.10.0, rerunfailures-16.7, xdist-3.8.0
collecting ... collected 7 items

tests/test_cart.py::test_add_from_search[chromium] PASSED                [ 14%]
tests/test_cart.py::test_quantity_updates_total[chromium] PASSED         [ 28%]
tests/test_cart.py::test_remove_line[chromium] PASSED                    [ 42%]
tests/test_cart.py::test_coupons[chromium-save10-capped] PASSED          [ 57%]
tests/test_cart.py::test_coupons[chromium-flat200] PASSED                [ 71%]
tests/test_cart.py::test_coupons[chromium-save10-below-min] PASSED       [ 85%]
tests/test_cart.py::test_coupons[chromium-flat200-just-below] PASSED     [100%]

============================= 7 passed in 15.62s ==============================

The boundary case flat200-just-below uses three handbooks (3 × ₹499 = ₹1,497), ₹2 short of FLAT200’s ₹1,499 minimum. Boundary values like this are where pricing bugs live.


💳 Checkout Tests

📄 tests/test_checkout.py

import re

import pytest
from playwright.sync_api import expect

from framework.cart_builder import EARBUDS, CartBuilder
from framework.money import money


@pytest.mark.smoke
@pytest.mark.parametrize("pay, status", [
    pytest.param(lambda c: c.pay_by_card(), "Paid · confirmed", id="card"),
    pytest.param(lambda c: c.pay_by_upi("success@upi"), "Paid · confirmed", id="upi"),
    pytest.param(lambda c: c.pay_cash_on_delivery(), "Confirmed · pay on delivery", id="cod"),
])
def test_guest_checkout(cart_with, pay, status):
    cart = cart_with(CartBuilder().add(EARBUDS))
    checkout = cart.checkout().contact().delivery()
    total = money(pay(checkout).total.inner_text())
    order = checkout.place_order().confirmed_order()

    expect(order.title).to_have_text("Order placed successfully!")
    expect(order.order_id).to_have_text(re.compile(r"^OD\d{14}$"))
    expect(order.status).to_contain_text(status)
    assert money(order.paid.inner_text()) == total
    expect(order.header.cart_count).to_have_text("0")                     # the cart is emptied


def test_express_delivery_costs_more(cart_with):
    standard = cart_with(CartBuilder().add(EARBUDS)).checkout().contact().delivery(express=False)
    standard_total = money(standard.total.inner_text())
    standard.page.get_by_role("button", name="← Back").click()
    express = standard.wait_for_step("address").delivery(express=True)
    fee = money(express.delivery_fee.inner_text())
    print(f"\nexpress delivery fee: ₹{fee}")
    assert fee > 0
    assert money(express.total.inner_text()) == standard_total + fee


def test_member_details_are_prefilled(member, cart_with):
    cart = cart_with(CartBuilder().add(EARBUDS))
    checkout = cart.checkout()
    expect(checkout.page.get_by_test_id("logged-in-note")).to_contain_text("Signed in as Test User")
    expect(checkout.page.get_by_test_id("checkout-email")).to_have_value("test.user@example.com")

⌨️ Terminal

pytest tests/test_checkout.py -v -s

🖥️ Output

============================= test session starts =============================
platform win32 -- Python 3.15.1, pytest-9.2.0, pluggy-1.7.0 -- C:\Users\you\playwright-python\.venv\Scripts\python.exe
cachedir: .pytest_cache
baseurl: https://sqatools.in
rootdir: C:\Users\you\playwright-python
configfile: pytest.ini
plugins: allure-pytest-2.16.2, base-url-2.1.0, bdd-9.0.1, html-4.2.0, metadata-3.1.1, playwright-0.10.0, rerunfailures-16.7, xdist-3.8.0
collecting ... collected 5 items

tests/test_checkout.py::test_guest_checkout[chromium-card] PASSED
tests/test_checkout.py::test_guest_checkout[chromium-upi] PASSED
tests/test_checkout.py::test_guest_checkout[chromium-cod] PASSED
tests/test_checkout.py::test_express_delivery_costs_more[chromium] 
express delivery fee: ₹149
PASSED
tests/test_checkout.py::test_member_details_are_prefilled[chromium] PASSED

============================= 5 passed in 19.53s ==============================

The parametrized test takes a lambda that performs the payment step, so three payment methods share one test body. The order ID format, status text, the amount paid and the emptied cart are all verified.


🚫 Error Paths

📄 tests/test_checkout_errors.py

from playwright.sync_api import expect

from framework.cart_builder import EARBUDS, CartBuilder
from pages.checkout import CARD_DECLINED


def test_contact_is_validated(cart_with):
    checkout = cart_with(CartBuilder().add(EARBUDS)).checkout()
    checkout.contact(email="not-an-email", phone="12345")
    expect(checkout.page.get_by_test_id("step-contact")).to_be_visible()      # still on step 1
    expect(checkout.error_for("ck-email")).not_to_be_empty()
    expect(checkout.error_for("ck-phone")).not_to_be_empty()


def test_unserviceable_pincode(cart_with):
    checkout = cart_with(CartBuilder().add(EARBUDS)).checkout().contact()
    checkout.delivery(pincode="900001")
    expect(checkout.error_for("ad-pin")).to_have_text("Sorry, we do not deliver to this pincode yet.")


def test_declined_card_does_not_create_an_order(cart_with):
    checkout = cart_with(CartBuilder().add(EARBUDS)).checkout().contact().delivery().pay_by_card(CARD_DECLINED)
    checkout.place_order()
    expect(checkout.place_error).to_contain_text("Payment declined by the bank", timeout=10_000)
    expect(checkout.header.cart_count).to_have_text("1")                       # nothing was bought


def test_terms_are_required(cart_with):
    checkout = cart_with(CartBuilder().add(EARBUDS)).checkout().contact().delivery().pay_by_card()
    checkout.place_order(accept_terms=False)
    expect(checkout.page.locator("#agree-err")).to_have_text("Please accept the terms to place the order.")

📦 Order Tracking

📄 tests/test_orders.py

from playwright.sync_api import expect

from framework.cart_builder import HANDBOOK, CartBuilder
from pages.order import TrackOrderPage


def test_track_order_by_id_and_email(cart_with):
    checkout = cart_with(CartBuilder().add(HANDBOOK)).checkout().contact(email="tracker@example.com")
    order = checkout.pay_by_upi().place_order().confirmed_order()        # digital product: no delivery step
    order_id = order.order_id.inner_text()

    tracked = TrackOrderPage(order.page).open().track(order_id, "tracker@example.com")
    expect(tracked.order_id).to_have_text(order_id)


def test_unknown_order(shop):
    tracked = TrackOrderPage(shop.page).open().track("OD00000000000000", "nobody@example.com")
    expect(tracked.page.locator("#track-id-err")).to_have_text("No order found for this ID and email in this browser.")

⌨️ Terminal

pytest tests/test_checkout_errors.py tests/test_orders.py -v

🖥️ Output

============================= test session starts =============================
platform win32 -- Python 3.15.1, pytest-9.2.0, pluggy-1.7.0 -- C:\Users\you\playwright-python\.venv\Scripts\python.exe
cachedir: .pytest_cache
baseurl: https://sqatools.in
rootdir: C:\Users\you\playwright-python
configfile: pytest.ini
plugins: allure-pytest-2.16.2, base-url-2.1.0, bdd-9.0.1, html-4.2.0, metadata-3.1.1, playwright-0.10.0, rerunfailures-16.7, xdist-3.8.0
collecting ... collected 6 items

tests/test_checkout_errors.py::test_contact_is_validated[chromium] PASSED [ 16%]
tests/test_checkout_errors.py::test_unserviceable_pincode[chromium] PASSED [ 33%]
tests/test_checkout_errors.py::test_declined_card_does_not_create_an_order[chromium] PASSED [ 50%]
tests/test_checkout_errors.py::test_terms_are_required[chromium] PASSED  [ 66%]
tests/test_orders.py::test_track_order_by_id_and_email[chromium] PASSED  [ 83%]
tests/test_orders.py::test_unknown_order[chromium] PASSED                [100%]

============================= 6 passed in 20.35s ==============================

test_track_order_by_id_and_email also checks a business rule hidden in the flow: an eBook is a digital product, so checkout goes straight from contact to payment without a delivery step.


⚡ Run the Whole Framework in Parallel

⌨️ Terminal

pytest -n 4 -q --html=reports/report.html --self-contained-html

🖥️ Output

bringing up nodes...
bringing up nodes...

..................                                                       [100%]
- Generated html report: file:///C:/Users/you/playwright-python/reports/report.html -
18 passed in 23.35s

All tests are independent (each seeds its own cart in its own browser context), so four workers run them safely in parallel. Failures would leave screenshots and traces in test-results/ thanks to the options in pytest.ini.


🧠 Design Decisions Worth Copying

Decision Why
One CheckoutPage with step methods returning self The checkout is one URL with internal steps; chaining reads like the user journey
Step methods synchronise (wait_for_step, cart badge) Prevents races in a single-page app (Lesson 56)
CartBuilder + add_init_script Cart setup in milliseconds; only one test exercises adding via search
money() helper Arithmetic assertions instead of string comparisons
Payment as a lambda parameter Several payment methods without duplicating the flow
Error tests stay on the right step and check nothing was bought Negative tests verify side effects, not just messages

🏋️ Practice Exercises

Try each exercise on your own first, then open the answer to compare. The answers use the same practice sites and project layout as the lesson.

Exercise 1: Add a pay_by_netbanking(bank) method to CheckoutPage and a test that places an order with “Demo National Bank”.

Show answer
def pay_by_netbanking(self, bank: str = "Demo National Bank"):
    self.page.get_by_test_id("pay-netbanking").check()
    self.page.get_by_test_id("bank").select_option(bank)
    return self._to_review()
def test_netbanking(cart_with):
    checkout = cart_with(CartBuilder().add(EARBUDS)).checkout().contact().delivery().pay_by_netbanking()
    order = checkout.place_order().confirmed_order()
    expect(order.title).to_have_text("Order placed successfully!")

Exercise 2: Write a test that UPI failure@upi leads to the declined message and keeps the cart.

Show answer
def test_upi_failure(cart_with):
    checkout = cart_with(CartBuilder().add(EARBUDS)).checkout().contact().delivery().pay_by_upi("failure@upi")
    checkout.place_order()
    expect(checkout.place_error).to_contain_text("Payment declined", timeout=10_000)
    expect(checkout.header.cart_count).to_have_text("1")

Exercise 3: Clothing items need a size. Extend CartBuilder usage to seed a T-shirt (CL-001) in size M, and assert the cart shows the size.

Show answer
cart = cart_with(CartBuilder().add(TSHIRT, size="M"))
expect(cart.page.get_by_test_id("cart-item")).to_contain_text("M")

CartBuilder.add already accepts size; the cart line stores it and the cart shows it with the item.

Exercise 4: The marketing team adds a coupon WELCOME50 (₹50 off, no minimum). Which single change gives you a test for it?

Show answer

Add one pytest.param(CartBuilder().add(HANDBOOK), "WELCOME50", "Coupon WELCOME50 applied.", "−₹50", id="welcome50") to the test_coupons parameter list. The framework already knows how to seed carts, apply coupons and read discounts; new business rules become new data rows.


🧠 MCQ Quiz: Project 2: E-commerce End-to-End Framework

10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.

  1. Why is CheckoutPage one class with step methods instead of four page classes?
  2. What does wait_for_step("review") do?
  3. How do most tests get items into the cart?
  4. Why is the payment step passed as a lambda in test_guest_checkout?
  5. What does flat200-just-below test?
  6. What does the declined-card test verify besides the error message?
  7. Why does confirmed_order() wait up to 10 seconds?
  8. Why can this suite run with -n 4 safely?
  9. How does test_track_order_by_id_and_email reveal a business rule?
  10. How would you add a new coupon rule to the tests?

Want a longer, timed test? Take the Playwright Python mock interviews (13 modules, 20 MCQs each).


❓ Frequently Asked Questions

🤔 Why not create carts through an API?

SQA Shop is a client-side app with no backend API, so the equivalent of “create via API” is seeding its browser storage. In an application with a server, use page.request calls instead (Lesson 55); the fixture interface stays the same.

🤔 Should assertions live in page objects here?

No. Page objects expose locators and actions and synchronise; tests decide what is correct. The only waits inside page objects are for the next screen, never verdicts.

🤔 How do I add a mobile run of this framework?

Run it with --device "Pixel 7" (Lesson 50). The locators are test ids, so they work unchanged on the mobile layout; add separate tests for mobile-only elements such as the filter drawer.

🤔 Where would Allure fit in?

Decorate page-object methods with @allure.step (Lesson 64) and every test gets a readable step tree for free.

🤔 How big should a real e-commerce suite be?

Cover every pricing and payment rule with focused tests like these, keep a handful of full journeys as smoke tests, and move combinatorial pricing checks to API or unit tests where possible.


🏁 Summary

  • A page-object framework mirrors the app: a shared Header, search results, cart, a step-based checkout and order pages.
  • Step methods return the page and synchronise on the next step; fixtures seed carts and member state instantly.
  • Tests cover cart behaviour, coupon boundaries, three payment methods, express delivery arithmetic, validation, declined payments and order tracking.
  • Money values are compared as numbers; negative tests check that nothing was bought.
  • Independent tests run in parallel with an HTML report and failure artifacts.

🎬 Watch the Playwright tutorial series on YouTube!

Subscribe to SqaToolsByDY • Practice on the SQA Tools Automation Practice Page

“Project 1: Flight Booking Automation with Playwright Python (Beginner)”

Lessons teach one skill at a time; projects show how the skills fit together. In this first project you will automate the SQA Tools dummy flight booking website from scratch with Playwright and pytest: a clean project folder, fixtures for logging in, data-driven login and search-validation tests, a complete end-to-end booking (search, flight, traveller details, seats, promo code, card payment and PNR), fare calculations checked to the rupee, and an HTML report with screenshots of failures. Every file is shown in full and every test was run before publishing.

📖 What You’ll Learn: planning test scenarios from an application, setting up the project folder, pytest.ini, conftest.py fixtures for login and search, data-driven login tests, search validation messages, an end-to-end booking test, reading money values and checking fare arithmetic, payment success and failure paths, an HTML report, and extension tasks to continue on your own.


🎯 The Application and the Plan

The SQA Tools dummy booking website is a practice flight-booking app with a realistic five-step flow:

  1. Login (testuser / Test@123; lockeduser is locked)
  2. Search: one-way or round trip, cities, dates, travellers, cabin
  3. Flights: results with prices, sorting, select a flight
  4. Travellers: names, dates of birth, nationality, contact details
  5. Seats and Payment: seat map, promo code SQA100 (₹100 off), test cards (4111 1111 1111 1111 succeeds, 4000 0000 0000 0002 is declined), then a confirmation with PNR

Every element has a data-testid, so locators are simple. Before writing code, turn the app into test scenarios:

Area Scenarios
Login valid user; wrong password; locked user; empty fields
Search validation same origin and destination; past date; more infants than adults; more than 9 travellers
Booking one-way booking ends with a PNR; promo code reduces the total by ₹100
Fares total = base fare + taxes + convenience fee − promo
Payment declined card shows an error and no booking

🗂️ Project Setup

flight-booking-tests/
├── pytest.ini
├── requirements.txt
├── conftest.py
└── tests/
    ├── test_login.py
    ├── test_search_validation.py
    ├── test_booking.py
    └── test_payment.py

📄 requirements.txt

playwright==1.65.2
pytest==9.2.0
pytest-playwright==0.10.0
pytest-base-url==2.1.0
pytest-html==4.2.0

⌨️ Terminal

python -m venv .venv
.venv\Scripts\activate                 # Windows   (macOS/Linux: source .venv/bin/activate)
pip install -r requirements.txt
playwright install chromium

📄 pytest.ini

[pytest]
addopts = --base-url https://sqatools.in --screenshot only-on-failure
testpaths = tests

🧩 conftest.py: Shared Fixtures

Three fixtures remove repetition from every test: the app’s URL, a logged-in page and a helper that runs a search. A money() helper turns "₹3,313" into the number 3313.

📄 conftest.py

import re
from datetime import date, timedelta

import pytest
from playwright.sync_api import Page, expect

APP = "/dummy-booking-website/"


def money(text: str) -> int:
    """'₹3,313' -> 3313 (also works for '-₹100')."""
    return int(re.sub(r"[^\d]", "", text))


def future(days: int) -> str:
    return (date.today() + timedelta(days=days)).isoformat()


@pytest.fixture
def logged_in(page: Page) -> Page:
    page.goto(APP)
    page.get_by_test_id("login-username").fill("testuser")
    page.get_by_test_id("login-password").fill("Test@123")
    page.get_by_test_id("login-button").click()
    expect(page.get_by_test_id("step-search")).to_be_visible()
    return page


@pytest.fixture
def search(logged_in: Page):
    """search(origin, destination, days_ahead=14, adults=1, infants=0) fills and submits the search form."""
    def _search(origin="DEL", destination="BOM", days_ahead=14, adults=1, children=0, infants=0):
        p = logged_in
        p.get_by_test_id("from-city").select_option(origin)
        p.get_by_test_id("to-city").select_option(destination)
        p.get_by_test_id("depart-date").fill(future(days_ahead))
        p.get_by_test_id("adults").select_option(str(adults))
        p.get_by_test_id("children").select_option(str(children))
        p.get_by_test_id("infants").select_option(str(infants))
        p.get_by_test_id("search-button").click()
        return p
    return _search

search is a factory fixture (Lesson 58): it returns a function, so each test can search with its own values while the form-filling code exists once.


🔐 Login Tests (Data-Driven)

📄 tests/test_login.py

import pytest
from playwright.sync_api import Page, expect

from conftest import APP


@pytest.mark.parametrize("username, password, error", [
    pytest.param("testuser", "wrong", "Invalid username or password.", id="wrong-password"),
    pytest.param("lockeduser", "Test@123", "This account is locked. Please contact support.", id="locked-user"),
    pytest.param("", "", "Username and password are required.", id="empty-fields"),
])
def test_login_errors(page: Page, username, password, error):
    page.goto(APP)
    page.get_by_test_id("login-username").fill(username)
    page.get_by_test_id("login-password").fill(password)
    page.get_by_test_id("login-button").click()
    expect(page.get_by_test_id("login-error")).to_have_text(error)
    expect(page.get_by_test_id("step-search")).to_be_hidden()


def test_valid_login_shows_user(logged_in: Page):
    expect(logged_in.get_by_test_id("user-bar")).to_contain_text("Signed in as Test User")

🔎 Search Validation Tests

Each validation rule gets one case. The expected messages come from the application, so a changed message is detected immediately.

📄 tests/test_search_validation.py

import pytest
from playwright.sync_api import expect


@pytest.mark.parametrize("kwargs, message", [
    pytest.param({"origin": "DEL", "destination": "DEL"}, "Origin and destination cannot be the same city.", id="same-city"),
    pytest.param({"days_ahead": -1}, "Depart date cannot be in the past.", id="past-date"),
    pytest.param({"days_ahead": 400}, "You can book up to 365 days ahead.", id="too-far-ahead"),
    pytest.param({"adults": 1, "infants": 2}, "Each infant must travel with an adult.", id="infants-over-adults"),
    pytest.param({"adults": 6, "children": 4}, "You can book up to 9 travellers (adults and children) at a time.", id="ten-travellers"),
])
def test_search_validation(search, kwargs, message):
    page = search(**kwargs)
    expect(page.get_by_test_id("search-error")).to_have_text(message)
    expect(page.get_by_test_id("step-flights")).to_be_hidden()


def test_valid_search_lists_flights(search):
    page = search("DEL", "BOM")
    expect(page.get_by_test_id("step-flights")).to_be_visible()
    expect(page.get_by_test_id("flight-card").first).to_be_visible()
    expect(page.get_by_test_id("flights-count")).to_contain_text("flights found")

⌨️ Terminal

pytest tests/test_login.py tests/test_search_validation.py -v

🖥️ Output

============================= test session starts =============================
platform win32 -- Python 3.15.1, pytest-9.2.0, pluggy-1.7.0 -- C:\Users\you\playwright-python\.venv\Scripts\python.exe
cachedir: .pytest_cache
baseurl: https://sqatools.in
rootdir: C:\Users\you\playwright-python
configfile: pytest.ini
plugins: allure-pytest-2.16.2, base-url-2.1.0, bdd-9.0.1, html-4.2.0, metadata-3.1.1, playwright-0.10.0, rerunfailures-16.7, xdist-3.8.0
collecting ... collected 10 items

tests/test_login.py::test_login_errors[chromium-wrong-password] PASSED   [ 10%]
tests/test_login.py::test_login_errors[chromium-locked-user] PASSED      [ 20%]
tests/test_login.py::test_login_errors[chromium-empty-fields] PASSED     [ 30%]
tests/test_login.py::test_valid_login_shows_user[chromium] PASSED        [ 40%]
tests/test_search_validation.py::test_search_validation[chromium-same-city] PASSED [ 50%]
tests/test_search_validation.py::test_search_validation[chromium-past-date] PASSED [ 60%]
tests/test_search_validation.py::test_search_validation[chromium-too-far-ahead] PASSED [ 70%]
tests/test_search_validation.py::test_search_validation[chromium-infants-over-adults] PASSED [ 80%]
tests/test_search_validation.py::test_search_validation[chromium-ten-travellers] PASSED [ 90%]
tests/test_search_validation.py::test_valid_search_lists_flights[chromium] PASSED [100%]

============================= 10 passed in 17.85s =============================

✈️ The End-to-End Booking

The main test walks the whole journey. Each step is a small helper function inside the test module, so the test body reads like the user’s story:

📄 tests/test_booking.py

import re

from playwright.sync_api import Page, expect

from conftest import money


def choose_first_flight(page: Page):
    page.get_by_test_id("select-flight").first.click()
    expect(page.get_by_test_id("step-passengers")).to_be_visible()


def fill_travellers(page: Page):
    page.get_by_test_id("pax-continue").click()                       # empty form first: validation
    expect(page.get_by_test_id("pax-error")).to_contain_text("Please fix")
    page.get_by_test_id("fill-dummy").click()                         # the app's "fill test data" button
    expect(page.get_by_test_id("contact-email")).to_have_value("test.user@example.com")
    page.get_by_test_id("pax-continue").click()
    expect(page.get_by_test_id("step-seats")).to_be_visible()


def choose_seats(page: Page):
    page.get_by_test_id("auto-assign-seats").click()
    page.get_by_test_id("seats-continue").click()
    expect(page.get_by_test_id("step-payment")).to_be_visible()


def pay_with_card(page: Page, number="4111 1111 1111 1111"):
    page.get_by_test_id("card-name").fill("Test User")
    page.get_by_test_id("card-number").fill(number)
    page.get_by_test_id("card-expiry").fill("12/30")
    page.get_by_test_id("card-cvv").fill("123")
    page.get_by_test_id("accept-terms").check()
    page.get_by_test_id("pay-button").click()


def test_one_way_booking_with_promo(search):
    page = search("DEL", "BOM")
    choose_first_flight(page)
    fill_travellers(page)
    choose_seats(page)

    total_before = money(page.get_by_test_id("fare-summary-payment").get_by_test_id("total-price").inner_text())
    page.get_by_test_id("promo-code").fill("SQA100")
    page.get_by_test_id("apply-promo").click()
    expect(page.get_by_test_id("promo-message")).to_have_text("Promo applied: ₹100 off.")

    pay_with_card(page)
    expect(page.get_by_test_id("confirm-title")).to_have_text("Booking confirmed!", timeout=10_000)
    expect(page.get_by_test_id("pnr")).to_have_text(re.compile(r"^[A-Z2-9]{6}$"))
    expect(page.get_by_test_id("booking-id")).to_have_text(re.compile(r"^SQA-\d{8}-\d{5}$"))
    assert money(page.get_by_test_id("amount-paid").inner_text()) == total_before - 100
    expect(page.get_by_test_id("confirm-passengers")).to_contain_text("Mr Ravi Sharma")
    print(f"\nPNR {page.get_by_test_id('pnr').inner_text()} paid {page.get_by_test_id('amount-paid').inner_text()}")


def test_fare_breakdown_adds_up(search):
    page = search("DEL", "BLR", adults=2)
    choose_first_flight(page)
    breakdown = page.get_by_test_id("fare-summary-passengers").get_by_test_id("fare-breakdown")
    values = dict(zip(breakdown.locator("dt").all_inner_texts(), breakdown.locator("dd").all_inner_texts()))
    print("\n", values)
    base, taxes, fee, total = (money(values[k]) for k in ("Base fare", "Taxes and fees", "Convenience fee", "Total"))
    assert total == base + taxes + fee
    assert fee == 199

⌨️ Terminal

pytest tests/test_booking.py -v -s

🖥️ Output

============================= test session starts =============================
platform win32 -- Python 3.15.1, pytest-9.2.0, pluggy-1.7.0 -- C:\Users\you\playwright-python\.venv\Scripts\python.exe
cachedir: .pytest_cache
baseurl: https://sqatools.in
rootdir: C:\Users\you\playwright-python
configfile: pytest.ini
plugins: allure-pytest-2.16.2, base-url-2.1.0, bdd-9.0.1, html-4.2.0, metadata-3.1.1, playwright-0.10.0, rerunfailures-16.7, xdist-3.8.0
collecting ... collected 2 items

tests/test_booking.py::test_one_way_booking_with_promo[chromium] 
PNR LRWLS6 paid ₹3,213
PASSED
tests/test_booking.py::test_fare_breakdown_adds_up[chromium] 
 {'Base fare': '₹6,080', 'Taxes and fees': '₹730', 'Convenience fee': '₹199', 'Total': '₹7,009'}
PASSED

============================== 2 passed in 7.27s ==============================

Notes on the techniques used:

  • Waiting for steps: each helper ends with an expect(...).to_be_visible() on the next step, so the following helper never starts too early (the same synchronisation idea as Lesson 56).
  • Money parsing: comparing numbers (total_before - 100) is more meaningful than comparing strings, and it catches rounding bugs.
  • Regex assertions: a PNR is random, but its format (six letters/digits, no confusable 0, 1, I, O) is a requirement you can test.
  • timeout=10_000 on the confirmation: the app shows a 2-second “processing” overlay, so the default 5 seconds is enough today but the larger timeout documents that this step is slow by design.

💳 Payment Failure Path

A good suite tests what happens when things go wrong, not just the happy path:

📄 tests/test_payment.py

from playwright.sync_api import expect

from tests.test_booking import choose_first_flight, choose_seats, fill_travellers, pay_with_card


def go_to_payment(search):
    page = search("BOM", "GOI")
    choose_first_flight(page)
    fill_travellers(page)
    choose_seats(page)
    return page


def test_declined_card(search):
    page = go_to_payment(search)
    pay_with_card(page, number="4000 0000 0000 0002")
    expect(page.get_by_test_id("pay-error")).to_contain_text("Payment declined by the bank", timeout=10_000)
    expect(page.get_by_test_id("confirm-title")).to_have_count(0)


def test_terms_are_required(search):
    page = go_to_payment(search)
    page.get_by_test_id("card-name").fill("Test User")
    page.get_by_test_id("card-number").fill("4111 1111 1111 1111")
    page.get_by_test_id("card-expiry").fill("12/30")
    page.get_by_test_id("card-cvv").fill("123")
    page.get_by_test_id("pay-button").click()                         # terms not accepted
    expect(page.get_by_test_id("pay-error")).to_have_text("Please check the payment details.")

📊 Run Everything with a Report

⌨️ Terminal

pytest --html=reports/report.html --self-contained-html -q

🖥️ Output

..............                                                           [100%]
- Generated html report: file:///C:/Users/you/playwright-python/reports/report.html -
14 passed in 31.98s

All tests pass, and reports/report.html holds the results (with a screenshot for any failure, thanks to --screenshot only-on-failure and Lesson 63’s hook if you add it). Open it in a browser and share it.

💡 Tip: Run the suite in parallel once you are confident the tests are independent: pip install pytest-xdist and pytest -n 4 (Lesson 65). Every test here logs in with its own browser context, so they can run side by side.


🧠 What This Project Practised

Skill Where
Fixtures and factory fixtures logged_in, search in conftest.py (Lessons 25, 58)
Data-driven tests with ids login errors, search validation (Lesson 45)
Locators by test id, scoped locators fare-summary-payment → total-price (Lessons 31, 32)
Web-first assertions and regex matching to_have_text(re.compile(...)) (Lesson 37)
Synchronising multi-step flows step helpers ending with expect (Lessons 38, 56)
Reporting pytest-html, screenshots on failure (Lessons 39, 63)

🏋️ Practice Exercises

Try each exercise on your own first, then open the answer to compare. The answers use the same practice sites and project layout as the lesson.

Exercise 1: Add a test for a round trip DEL → BOM with a return date 5 days after departure. Which extra steps does the flow need? Write the search part.

Show answer
def test_round_trip_search(logged_in):
    p = logged_in
    p.get_by_test_id("trip-round").check()
    p.get_by_test_id("from-city").select_option("DEL")
    p.get_by_test_id("to-city").select_option("BOM")
    p.get_by_test_id("depart-date").fill(future(14))
    p.get_by_test_id("return-date").fill(future(19))
    p.get_by_test_id("search-button").click()
    expect(p.get_by_test_id("step-flights")).to_be_visible()

A round trip has two legs, so you select an outbound and a return flight, and the seat step asks for seats on both legs. Also add a validation case: a return date before the depart date must show “Return date cannot be before the depart date.”

Exercise 2: Write a test that sorts the results by “Lowest price” and checks that the flight prices are in ascending order.

Show answer
def test_sort_by_price(search):
    page = search("DEL", "BOM")
    page.get_by_test_id("sort-by").select_option(label="Lowest price")
    prices = [money(t) for t in page.get_by_test_id("flight-price").all_inner_texts()]
    assert prices == sorted(prices)

Exercise 3: Pay with UPI instead of a card. The UPI radio has test id pay-upi, the field upi-id; success@upi succeeds and failure@upi is declined. Write the helper.

Show answer
def pay_with_upi(page, upi="success@upi"):
    page.get_by_test_id("pay-upi").check()
    page.get_by_test_id("upi-id").fill(upi)
    page.get_by_test_id("accept-terms").check()
    page.get_by_test_id("pay-button").click()

Use it in a parametrized test with ("success@upi", "Booking confirmed!") and ("failure@upi", "Payment declined").

Exercise 4: The project repeats the steps from search to payment in two test modules. How would you refactor it as the suite grows?

Show answer

Move the step helpers into page objects (one class per step: SearchPage, FlightsPage, TravellersPage, SeatsPage, PaymentPage) and add a fixture such as payment_page that returns the payment step ready to use. That is exactly what Project 2 does for the e-commerce site (Lessons 56 and 58 show the patterns).


🧠 MCQ Quiz: Project 1: Flight Booking Automation (Beginner)

10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.

  1. Why does each step helper end with an expect(...).to_be_visible() on the next step?
  2. What is the search fixture in conftest.py?
  3. Why convert “₹3,313” to an integer before comparing?
  4. How does the test check a random PNR?
  5. Why test a declined card?
  6. What does --screenshot only-on-failure in pytest.ini do?
  7. How are the search-validation cases kept readable?
  8. Which locator gets the total price on the payment step only?
  9. Why does the confirmation assertion use timeout=10_000?
  10. What is the natural next step as this suite grows?

Want a longer, timed test? Take the Playwright Python mock interviews (13 modules, 20 MCQs each).


❓ Frequently Asked Questions

🤔 Can I run this project against another booking site?

The structure, yes; the locators and messages are specific to the SQA Tools app. Real sites usually need test accounts, test payment modes and permission to automate them.

🤔 Why do tests import from conftest.py?

money(), future() and APP are small shared helpers. Importing them from conftest.py is fine for a small project; in a bigger one, move them into a utils/ package (Lesson 57).

🤔 Will these tests break when dates change?

No: dates are computed relative to today (future(14)), and the app’s flights are generated for any date. Never hard-code dates in tests that check “past” or “future” rules.

🤔 How long does the suite take?

About a minute on one worker. With pytest-xdist and four workers it drops to around 20 seconds.

🤔 Where can I compare my solution?

Run your tests against the same app and compare the results with the outputs above. The practice questions extend the project with round trips, sorting and UPI payments.


🏁 Summary

  • You planned scenarios from the app, then built a small, clean pytest project with shared fixtures.
  • Login and search validation are data-driven with readable ids; the end-to-end test books a flight and checks the PNR format and the money arithmetic.
  • Step helpers synchronise with expect, and negative paths (declined card, missing terms) are tested too.
  • The suite produces an HTML report with failure screenshots.
  • Next: Project 2 turns these ideas into a full page-object framework for an e-commerce site.

🎬 Watch the Playwright tutorial series on YouTube!

Subscribe to SqaToolsByDY • Practice on the SQA Tools Automation Practice Page

AI Tools for Python Test Automation with Playwright (and What Is JS-Only)

AI assistants can now write, run, fix and explain Playwright tests. Used well, they remove the boring parts of automation: boilerplate, locator hunting, first-pass failure analysis. Used carelessly, they produce tests that pass for the wrong reasons. In this lesson you will see the AI tooling available to Python testers in late 2026, analyse a failed test with the Playwright trace command line, make every failure report “AI-ready” with a small pytest hook, use a reliable workflow for generating and fixing tests with a coding agent, and learn which Playwright AI features exist only for the TypeScript test runner.

📖 What You’ll Learn: the categories of AI tools for testers, coding agents (Claude Code, GitHub Copilot, Cursor) in a pytest project, project instructions files, the playwright trace CLI (open, actions, errors, requests), an AI-ready failure prompt generated by a pytest hook, a generate-run-review workflow, using AI for test data and refactoring, reviewing AI-written tests, Playwright features that are TypeScript-only (test agents, UI mode, the HTML reporter) and their Python equivalents, privacy and cost.


🧭 The AI Tool Landscape for Python Testers

Category Examples What they do for you
Coding agents Claude Code, GitHub Copilot agent mode, Cursor Read your repository, write and edit tests, run pytest, fix failures
Browser tools for agents Playwright MCP, playwright-cli (Lesson 70) Let the agent open the app, read accessibility snapshots, find locators
Failure analysis Playwright trace CLI, AI-ready reports, chat assistants Explain why a test failed from trace, logs and page state
Inline completion Copilot, editor assistants Finish the line or the test you are typing
LLM APIs in your own tools Anthropic, OpenAI and other SDKs Custom helpers such as test-case generators or triage bots (see the AI for Software Testers course)

The common thread: AI is fastest when it has context (your code, your conventions, the failure evidence) and a way to check its own work (running the tests).


🧑‍💻 Coding Agents in a pytest Project

A coding agent works best in a repository that explains itself. Most agents read an instructions file at the project root (CLAUDE.md for Claude Code, .github/copilot-instructions.md for Copilot, AGENTS.md for several others):

📄 CLAUDE.md

# Test project instructions

- Stack: Python 3.13, pytest 9, pytest-playwright 0.10, Playwright 1.65 (sync API).
- Run tests: `pytest` (base URL comes from pytest.ini). One test: `pytest -k <name>`.
- Page objects live in pages/, fixtures in tests/conftest.py. Reuse them; do not duplicate locators.
- Locators: get_by_test_id or get_by_role. No XPath, no CSS chains, no time.sleep().
- Every test needs expect() assertions on visible outcomes.
- Test data: test accounts from .env (never hard-code real credentials).
- Debugging: run with --tracing retain-on-failure, then inspect with `python -m playwright trace`.

With that file, a request such as “Add a test that the SAVE10 coupon gives ₹500 off on a cart with Wireless Earbuds; run it and fix it until it passes” produces code that follows your conventions, because the agent was told them. Without it, you get generic code.

💡 Tip: Keep the instructions short and factual: commands, folders, rules. Agents follow concrete rules (“no XPath”) much better than general advice (“write good tests”).


🔍 Failure Analysis with the Trace CLI

Playwright Python includes a trace command line (python -m playwright trace) that reads trace files without opening a browser. It is designed for exactly this situation: an agent, or you in a terminal, investigating a failure.

Let’s produce a failure with a trace:

📄 pytest.ini

[pytest]
addopts = --base-url https://sqatools.in

📄 tests/test_coupon.py

from playwright.sync_api import Page, expect

SHOP = "/dummy-ecommerce-website/"


def test_flat200_discount(page: Page):
    page.goto(SHOP + "#/search/earbuds")
    page.get_by_role("button", name="Add to cart").first.click()
    page.goto(SHOP + "#/cart")
    page.get_by_test_id("coupon-input").fill("FLAT200")
    page.get_by_test_id("apply-coupon").click()
    expect(page.get_by_test_id("coupon-discount")).to_have_text("−₹250", timeout=3_000)   # expectation is wrong

⌨️ Terminal

pytest --tracing retain-on-failure -q --tb=no

🖥️ Output

F                                                                        [100%]
=========================== short test summary info ===========================
FAILED tests/test_coupon.py::test_flat200_discount[chromium] - AssertionError...
1 failed in 5.84s

Now inspect the trace from the terminal:

📄 find_trace.py

from pathlib import Path

print(next(Path("test-results").rglob("trace.zip")).as_posix())

⌨️ Terminal

python find_trace.py
python -m playwright trace open test-results/tests-test-coupon-py-test-flat200-discount-chromium/trace.zip

🖥️ Output

test-results/tests-test-coupon-py-test-flat200-discount-chromium/trace.zip
  Browser:      chromium
  Platform:     win32
  Playwright:   1.65.1
  Title:        tests-test-coupon-py-test-flat200-discount-chromium
  Duration:     4.9s
  Start time:   2026-11-24T13:33:17.291Z
  Viewport:     1280x720
  Actions:      7
  Pages:        1
  Network:      34 requests
  Errors:       1
  Attachments:  0
  Console:      1 messages

⌨️ Terminal

python -m playwright trace actions

🖥️ Output

     # Time       Action                                                  Duration
  ──── ─────────  ─────────────────────────────────────────────────────── ────────
    1. 0:00.004  Create page                                                 92ms
    2. 0:00.099  Navigate                                                    1.6s
                 /dummy-ecommerce-website/#/search/earbuds
    3. 0:01.696  Click                                                       59ms
                 getByRole('button', { name: 'Add to cart' }).first()
    4. 0:01.760  Navigate                                                     8ms
                 /dummy-ecommerce-website/#/cart
    5. 0:01.791  Fill "FLAT200"                                              22ms
                 getByTestId('coupon-input')
    6. 0:01.819  Click                                                       52ms
                 getByTestId('apply-coupon')
    7. 0:01.875  Expect "to_have_text"                                       3.0s  ✗
                 getByTestId('coupon-discount')

⌨️ Terminal

python -m playwright trace errors

🖥️ Output

  ✗ Expect "to_have_text" getByTestId('coupon-discount')
    at test_coupon.py:12:0

    Expect failed

The action list shows every step with its duration and marks the failed one (✗); errors shows the failing assertion with its source line. Other commands include trace action <id> (parameters, call log and snapshots of one step), trace requests, trace console and trace snapshot <id>.

This is why the trace CLI matters for AI: an agent can read these short text outputs, open the snapshot of the failing step, and tell you whether the app or the test is wrong, instead of guessing from a stack trace.


📝 Make Every Failure AI-Ready

You do not need an agent to benefit. A small hook can write a ready-to-paste prompt for every failed test, containing the evidence any assistant (or teammate) needs:

📄 tests/conftest.py

from pathlib import Path

import pytest

PROMPTS = Path("ai-prompts")


@pytest.hookimpl(wrapper=True)
def pytest_runtest_makereport(item, call):
    report = yield
    if report.when == "call" and report.failed:
        page = item.funcargs.get("page")
        snapshot = ""
        if page is not None and not page.is_closed():
            try:
                snapshot = page.locator("#sp-view").aria_snapshot(timeout=2_000)   # the store's main view
            except Exception:
                snapshot = page.locator("body").aria_snapshot(timeout=2_000)
        source = Path(item.path).read_text(encoding="utf-8")
        PROMPTS.mkdir(exist_ok=True)
        (PROMPTS / f"{item.name}.md").write_text(
            f"# Failing Playwright test: {item.nodeid}\n\n"
            f"Decide whether the application or the test is wrong, and propose a minimal fix.\n\n"
            f"## Error\n```\n{report.longreprtext[-2500:]}\n```\n\n"
            f"## Page URL\n{page.url if page else 'n/a'}\n\n"
            f"## Accessibility snapshot of the page at failure\n```yaml\n{snapshot[:4000]}\n```\n\n"
            f"## Test source\n```python\n{source}\n```\n",
            encoding="utf-8")
    return report

⌨️ Terminal

pytest -q --tb=no
python -c "import pathlib; t = pathlib.Path('ai-prompts/test_flat200_discount[chromium].md').read_text(encoding='utf-8'); i = t.index('## Accessibility'); print(t[:300]); print('...'); print(t[i:i+1400])"

🖥️ Output

F                                                                        [100%]
=========================== short test summary info ===========================
FAILED tests/test_coupon.py::test_flat200_discount[chromium] - AssertionError...
1 failed in 5.71s
# Failing Playwright test: tests/test_coupon.py::test_flat200_discount[chromium]

Decide whether the application or the test is wrong, and propose a minimal fix.

## Error
```
E   AssertionError: Locator expected to have text '−₹250'
    Actual value: −₹200 
    Call log:
      - Expect "to_have_tex
...
## Accessibility snapshot of the page at failure
```yaml
- main:
  - heading "Shopping cart (1 item)" [level=2]
  - link "Wireless Earbuds":
    - /url: "#/p/EL-013"
    - img "Wireless Earbuds":
      - img "🎧"
  - heading "Wireless Earbuds" [level=4]:
    - link "Wireless Earbuds":
      - /url: "#/p/EL-013"
  - text: Voltix · Black
  - group "Quantity for Wireless Earbuds":
    - button "Decrease quantity" [disabled]: −
    - textbox "Quantity": "1"
    - button "Increase quantity": +
  - button "Save for later"
  - button "Remove"
  - text: ₹13,299 ₹16,619
  - complementary:
    - heading "Price details" [level=3]
    - term: Price (1 item)
    - definition: ₹16,619
    - term: Discount
    - definition: −₹3,320
    - term: Coupon (FLAT200)
    - definition: −₹200
    - term: Delivery
    - definition: Free
    - term: Total amount
    - definition: ₹13,099
    - paragraph: You save ₹3,520 on this order
    - text: Coupon code
    - textbox "Coupon code": FLAT200
    - button "Apply"
    - paragraph: Coupon FLAT200 applied.
    - button "Proceed to checkout"
    - link "← Continue shopping":
      - /url: "#/"
```

## Test source
```python
from playwright.sync_api import Page, expect

SHOP = "/dummy-ecommerce-website/"


def test_flat200_discount(page: Page):
    page.goto(SHOP + "#/search/earbuds")
    page.get_by_role("button", name="Add to cart").first.click()
    page.g

The snapshot of the cart shows the discount line −₹200 next to the coupon message, so any assistant (or a human reading the file) can see immediately that the test expected the wrong amount. Accessibility snapshots are compact text, which is exactly what language models read best, and cheaper than screenshots.

⚠️ Watch out: Failure prompts contain page content and test code. Do not paste them into AI services that your company has not approved, and never include real customer data or secrets.


🔁 A Generate, Run, Review Workflow

The most reliable way to use a coding agent for new tests:

  1. Describe the behaviour, not the clicks: “A guest applying FLAT200 to a cart under ₹1,499 sees ‘Add ₹X more to use FLAT200.'”
  2. Point to the conventions: the instructions file, an existing similar test, the page objects to reuse.
  3. Let it explore the app with playwright-cli or MCP (Lesson 70) to find stable locators.
  4. Require a green run: “Run the test with pytest and iterate until it passes.”
  5. Review like a pull request, with the checklist below.
  6. Break it on purpose once: change the expected value and confirm the test fails. A test that cannot fail is worthless.

Review checklist for AI-written tests

Check Why
Does every test assert a visible outcome with expect? Agents sometimes “pass” tests by removing assertions
Are expected values from the requirement, not copied from the current app? Otherwise today’s bug becomes tomorrow’s expectation
Are locators role/test-id based and reused from page objects? Generated XPath and CSS chains are brittle
No sleeps, no retries added to hide flakiness? They hide real timing bugs (Lesson 44)
Is test data unique and cleaned up? Collisions in parallel runs (Lesson 65)
Does it fail when the behaviour is broken? Mutation check from step 6

🧰 Other Good Uses of AI in Test Work

  • Test ideas and edge cases: ask for boundary values and negative cases for a form, then choose the valuable ones.
  • Test data: realistic but fake names, addresses and products for factories (Lesson 58), never real personal data.
  • Refactoring: “Move the locators of these five tests into page objects”, followed by a full test run.
  • Explaining legacy tests and translating Selenium or TypeScript Playwright tests to Python.
  • Flaky test triage: give the agent traces from a passing and a failing run of the same test and ask what differs.

🚫 What Is TypeScript-Only (and the Python Equivalent)

Some Playwright AI and developer-experience features are part of Playwright Test, the TypeScript/JavaScript test runner, and are not available in Python:

Playwright Test (TypeScript) feature Python equivalent
Test agents (planner, generator, healer) set up with npx playwright init-agents A coding agent with playwright-cli or MCP, your instructions file and the workflow above
UI mode (npx playwright test --ui) --headed, PWDEBUG=1, the Inspector and the Trace Viewer (Lessons 61, 62)
Built-in HTML reporter with trace links pytest-html or Allure (Lessons 63, 64)
test.step() grouping in reports and traces allure.step in Allure; context.tracing.group() in traces
Built-in projects, retries, sharding in playwright.config.ts pytest markers, pytest-rerunfailures, pytest-xdist, CI matrices

The browser automation API, Codegen, the Trace Viewer, the trace CLI, playwright-cli and the MCP server are shared, so Python testers have the essential building blocks. If your team needs the TypeScript-only features, the Playwright TypeScript course covers them.


🔐 Privacy, Security and Cost

  • Use AI services your organisation has approved; check what is sent and where it is stored.
  • Keep secrets out of prompts and instructions files; use environment variables and storage-state files.
  • Give agents test environments and accounts, and keep a human in the loop for anything irreversible.
  • Agent sessions cost tokens and time. Use them to create and repair tests; run the resulting suite in CI with plain pytest.

🏋️ Practice Exercises

Try each exercise on your own first, then open the answer to compare. The answers use the same practice sites and project layout as the lesson.

Exercise 1: Write three rules you would put in a project’s agent instructions file to stop generated tests from using fragile locators and fixed waits.

Show answer
- Locators: use page objects from pages/; otherwise get_by_test_id or get_by_role with exact names. Never XPath or nth-child CSS.
- Never use time.sleep() or page.wait_for_timeout(); use expect() assertions, which wait automatically.
- Every new test must contain at least one expect() assertion on a user-visible outcome and must be run with pytest before you finish.

Exercise 2: Which trace CLI commands would you run, in order, to find the failing step of a trace and the network requests around it?

Show answer
python -m playwright trace open test-results/<test-folder>/trace.zip
python -m playwright trace errors
python -m playwright trace actions
python -m playwright trace requests
python -m playwright trace close

errors points to the failing action, actions gives its ID and timing, and requests shows whether the backend answered.

Exercise 3: An AI agent “fixed” a failing test by changing to_have_text("−₹250") to to_have_text(re.compile(".*")). What is wrong and how would your review checklist catch it?

Show answer

The assertion can no longer fail, so the test checks nothing. The checklist items “does every test assert a visible outcome” and “does it fail when the behaviour is broken” (the mutation check) catch it. The real fix is to compare the expected value with the requirement: FLAT200 gives ₹200 off, so the expectation should be −₹200.

Exercise 4: Extend the failure-prompt hook so it also includes the last five browser console errors. Assume an autouse fixture console_errors (a list) like in Lesson 63.

Show answer
errors = item.funcargs.get("console_errors") or []
console_section = "\n".join(errors[-5:]) or "none"
# then add to the file:
f"## Console errors\n```\n{console_section}\n```\n\n"

Console errors often reveal application bugs (failed scripts, API errors) that explain a UI failure.


🧠 MCQ Quiz: AI Tools for Python Test Automation

10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.

  1. What makes coding agents most effective in a test project?
  2. Which file does Claude Code read for project instructions?
  3. What does python -m playwright trace actions show?
  4. Why are accessibility snapshots good input for AI failure analysis?
  5. What is the purpose of the mutation check in the workflow?
  6. Which Playwright feature is TypeScript-only?
  7. What is the Python equivalent of Playwright Test’s UI mode for debugging?
  8. An AI suggests fixing a flaky test by adding time.sleep(5). What should you do?
  9. What should never be included in prompts sent to AI services?
  10. Where should AI agents run tests and explore the app?

Want a longer, timed test? Take the Module 13 mock interview (20 MCQs in 20 minutes).


❓ Frequently Asked Questions

🤔 Which AI tool should a Python tester start with?

A coding agent you are allowed to use at work (Claude Code, GitHub Copilot or similar), plus a project instructions file. Add playwright-cli when you want the agent to explore the application itself.

🤔 Can AI write my whole framework?

It can draft much of it, but framework decisions (structure, data strategy, environments, what to test) depend on your product and team. Use AI to speed up implementation of a design you understand, following Module 10.

🤔 Will self-healing tests come to Python?

The idea (an agent that repairs broken locators) works in Python today through coding agents with the trace CLI and playwright-cli. Fully automatic healing in CI is risky: a “healed” test may now check the wrong element. Prefer agents that propose fixes as pull requests for review.

🤔 Does using AI make tests flakier?

Only if generated code is accepted without review. With the conventions file, the review checklist and the mutation check, AI-written tests are as reliable as hand-written ones.

🤔 How do I practise these skills?

Use the SQA Tools practice apps (store, bank, booking) and the practice API with your agent, then compare its tests with the ones in this course. The projects in Module 14 make good targets.


🏁 Summary

  • Python testers can use coding agents, playwright-cli and MCP, the trace CLI and LLM APIs; context and a test-run feedback loop make them effective.
  • A short project instructions file (commands, folders, locator and assertion rules) steers agents toward your conventions.
  • python -m playwright trace open/actions/errors/requests analyses failures in text; a pytest hook can write AI-ready failure prompts with error, URL, accessibility snapshot and source.
  • Follow describe, explore, run, review and mutation-check; review AI tests for real assertions, stable locators and no sleeps.
  • Playwright Test agents, UI mode and the HTML reporter are TypeScript-only; Python has equivalents for each need.

🎬 Watch the Playwright tutorial series on YouTube!

Subscribe to SqaToolsByDY • Practice on the SQA Tools Automation Practice Page

Playwright MCP and playwright-cli for Python Testers

AI coding agents such as Claude Code and GitHub Copilot can drive a real browser through Playwright, look at the page, and write the test code for you. Two official tools make that possible: the Playwright MCP server and the newer, token-efficient playwright-cli, which ships inside the Playwright Python package. In this lesson you will drive the SQA Shop from the terminal with playwright-cli, read its accessibility snapshots and element refs, turn the Python code it prints into a pytest test, connect the Playwright MCP server to an AI agent with Python code generation, use both safely, and understand what these tools are good at and where you still need to think for yourself.

📖 What You’ll Learn: what MCP is and how Playwright MCP works, the difference between MCP and playwright-cli, running python -m playwright cli, sessions, open, snapshot, find, fill, click and close, element refs and why they expire, the Python code the CLI prints, state-save and Lesson 51, turning a session into a pytest test, the –playwright-debug=cli option of pytest-playwright, configuring Playwright MCP for Claude Code and VS Code with –codegen python, useful MCP options, a prompt workflow for test generation, bot protection, safety rules and limits.


🤖 MCP in One Minute

The Model Context Protocol (MCP) is an open standard that lets AI applications call tools: “navigate to this URL”, “click this element”, “read this file”. An MCP server offers tools; an MCP client (Claude Code, Claude Desktop, VS Code with Copilot, Cursor …) lets the AI model call them. The SQA Tools MCP lesson explains the protocol itself.

Microsoft publishes two ways for AI agents to drive Playwright:

Playwright MCP (@playwright/mcp) playwright-cli
Interface MCP tools (browser_navigate, browser_click, browser_snapshot …) Shell commands (open, click, snapshot …)
Best for Long, exploratory agent sessions with rich page context Coding agents working in a repository: fewer tokens, short outputs
Page data in the model’s context Accessibility snapshots after actions Only what the agent asks for (snapshots are saved to files)
Python code output --codegen python Printed after every action
Install Node.js: npx @playwright/mcp@latest Included in Playwright Python 1.59+ (python -m playwright cli), or npm i -g @playwright/cli

Both work on the same idea: instead of screenshots, the agent reads an accessibility snapshot, a compact text tree of roles and names where every element has a short ref such as e113.


⌨️ playwright-cli from Python

Playwright Python 1.65 includes the CLI. No Node.js is needed:

⌨️ Terminal

python -m playwright cli --help

Here is a recorded session against the SQA Shop login page (24 November 2026). First open a browser session and the page:

⌨️ Terminal

python -m playwright cli open --browser firefox "https://sqatools.in/dummy-ecommerce-website/#/login"

🖥️ Example output

### Browser `default` opened with pid 2864.
### Ran Playwright code
    page.goto("https://sqatools.in/dummy-ecommerce-website/#/login")
### Page
- Page URL: https://sqatools.in/dummy-ecommerce-website/#/login
- Page Title: Dummy E-commerce Website For Automation Practice | SQA Tools
### Snapshot
- [Snapshot](.playwright-cli\page-2026-11-24T12-58-57-802Z.yml)

The browser stays open in the background between commands (a session). The full snapshot is written to a file in .playwright-cli/ instead of being printed, which is what keeps the CLI token-efficient for AI agents. Search it instead of reading all of it:

⌨️ Terminal

python -m playwright cli find "Username"

🖥️ Example output

### Result
Found 2 matches for "Username":
...
                  - heading "Log in" [level=2] [ref=e109]
                  - paragraph [ref=e110]: Logging in is optional. You can also check out as a guest.
                  - generic [ref=e111]:
                    - generic [ref=e112]: Username
                    - textbox "Username" [ref=e113]
                  - generic [ref=e114]:
                    - generic [ref=e115]: Password
                    - textbox "Password" [ref=e116]

Act on elements by ref, or with a Playwright locator, and watch the Python code the CLI prints (the CLI prints Markdown; the code fences are shown indented here):

⌨️ Terminal

python -m playwright cli fill e113 testuser
python -m playwright cli fill e116 "Test@123"
python -m playwright cli click "getByRole('button', { name: 'Log in', exact: true })"

🖥️ Example output

### Ran Playwright code
    page.get_by_test_id("login-username").fill("testuser")
### Ran Playwright code
    page.get_by_test_id("login-password").fill("Test@123")
### Ran Playwright code
    page.get_by_role("button", name="Log in", exact=True).click()
### Page
- Page URL: https://sqatools.in/dummy-ecommerce-website/#/

Three things stand out:

  1. The CLI turned ref e113 into the best stable locator it could find, here the data-testid, exactly what you would choose by hand (Lesson 31).
  2. Locator arguments use the JavaScript form (getByRole('button', {...})); the printed code is Python.
  3. After the click the page navigated to #/. Old refs are now invalid: generate-locator e113 answers “Ref e113 not found in the current page snapshot. Try capturing new snapshot.” Take a new snapshot (or find) after every navigation.

Finish the session:

⌨️ Terminal

python -m playwright cli find "Hi, Test"
python -m playwright cli state-save shopper.json
python -m playwright cli close

state-save writes a storage-state file, the same format as Lesson 51, so a logged-in session explored by hand or by an agent can be reused in your tests.

⚠️ Watch out: Bot protection. In this session Chrome was blocked: the SQA Tools host answered the CLI’s default Chrome browser with a “Checking your browser” page (HTTP 403), while --browser firefox and normal pytest-playwright runs worked. Many production sites protect themselves against automated browsers. Test against your own test environments, and ask the site owner before automating anyone else’s site.


🧪 From Session to pytest Test

The printed code is a draft. Paste it into a test, then do the part only a tester can do: decide what to assert.

📄 pytest.ini

[pytest]
addopts = --base-url https://sqatools.in

📄 tests/test_from_cli.py

from playwright.sync_api import Page, expect


def test_login_recorded_with_cli(page: Page):
    page.goto("/dummy-ecommerce-website/#/login")
    page.get_by_test_id("login-username").fill("testuser")                 # printed by the CLI
    page.get_by_test_id("login-password").fill("Test@123")                 # printed by the CLI
    page.get_by_role("button", name="Log in", exact=True).click()          # printed by the CLI
    expect(page.get_by_test_id("account-button")).to_contain_text("Hi, Test")   # added by you
    expect(page).to_have_url("https://sqatools.in/dummy-ecommerce-website/#/")  # added by you

⌨️ Terminal

pytest -v

🖥️ Output

============================= test session starts =============================
platform win32 -- Python 3.15.1, pytest-9.2.0, pluggy-1.7.0 -- C:\Users\you\playwright-python\.venv\Scripts\python.exe
cachedir: .pytest_cache
baseurl: https://sqatools.in
rootdir: C:\Users\you\playwright-python
configfile: pytest.ini
plugins: allure-pytest-2.16.2, base-url-2.1.0, bdd-9.0.1, html-4.2.0, metadata-3.1.1, playwright-0.10.0, rerunfailures-16.7, xdist-3.8.0
collecting ... collected 1 item

tests/test_from_cli.py::test_login_recorded_with_cli[chromium] PASSED    [100%]

============================== 1 passed in 2.66s ==============================

Recorded steps without assertions are not a test. The CLI (like Codegen in Lesson 7) gives you reliable locators and actions; you add expectations, data and structure (page objects, fixtures).


🐞 Debug a Failing Test with the CLI

pytest-playwright 0.10 adds --playwright-debug=cli. The test pauses at the start, prints an attach command, and you (or an AI agent) can inspect and drive the paused browser with CLI commands:

⌨️ Terminal

pytest tests/test_from_cli.py --playwright-debug=cli -s

🖥️ Example output

### The test is currently paused at the start

### Debugging Instructions
- Run `python -m playwright cli attach tw-3f9a1c` to attach to this test

It requires -s (so the attach command is visible) and a single worker (no -n). It is a powerful way to let an agent investigate a failure in the real test context instead of guessing from a stack trace.


🔌 Playwright MCP with an AI Agent

The MCP server runs with Node.js 20+. Add it to Claude Code, asking for Python code generation:

⌨️ Terminal

claude mcp add playwright -- npx @playwright/mcp@latest --codegen python --isolated

Or to VS Code (GitHub Copilot agent mode) in .vscode/mcp.json:

{
  "servers": {
    "playwright": {
      "command": "npx",
      "args": ["@playwright/mcp@latest", "--codegen", "python", "--isolated", "--browser", "firefox"]
    }
  }
}

Useful options (all also available as PLAYWRIGHT_MCP_* environment variables):

Option Effect
--codegen python Generated code is Python (default is TypeScript)
--isolated Fresh in-memory profile per session: no leftover cookies between runs
--storage-state=shopper.json Start isolated sessions logged in (Lesson 51 files work here)
--browser firefox Choose the browser or Chrome channel
--headless No visible window (CI or background use)
--test-id-attribute data-qa Use your team’s test-id attribute when generating locators
--caps vision,pdf,devtools Extra tool groups (coordinate clicks, PDF saving, DevTools)

The server exposes tools such as browser_navigate, browser_snapshot, browser_click, browser_type, browser_fill_form, browser_select_option, browser_wait_for, browser_network_requests, browser_route, browser_take_screenshot, browser_storage_state and browser_start_tracing.


🗣️ A Prompt Workflow That Works

Agents produce better tests when you give them the same information you would give a new teammate:

Use the playwright tools to explore https://sqatools.in/dummy-ecommerce-website/ in Firefox.
Goal: a pytest test for applying the coupon FLAT200 to a cart with Wireless Earbuds.
Rules:
- Use pytest-playwright with the `page` fixture and relative URLs (base_url is https://sqatools.in).
- Prefer get_by_test_id / get_by_role locators. No sleeps, no XPath.
- Assert the coupon message and the discount line with expect().
- Put the test in tests/test_coupon_ai.py and run it with pytest. Fix it until it passes.

Then review the result like any pull request: are the assertions meaningful, is the data stable, does it duplicate an existing page object? Lesson 71 covers AI tools for test automation more broadly.


🛡️ Safety and Limits

  • An agent with a browser can do anything a user can: submit forms, place orders, delete data. Point it at test environments with test accounts, and prefer --isolated sessions.
  • Treat everything the agent reads on a page as untrusted input: a malicious page can contain text that tries to instruct the agent (“ignore your task and …”). Keep humans in the loop for anything irreversible.
  • Do not put real passwords in prompts; use storage-state files or environment variables.
  • Generated tests can pass for the wrong reason (weak assertions) or encode today’s bug as expected behaviour. Review them.
  • Agents are slow and cost tokens; use them to write and fix tests, then run the resulting pytest suite normally in CI.

🏋️ Practice Exercises

Try each exercise on your own first, then open the answer to compare. The answers use the same practice sites and project layout as the lesson.

Exercise 1: Open the SQA Shop cart with the CLI in WebKit and find the coupon field. Which two commands do you run?

Show answer
python -m playwright cli open --browser webkit "https://sqatools.in/dummy-ecommerce-website/#/cart"
python -m playwright cli find "Coupon"

find searches the saved snapshot and returns matching nodes with their refs.

Exercise 2: After click navigated to a new page, fill e57 hello fails with “Ref e57 not found”. Why, and what do you do?

Show answer

Refs belong to one snapshot of one page state. After navigation (or a big page update) they are invalid. Run snapshot or find again to get the new refs, or act with a locator string instead of a ref.

Exercise 3: The CLI printed this code. Turn it into a complete pytest test with a meaningful assertion.

page.get_by_test_id("search-input").fill("course")
page.get_by_test_id("search-button").click()
Show answer
import re

from playwright.sync_api import Page, expect


def test_search_courses(page: Page):
    page.goto("/dummy-ecommerce-website/")
    page.get_by_test_id("search-input").fill("course")
    page.get_by_test_id("search-button").click()
    expect(page).to_have_url(re.compile(r"#/search/course$"))
    expect(page.get_by_test_id("product-card").first).to_be_visible()

The assertions check the result, not just that the clicks did not fail.

Exercise 4: Write the VS Code mcp.json entry that starts Playwright MCP headless, isolated, logged in with .auth/shopper.json, generating Python code.

Show answer
{
  "servers": {
    "playwright": {
      "command": "npx",
      "args": ["@playwright/mcp@latest", "--headless", "--isolated",
               "--storage-state=.auth/shopper.json", "--codegen", "python"]
    }
  }
}

🧠 MCQ Quiz: Playwright MCP for Python Testers

10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.

  1. What is MCP?
  2. How do Playwright MCP and playwright-cli let an AI “see” a page?
  3. Why is playwright-cli described as token-efficient?
  4. How do you run playwright-cli with only Playwright Python installed?
  5. What happens to element refs after the page navigates?
  6. Which MCP option makes generated code Python?
  7. What does --isolated do for Playwright MCP?
  8. What does pytest-playwright’s --playwright-debug=cli do?
  9. What must a tester still add to code generated by the CLI or MCP?
  10. Which is a safety rule when giving an AI agent a browser?

Want a longer, timed test? Take the Module 13 mock interview (20 MCQs in 20 minutes).


❓ Frequently Asked Questions

🤔 Do I need Node.js to use these tools from Python?

Not for playwright-cli: it is bundled with Playwright Python (python -m playwright cli). The Playwright MCP server is a Node.js package (npx @playwright/mcp@latest), but it generates Python code with --codegen python.

🤔 Will AI agents replace writing Playwright tests?

They change how tests are written, not the need for test design. Agents are good at exploring pages, finding locators and drafting code. Deciding what matters, what to assert and how to keep a suite maintainable remains the tester’s job.

🤔 Is Playwright MCP the same as Playwright’s test agents?

No. Playwright Test (TypeScript) also ships planner, generator and healer test agents built on these tools. They target the TypeScript test runner; in Python you get the same building blocks through MCP, the CLI and your own prompts. The next lesson compares the AI options for Python.

🤔 Can the CLI record a trace or video for me?

Yes: tracing-start / tracing-stop and video commands exist, and the traces open in the normal Trace Viewer (Lesson 62).

🤔 Why did my AI agent click the wrong element?

Usually because the accessibility snapshot was stale or names were ambiguous. Ask it to take a fresh snapshot and to use exact role names or test ids, the same rules you follow yourself (Lessons 31 and 61).


🏁 Summary

  • MCP lets AI clients call tools; Playwright MCP and playwright-cli both drive real browsers using accessibility snapshots and element refs.
  • python -m playwright cli (bundled with Playwright Python) opens sessions, finds elements, acts by ref or locator, and prints the equivalent Python code; refs expire after navigation.
  • Turn recorded code into real tests by adding assertions, and use --playwright-debug=cli to inspect a paused pytest test.
  • Configure Playwright MCP for Claude Code or VS Code with --codegen python, --isolated and storage-state files.
  • Use these tools on test environments with test accounts, treat page text as untrusted, and review everything they generate.

🎬 Watch the Playwright tutorial series on YouTube!

Subscribe to SqaToolsByDY • Practice on the SQA Tools Automation Practice Page

The Playwright Python Async API (async_playwright and pytest-playwright-asyncio)

Everything in this course so far used Playwright’s sync API, which is the simplest choice for tests. Playwright Python also has an async API built on asyncio. You need it when your test code lives inside an async application (FastAPI, an async bot, an AI agent), when one script should drive many pages concurrently, or when your team’s code base is async already. In this lesson you will translate sync code to async, run pages concurrently with asyncio.gather, handle events and routes with async functions, avoid the common mistakes, and write async pytest tests with the official pytest-playwright-asyncio plugin.

📖 What You’ll Learn: sync vs async API and when to choose each, async_playwright and asyncio.run, the await rules (actions, expect, evaluate), what is not awaited (locators, page.on), translating sync code step by step, concurrent pages with asyncio.gather and a semaphore, async route handlers and event handlers, wait_for_event and expect_response in async code, installing pytest-playwright-asyncio and pytest-asyncio, loop scope settings, async fixtures and tests, and mistakes such as a missing await or mixing sync and async.


⚖️ Sync or Async?

Both APIs have the same classes and methods (Page, Locator, expect …) and drive the same browsers. The difference is how your Python code waits:

Sync API (playwright.sync_api) Async API (playwright.async_api)
Calls page.goto(url) await page.goto(url)
Runs in Normal functions async def functions inside an asyncio event loop
Concurrency One thing at a time per thread (use xdist for parallel tests) Many pages at once in one thread with asyncio.gather
pytest plugin pytest-playwright pytest-playwright-asyncio
Choose when Writing tests (the default for most teams) Your code is already async, or you need concurrency inside one process

📌 Note: This lesson uses its own virtual environment with pytest-playwright-asyncio and pytest-asyncio instead of pytest-playwright. Install one of the two pytest plugins per environment: both provide fixtures named page, context and browser.


🚀 Your First Async Script

📄 first_async.py

import asyncio

from playwright.async_api import async_playwright, expect


async def main():
    async with async_playwright() as p:
        browser = await p.chromium.launch()
        page = await browser.new_page()
        await page.goto("https://sqatools.in/dummy-ecommerce-website/")
        await expect(page.get_by_test_id("product-card").first).to_be_visible()
        print("title:", await page.title())
        print("cards:", await page.get_by_test_id("product-card").count())
        await browser.close()


asyncio.run(main())

⌨️ Terminal

python first_async.py

🖥️ Output

title: Dummy E-commerce Website For Automation Practice | SQA Tools
cards: 12

Compare with the sync version from Lesson 3: the shape is identical; async with, async def and await are the only additions.


✍️ The await Rules

Everything that talks to the browser returns a coroutine and must be awaited. Things that only build descriptions do not:

Awaited Not awaited
await page.goto(...), await locator.click(), await locator.fill(...) page.get_by_role(...), page.locator(...), locator.filter(...), locator.first (they create locators)
await expect(locator).to_have_text(...) expect(locator) itself
await page.title(), await locator.count(), await locator.inner_text() page.url (a property)
await page.evaluate(...), await page.screenshot(...) page.on("console", handler) (registering a handler)

The most common async bug is a forgotten await. Python does not stop you; it just creates a coroutine that never runs:

📄 missing_await.py

import asyncio
import warnings

from playwright.async_api import async_playwright

warnings.simplefilter("always")


async def main():
    async with async_playwright() as p:
        browser = await p.chromium.launch()
        page = await browser.new_page()
        page.goto("https://sqatools.in/dummy-ecommerce-website/")      # BUG: no await
        print("url after goto:", page.url)
        await browser.close()


asyncio.run(main())

⌨️ Terminal

python missing_await.py

🖥️ Output

url after goto: about:blank

C:\Users\you\playwright-python\missing_await.py:13: RuntimeWarning: coroutine 'Page.goto' was never awaited
  page.goto("https://sqatools.in/dummy-ecommerce-website/")      # BUG: no await
RuntimeWarning: Enable tracemalloc to get the object allocation traceback

The URL is still about:blank and Python prints RuntimeWarning: coroutine ... was never awaited. Treat that warning as an error. Type checkers catch it before you run the code: Pyright (used by VS Code’s Pylance) reports an unused coroutine by default.


⚡ Concurrency: Many Pages at Once

The real power of async is doing several slow things at the same time in one process. asyncio.gather runs coroutines concurrently; while one page waits for the network, others make progress:

📄 concurrent_pages.py

import asyncio
import time

from playwright.async_api import BrowserContext, async_playwright, expect

SHOP = "https://sqatools.in/dummy-ecommerce-website/#/search/"
TERMS = ["earbuds", "course", "jeans", "watch", "laptop", "shirt"]


async def count_results(context: BrowserContext, term: str) -> tuple[str, int]:
    page = await context.new_page()
    await page.goto(SHOP + term)
    await expect(page.get_by_test_id("product-card").first).to_be_visible()
    n = await page.get_by_test_id("product-card").count()
    await page.close()
    return term, n


async def main():
    async with async_playwright() as p:
        browser = await p.chromium.launch()
        context = await browser.new_context()

        start = time.perf_counter()
        for term in TERMS:
            await count_results(context, term)                       # one after another
        sequential = time.perf_counter() - start

        start = time.perf_counter()
        results = await asyncio.gather(*(count_results(context, t) for t in TERMS))
        concurrent = time.perf_counter() - start

        print(dict(results))
        print(f"sequential {sequential:.1f}s, concurrent {concurrent:.1f}s")
        await browser.close()


asyncio.run(main())

⌨️ Terminal

python concurrent_pages.py

🖥️ Output

{'earbuds': 1, 'course': 6, 'jeans': 6, 'watch': 4, 'laptop': 7, 'shirt': 12}
sequential 6.0s, concurrent 1.2s

asyncio.gather returns results in the same order as the coroutines you passed, whatever order they finish in.

For many pages, limit concurrency so the browser and the server are not overwhelmed. A semaphore allows at most N at a time:

limit = asyncio.Semaphore(4)

async def limited(context, term):
    async with limit:                       # at most 4 pages open at once
        return await count_results(context, term)

results = await asyncio.gather(*(limited(context, t) for t in many_terms))

💡 Tip: Concurrency inside one browser is great for scripts: crawling, link checks, data collection, warming caches. For test suites, pytest-xdist (Lesson 65) is still the simpler way to run tests in parallel, because each test stays a simple, isolated function.


🎧 Events and Routes in Async Code

Handlers can be normal or async functions. Route handlers that call Playwright must be async and await their calls:

📄 async_handlers.py

import asyncio

from playwright.async_api import Route, async_playwright, expect

CATALOG = """<ul id="list"></ul><script>
fetch('/wp-json/sqa-api/v1/products?per_page=3').then(r => r.json()).then(b => {
  document.getElementById('list').innerHTML = b.data.map(p => `<li>${p.name}</li>`).join('');
  console.log('rendered ' + b.data.length + ' products');
});
</script>"""


async def fake_products(route: Route):
    await route.fulfill(json={"data": [{"name": "Async Laptop"}, {"name": "Async Phone"}]})


async def main():
    async with async_playwright() as p:
        browser = await p.chromium.launch()
        page = await browser.new_page()
        page.on("console", lambda msg: print("console:", msg.text))           # sync handler is fine for logging
        await page.route("https://sqatools.in/pw-demo", lambda route: route.fulfill(body=CATALOG, content_type="text/html"))
        await page.route("**/sqa-api/v1/products*", fake_products)             # async handler

        async with page.expect_response("**/sqa-api/v1/products*") as info:
            await page.goto("https://sqatools.in/pw-demo")
        response = await info.value
        print("status:", response.status, "| body:", await response.json())
        await expect(page.locator("#list li")).to_have_text(["Async Laptop", "Async Phone"])
        await browser.close()


asyncio.run(main())

⌨️ Terminal

python async_handlers.py

🖥️ Output

console: rendered 2 products
status: 200 | body: {'data': [{'name': 'Async Laptop'}, {'name': 'Async Phone'}]}

Note async with page.expect_response(...) and await info.value: the waiting helpers from Lesson 52 become async context managers whose value is awaited.


🧪 Async Tests with pytest-playwright-asyncio

The official pytest-playwright-asyncio plugin provides async versions of the familiar fixtures (page, context, browser, browser_context_args …) and the same command-line options (--browser, --headed, --base-url, --tracing …). It builds on pytest-asyncio.

⌨️ Terminal

pip install pytest-playwright-asyncio pytest-asyncio

Configure pytest-asyncio so the browser and the tests share one event loop for the whole session:

📄 pytest.ini

[pytest]
addopts = --base-url https://sqatools.in
asyncio_mode = auto
asyncio_default_fixture_loop_scope = session
asyncio_default_test_loop_scope = session
# pytest 9 warns about how the plugin defines one fixture; harmless, so it is filtered
filterwarnings =
    ignore::pytest.PytestRemovedIn10Warning
  • asyncio_mode = auto treats every async def test_... as an asyncio test (otherwise each needs @pytest.mark.asyncio).
  • The two loop_scope = session settings matter: Playwright’s session-scoped browser lives in one event loop, and tests must run in that same loop.

📄 tests/test_async_shop.py

import asyncio

import pytest
from playwright.async_api import BrowserContext, Page, expect

SHOP = "/dummy-ecommerce-website/"


async def test_login(page: Page):
    await page.goto(SHOP + "#/login")
    await page.get_by_test_id("login-username").fill("testuser")
    await page.get_by_test_id("login-password").fill("Test@123")
    await page.get_by_test_id("login-button").click()
    await expect(page.get_by_test_id("account-button")).to_contain_text("Hi, Test")


@pytest.mark.parametrize("term", ["earbuds", "course"])
async def test_search(page: Page, term):
    await page.goto(SHOP + "#/search/" + term)
    await expect(page.get_by_test_id("product-card").first).to_be_visible()


async def test_two_shoppers_at_once(context: BrowserContext, browser):
    """Two isolated users side by side: a guest and a logged-in shopper."""
    member_context = await browser.new_context(base_url="https://sqatools.in")
    guest, member = await context.new_page(), await member_context.new_page()

    async def log_in(p: Page):
        await p.goto(SHOP + "#/login")
        await p.get_by_test_id("login-username").fill("testuser")
        await p.get_by_test_id("login-password").fill("Test@123")
        await p.get_by_test_id("login-button").click()

    await asyncio.gather(guest.goto(SHOP), log_in(member))
    await expect(guest.get_by_test_id("account-button")).to_contain_text("Login")
    await expect(member.get_by_test_id("account-button")).to_contain_text("Hi, Test")
    await member_context.close()

⌨️ Terminal

pytest -v

🖥️ Output

============================= test session starts =============================
platform win32 -- Python 3.15.1, pytest-9.2.0, pluggy-1.7.0 -- C:\Users\you\playwright-python\.venv\Scripts\python.exe
cachedir: .pytest_cache
rootdir: C:\Users\you\playwright-python
configfile: pytest.ini
plugins: asyncio-1.5.0, playwright-asyncio-0.10.0
asyncio: mode=Mode.AUTO, debug=False, asyncio_default_fixture_loop_scope=session, asyncio_default_test_loop_scope=session
collecting ... collected 4 items

tests/test_async_shop.py::test_login[chromium] PASSED                    [ 25%]
tests/test_async_shop.py::test_search[chromium-earbuds] PASSED           [ 50%]
tests/test_async_shop.py::test_search[chromium-course] PASSED            [ 75%]
tests/test_async_shop.py::test_two_shoppers_at_once[chromium] PASSED     [100%]

============================== 4 passed in 7.12s ==============================

Async fixtures work the same way:

📄 tests/conftest.py

import pytest_asyncio
from playwright.async_api import Page


@pytest_asyncio.fixture
async def shop_home(page: Page) -> Page:
    await page.goto("/dummy-ecommerce-website/")
    return page

📄 tests/test_fixture.py

from playwright.async_api import Page, expect


async def test_cart_starts_empty(shop_home: Page):
    await expect(shop_home.get_by_test_id("cart-count")).to_have_text("0")

⌨️ Terminal

pytest tests/test_fixture.py -q

🖥️ Output

.                                                                        [100%]
1 passed in 2.37s

⚠️ Common Async Mistakes

Mistake Symptom Fix
Missing await “coroutine was never awaited”, steps silently skipped Await every browser call; enable linters
Calling sync API inside async code “It looks like you are using Playwright Sync API inside the asyncio loop” Use playwright.async_api everywhere in async code
time.sleep() in async code Blocks every page at once await asyncio.sleep() (or better, expect)
pytest-playwright and pytest-playwright-asyncio installed together Fixture conflicts, confusing errors One plugin per environment
Function-scoped event loop “attached to a different loop” errors Session loop scope as configured above
Unlimited gather Memory spikes, server rate limits A semaphore to cap concurrency

🏋️ Practice Exercises

Try each exercise on your own first, then open the answer to compare. The answers use the same practice sites and project layout as the lesson.

Exercise 1: Convert this sync snippet to the async API:

page.goto(SHOP + "#/cart")
page.get_by_test_id("coupon-input").fill("SAVE10")
page.get_by_test_id("apply-coupon").click()
expect(page.get_by_test_id("coupon-message")).to_have_text("Coupon SAVE10 applied.")
Show answer
await page.goto(SHOP + "#/cart")
await page.get_by_test_id("coupon-input").fill("SAVE10")
await page.get_by_test_id("apply-coupon").click()
await expect(page.get_by_test_id("coupon-message")).to_have_text("Coupon SAVE10 applied.")

Locators (page.get_by_test_id(...)) are not awaited; the actions and the assertion are.

Exercise 2: Write an async function titles(urls) that opens all URLs concurrently in one context, at most 3 at a time, and returns their titles in the same order.

Show answer
async def titles(context, urls):
    limit = asyncio.Semaphore(3)

    async def one(url):
        async with limit:
            page = await context.new_page()
            await page.goto(url)
            title = await page.title()
            await page.close()
            return title

    return await asyncio.gather(*(one(u) for u in urls))

Exercise 3: A teammate’s async test fails with “It looks like you are using Playwright Sync API inside the asyncio loop”. What did they do?

Show answer

They imported from playwright.sync_api (or used a sync helper) inside async code. Inside an event loop only the async API may be used: import Page, expect and friends from playwright.async_api and await the calls.

Exercise 4: Write an async route handler that adds a header X-Test: async to every request to **/sqa-api/** and continues it.

Show answer
async def add_header(route):
    await route.continue_(headers={**route.request.headers, "X-Test": "async"})

await page.route("**/sqa-api/**", add_header)

🧠 MCQ Quiz: The Async API: async_playwright

10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.

  1. Which import gives you the async API?
  2. Which of these is NOT awaited?
  3. What happens if you forget await before page.goto(...)?
  4. What does asyncio.gather(*coros) return?
  5. How do you limit how many pages run at the same time?
  6. Which plugin provides async pytest fixtures for Playwright?
  7. Why should pytest-playwright and pytest-playwright-asyncio not be installed together?
  8. What does asyncio_mode = auto do?
  9. Why set the loop scope to session?
  10. In async code, how do you use expect_response?

Want a longer, timed test? Take the Module 13 mock interview (20 MCQs in 20 minutes).


❓ Frequently Asked Questions

🤔 Is the async API faster?

Not per action: the browser does the same work. It is faster when you run independent work concurrently in one process. For ordinary test suites, the sync API with pytest-xdist is just as fast and simpler.

🤔 Can I use Playwright’s async API with FastAPI or Django?

Yes. Inside async views or background tasks use async_playwright. Create the Playwright instance once (for example at application start-up) and reuse the browser; launching a browser per request is slow.

🤔 Do I need async for AI agents and MCP servers?

Most agent frameworks and the MCP Python SDK are async, so the async API fits naturally there. The next two lessons look at Playwright MCP and AI tools.

🤔 Can I mix sync tests and async tests in one project?

Not in the same environment with both pytest plugins. Keep separate test folders with separate virtual environments, or stay with one API.

🤔 Does tracing work with the async API?

Yes: await context.tracing.start(...) / await context.tracing.stop(path=...), and pytest-playwright-asyncio supports --tracing retain-on-failure like the sync plugin.


🏁 Summary

  • The async API mirrors the sync API; add async def, async with async_playwright() and await on every browser call.
  • Locators and expect(...) are built without await; actions, assertions, queries and evaluate are awaited.
  • asyncio.gather (with a semaphore) drives many pages concurrently in one process; handlers can be async.
  • pytest-playwright-asyncio plus pytest-asyncio provide async fixtures; set asyncio_mode = auto and session loop scopes, and keep it in its own environment.
  • Watch for missing awaits, sync API calls inside async code and blocking sleeps.

🎬 Watch the Playwright tutorial series on YouTube!

Subscribe to SqaToolsByDY • Practice on the SQA Tools Automation Practice Page