Design Patterns for Playwright Python Test Frameworks

Page objects solve one problem: where locators live. As a suite grows, other problems appear: test data that is copied and collides, long payloads built by hand, the same five-step journey in fifty tests, and if statements choosing how to log in. Classic design patterns, applied lightly, solve these. In this lesson you will add five patterns to a Playwright Python framework, each with a working example on the SQA Shop and the practice API: a test-data factory, a builder, the factory-as-fixture pattern with automatic clean-up, a facade for user journeys, and a strategy for interchangeable login methods.

📖 What You’ll Learn: why patterns matter in test code, the factory pattern for unique valid test data, the builder pattern for complex payloads, the factory-as-fixture pattern with clean-up, a facade or steps layer for user journeys, the strategy pattern for login methods chosen by configuration, why configuration should be a session fixture and not a global singleton, and when a pattern is overkill.


🧠 Why Patterns in Test Code?

Test code is real code: it is read far more often than it is written, and it changes every time the product changes. Patterns give names to solutions that keep it easy to change. Use them when you feel a specific pain:

Pain Pattern
Copied test data, collisions between runs Factory
Payloads with many optional fields Builder
Fixtures that create one object, tests that need several Factory as fixture
The same multi-page journey repeated in many tests Facade / steps
if statements choosing how to do something Strategy

📄 pytest.ini

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

🏭 Factory: Valid, Unique Test Data

Tests often need “a valid object, I do not care about most fields”. A factory returns one with sensible defaults and a unique part, and lets the test override only what matters:

📄 framework/factories.py

import itertools
import uuid

_counter = itertools.count(1)


def unique(prefix: str) -> str:
    return f"{prefix}-{next(_counter)}-{uuid.uuid4().hex[:6]}"


def make_user(**overrides) -> dict:
    user = {"name": "Test User", "email": f"{unique('user')}@example.com", "age": 30}
    user.update(overrides)
    return user


def make_object(**overrides) -> dict:
    obj = {"name": unique("pw-object"), "data": {"price": 999, "color": "black"}}
    obj.update(overrides)
    return obj

📄 tests/test_factory.py

from framework.factories import make_user


def test_factory_defaults_are_valid_and_unique(playwright):
    api = playwright.request.new_context(base_url="https://sqatools.in/wp-json/sqa-api/v1/")
    a, b = make_user(), make_user()
    assert a["email"] != b["email"]
    assert api.post("validate/user", data=a).status == 200          # defaults pass validation


def test_override_only_what_matters(playwright):
    api = playwright.request.new_context(base_url="https://sqatools.in/wp-json/sqa-api/v1/")
    response = api.post("validate/user", data=make_user(age=17))     # the one field this test is about
    assert response.status == 422
    assert [d["field"] for d in response.json()["error"]["details"]] == ["age"]

⌨️ Terminal

pytest tests/test_factory.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 2 items

tests/test_factory.py::test_factory_defaults_are_valid_and_unique PASSED [ 50%]
tests/test_factory.py::test_override_only_what_matters PASSED            [100%]

============================= 2 passed in 13.64s ==============================

The second test states its intent in one argument, age=17. Every other field is valid, so a failure can only come from the age rule.

💡 Tip: Libraries such as Faker (realistic names, addresses) and factory_boy (factories with sequences and relations) build on the same idea. Plain functions are enough until you need them.


🧱 Builder: Complex Payloads Step by Step

When an object has many optional parts, keyword arguments get unwieldy. A builder assembles it in readable steps and returns the result with build():

📄 framework/builders.py

import json
from dataclasses import dataclass, field


@dataclass
class CartBuilder:
    """Builds the SQA Shop cart (localStorage 'spCart') for fast test setup."""

    lines: list[dict] = field(default_factory=list)

    def with_item(self, product_id: str, qty: int = 1, size: str = "", color: str = ""):
        self.lines.append({"id": product_id, "size": size, "color": color, "qty": qty})
        return self                                   # returning self enables chaining

    def with_earbuds(self, qty: int = 1):
        return self.with_item("EL-013", qty)

    def with_handbook(self, qty: int = 1):
        return self.with_item("DG-010", qty)

    def build(self) -> list[dict]:
        return list(self.lines)

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

📄 tests/test_builder.py

from playwright.sync_api import BrowserContext, Page, expect

from framework.builders import CartBuilder


def test_cart_total_items(context: BrowserContext, page: Page):
    cart = CartBuilder().with_earbuds().with_handbook(qty=3)
    context.add_init_script(cart.as_init_script())
    page.goto("/dummy-ecommerce-website/#/cart")
    expect(page.get_by_test_id("cart-count")).to_have_text("4")
    expect(page.get_by_test_id("cart-item-name")).to_have_text(["Wireless Earbuds", "Agile Testing Handbook"])

⌨️ Terminal

pytest tests/test_builder.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 1 item

tests/test_builder.py::test_cart_total_items[chromium] PASSED            [100%]

============================== 1 passed in 2.06s ==============================

CartBuilder().with_earbuds().with_handbook(qty=3) reads like the test’s precondition, and the details of the storage format live in one class.


🧪 Factory as Fixture: Create Many, Clean Up All

A normal fixture creates one object. Often a test needs two or five. The factory-as-fixture pattern returns a function that creates objects on demand, remembers them, and deletes them all in teardown:

📄 tests/conftest.py

import pytest
from playwright.sync_api import Playwright

from framework.factories import make_object


@pytest.fixture(scope="session")
def api(playwright: Playwright):
    context = playwright.request.new_context(base_url="https://sqatools.in/wp-json/sqa-api/v1/")
    yield context
    context.dispose()


@pytest.fixture
def create_object(api):
    created: list[str] = []

    def _create(**overrides) -> dict:
        response = api.post("objects", data=make_object(**overrides))
        assert response.status == 201, response.text()
        obj = response.json()
        created.append(obj["id"])
        return obj

    yield _create
    for object_id in created:                    # clean up everything this test created
        api.delete(f"objects/{object_id}")
    print(f"\n[teardown] deleted {len(created)} object(s)")

📄 tests/test_factory_fixture.py

def test_two_objects_are_independent(api, create_object):
    first = create_object(data={"price": 100})
    second = create_object(data={"price": 200})
    api.patch(f"objects/{first['id']}", data={"data": {"price": 150}})
    assert api.get(f"objects/{second['id']}").json()["data"]["price"] == 200

⌨️ Terminal

pytest tests/test_factory_fixture.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 1 item

tests/test_factory_fixture.py::test_two_objects_are_independent PASSED
[teardown] deleted 2 object(s)


============================== 1 passed in 5.57s ==============================

The test creates exactly what it needs, and the teardown line proves both objects were removed, even if an assertion had failed.


🎭 Facade: One Call for a User Journey

Page objects model screens. Many tests, though, need the same journey across several screens: log in, find a product, add it, open the cart. A facade (often called a steps or actions layer) wraps the journey in one method built on the page objects:

📄 framework/shop.py

from playwright.sync_api import Page

SHOP = "/dummy-ecommerce-website/"


class Shop:
    """Facade over the SQA Shop page interactions, named after user goals."""

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

    def login(self, username: str = "testuser", password: str = "Test@123"):
        self.page.goto(SHOP + "#/login")
        self.page.get_by_test_id("login-username").fill(username)
        self.page.get_by_test_id("login-password").fill(password)
        self.page.get_by_test_id("login-button").click()
        self.page.get_by_test_id("account-button").filter(has_text="Hi,").wait_for()
        return self

    def add_to_cart(self, search_term: str, product_name: str):
        self.page.goto(SHOP + "#/search/" + search_term)
        card = self.page.get_by_test_id("product-card").filter(has_text=product_name).first
        card.get_by_role("button", name="Add to cart").click()
        return self

    def open_cart_with_coupon(self, code: str):
        self.page.goto(SHOP + "#/cart")
        self.page.get_by_test_id("coupon-input").fill(code)
        self.page.get_by_test_id("apply-coupon").click()
        return self

📄 tests/test_facade.py

from playwright.sync_api import Page, expect

from framework.shop import Shop


def test_member_gets_flat200(page: Page):
    Shop(page).login().add_to_cart("earbuds", "Wireless Earbuds").open_cart_with_coupon("FLAT200")
    expect(page.get_by_test_id("coupon-discount")).to_have_text("−₹200")

⌨️ Terminal

pytest tests/test_facade.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 1 item

tests/test_facade.py::test_member_gets_flat200[chromium] PASSED          [100%]

============================== 1 passed in 2.31s ==============================

In a full framework the facade methods call page objects (LoginPage(...).login(...)) instead of raw locators; it is shown flat here to keep the example short. The facade sits above page objects: page objects know screens, the facade knows journeys, tests know expectations.


🔀 Strategy: Interchangeable Ways to Log In

Sometimes there are several ways to reach the same state: log in through the UI, load a saved storage state, or log in through an API. Writing if method == "ui": ... elif ... in fixtures spreads that choice everywhere. The strategy pattern gives each way its own class with the same method, and the configuration picks one:

📄 framework/login_strategies.py

import json
from typing import Protocol

from playwright.sync_api import BrowserContext, Page

SHOP = "/dummy-ecommerce-website/"


class LoginStrategy(Protocol):
    def login(self, context: BrowserContext, page: Page) -> None: ...


class UiLogin:
    """Slow but realistic: types into the login form."""

    def login(self, context, page):
        page.goto(SHOP + "#/login")
        page.get_by_test_id("login-username").fill("testuser")
        page.get_by_test_id("login-password").fill("Test@123")
        page.get_by_test_id("remember-me").check()
        page.get_by_test_id("login-button").click()
        page.get_by_test_id("account-button").filter(has_text="Hi,").wait_for()


class StoredLogin:
    """Fast: writes the 'remembered user' the app reads, before any page script runs."""

    def login(self, context, page):
        context.add_init_script(f"localStorage.setItem('spUser', {json.dumps(json.dumps('testuser'))});")


STRATEGIES: dict[str, LoginStrategy] = {"ui": UiLogin(), "stored": StoredLogin()}

The option is registered in the root conftest.py. pytest calls pytest_addoption only for plugins and for the conftest files it loads before parsing the command line; a conftest in a sub-folder is loaded that early only when that folder is passed as an argument, so its option would vanish when someone runs plain pytest.

📄 conftest.py

from framework.login_strategies import STRATEGIES


def pytest_addoption(parser):
    parser.addoption("--login", default="stored", choices=sorted(STRATEGIES), help="how tests log in")

📄 tests/strategy/test_member_area.py

import pytest
from playwright.sync_api import Page, expect

from framework.login_strategies import STRATEGIES


@pytest.fixture
def member_page(request, context, page: Page) -> Page:
    STRATEGIES[request.config.getoption("--login")].login(context, page)
    return page


def test_greeting(member_page: Page):
    member_page.goto("/dummy-ecommerce-website/")
    expect(member_page.get_by_test_id("account-button")).to_contain_text("Hi, Test")

⌨️ Terminal

pytest tests/strategy -v --login stored --durations=1
pytest tests/strategy -v --login ui --durations=1

🖥️ 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/strategy/test_member_area.py::test_greeting[chromium] PASSED       [100%]

============================= slowest 1 durations =============================
1.45s call     tests/strategy/test_member_area.py::test_greeting[chromium]
============================== 1 passed in 1.91s ==============================
============================= 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/strategy/test_member_area.py::test_greeting[chromium] PASSED       [100%]

============================= slowest 1 durations =============================
1.76s setup    tests/strategy/test_member_area.py::test_greeting[chromium]
============================== 1 passed in 2.38s ==============================

Same test, two strategies, chosen from the command line. Run the fast one on every commit and the realistic one nightly. Adding an API login later means adding one class, not editing every fixture.


🚫 Configuration: Session Fixture, Not a Global Singleton

The singleton pattern (“exactly one instance”) is often used for configuration. In pytest, a module-level global that reads environment variables at import time is hard to override in tests and leaks between them. A session-scoped fixture gives you the same “one instance per run” with none of the downsides:

@pytest.fixture(scope="session")
def settings() -> Settings:          # created once per run, easy to override in a conftest
    return load_settings()

Tests that need special settings can override the fixture locally, which a global variable cannot offer.


⚖️ When a Pattern Is Overkill

  • Three tests do not need a facade. Add one when the same journey appears in many tests.
  • A builder for an object with two fields is noise; a factory function is enough.
  • Patterns that hide what the test does are harmful. A reader should still see the important inputs and the expected result in the test itself.

🏋️ 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 factory make_product(**overrides) for the practice API that returns a product dictionary with a unique name, price 499 and category “books”, and use it to create a product with price=0 for a negative test.

Show answer
def make_product(**overrides) -> dict:
    product = {"name": unique("book"), "price": 499, "category": "books"}
    product.update(overrides)
    return product


bad = make_product(price=0)

Only the field under test differs from a valid default.

Exercise 2: Extend CartBuilder with with_size(product_id, size) for clothing items and use it to build a cart with one T-shirt CL-001 in size M.

Show answer
def with_size(self, product_id: str, size: str, qty: int = 1):
    return self.with_item(product_id, qty=qty, size=size)

cart = CartBuilder().with_size("CL-001", "M").build()

Exercise 3: Convert this fixture into the factory-as-fixture pattern so tests can create several users and all are deleted afterwards:

@pytest.fixture
def user(api):
    u = api.post("users", data=make_user()).json()
    yield u
    api.delete(f"users/{u['id']}")
Show answer
@pytest.fixture
def create_user(api):
    created = []

    def _create(**overrides):
        u = api.post("users", data=make_user(**overrides)).json()
        created.append(u["id"])
        return u

    yield _create
    for user_id in created:
        api.delete(f"users/{user_id}")

Exercise 4: Add an ApiLogin strategy to the lesson’s STRATEGIES for an application whose login API sets a session cookie. Which object should it use to call the API, and why?

Show answer
class ApiLogin:
    def login(self, context, page):
        response = context.request.post("https://app.example.com/api/login", data={"username": "testuser", "password": "..."})
        assert response.ok

Use context.request, because it shares the browser context’s cookie jar: the session cookie from the API response is then available to every page (Lesson 55).


🧠 MCQ Quiz: Design Patterns for Playwright Python

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 test-data factory return?
  2. Why include a unique part (counter or UUID) in factory data?
  3. What does a builder’s method usually return to allow chaining?
  4. What does the factory-as-fixture pattern yield?
  5. Where does a facade sit in a framework?
  6. What problem does the strategy pattern solve in the lesson?
  7. Why should pytest_addoption live in the root conftest.py?
  8. Why prefer a session-scoped settings fixture over a global singleton?
  9. In make_user(age=17), why is the test easy to understand?
  10. When is a pattern overkill?

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


❓ Frequently Asked Questions

🤔 What is the Screenplay pattern?

An alternative to page objects where actors perform tasks made of interactions and ask questions. It scales well for very large suites but adds more classes. Most Python teams get far with page objects plus a facade.

🤔 Should factories call the API or only return dictionaries?

Keep both layers: a pure function that returns data (make_object) and a fixture that sends it (create_object). Pure factories are reusable for negative tests and for UI form input.

🤔 Where should these modules live?

In a framework package such as framework/ or split by role (data/factories.py, flows/shop.py). See Lesson 57 for the layout.

🤔 Can a facade method contain assertions?

Prefer synchronisation (wait until the next page is ready) over verdicts. Leave the expected outcome to the test, so the same journey serves positive and negative tests.

🤔 Is dependency injection a pattern in pytest?

Yes, and you use it constantly: fixtures are pytest’s dependency injection. Asking for page, api or settings in a test’s arguments is exactly that.


🏁 Summary

  • Factory: valid, unique defaults with overrides; tests state only what matters.
  • Builder: readable, chainable construction of complex data such as carts and payloads.
  • Factory as fixture: create many objects on demand and clean up all of them in teardown.
  • Facade: user journeys built on page objects, so tests stay short and intent-focused.
  • Strategy: interchangeable implementations (UI, stored, API login) chosen by configuration; prefer session fixtures over global singletons.

🎬 Watch the Playwright tutorial series on YouTube!

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

Playwright Python Framework Folder Structure and Best Practices

A folder of fifty test files with copied helpers works until the second person joins the project. A clear structure tells everyone where pages, data, API clients, fixtures and tests belong, and it keeps the suite fast to change as it grows to hundreds of tests. In this lesson you will build a complete, runnable framework skeleton for the SQA Shop: a proven folder layout, all pytest settings in pyproject.toml, layered conftest.py files for UI and API tests, registered markers, one config module, pinned dependencies and the naming rules that keep it readable.

📖 What You’ll Learn: a proven folder layout and what goes where, pyproject.toml with [tool.pytest.ini_options], testpaths, pythonpath, addopts and strict markers, layered conftest.py files (root, ui, api), a config module, page objects and API clients as packages, test data folders, requirements with pinned versions, .gitignore for artifacts, naming conventions for files, tests and fixtures, checking the suite with –collect-only and markers, and the rules that keep tests independent.


🗺️ The Target Layout

This is the structure we will build. Each folder has one job:

shop-tests/
├── pyproject.toml          pytest settings, markers, project metadata
├── requirements.txt        pinned dependencies
├── .env.example            names of required environment variables (copy to .env)
├── .gitignore              .env, .auth/, reports/, test-results/
├── config/
│   ├── __init__.py
│   └── settings.py         one Settings object: URLs, credentials, timeouts
├── pages/                  page objects and components (Lesson 56)
│   ├── __init__.py
│   ├── base_page.py
│   ├── login_page.py
│   └── cart_page.py
├── api/                    API clients (Module 9)
│   ├── __init__.py
│   └── practice_api.py
├── data/
│   └── coupons.json        test data files (Lesson 46)
└── tests/
    ├── conftest.py         fixtures for ALL tests: settings, markers, report header
    ├── ui/
    │   ├── conftest.py     browser fixtures: page objects, logged-in state
    │   ├── test_login.py
    │   └── test_cart.py
    └── api/
        ├── conftest.py     API client fixture (no browser)
        └── test_products.py

Rules of thumb:

  • Tests only describe behaviour. Locators live in pages/, HTTP details in api/, values in config/ and data/.
  • Fixtures live in conftest.py files at the level where they are needed: shared ones at tests/, browser ones at tests/ui/, API ones at tests/api/.
  • Artifacts never go into Git: reports, traces, screenshots, .auth/ and .env.

⚙️ pyproject.toml: One Place for Settings

Modern Python projects keep tool settings in pyproject.toml. pytest reads the [tool.pytest.ini_options] table:

📄 pyproject.toml

[project]
name = "shop-tests"
version = "1.0.0"
requires-python = ">=3.10"

[tool.pytest.ini_options]
testpaths = ["tests"]
pythonpath = ["."]
addopts = [
    "--base-url=https://sqatools.in",
    "--strict-markers",
    "-ra",
]
markers = [
    "smoke: fast checks for every commit",
    "regression: full regression suite",
    "api: API tests (no browser)",
]
Setting Why
testpaths pytest with no arguments only looks in tests/ (faster collection, no accidental scripts)
pythonpath = ["."] import pages, import config work from any test without sys.path hacks
--strict-markers A typo like @pytest.mark.smokee becomes an error instead of a silently unused marker
-ra The summary lists every skipped, failed and xfailed test with its reason
markers Documents and registers the markers your team uses

📌 Note: Use either pytest.ini or pyproject.toml, not both: if a pytest.ini exists, pytest uses it and ignores the TOML settings.


🔧 config/: One Settings Object

📄 config/settings.py

import os
from dataclasses import dataclass, field
from pathlib import Path

from dotenv import load_dotenv

ROOT = Path(__file__).resolve().parent.parent
load_dotenv(ROOT / ".env")


@dataclass(frozen=True)
class Settings:
    shop_path: str = "/dummy-ecommerce-website/"
    api_url: str = "https://sqatools.in/wp-json/sqa-api/v1/"
    shop_user: str = "testuser"
    shop_password: str = field(default="", repr=False)
    expect_timeout_ms: int = 5_000


def load_settings() -> Settings:
    return Settings(
        shop_user=os.getenv("SHOP_USER", "testuser"),
        shop_password=os.getenv("SHOP_PASSWORD", "Test@123"),
        expect_timeout_ms=int(os.getenv("EXPECT_TIMEOUT", "5000")),
    )

📄 .env.example

SHOP_USER=testuser
SHOP_PASSWORD=
EXPECT_TIMEOUT=5000

The defaults make the public practice site work out of the box; in a real project the password would have no default (Lesson 47).


📄 pages/ and api/: Reusable Building Blocks

📄 pages/base_page.py

from playwright.sync_api import Page


class BasePage:
    path = ""

    def __init__(self, page: Page, shop_path: str):
        self.page = page
        self.shop_path = shop_path
        self.cart_count = page.get_by_test_id("cart-count")
        self.account_button = page.get_by_test_id("account-button")

    def open(self):
        self.page.goto(self.shop_path + self.path)
        return self

📄 pages/login_page.py

from pages.base_page import BasePage


class LoginPage(BasePage):
    path = "#/login"

    def __init__(self, page, shop_path):
        super().__init__(page, shop_path)
        self.username = page.get_by_test_id("login-username")
        self.password = page.get_by_test_id("login-password")
        self.button = page.get_by_test_id("login-button")
        self.error = page.get_by_test_id("login-error")

    def submit(self, username: str, password: str):
        self.username.fill(username)
        self.password.fill(password)
        self.button.click()
        return self

📄 pages/cart_page.py

from pages.base_page import BasePage


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

    def __init__(self, page, shop_path):
        super().__init__(page, shop_path)
        self.coupon_input = page.get_by_test_id("coupon-input")
        self.apply_button = page.get_by_test_id("apply-coupon")
        self.coupon_message = page.get_by_test_id("coupon-message")

    def apply_coupon(self, code: str):
        self.coupon_input.fill(code)
        self.apply_button.click()
        return self

📄 api/practice_api.py

from playwright.sync_api import APIRequestContext


class PracticeApi:
    """Thin client: one method per endpoint the tests use."""

    def __init__(self, request: APIRequestContext):
        self.request = request

    def products(self, **params) -> list[dict]:
        response = self.request.get("products", params=params)
        assert response.ok, response.text()
        return response.json()["data"]

🧩 Layered conftest.py Files

pytest loads every conftest.py from the root down to the test’s folder. Use that to scope fixtures:

📄 tests/conftest.py

"""Fixtures for every test (UI and API)."""
import pytest

from config.settings import Settings, load_settings


@pytest.fixture(scope="session")
def settings() -> Settings:
    return load_settings()


def pytest_report_header(config):
    return f"shop-tests framework | config: {load_settings()}"

📄 tests/ui/conftest.py

"""Browser-only fixtures."""
import pytest
from playwright.sync_api import Page, expect

from pages.cart_page import CartPage
from pages.login_page import LoginPage


@pytest.fixture(scope="session", autouse=True)
def _expect_timeout(settings):
    expect.set_options(timeout=settings.expect_timeout_ms)


@pytest.fixture
def login_page(page: Page, settings) -> LoginPage:
    return LoginPage(page, settings.shop_path).open()


@pytest.fixture
def cart_with_earbuds(page: Page, settings) -> CartPage:
    page.goto(settings.shop_path + "#/search/earbuds")
    page.get_by_test_id("product-card").filter(has_text="Wireless Earbuds").get_by_role("button", name="Add to cart").click()
    return CartPage(page, settings.shop_path).open()

📄 tests/api/conftest.py

"""API-only fixtures: no browser is started for these tests."""
from pathlib import Path

import pytest
from playwright.sync_api import Playwright

from api.practice_api import PracticeApi


@pytest.fixture(scope="session")
def practice_api(playwright: Playwright, settings) -> PracticeApi:
    request = playwright.request.new_context(base_url=settings.api_url)
    yield PracticeApi(request)
    request.dispose()


API_DIR = Path(__file__).parent


def pytest_collection_modifyitems(items):
    # This hook receives ALL collected items, even in a sub-folder conftest, so filter by path.
    for item in items:
        if item.path.is_relative_to(API_DIR):
            item.add_marker("api")           # every test in tests/api/ is an API test

📄 data/coupons.json

[
  {"code": "SAVE10", "message": "Coupon SAVE10 applied."},
  {"code": "FLAT200", "message": "Coupon FLAT200 applied."},
  {"code": "WINTER99", "message": "This coupon code is not valid."}
]

🧪 Tests That Only Describe Behaviour

📄 tests/ui/test_login.py

import pytest
from playwright.sync_api import expect


@pytest.mark.smoke
def test_valid_login(login_page, settings):
    login_page.submit(settings.shop_user, settings.shop_password)
    expect(login_page.account_button).to_contain_text("Hi, Test")


def test_locked_user(login_page):
    login_page.submit("lockeduser", "Test@123")
    expect(login_page.error).to_have_text("This account is locked. Please contact support.")

📄 tests/ui/test_cart.py

import json
from pathlib import Path

import pytest
from playwright.sync_api import expect

COUPONS = json.loads((Path(__file__).resolve().parents[2] / "data" / "coupons.json").read_text(encoding="utf-8"))


@pytest.mark.regression
@pytest.mark.parametrize("coupon", COUPONS, ids=lambda c: c["code"].lower())
def test_coupon_codes(cart_with_earbuds, coupon):
    cart_with_earbuds.apply_coupon(coupon["code"])
    expect(cart_with_earbuds.coupon_message).to_have_text(coupon["message"])

📄 tests/api/test_products.py

import pytest


@pytest.mark.smoke
def test_books_are_books(practice_api):
    books = practice_api.products(category="books")
    assert books and {b["category"] for b in books} == {"books"}


def test_prices_are_positive_integers(practice_api):
    for product in practice_api.products(per_page=50):
        assert isinstance(product["price"], int) and product["price"] > 0

✅ Check the Structure

--collect-only lists what pytest would run, without running it. It is the fastest way to check that the layout, imports and markers are right:

⌨️ Terminal

pytest --collect-only -q

🖥️ Output

tests/api/test_products.py::test_books_are_books
tests/api/test_products.py::test_prices_are_positive_integers
tests/ui/test_cart.py::test_coupon_codes[chromium-save10]
tests/ui/test_cart.py::test_coupon_codes[chromium-flat200]
tests/ui/test_cart.py::test_coupon_codes[chromium-winter99]
tests/ui/test_login.py::test_valid_login[chromium]
tests/ui/test_login.py::test_locked_user[chromium]

7 tests collected in 0.02s

Run only the smoke tests across UI and API, then only API tests:

⌨️ Terminal

pytest -m smoke -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
shop-tests framework | config: Settings(shop_path='/dummy-ecommerce-website/', api_url='https://sqatools.in/wp-json/sqa-api/v1/', shop_user='testuser', expect_timeout_ms=5000)
rootdir: C:\Users\you\playwright-python
configfile: pyproject.toml
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 7 items / 5 deselected / 2 selected

tests/api/test_products.py::test_books_are_books PASSED                  [ 50%]
tests/ui/test_login.py::test_valid_login[chromium] PASSED                [100%]

======================= 2 passed, 5 deselected in 2.58s =======================

⌨️ Terminal

pytest -m api -q

🖥️ Output

..                                                                       [100%]
2 passed, 5 deselected in 1.35s

The API tests ran without starting a browser, because nothing in tests/api/ asks for page. And the whole suite:

⌨️ Terminal

pytest

🖥️ Output

============================= test session starts =============================
platform win32 -- Python 3.15.1, pytest-9.2.0, pluggy-1.7.0
baseurl: https://sqatools.in
shop-tests framework | config: Settings(shop_path='/dummy-ecommerce-website/', api_url='https://sqatools.in/wp-json/sqa-api/v1/', shop_user='testuser', expect_timeout_ms=5000)
rootdir: C:\Users\you\playwright-python
configfile: pyproject.toml
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
collected 7 items

tests\api\test_products.py ..                                            [ 28%]
tests\ui\test_cart.py ...                                                [ 71%]
tests\ui\test_login.py ..                                                [100%]

============================== 7 passed in 9.31s ==============================

--strict-markers at work: a typo in a marker fails collection immediately.

📄 typo_demo/test_typo.py

import pytest


@pytest.mark.smokee
def test_with_typo():
    pass

⌨️ Terminal

pytest typo_demo/test_typo.py -q

🖥️ Output

=================================== ERRORS ====================================
___________________ ERROR collecting typo_demo/test_typo.py ___________________
'smokee' not found in `markers` configuration option
=========================== short test summary info ===========================
ERROR typo_demo/test_typo.py - Failed: 'smokee' not found in `markers` config...
!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!!
1 error in 0.10s

📌 Pin Your Dependencies

A suite that passed yesterday and fails today without code changes is often a new library version. Pin exact versions and upgrade on purpose:

📄 requirements.txt

playwright==1.65.2
pytest==9.2.0
pytest-playwright==0.10.0
pytest-base-url==2.1.0
python-dotenv==1.2.4

📄 .gitignore

.venv/
.env
.auth/
reports/
test-results/
__pycache__/
.pytest_cache/

pip freeze > requirements.txt captures everything installed; a hand-written list of direct dependencies (as above) is easier to read and upgrade. Upgrade Playwright deliberately, then run playwright install to fetch the matching browsers.


🏷️ Naming Conventions

What Convention Example
Test files test_<feature>.py test_cart.py
Test functions test_<behaviour> that reads as a sentence test_locked_user_sees_error
Page classes <Name>Page, components without suffix CartPage, Header
Fixtures Named after what they give you cart_with_earbuds, practice_api
Markers Lower-case, registered smoke, regression, api
Data files <feature>_cases.<ext> with an id column coupons.json

🧭 Rules That Keep a Framework Healthy

  1. Every test runs alone (pytest path::test_name) and in any order. No test depends on another test’s data.
  2. No sleep(). Use auto-waiting actions and expect.
  3. No secrets in the repository. Use .env locally and CI secrets in pipelines.
  4. Fixtures over helpers with side effects. Setup and clean-up belong in yield fixtures.
  5. Small modules. If a page class passes 200 lines, split out components.
  6. Review tests like production code. Lint them (for example with ruff) and keep them in the same pull request as the feature when possible.

🏋️ 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: Your team keeps pytest.ini and also adds [tool.pytest.ini_options] to pyproject.toml, but the new markers are “unknown”. Why?

Show answer

When a pytest.ini file exists, pytest uses it as the configuration file and ignores [tool.pytest.ini_options] in pyproject.toml. Move all settings into one file (and delete the other).

Exercise 2: Add a marker checkout to the framework so that pytest -m checkout works with --strict-markers. Show the change.

Show answer
[tool.pytest.ini_options]
markers = [
    "smoke: fast checks for every commit",
    "regression: full regression suite",
    "api: API tests (no browser)",
    "checkout: checkout flow tests",
]

Then decorate tests with @pytest.mark.checkout.

Exercise 3: Where should a fixture admin_api_token go in this layout, and why?

Show answer

In tests/api/conftest.py if only API tests use it; in tests/conftest.py if UI tests also need it (for example for hybrid setup). Put fixtures at the lowest level that covers every test that uses them, so other tests do not see or load them.

Exercise 4: A new tester puts time.sleep(3) in CartPage.apply_coupon() “because the message is slow”. What do you suggest?

Show answer

Remove the sleep. Let the action finish and assert the message in the test with expect(cart.coupon_message).to_have_text(...), which waits up to the expect timeout (configurable in Settings). Sleeps make every call slower and still fail when the app is slower than the guess.


🧠 MCQ Quiz: Framework Folder Structure and Best Practices

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 testpaths = ["tests"] do?
  2. What does --strict-markers change?
  3. Which file does pytest use if both pytest.ini and pyproject.toml exist?
  4. Why put the API client fixture in tests/api/conftest.py?
  5. What is the fastest way to check imports, layout and markers without running tests?
  6. What does -ra in addopts add?
  7. Why pin dependency versions in requirements.txt?
  8. Where do locators belong in this framework?
  9. Which item must be in .gitignore?
  10. Which rule keeps tests reliable as the suite grows?

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


❓ Frequently Asked Questions

🤔 Should tests be grouped by page or by feature?

By feature or user journey (test_cart.py, test_checkout.py). Page objects are already grouped by page; grouping tests the same way often splits one journey across several files.

🤔 Do I need __init__.py files in test folders?

With pythonpath = ["."] and pytest’s default import mode, no. Add them only if two test files in different folders share a name (for example two test_login.py), or use unique file names.

🤔 Where do helper functions go?

In a utils/ package if they are general (date formatting, random data), or next to what they support (pages/, api/). Avoid one huge helpers.py.

🤔 How do I share this framework between several projects?

Package the reusable parts (base page, API client, fixtures) as an installable Python package or a pytest plugin, and keep each product’s pages and tests in its own repository.

🤔 Is this layout too much for a small project?

Start with pages/, tests/ and one conftest.py, and add config/, api/ and data/ when you first need them. The point is to know where each kind of code will go.


🏁 Summary

  • Give every folder one job: config/, pages/, api/, data/, tests/ (split into ui/ and api/).
  • Put pytest settings in pyproject.toml: testpaths, pythonpath, addopts with --strict-markers and -ra, and registered markers.
  • Layer conftest.py files: shared fixtures at tests/, browser fixtures in tests/ui/, API fixtures in tests/api/.
  • Pin dependencies, ignore artifacts and secrets, and follow naming conventions.
  • Check the structure with --collect-only, and keep every test independent and sleep-free.

🎬 Watch the Playwright tutorial series on YouTube!

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

Page Object Model in Playwright Python Step by Step

When ten tests all contain page.get_by_test_id("login-username"), a single change to the login form breaks ten files. The Page Object Model (POM) fixes that by giving every page of the application one Python class that knows its locators and actions. Tests then read like user stories: log in, search, add to cart. In this lesson you will refactor real SQA Shop tests into page objects step by step: a base page, page classes with locators and actions, methods that return the next page, a shared header component, pytest fixtures that hand out page objects, and the rules that keep a POM clean as it grows.

📖 What You’ll Learn: the problem POM solves, what belongs in a page object and what does not, a BasePage, locators defined once in init, action methods, methods that return the next page object, keeping assertions in tests, small assertion helpers, components for shared parts like the header, page-object fixtures in conftest.py, and common POM mistakes.


😖 The Problem: Locators Everywhere

Here are two ordinary tests for the SQA Shop:

📄 pytest.ini

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

pythonpath = . puts the project root on Python’s import path, so tests can import pages... from the pages/ folder you are about to create.

📄 tests/test_before_pom.py

from playwright.sync_api import Page, expect

SHOP = "/dummy-ecommerce-website/"


def test_login_and_add_to_cart(page: Page):
    page.goto(SHOP + "#/login")
    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("account-button")).to_contain_text("Hi, Test")
    page.get_by_test_id("search-input").fill("earbuds")
    page.get_by_test_id("search-button").click()
    page.get_by_role("button", name="Add to cart").first.click()
    expect(page.get_by_test_id("cart-count")).to_have_text("1")


def test_coupon(page: Page):
    page.goto(SHOP + "#/login")
    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()
    page.get_by_test_id("search-input").fill("earbuds")
    page.get_by_test_id("search-button").click()
    page.get_by_role("button", name="Add to cart").first.click()
    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.")

⌨️ Terminal

pytest tests/test_before_pom.py -q

🖥️ Output

..                                                                       [100%]
2 passed in 4.07s

They pass, but:

  • The login steps are copied. If the login form changes, every copy must change.
  • A reader must decode locators to understand the intent: what does get_by_test_id("apply-coupon") mean for the business?
  • Nothing stops one test from using a slightly different (and worse) locator for the same button.

🧱 Step 1: A Base Page

A page object is a class that represents one page (or one view of a single-page app). It holds the Playwright Page and exposes the page’s elements and actions. Start with a small base class for what all pages share:

📄 pages/base_page.py

from playwright.sync_api import Page

SHOP = "/dummy-ecommerce-website/"


class BasePage:
    """Shared plumbing for all SQA Shop pages."""

    path = ""                                   # each page sets its own route, e.g. "#/login"

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

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

open() returns self, so a test can write LoginPage(page).open().login(...).


🔐 Step 2: The Login Page

Define each locator once, in __init__, with a name that says what it is. Locators in Playwright are lazy (nothing is searched until you act), so creating them up front costs nothing.

📄 pages/login_page.py

from playwright.sync_api import Page

from pages.base_page import BasePage


class LoginPage(BasePage):
    path = "#/login"

    def __init__(self, page: Page):
        super().__init__(page)
        self.username = page.get_by_test_id("login-username")
        self.password = page.get_by_test_id("login-password")
        self.remember_me = page.get_by_test_id("remember-me")
        self.submit_button = page.get_by_test_id("login-button")
        self.error = page.get_by_test_id("login-error")

    def submit(self, username: str, password: str, remember: bool = False):
        """Fill the form and press Log in. Use for negative tests (wrong password, locked user)."""
        self.username.fill(username)
        self.password.fill(password)
        if remember:
            self.remember_me.check()
        self.submit_button.click()
        return self

    def login(self, username: str, password: str, remember: bool = False):
        """Log in successfully and return the home page once it is ready."""
        self.submit(username, password, remember)
        from pages.home_page import HomePage     # imported here to avoid a circular import
        home = HomePage(self.page)
        home.header.account_button.filter(has_text="Hi,").wait_for()   # synchronise: the login has finished
        return home

login() returns the next page the user lands on. This makes the flow visible in the test and lets your editor autocomplete what you can do next.

Notice the wait_for() line. It is not an assertion; it is synchronisation. While this lesson was being written, a version without it was flaky: after the click, the store switches to its home view a moment later, and a test that searched immediately sometimes had its search results replaced by that home view. A navigation method should return only when the next page is ready, so every test that calls it is safe. Negative tests use submit(), which does not wait for a successful login.


🏠 Step 3: A Component for the Header

The header (search box, account menu, cart badge) appears on every page. Do not copy its locators into each page class; make it a component and attach it to the pages:

📄 pages/components.py

from playwright.sync_api import Page


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.account_button = page.get_by_test_id("account-button")
        self.cart_count = page.get_by_test_id("cart-count")
        self.cart_link = page.get_by_test_id("cart-link")

    def search(self, term: str):
        self.search_input.fill(term)
        self.search_button.click()
        from pages.home_page import SearchResults
        return SearchResults(self.page)

    def open_cart(self):
        self.cart_link.click()
        from pages.cart_page import CartPage
        return CartPage(self.page)

Now give every page a header through the base class:

📄 pages/base_page.py

from playwright.sync_api import Page

SHOP = "/dummy-ecommerce-website/"


class BasePage:
    """Shared plumbing for all SQA Shop pages."""

    path = ""

    def __init__(self, page: Page):
        self.page = page
        from pages.components import Header
        self.header = Header(page)

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

🛍️ Step 4: Home, Search Results and Cart

📄 pages/home_page.py

from playwright.sync_api import Locator, Page

from pages.base_page import BasePage


class HomePage(BasePage):
    path = "#/"


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

    def card(self, name: str) -> Locator:
        return self.cards.filter(has_text=name).first

    def add_to_cart(self, name: str):
        self.card(name).get_by_role("button", name="Add to cart").click()
        return self

📄 pages/cart_page.py

from playwright.sync_api import Page

from pages.base_page import BasePage


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

    def __init__(self, page: Page):
        super().__init__(page)
        self.item_names = page.get_by_test_id("cart-item-name")
        self.coupon_input = page.get_by_test_id("coupon-input")
        self.apply_coupon_button = page.get_by_test_id("apply-coupon")
        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")

    def apply_coupon(self, code: str):
        self.coupon_input.fill(code)
        self.apply_coupon_button.click()
        return self

card(name) shows a useful idea: page objects can return locators built from parameters, so tests can target “the Wireless Earbuds card” without knowing how cards are found.


🧪 Step 5: Tests with Page Objects

Expose page objects as fixtures so tests just ask for them:

📄 tests/conftest.py

import pytest
from playwright.sync_api import Page

from pages.cart_page import CartPage
from pages.home_page import HomePage
from pages.login_page import LoginPage


@pytest.fixture
def login_page(page: Page) -> LoginPage:
    return LoginPage(page)


@pytest.fixture
def home(page: Page) -> HomePage:
    return HomePage(page).open()


@pytest.fixture
def logged_in_home(login_page: LoginPage) -> HomePage:
    return login_page.open().login("testuser", "Test@123")

📄 tests/test_with_pom.py

from playwright.sync_api import expect

from pages.login_page import LoginPage


def test_login_and_add_to_cart(logged_in_home):
    expect(logged_in_home.header.account_button).to_contain_text("Hi, Test")
    results = logged_in_home.header.search("earbuds")
    results.add_to_cart("Wireless Earbuds")
    expect(results.header.cart_count).to_have_text("1")


def test_coupon(logged_in_home):
    logged_in_home.header.search("earbuds").add_to_cart("Wireless Earbuds")
    cart = logged_in_home.header.open_cart()
    cart.apply_coupon("SAVE10")
    expect(cart.coupon_message).to_have_text("Coupon SAVE10 applied.")
    expect(cart.coupon_discount).to_have_text("−₹500")


def test_locked_user_sees_error(login_page: LoginPage):
    login_page.open().submit("lockeduser", "Test@123")
    expect(login_page.error).to_have_text("This account is locked. Please contact support.")

⌨️ Terminal

pytest tests/test_with_pom.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 3 items

tests/test_with_pom.py::test_login_and_add_to_cart[chromium] PASSED      [ 33%]
tests/test_with_pom.py::test_coupon[chromium] PASSED                     [ 66%]
tests/test_with_pom.py::test_locked_user_sees_error[chromium] PASSED     [100%]

============================== 3 passed in 5.45s ==============================

Compare test_coupon with the version at the top: the test now says what happens (log in, search, add, open cart, apply coupon) and the page objects know how.

Your project now looks like this:

project/
├── pages/
│   ├── base_page.py      BasePage (+ header for every page)
│   ├── components.py     Header
│   ├── login_page.py     LoginPage
│   ├── home_page.py      HomePage, SearchResults
│   └── cart_page.py      CartPage
├── tests/
│   ├── conftest.py       page-object fixtures
│   └── test_with_pom.py
└── pytest.ini

✅ Where Do Assertions Go?

Two schools exist. The rule that scales best:

  • Page objects expose locators and actions; they do not decide whether a test passes.
  • Tests make the assertions with expect(...) on the page object’s locators.

This keeps page objects reusable: submit() serves the locked-user test, login() the happy paths, and each test states its own expectation. (Waiting for the next page inside login() is synchronisation, not a test verdict.) If you have checks that many tests repeat, add a small, clearly named helper that wraps expect:

📄 pages/assertions.py

from playwright.sync_api import expect

from pages.base_page import BasePage


def expect_logged_in_as(page_object: BasePage, first_name: str):
    expect(page_object.header.account_button).to_contain_text(f"Hi, {first_name}")

📄 tests/test_helpers.py

from pages.assertions import expect_logged_in_as


def test_greeting(logged_in_home):
    expect_logged_in_as(logged_in_home, "Test")

⌨️ Terminal

pytest -q

🖥️ Output

......                                                                   [100%]
6 passed in 12.18s

⚠️ Common POM Mistakes

Mistake Why it hurts Instead
A “god” page class with every locator of the app Hard to find anything, merge conflicts One class per page or view, components for shared parts
time.sleep() or manual waits inside page methods Slow and flaky Rely on auto-waiting actions and expect in tests
Returning raw strings like get_text() everywhere Loses Playwright’s retrying assertions Expose locators; assert with expect
Page objects that open the browser or read config Hidden dependencies, hard to test Pass in the Page; let fixtures handle setup
Deep inheritance trees (BasePage > ShopPage > CheckoutPage > ...) Changes ripple unpredictably Keep a thin base class; prefer composition (components)
Locators as long CSS/XPath strings Brittle get_by_role, get_by_label, get_by_test_id (Module 4)

💡 Tip: Name methods after user intent (apply_coupon, add_to_cart), not after UI mechanics (click_apply_button). When the UI changes from a button to pressing Enter, the method body changes and the tests do not.


🏋️ 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 ProductPage class for the product detail view (#/p/<id>), with an open_product(product_id) method, a locator for the title and an add_to_cart() action. The title has the test id pdp-title and the button pdp-add-to-cart.

Show answer
class ProductPage(BasePage):
    def __init__(self, page: Page):
        super().__init__(page)
        self.title = page.get_by_test_id("pdp-title")
        self.add_button = page.get_by_test_id("pdp-add-to-cart")

    def open_product(self, product_id: str):
        self.page.goto(SHOP + f"#/p/{product_id}")
        return self

    def add_to_cart(self):
        self.add_button.click()
        return self

Use it as ProductPage(page).open_product("EL-013").add_to_cart(). The product page also has pdp-price, pdp-qty and pdp-buy-now if you want to extend it.

Exercise 2: A teammate wrote def get_cart_count(self) -> str: return self.cart_count.inner_text() and tests do assert header.get_cart_count() == "1". Why is this flaky, and what is better?

Show answer

inner_text() reads the value once, immediately; if the badge updates a moment later the assertion fails. Expose the locator and assert with a retrying assertion: expect(header.cart_count).to_have_text("1").

Exercise 3: Write a fixture cart_with_earbuds that returns a CartPage with Wireless Earbuds already added, using the page objects from the lesson.

Show answer
@pytest.fixture
def cart_with_earbuds(home: HomePage) -> CartPage:
    home.header.search("earbuds").add_to_cart("Wireless Earbuds")
    return home.header.open_cart()

Fixtures that return page objects in a known state make tests very short: def test_flat200(cart_with_earbuds): ....

Exercise 4: Why does LoginPage.login() return a HomePage instead of None, and why does it wait for the greeting before returning?

Show answer

Returning HomePage documents the navigation, lets tests chain calls (LoginPage(page).open().login(...).header.search(...)), and gives editors type information. Waiting for the greeting makes sure the app has finished its own navigation before the test continues; without it, a fast next step can race with the app’s re-render and become flaky.


🧠 MCQ Quiz: Page Object Model in Python

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 problem does the Page Object Model mainly solve?
  2. Where should a page object’s locators be defined?
  3. Why is creating locators in __init__ cheap in Playwright?
  4. What should LoginPage.login() return?
  5. In the recommended style, where do assertions live?
  6. How should a header that appears on every page be modelled?
  7. Which is a POM anti-pattern?
  8. What does a fixture like logged_in_home give tests?
  9. Why import HomePage inside login() in the lesson?
  10. Which method name is better in a page object?

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


❓ Frequently Asked Questions

🤔 Should a page object have a method for every element?

No. Expose locators as attributes and add methods only for meaningful actions (log in, search, apply coupon). Tests can still act on a locator directly when a one-off interaction is clearer.

🤔 Can I use POM with single-page apps like SQA Shop?

Yes. Treat each view (login, search results, cart, checkout) as a “page” even though the URL only changes after the #. What matters is a class per screen the user sees.

🤔 How do I handle elements that appear on some pages only, like a cookie banner?

Make it a component with its own class (for example CookieBanner) and create it where it can appear, or handle it once in a fixture with page.add_locator_handler() so it never blocks a test.

🤔 Should page objects use dataclasses or properties?

Plain attributes set in __init__ are simplest. Use @property when a locator depends on state (for example the current user), and parameterised methods like card(name) for dynamic elements.

🤔 What comes after POM in a framework?

A clear folder structure (next lesson), design patterns such as factories and builders for test data (Lesson 58), and a complete framework with config, API clients and reporting (Lesson 60).


🏁 Summary

  • Page objects give each page or view one class with its locators and actions, removing duplication from tests.
  • Define locators once in __init__; name actions after user intent; return the next page object.
  • Model shared UI (header, menus, dialogs) as components and keep the base class thin.
  • Keep assertions in tests with expect, plus small named helpers for repeated checks.
  • Hand page objects to tests through fixtures, and avoid sleeps, god classes and raw-string getters.

🎬 Watch the Playwright tutorial series on YouTube!

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

Combine API and UI Tests in Playwright Python

The slowest and most fragile part of most UI tests is not the step being tested but the setup before it: logging in, creating data, filling a cart. An API call does the same work in milliseconds. In this lesson you will mix API and UI steps in one Playwright test: see how page.request shares cookies with the browser, log in through an API and continue in the browser, check that the UI shows exactly what the API returns, set up application state directly instead of clicking through it, and use the API to verify what a UI action did.

📖 What You’ll Learn: the arrange-act-assert split between API and UI, page.request and context.request vs a standalone client, sharing cookies in both directions, logging in with an API call and continuing in the browser, comparing UI content with the API response, seeding client-side state with add_init_script, verifying UI actions through storage or the API, cleaning up with the API, and when hybrid tests are worth it.


🔀 Why Combine API and UI?

Every test has three parts: arrange (get into the right state), act (do the thing being tested) and assert (check the result). Only the act needs to go through the UI in a UI test. The other parts can use faster, more reliable channels:

Part UI only Hybrid
Arrange Click through login, create data in forms API login, API-created data, seeded state
Act UI UI
Assert Read the screen Read the screen and check the API or stored state

Typical gains: 3 to 10 times faster tests, fewer failures in steps unrelated to the test, and stronger assertions (the UI says “Saved”, and the API confirms it really was).


🍪 page.request Shares Cookies with the Browser

Playwright gives every browser context an API client: context.request (also available as page.request). Unlike playwright.request.new_context(), it uses the browser context’s cookie jar: cookies set by an API response appear in the browser, and browser cookies are sent with API calls.

The SQA Tools practice API has a cookie-session login: POST /auth-lab/session/login sets an HttpOnly session cookie (sqa_lab_session), and GET /auth-lab/session/profile works only when that cookie is sent back.

📄 pytest.ini

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

📄 tests/test_shared_cookies.py

from playwright.sync_api import BrowserContext, Page, Playwright, expect

LAB = "/wp-json/sqa-api/v1/auth-lab/session"
VIEWER = {"username": "viewer", "password": "viewer@123"}


def test_api_login_is_visible_to_the_browser(page: Page, context: BrowserContext, base_url):
    # 1. log in with an API call that shares the browser's cookie jar
    response = page.request.post(base_url + LAB + "/login", data=VIEWER)
    assert response.status == 200

    # 2. the cookie set by the API response is now in the browser context
    names = [c["name"] for c in context.cookies()]
    print("\nbrowser cookies after API login:", [n for n in names if n.startswith("sqa")])
    assert "sqa_lab_session" in names

    # 3. the browser itself is logged in: opening the profile URL shows the user
    page.goto(LAB + "/profile")
    expect(page.locator("body")).to_contain_text('"username":"viewer"')


def test_standalone_client_has_its_own_cookies(page: Page, playwright: Playwright, base_url):
    page.request.post(base_url + LAB + "/login", data=VIEWER)          # browser context is logged in
    other = playwright.request.new_context(base_url=base_url)          # separate cookie jar
    assert page.request.get(base_url + LAB + "/profile").status == 200
    assert other.get(LAB + "/profile").status == 401
    other.dispose()

⌨️ Terminal

pytest tests/test_shared_cookies.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_shared_cookies.py::test_api_login_is_visible_to_the_browser[chromium] 
browser cookies after API login: ['sqa_lab_session']
PASSED
tests/test_shared_cookies.py::test_standalone_client_has_its_own_cookies[chromium] PASSED

============================== 2 passed in 3.11s ==============================

This is the key building block of hybrid tests: log in with one fast API call, then continue in the browser already logged in. It works for any application whose login sets a session cookie.

📌 Note: page.request does not use the page’s base_url automatically in every version, so these tests pass full URLs built from the base_url fixture. Relative URLs with page.goto() work as usual.


🪞 The UI Shows What the API Returns

A classic hybrid check: fetch the data through the API and compare it with what the page renders. This catches mapping bugs (wrong field, wrong order, missing items, formatting). The page here is the mini catalog from Lesson 52, which lists products from the practice API:

📄 tests/test_ui_matches_api.py

from pathlib import Path

from playwright.sync_api import Page, expect

CATALOG_URL = "https://sqatools.in/pw-demo/catalog"


def test_catalog_lists_what_the_api_returns(page: Page):
    page.route(CATALOG_URL, lambda route: route.fulfill(path=Path(__file__).parent / "catalog.html"))

    api_products = page.request.get("https://sqatools.in/wp-json/sqa-api/v1/products?per_page=5").json()["data"]
    expected = [f"{p['name']} — ₹{p['price']}" + ("" if p["in_stock"] else " (out of stock)") for p in api_products]

    page.goto(CATALOG_URL)
    expect(page.get_by_test_id("product")).to_have_text(expected)
    print("\n" + "\n".join(expected))

⌨️ Terminal

pytest tests/test_ui_matches_api.py -q -s

🖥️ Output

Wireless Mouse — ₹799
Mechanical Keyboard — ₹3499
USB-C Hub 7-in-1 — ₹2199 (out of stock)
27-inch Monitor — ₹15999
Cotton T-Shirt — ₹499
.
1 passed in 2.01s

to_have_text() with a list checks every item and the order in one assertion, and retries until the page has rendered.


⚡ Fast Setup: Seed State Instead of Clicking

The SQA Shop practice store keeps its cart in the browser (localStorage, key spCart), not on a server. For apps like this, the equivalent of “create data with the API” is to write the state directly before the page loads. context.add_init_script() runs before the store’s own JavaScript, so the app starts with the cart you want:

📄 tests/test_checkout_seeded.py

import json

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

SHOP = "/dummy-ecommerce-website/"


@pytest.fixture
def seeded_cart(context: BrowserContext):
    """Start the store with two items in the cart, without clicking through search and product pages."""
    cart = [{"id": "EL-013", "size": "", "color": "", "qty": 1},     # Wireless Earbuds
            {"id": "DG-010", "size": "", "color": "", "qty": 2}]     # Agile Testing Handbook
    context.add_init_script(f"""
        if (!sessionStorage.getItem('seeded')) {{
            localStorage.setItem('spCart', {json.dumps(json.dumps(cart))});
            sessionStorage.setItem('seeded', '1');
        }}""")
    return cart


def test_cart_page_shows_seeded_items(page: Page, seeded_cart):
    page.goto(SHOP + "#/cart")
    expect(page.get_by_test_id("cart-count")).to_have_text("3")
    expect(page.get_by_test_id("cart-item-name")).to_have_text(["Wireless Earbuds", "Agile Testing Handbook"])


def test_coupon_on_seeded_cart(page: Page, seeded_cart):
    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("−₹200")

⌨️ Terminal

pytest tests/test_checkout_seeded.py -v --durations=3

🖥️ 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_checkout_seeded.py::test_cart_page_shows_seeded_items[chromium] PASSED [ 50%]
tests/test_checkout_seeded.py::test_coupon_on_seeded_cart[chromium] PASSED [100%]

============================= slowest 3 durations =============================
1.91s call     tests/test_checkout_seeded.py::test_cart_page_shows_seeded_items[chromium]
1.56s call     tests/test_checkout_seeded.py::test_coupon_on_seeded_cart[chromium]
0.42s setup    tests/test_checkout_seeded.py::test_cart_page_shows_seeded_items[chromium]
============================== 2 passed in 4.09s ==============================

Two details:

  • The seeded flag in sessionStorage makes the script seed the cart only on the first page load. Without it, every navigation would reset the cart and you could never test removing an item.
  • json.dumps(json.dumps(cart)) produces a JavaScript string literal containing JSON, which is what localStorage.setItem expects.

For server-side applications you would do the same with page.request.post("/api/cart", data=...) after an API login.


🔍 Verify UI Actions Behind the Scenes

The other direction: act in the UI, then check the source of truth rather than only the screen. In SQA Shop that is the stored cart; in a server-side app it is an API call.

📄 tests/test_verify_state.py

import json

from playwright.sync_api import Page, expect

SHOP = "/dummy-ecommerce-website/"


def stored_cart(page: Page) -> list[dict]:
    return json.loads(page.evaluate("localStorage.getItem('spCart') || '[]'"))


def test_quantity_change_is_saved(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("cart-plus-EL-013").click()                       # UI action

    expect(page.get_by_test_id("cart-count")).to_have_text("2")           # the screen says 2
    assert [(line["id"], line["qty"]) for line in stored_cart(page)] == [("EL-013", 2)]   # the data says 2

⌨️ Terminal

pytest tests/test_verify_state.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 1 item

tests/test_verify_state.py::test_quantity_change_is_saved[chromium] PASSED [100%]

============================== 1 passed in 2.21s ==============================

A screen can show a number that was never saved (an optimistic update that later fails). Checking the stored data, or the API, catches that.


🧹 Clean Up with the API

When a UI test creates server data (an order, a user, a ticket), delete it through the API in the fixture’s teardown, so the next run starts clean:

@pytest.fixture
def created_ticket_ids(page):
    ids = []
    yield ids                                    # the test appends the IDs it created
    for ticket_id in ids:
        page.request.delete(f"https://app.example.com/api/tickets/{ticket_id}")

Clean-up through the API is fast and keeps working even when the UI for deleting is broken.


⚖️ When Hybrid Tests Are Worth It

Use API steps for setup and clean-up that are not what the test is about (login, test data, feature flags), and for assertions that need the source of truth.

Keep pure UI steps for the behaviour under test, and keep a few full end-to-end journeys (for example “new user signs up, logs in, orders”) completely in the UI, because those are the flows real users take.

A common shape for a mature suite: many hybrid tests (API arrange, UI act, UI + API assert), a handful of pure end-to-end journeys, and a fast API test layer (Lesson 54).


🏋️ 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 test that logs in to the auth-lab cookie session with page.request, then calls page.request.post on /auth-lab/session/logout, and finally checks that opening /auth-lab/session/profile in the browser no longer shows the user.

Show answer
def test_logout_clears_browser_session(page, base_url):
    lab = base_url + "/wp-json/sqa-api/v1/auth-lab/session"
    page.request.post(lab + "/login", data={"username": "viewer", "password": "viewer@123"})
    page.request.post(lab + "/logout")
    page.goto(lab + "/profile")
    expect(page.locator("body")).not_to_contain_text('"username":"viewer"')

The logout response clears the cookie in the shared jar, so the browser is logged out too.

Exercise 2: Seed the SQA Shop cart with three units of EL-013 and check that the cart page shows the quantity 3. Reuse the add_init_script approach.

Show answer
def test_three_earbuds(context, page):
    cart = [{"id": "EL-013", "size": "", "color": "", "qty": 3}]
    context.add_init_script(f"if (!sessionStorage.getItem('s')) {{ localStorage.setItem('spCart', {json.dumps(json.dumps(cart))}); sessionStorage.setItem('s','1'); }}")
    page.goto("/dummy-ecommerce-website/#/cart")
    expect(page.get_by_test_id("cart-qty-EL-013")).to_have_value("3")

The quantity is a read-only <input>, so check its value, not its text.

Exercise 3: Your hybrid test logs in with playwright.request.new_context().post(...) and then opens the app in page, but the page is not logged in. Why?

Show answer

A standalone request context has its own cookie jar, so the session cookie never reaches the browser context. Use page.request or context.request (shared cookies), or save the standalone client’s state with request_context.storage_state() and pass it to browser.new_context(storage_state=...).

Exercise 4: Write the assertion that checks each catalog item contains the matching product name from page.request.get(...), in the same order, in one line.

Show answer
expect(page.get_by_test_id("product")).to_contain_text([p["name"] for p in api_products])

With a list, to_contain_text checks that there are as many elements as names and that each element contains its name, in order, with auto-retry. The items also contain prices, so to_contain_text fits better than to_have_text here.


🧠 MCQ Quiz: Combine API and UI Tests

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 part of a hybrid test should normally go through the UI?
  2. What is special about page.request compared with playwright.request.new_context()?
  3. After page.request.post(login_url, ...) sets a session cookie, what happens in the browser?
  4. In the lesson, why did the standalone client get 401 for the profile?
  5. What does expect(locator).to_have_text([...]) with a list check?
  6. Why seed the SQA Shop cart with add_init_script?
  7. Why did the seeding script use a sessionStorage flag?
  8. Why check stored data or the API after a UI action?
  9. Where is API clean-up best placed?
  10. Which tests should stay fully UI from start to finish?

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


❓ Frequently Asked Questions

🤔 Can I log in through the API if my app uses tokens in localStorage, not cookies?

Yes. Call the login API, take the token from the response, and put it into localStorage with add_init_script (as the cart example does), or create a storage-state file with the token and load it (Lesson 51).

🤔 Does page.request appear in the trace?

Yes. API calls made with page.request or context.request are recorded in Playwright traces, so you can see them next to the UI steps when debugging.

🤔 What if the API and the UI are on different domains?

Cookies are per domain, so an API login on api.example.com sets cookies for that domain only. Hybrid login works when the session cookie is valid for the domain the browser opens (often a shared parent domain such as .example.com).

🤔 Is seeding client-side state cheating?

No, as long as the seeded state is one the app can really be in and the test is not about the steps you skipped. Keep a separate UI test for the skipped flow (here: adding to the cart from a product page).

🤔 How do I share an API-created object ID with the UI test?

Return it from the fixture (yield obj["id"]) and use it in the URL or locator, for example page.goto(f"/orders/{order_id}").


🏁 Summary

  • Use the API for arrange and clean-up, the UI for the action under test, and both for assertions.
  • page.request / context.request share cookies with the browser: an API login logs in the browser too.
  • Compare what the UI shows with what the API returns using to_have_text([...]).
  • For client-side apps, seed state with add_init_script; for server apps, create it with API calls.
  • Verify UI actions against stored data or the API, and keep a few pure end-to-end journeys.

🎬 Watch the Playwright tutorial series on YouTube!

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

API Testing with Playwright Python (APIRequestContext)

Playwright is not only a browser tool. Its APIRequestContext sends HTTP requests directly, without a browser, so the same pytest project can test your REST API and your UI with one set of fixtures, one report and one CI job. In this lesson you will build an API test suite against the SQA Tools practice API: a session fixture for the client, GET with query parameters, POST, PUT, PATCH and DELETE on real temporary objects, response assertions, API keys, Basic auth and Bearer tokens, validation errors, and clean-up after every test.

📖 What You’ll Learn: what APIRequestContext is, playwright.request.new_context with base_url and extra_http_headers, the base_url trailing-slash rule, a session-scoped api fixture, GET with params, response.status, ok, json() and headers, expect(response).to_be_ok(), POST with data, PUT, PATCH and DELETE, CRUD with clean-up fixtures, API key and Basic auth, logging in for a Bearer token, testing 401 and 422 errors, fail_on_status_code, timeouts, and page.request sharing cookies with the browser.


🔌 What Is APIRequestContext?

APIRequestContext is Playwright’s HTTP client. It has methods for every HTTP verb (get, post, put, patch, delete, head, fetch) and returns an APIResponse with the status, headers and body.

Why use it instead of the requests library?

  • One toolkit: the same fixtures, reports, traces and CI setup as your UI tests.
  • Shared cookies: page.request and context.request use the browser context’s cookies, so you can log in through the API and continue in the UI (next lesson).
  • Playwright assertions: expect(response).to_be_ok() prints the response body when it fails.

There are three ways to get one:

Object Cookies Typical use
playwright.request.new_context(...) Its own, isolated Pure API tests
context.request / page.request Shared with the browser context Mixing API and UI steps

🧪 The Practice API

All examples use the free SQA Tools practice API at https://sqatools.in/wp-json/sqa-api/v1. It has read-only data (/people, /products, /orders), temporary objects you can create, change and delete (/objects, kept for 10 minutes), and endpoints behind an API key, Basic auth and Bearer tokens. The credentials below are the public practice ones shown on that page.


🧰 The api Fixture

Create the client once per test session:

📄 pytest.ini

[pytest]
markers =
    smoke: quick API checks

📄 tests/conftest.py

from typing import Generator

import pytest
from playwright.sync_api import APIRequestContext, Playwright

API_URL = "https://sqatools.in/wp-json/sqa-api/v1/"     # note the trailing slash


@pytest.fixture(scope="session")
def api(playwright: Playwright) -> Generator[APIRequestContext, None, None]:
    context = playwright.request.new_context(
        base_url=API_URL,
        extra_http_headers={"Accept": "application/json"},
        timeout=15_000,
    )
    yield context
    context.dispose()                                         # release resources when the run ends

playwright is a pytest-playwright fixture, so no browser is launched for these tests.

⚠️ Watch out: The trailing-slash rule. With base_url="https://sqatools.in/wp-json/sqa-api/v1/", a request to "products" goes to .../v1/products. A request to "/products" (leading slash) replaces the whole path and goes to https://sqatools.in/products. Always end the base URL with / and write endpoint paths without a leading slash. The test below proves it.

📄 tests/test_base_url_rule.py

def test_relative_paths(api):
    ok = api.get("products")
    wrong = api.get("/products")
    print(f"\n'products'  -> {ok.url} {ok.status}\n'/products' -> {wrong.url} {wrong.status}")
    assert ok.status == 200 and wrong.status == 404

⌨️ Terminal

pytest tests/test_base_url_rule.py -q -s

🖥️ Output

'products'  -> https://sqatools.in/wp-json/sqa-api/v1/products 200
'/products' -> https://sqatools.in/products 404
.
1 passed in 1.00s

📥 GET Requests and Response Checks

📄 tests/test_get.py

import pytest
from playwright.sync_api import APIRequestContext, expect


@pytest.mark.smoke
def test_health(api: APIRequestContext):
    response = api.get("health")
    expect(response).to_be_ok()                      # status 200-299, shows the body on failure
    assert response.json()["status"] == "ok"


def test_people_first_page(api: APIRequestContext):
    response = api.get("people", params={"per_page": 3, "page": 1})
    assert response.status == 200
    assert response.headers["content-type"].startswith("application/json")
    body = response.json()
    assert [p["name"] for p in body["data"]] == ["Asha Verma", "Rahul Mehta", "Priya Nair"]
    assert body["meta"] == {"page": 1, "per_page": 3, "total": 12, "total_pages": 4, "sort": "id", "order": "asc"}


def test_filter_products(api: APIRequestContext):
    body = api.get("products", params={"category": "books", "in_stock": "true"}).json()
    assert body["data"], "expected at least one book in stock"
    for product in body["data"]:
        assert product["category"] == "books"
        assert product["in_stock"] is True


def test_unknown_product_is_404(api: APIRequestContext):
    response = api.get("products/99999")
    assert response.status == 404
    assert response.json()["error"]["code"] == "not_found"

⌨️ Terminal

pytest tests/test_get.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
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 4 items

tests/test_get.py::test_health PASSED                                    [ 25%]
tests/test_get.py::test_people_first_page PASSED                         [ 50%]
tests/test_get.py::test_filter_products PASSED                           [ 75%]
tests/test_get.py::test_unknown_product_is_404 PASSED                    [100%]

============================== 4 passed in 2.06s ==============================

The main APIResponse members:

Member Returns
status, status_text, ok 200, "OK", True for 2xx
headers Dictionary of response headers (lower-case names)
json(), text(), body() Parsed JSON, a string, raw bytes
url The final URL after redirects

params= builds the query string (?category=books&in_stock=true) and encodes values safely; never concatenate query strings by hand.


✍️ POST, PUT, PATCH and DELETE

The /objects endpoint stores temporary objects for 10 minutes, so you can practise the full lifecycle:

📄 tests/test_crud.py

from playwright.sync_api import APIRequestContext, expect


def test_object_lifecycle(api: APIRequestContext):
    # CREATE
    created = api.post("objects", data={"name": "Playwright laptop", "data": {"price": 55000, "color": "grey"}})
    assert created.status == 201
    obj = created.json()
    object_id = obj["id"]
    assert obj["name"] == "Playwright laptop" and obj["version"] == 1

    # READ
    expect(api.get(f"objects/{object_id}")).to_be_ok()

    # PATCH: change one field, keep the rest
    patched = api.patch(f"objects/{object_id}", data={"data": {"price": 52000}})
    assert patched.status == 200
    print("\nafter PATCH:", patched.json()["data"], "version", patched.json()["version"])

    # PUT: replace the whole object
    replaced = api.put(f"objects/{object_id}", data={"name": "Playwright laptop v2", "data": {"price": 50000}})
    assert replaced.status == 200
    print("after PUT:  ", replaced.json()["name"], replaced.json()["data"], "version", replaced.json()["version"])

    # DELETE, then it is gone
    assert api.delete(f"objects/{object_id}").status in (200, 204)
    assert api.get(f"objects/{object_id}").status == 404

⌨️ Terminal

pytest tests/test_crud.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
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_crud.py::test_object_lifecycle 
after PATCH: {'price': 52000, 'color': 'grey'} version 2
after PUT:   Playwright laptop v2 {'price': 50000} version 3
PASSED

============================== 1 passed in 2.78s ==============================
  • data= with a dictionary sends JSON and sets Content-Type: application/json. Use form= for HTML form encoding and multipart= for file uploads.
  • The output shows the difference between PATCH (merge: color survived) and PUT (replace: color is gone), and the server incrementing version on every change.

🧹 Create Test Data with a Fixture and Clean Up

Tests that create data must remove it, even when they fail. A yield fixture does both:

📄 tests/test_fixture_data.py

from typing import Generator

import pytest
from playwright.sync_api import APIRequestContext


@pytest.fixture
def temp_object(api: APIRequestContext) -> Generator[dict, None, None]:
    obj = api.post("objects", data={"name": "fixture object", "data": {"qty": 1}}).json()
    yield obj
    api.delete(f"objects/{obj['id']}")             # runs after the test, pass or fail


def test_rename(api: APIRequestContext, temp_object):
    response = api.patch(f"objects/{temp_object['id']}", data={"name": "renamed"})
    assert response.json()["name"] == "renamed"


def test_listing_contains_it(api: APIRequestContext, temp_object):
    ids = [o["id"] for o in api.get("objects", params={"per_page": 100}).json()["data"]]
    assert temp_object["id"] in ids

⌨️ Terminal

pytest tests/test_fixture_data.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
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_fixture_data.py::test_rename PASSED                           [ 50%]
tests/test_fixture_data.py::test_listing_contains_it PASSED              [100%]

============================== 2 passed in 2.42s ==============================

🔐 Authentication

API key in a header

Put headers every request needs into the context with extra_http_headers:

📄 tests/test_auth.py

import pytest
from playwright.sync_api import APIRequestContext, Playwright


def test_api_key_missing(api: APIRequestContext):
    response = api.get("apikey/profile")
    assert response.status == 401
    assert response.json()["error"]["code"] == "missing_api_key"


def test_api_key(playwright: Playwright):
    client = playwright.request.new_context(base_url="https://sqatools.in/wp-json/sqa-api/v1/",
                                            extra_http_headers={"X-API-Key": "sqa-key-12345"})
    response = client.get("apikey/profile")
    assert response.status == 200
    print("\napikey profile:", response.json())
    client.dispose()


def test_basic_auth(playwright: Playwright):
    client = playwright.request.new_context(base_url="https://sqatools.in/wp-json/sqa-api/v1/",
                                            http_credentials={"username": "sqa_user", "password": "sqa@123"})
    assert client.get("auth-lab/basic").status == 200
    client.dispose()


@pytest.fixture(scope="session")
def admin_token(api: APIRequestContext) -> str:
    response = api.post("auth/login", data={"username": "admin", "password": "admin@123"})
    assert response.ok, response.text()
    return response.json()["access_token"]


def test_bearer_token(api: APIRequestContext, admin_token):
    me = api.get("auth/me", headers={"Authorization": f"Bearer {admin_token}"})
    assert me.status == 200
    assert me.json()["data"]["username"] == "admin"
    assert me.json()["data"]["can_write"] is True


def test_wrong_password(api: APIRequestContext):
    response = api.post("auth/login", data={"username": "admin", "password": "nope"})
    assert response.status == 401
    assert response.json()["error"]["code"] == "invalid_credentials"

⌨️ Terminal

pytest tests/test_auth.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
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_auth.py::test_api_key_missing PASSED
tests/test_auth.py::test_api_key 
apikey profile: {'data': {'client': 'api-client', 'auth': 'apikey', 'plan': 'free', 'message': 'API key accepted.'}}
PASSED
tests/test_auth.py::test_basic_auth PASSED
tests/test_auth.py::test_bearer_token PASSED
tests/test_auth.py::test_wrong_password PASSED

============================== 5 passed in 3.51s ==============================
  • extra_http_headers on the context applies to every request; headers= on one call adds or overrides headers for that call only.
  • http_credentials answers HTTP Basic challenges automatically.
  • The admin_token fixture logs in once per session, like the storage-state login in Lesson 51.

💡 Tip: Read real credentials from environment variables (Lesson 47). The practice API’s public demo credentials are written inline here only because they are published on its documentation page.


🚫 Testing Errors: 422 Validation

Negative tests matter as much as happy paths. The /validate/user endpoint returns 422 with one entry per invalid field:

📄 tests/test_validation.py

import pytest
from playwright.sync_api import APIRequestContext


@pytest.mark.parametrize(
    "payload, bad_fields",
    [
        pytest.param({}, {"name", "email", "age"}, id="empty-body"),
        pytest.param({"name": "Asha", "email": "not-an-email", "age": 30}, {"email"}, id="bad-email"),
        pytest.param({"name": "Asha", "email": "asha@example.com", "age": "30"}, {"age"}, id="age-as-string"),
        pytest.param({"name": "Asha", "email": "asha@example.com", "age": 17}, {"age"}, id="under-18"),
    ],
)
def test_invalid_user(api: APIRequestContext, payload, bad_fields):
    response = api.post("validate/user", data=payload)
    assert response.status == 422
    details = response.json()["error"]["details"]
    assert {d["field"] for d in details} == bad_fields


def test_valid_user(api: APIRequestContext):
    response = api.post("validate/user", data={"name": "Asha", "email": "asha@example.com", "age": 30})
    assert response.status == 200

⌨️ Terminal

pytest tests/test_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
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_validation.py::test_invalid_user[empty-body] PASSED           [ 20%]
tests/test_validation.py::test_invalid_user[bad-email] PASSED            [ 40%]
tests/test_validation.py::test_invalid_user[age-as-string] PASSED        [ 60%]
tests/test_validation.py::test_invalid_user[under-18] PASSED             [ 80%]
tests/test_validation.py::test_valid_user PASSED                         [100%]

============================== 5 passed in 2.34s ==============================

The age-as-string case shows why API tests matter: a UI form usually sends strings, so only an API test checks that the server really enforces the number type.


⚙️ Useful Request Options

Option Example Use
params params={"page": 2} Query string
data / form / multipart multipart={"file": {"name": "a.txt", "mimeType": "text/plain", "buffer": b"hi"}} Body formats
headers headers={"If-None-Match": etag} Per-request headers
timeout timeout=5_000 Fail slow endpoints fast (milliseconds)
fail_on_status_code fail_on_status_code=True Raise an error for non-2xx instead of returning the response
max_redirects max_redirects=0 Inspect a redirect instead of following it

📄 tests/test_options.py

import pytest
from playwright.sync_api import APIRequestContext, Error


def test_fail_on_status_code(api: APIRequestContext):
    with pytest.raises(Error) as info:
        api.get("status/503", fail_on_status_code=True)
    print("\n", str(info.value).splitlines()[0])


def test_etag_not_modified(api: APIRequestContext):
    first = api.get("products/101")
    etag = first.headers["etag"]
    second = api.get("products/101", headers={"If-None-Match": etag})
    assert second.status == 304


def test_redirect_not_followed(api: APIRequestContext):
    response = api.get("redirect", params={"status": 302}, max_redirects=0)
    assert response.status == 302
    assert "/echo" in response.headers["location"]

⌨️ Terminal

pytest tests/test_options.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
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 3 items

tests/test_options.py::test_fail_on_status_code 
 APIRequestContext.get: 503 Service Unavailable
PASSED
tests/test_options.py::test_etag_not_modified PASSED
tests/test_options.py::test_redirect_not_followed PASSED

============================== 3 passed in 1.85s ==============================

✅ Good Practices for API Tests

  1. Assert the status first, then the body. A wrong status explains most failures.
  2. Check structure and types, not only values, for example isinstance(item["price"], int). For larger APIs, validate against the JSON Schema with the jsonschema library (the practice API publishes its schemas under /schema/{name}).
  3. Create your own data in fixtures and delete it afterwards; never depend on data another test created.
  4. Cover negative cases: missing auth (401), wrong role (403), not found (404), validation (422), rate limits (429).
  5. Keep secrets out of code and logs; print response bodies only for non-sensitive endpoints.

🏋️ 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 test that gets people filtered by city=Pune and asserts that every returned person lives in Pune and that the result is not empty.

Show answer
def test_people_in_pune(api):
    response = api.get("people", params={"city": "Pune"})
    assert response.status == 200
    people = response.json()["data"]
    assert people
    assert all(p["city"] == "Pune" for p in people)

Exercise 2: Write a test that logs in as viewer / viewer@123 and checks that the viewer can read token/objects but gets 403 when creating one.

Show answer
def test_viewer_is_read_only(api):
    token = api.post("auth/login", data={"username": "viewer", "password": "viewer@123"}).json()["access_token"]
    headers = {"Authorization": f"Bearer {token}"}
    assert api.get("token/objects", headers=headers).status == 200
    assert api.post("token/objects", headers=headers, data={"name": "x"}).status == 403

Role checks are among the most valuable API tests, because the UI usually just hides buttons.

Exercise 3: Create a fixture api_with_key (session scope) that returns a client already sending X-API-Key: sqa-key-12345, and disposes of it at the end of the session.

Show answer
@pytest.fixture(scope="session")
def api_with_key(playwright):
    client = playwright.request.new_context(base_url="https://sqatools.in/wp-json/sqa-api/v1/",
                                            extra_http_headers={"X-API-Key": "sqa-key-12345"})
    yield client
    client.dispose()

Exercise 4: A test calls api.get("/people") with base_url="https://sqatools.in/wp-json/sqa-api/v1/" and gets 404. Explain and fix it.

Show answer

A path starting with / is resolved from the host root, so the request goes to https://sqatools.in/people. Remove the leading slash: api.get("people"). Keep the trailing slash on the base URL.


🧠 MCQ Quiz: API Testing with APIRequestContext

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 call creates a standalone API client in Playwright Python?
  2. With base_url="https://x.com/api/v1/", where does get("/users") go?
  3. What does data={"a": 1} do in api.post()?
  4. Which assertion prints the response body when it fails?
  5. What is the difference between PATCH and PUT in the lesson’s output?
  6. How do you send a header with every request of a client?
  7. Why is the test-data fixture written with yield?
  8. Which status code means the request was understood but the data failed validation?
  9. What does fail_on_status_code=True change?
  10. How do page.request and playwright.request.new_context() differ?

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


❓ Frequently Asked Questions

🤔 Should I use Playwright or the requests library for API tests?

For API tests that live next to Playwright UI tests, APIRequestContext is the better fit: one dependency, shared cookies with the browser, Playwright assertions and traces. For a pure API project with no UI, requests or httpx are equally good choices.

🤔 Can I validate responses against a JSON Schema?

Yes. Install jsonschema and call jsonschema.validate(instance=response.json(), schema=schema). The practice API serves its schemas at schema/user, schema/product and so on, so you can fetch the schema in a fixture.

🤔 How do I upload a file through the API?

Use multipart={"file": {"name": "report.csv", "mimeType": "text/csv", "buffer": path.read_bytes()}, "note": "nightly"}. Playwright builds the multipart body for you.

🤔 Do API tests appear in pytest-html and Allure reports?

Yes, they are ordinary pytest tests. Lessons 63 and 64 show how to attach request and response details to reports.

🤔 Does APIRequestContext follow redirects?

Yes, up to 20 by default. Set max_redirects=0 to inspect the redirect response itself, as the lesson does.


🏁 Summary

  • playwright.request.new_context(base_url=..., extra_http_headers=...) creates an API client; dispose of it at the end.
  • End the base URL with / and write paths without a leading slash.
  • Use get/post/put/patch/delete with params, data, headers; check status, json() and headers, or expect(response).to_be_ok().
  • Create test data in yield fixtures and clean up; log in once for Bearer tokens; use http_credentials for Basic auth.
  • Test negative cases (401, 403, 404, 422) as carefully as the happy path.

🎬 Watch the Playwright tutorial series on YouTube!

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

Record and Replay Network Traffic with HAR in Playwright Python

Hand-written mocks drift away from what the real server sends. A HAR file (HTTP Archive) fixes that: Playwright records the real requests and responses once, saves them to a file, and later serves them back to the page, so tests run with realistic data, no network and no surprises. In this lesson you will record API traffic to a HAR file, replay it with page.route_from_har(), prove the replay works without the server, control what happens to unrecorded requests, edit recorded data to create edge cases, and add a --update-har option to refresh recordings.

📖 What You’ll Learn: what a HAR file is, recording with record_har_path and record_har_url_filter, recording with route_from_har(update=True), update_content and update_mode, replaying with route_from_har, not_found=”abort” vs “fallback”, how requests are matched, proving a test runs offline, editing HAR responses, a pytest –update-har option, keeping HAR files small and safe, and when HAR is the right tool.


📼 What Is a HAR File?

A HAR (HTTP Archive) file is a JSON document that lists HTTP requests and their responses: URL, method, headers, body, status and timing. Browsers’ DevTools can export one (“Save all as HAR”), and Playwright can both write and read them.

In tests, HAR files give you recorded mocks:

  1. Record once against the real server.
  2. Replay in every test run: Playwright answers matching requests from the file.
  3. Refresh the recording when the API changes.

This lesson uses the mini catalog page from the previous lesson, which loads products from the SQA Tools practice API.

📄 tests/conftest.py

from pathlib import Path

import pytest
from playwright.sync_api import Page

HERE = Path(__file__).parent
CATALOG_URL = "https://sqatools.in/pw-demo/catalog"
API = "**/wp-json/sqa-api/v1/**"


@pytest.fixture
def open_catalog(page: Page):
    page.route(CATALOG_URL, lambda route: route.fulfill(path=HERE / "catalog.html"))

    def _open():
        page.goto(CATALOG_URL)
        return page

    return _open

🎙️ Recording, Option 1: record_har_path

The simplest way to record is a context option. Everything the context requests (filtered by URL) is written to the file when the context closes:

📄 record_context.py

from pathlib import Path

from playwright.sync_api import expect, sync_playwright

CATALOG_URL = "https://sqatools.in/pw-demo/catalog"

with sync_playwright() as p:
    browser = p.chromium.launch()
    context = browser.new_context(record_har_path="hars/catalog_full.har", record_har_url_filter="**/sqa-api/**")
    page = context.new_page()
    page.route(CATALOG_URL, lambda route: route.fulfill(path=Path("tests/catalog.html")))
    page.goto(CATALOG_URL)
    expect(page.get_by_test_id("product")).to_have_count(5)
    context.close()                          # the HAR file is written here
    browser.close()

import json

har = json.load(open("hars/catalog_full.har", encoding="utf-8"))
for entry in har["log"]["entries"]:
    print(entry["request"]["method"], entry["request"]["url"], "->", entry["response"]["status"])

⌨️ Terminal

python record_context.py

🖥️ Output

GET https://sqatools.in/wp-json/sqa-api/v1/products?per_page=5 -> 200

record_har_url_filter keeps the file small and free of unrelated traffic (fonts, analytics). Without it, every request of the page would be recorded.

⚠️ Watch out: Forgetting context.close() is the most common reason for an empty or missing HAR file: Playwright writes the archive only when the context is closed.


🎙️ Recording, Option 2: route_from_har(update=True)

The method you will use in tests is route_from_har(). With update=True it records instead of replaying, so the same line of code serves both purposes:

📄 tests/test_record.py

from playwright.sync_api import Page, expect

from tests.conftest import API, HERE


def test_record_catalog(page: Page, open_catalog):
    page.route_from_har(HERE / "hars" / "catalog.har", url=API, update=True, update_content="embed")
    page = open_catalog()
    expect(page.get_by_test_id("product")).to_have_count(5)

⌨️ Terminal

pytest tests/test_record.py -q

🖥️ Output

.                                                                        [100%]
1 passed in 3.18s

📄 show_har.py

import json

har = json.load(open("tests/hars/catalog.har", encoding="utf-8"))
entry = har["log"]["entries"][0]
print("entries:", len(har["log"]["entries"]))
print("url:    ", entry["request"]["url"])
print("status: ", entry["response"]["status"], entry["response"]["content"]["mimeType"])
print("body:   ", entry["response"]["content"]["text"][:120], "...")

⌨️ Terminal

python show_har.py

🖥️ Output

entries: 1
url:     https://sqatools.in/wp-json/sqa-api/v1/products?per_page=5
status:  200 application/json; charset=UTF-8
body:    {"data":[{"id":101,"name":"Wireless Mouse","category":"electronics","price":799,"currency":"INR","in_stock":true,"rating ...

Two options shape the file:

Option Values Meaning
update_content "embed" / "attach" Put response bodies inside the HAR (one readable file) or in separate files next to it (smaller HAR, binary-friendly)
update_mode "minimal" (default) / "full" Record only what replay needs, or everything including timings and cookies

Use embed for small JSON APIs (easy to read and edit in code review) and attach when responses are large or binary.


▶️ Replaying

Without update=True, route_from_har() serves matching requests from the file. The server is never contacted:

📄 tests/test_replay.py

from playwright.sync_api import Page, expect

from tests.conftest import API, HERE


def test_replay_catalog(page: Page, open_catalog):
    page.route_from_har(HERE / "hars" / "catalog.har", url=API)
    page = open_catalog()
    expect(page.get_by_test_id("product")).to_have_count(5)
    expect(page.get_by_test_id("status")).to_have_text("12 products")


def test_replay_works_without_the_api(page: Page, open_catalog):
    page.route("**/sqa-api/**", lambda route: route.abort())     # "server down" for anything not in the HAR
    page.route_from_har(HERE / "hars" / "catalog.har", url=API)  # registered last, so it is asked first
    page = open_catalog()
    expect(page.get_by_test_id("product").first).to_have_text("Wireless Mouse — ₹799")

⌨️ Terminal

pytest tests/test_replay.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
rootdir: C:\Users\you\playwright-python
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_replay.py::test_replay_catalog[chromium] PASSED               [ 50%]
tests/test_replay.py::test_replay_works_without_the_api[chromium] PASSED [100%]

============================== 2 passed in 2.27s ==============================

The second test proves the point: the real API is blocked, and the page still shows the products, because the HAR answered first (the most recently registered route runs first, as you saw in the previous lesson).


❔ Requests That Are Not in the HAR

What happens when the page requests something the recording does not contain? The not_found option decides:

not_found Unmatched request
"abort" (default) Fails, like a network error
"fallback" Passes to the next route handler, or to the real network

📄 tests/test_not_found.py

from playwright.sync_api import Page, expect

from tests.conftest import HERE

CATALOG_URL = "https://sqatools.in/pw-demo/catalog"


def other_page(page: Page, per_page: int):
    html = (HERE / "catalog.html").read_text(encoding="utf-8").replace("per_page=5", f"per_page={per_page}")
    page.route(CATALOG_URL, lambda route: route.fulfill(body=html, content_type="text/html"))
    page.goto(CATALOG_URL)


def test_unrecorded_request_is_aborted(page: Page):
    page.route_from_har(HERE / "hars" / "catalog.har", url="**/sqa-api/**")             # not_found="abort"
    other_page(page, per_page=3)                                                          # a URL the HAR never saw
    expect(page.get_by_test_id("status")).to_contain_text("Could not load products")


def test_unrecorded_request_falls_back_to_network(page: Page):
    page.route_from_har(HERE / "hars" / "catalog.har", url="**/sqa-api/**", not_found="fallback")
    other_page(page, per_page=3)
    expect(page.get_by_test_id("product")).to_have_count(3)                               # real API answered

⌨️ Terminal

pytest tests/test_not_found.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
rootdir: C:\Users\you\playwright-python
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_not_found.py::test_unrecorded_request_is_aborted[chromium] PASSED [ 50%]
tests/test_not_found.py::test_unrecorded_request_falls_back_to_network[chromium] PASSED [100%]

============================== 2 passed in 4.52s ==============================

Matching is done on the URL including the query string and the HTTP method (and, for POST requests, the body). per_page=3 is a different URL from per_page=5, so it is not in the archive. Use "abort" in CI so a missing recording fails loudly; use "fallback" when only some calls are recorded on purpose.


✏️ Edit Recorded Data for Edge Cases

A HAR file is just JSON, so you can derive edge cases from real data: copy the file, change a value, replay the copy. This keeps the overall shape of the response real while you control one detail:

📄 tests/test_edited_har.py

import json

from playwright.sync_api import Page, expect

from tests.conftest import API, HERE


def make_out_of_stock_har(tmp_path):
    har = json.loads((HERE / "hars" / "catalog.har").read_text(encoding="utf-8"))
    content = har["log"]["entries"][0]["response"]["content"]
    body = json.loads(content["text"])
    for product in body["data"]:
        product["in_stock"] = False
    content["text"] = json.dumps(body)
    path = tmp_path / "all_out_of_stock.har"
    path.write_text(json.dumps(har), encoding="utf-8")
    return path


def test_everything_out_of_stock(page: Page, open_catalog, tmp_path):
    page.route_from_har(make_out_of_stock_har(tmp_path), url=API)
    page = open_catalog()
    expect(page.get_by_test_id("product")).to_have_count(5)
    for item in page.get_by_test_id("product").all():
        expect(item).to_contain_text("(out of stock)")

⌨️ Terminal

pytest tests/test_edited_har.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
rootdir: C:\Users\you\playwright-python
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_edited_har.py::test_everything_out_of_stock[chromium] PASSED  [100%]

============================== 1 passed in 1.64s ==============================

tmp_path is a built-in pytest fixture that gives each test its own temporary folder, so edited copies never overwrite the original recording.


🔄 Refresh Recordings with –update-har

APIs change, and stale recordings hide real breakages. Make refreshing a one-flag operation:

import pytest


def pytest_addoption(parser):
    parser.addoption("--update-har", action="store_true", help="re-record HAR files from the real servers")


@pytest.fixture
def har_mode(request) -> dict:
    """Pass to route_from_har(**har_mode): records with --update-har, replays otherwise."""
    if request.config.getoption("--update-har"):
        return {"update": True, "update_content": "embed"}
    return {"not_found": "abort"}

A test then calls page.route_from_har(path, url=API, **har_mode). Normal runs replay; pytest --update-har re-records every HAR the tests use. Review the diff in Git before committing new recordings, exactly as you would review code.

📌 Note: pytest_addoption only works in a root conftest.py (or a plugin). In a real project move the two functions above into your top-level conftest.py.


🧹 Keep HAR Files Small and Safe

  • Filter: always record with a URL filter (record_har_url_filter or url= in route_from_har).
  • Minimal mode: the default update_mode="minimal" drops timings and other data replay does not need.
  • Secrets: a HAR contains headers and bodies, which may include cookies, tokens and personal data. Record with test accounts, search the file for Authorization and Cookie before committing, and never record production user data.
  • One HAR per feature (catalog, checkout, profile) keeps diffs readable.

⚖️ HAR vs Hand-Written Mocks vs Real API

Real API HAR replay Hand-written route.fulfill
Realistic data Yes Yes (as of recording) Only if you copy it
Works offline / deterministic No Yes Yes
Effort to create None One recording run Write each response
Edge cases (errors, empty) Hard Edit the file Easy
Detects API changes Yes Only when re-recorded No

A practical mix: HAR replay for pages that need lots of realistic data, route.fulfill for small edge cases, and a smaller set of tests (plus API tests in Module 9) against the real API.


🏋️ 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: Record all requests to **/sqa-api/** made while opening the catalog into hars/catalog.har using a context option, and make sure the file is actually written.

Show answer
context = browser.new_context(record_har_path="hars/catalog.har", record_har_url_filter="**/sqa-api/**")
page = context.new_page()
# ... open the page and wait for the data ...
context.close()   # writes the HAR

Exercise 2: Your replay test fails with “Could not load products” after a developer changed the page to request per_page=10. Why, and what are two ways to fix it?

Show answer

HAR matching includes the query string, so per_page=10 is not in the recording and the default not_found="abort" fails it. Fix: (1) re-record the HAR (pytest --update-har) so it contains the new URL, or (2) temporarily use not_found="fallback" to let unrecorded requests reach the real API. Re-recording is the right long-term fix.

Exercise 3: Write a helper har_with_status(path, status, tmp_path) that copies a HAR and sets the first entry’s response status, so you can test a 503 page from a real recording.

Show answer
import json


def har_with_status(path, status, tmp_path):
    har = json.loads(path.read_text(encoding="utf-8"))
    har["log"]["entries"][0]["response"]["status"] = status
    copy = tmp_path / f"status_{status}.har"
    copy.write_text(json.dumps(har), encoding="utf-8")
    return copy

Then page.route_from_har(har_with_status(HERE / "hars" / "catalog.har", 503, tmp_path), url=API) and expect “HTTP 503”.

Exercise 4: Which two things should you check in a HAR file before committing it?

Show answer

(1) That it contains only the traffic you need (URL filter applied, no analytics or unrelated hosts), and (2) that it contains no secrets or personal data: search for Authorization, Cookie, Set-Cookie, tokens and real emails, and re-record with test accounts if you find any.


🧠 MCQ Quiz: Record and Replay Network Traffic with HAR

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 a HAR file?
  2. When does a context created with record_har_path write the file?
  3. What does page.route_from_har(path, update=True) do?
  4. With the default settings, what happens to a request that is not in the HAR?
  5. Which request detail is part of HAR matching?
  6. What does update_content="attach" do?
  7. Why is record_har_url_filter (or url=) important when recording?
  8. In the lesson, how was replay proven to work without the API?
  9. What is the risk of committing HAR files without checking them?
  10. When should you re-record HAR files?

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


❓ Frequently Asked Questions

🤔 Can I replay a HAR exported from Chrome DevTools?

Yes. route_from_har() reads standard HAR files. DevTools exports can be large and contain unrelated traffic, so filter with url= when replaying and remove sensitive headers first.

🤔 Does HAR replay work for the page HTML itself?

Yes, if the document requests are in the HAR and match the url pattern. Most teams replay only API calls and let the real page load, which keeps the front end under test real.

🤔 Can I record with the Playwright CLI?

Yes: playwright open --save-har=example.har --save-har-glob="**/api/**" https://example.com opens a browser, and the HAR is saved when you close it.

🤔 Does route_from_har work at context level?

Yes, context.route_from_har(...) applies the recording to every page in the context, including pop-ups.

🤔 How is HAR different from Playwright’s trace?

A trace (Lesson 62) records actions, DOM snapshots, console and network for debugging after the fact. A HAR stores network traffic in a standard format that can be replayed. You can open a trace’s network tab, but you replay HARs.


🏁 Summary

  • A HAR file records real requests and responses; Playwright can write and replay it.
  • Record with record_har_path (written on context.close()) or route_from_har(..., update=True).
  • Replay with route_from_har(path, url=...); matching uses method, full URL and body; not_found chooses abort or fallback.
  • Edit copies of recordings to create realistic edge cases; refresh recordings with an --update-har option and review the diff.
  • Filter recordings, keep them per feature, and check them for secrets before committing.

🎬 Watch the Playwright tutorial series on YouTube!

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

Network Interception and API Mocking in Playwright Python (page.route)

Your front end talks to APIs, and many UI bugs only appear when those APIs answer with an empty list, an error, a slow response or nothing at all. Waiting for a real server to misbehave is not a test strategy. Playwright lets a test sit between the page and the network and decide what every request gets back. In this lesson you will intercept requests with page.route(), replace real API data with your own JSON, simulate server errors, network failures and slow responses, change a real response, check what the page sends, wait for specific responses, and block analytics and ads to make tests faster.

📖 What You’ll Learn: how routing works, page.route and context.route, URL patterns (glob, regex, predicate), route.fulfill with json, status, headers, body and path, route.abort for network failures, holding a route to test loading states, route.fetch to modify real responses, route.continue_ with changed headers, route.fallback, expect_request and expect_response, request.post_data_json, blocking third-party traffic, times and unroute, and what mocking should not replace.


🧭 How Routing Works

Every request the page makes (documents, scripts, images, fetch and XHR calls) passes through Playwright before it reaches the network. When you register a route for a URL pattern, Playwright pauses matching requests and calls your handler, which must do exactly one of these:

Handler call Effect
route.fulfill(...) Answer the request yourself: the server is never contacted
route.abort() Fail the request, as if the network were down
route.continue_(...) Send it to the server (optionally with changed URL, method, headers or body)
route.fetch() + route.fulfill(response=...) Get the real response, change it, then answer
route.fallback() Let the next matching route handler decide

page.route() applies to one page; context.route() applies to every page in the context, including pop-ups.


🛠️ The Demo Page

The lessons need a page whose data comes from an API. The SQA Tools practice REST API has a /products endpoint:

⌨️ Terminal

curl "https://sqatools.in/wp-json/sqa-api/v1/products?per_page=2"

This small HTML page lists products from that API and has a newsletter form that posts to the API’s /echo endpoint:

📄 tests/catalog.html

<!doctype html>
<html>
<head><meta charset="utf-8"><title>Mini catalog</title></head>
<body>
  <h1>Mini catalog</h1>
  <p id="status" data-testid="status"></p>
  <ul id="list" data-testid="list"></ul>
  <button id="reload">Reload</button>
  <form id="subscribe">
    <input id="email" type="email" aria-label="Email" value="tester@example.com">
    <button>Subscribe</button>
  </form>
  <p id="msg" data-testid="msg"></p>
  <script>
    const status = document.getElementById('status'), list = document.getElementById('list');
    async function load() {
      status.textContent = 'Loading…';
      list.innerHTML = '';
      try {
        const r = await fetch('/wp-json/sqa-api/v1/products?per_page=5');
        if (!r.ok) throw new Error('HTTP ' + r.status);
        const body = await r.json();
        list.innerHTML = body.data.map(p =>
          `<li data-testid="product">${p.name} — ₹${p.price}${p.in_stock ? '' : ' (out of stock)'}</li>`).join('');
        status.textContent = body.meta.total + ' products';
      } catch (e) {
        status.textContent = 'Could not load products: ' + e.message;
      }
    }
    document.getElementById('reload').onclick = load;
    document.getElementById('subscribe').onsubmit = async (e) => {
      e.preventDefault();
      const email = document.getElementById('email').value;
      const r = await fetch('/wp-json/sqa-api/v1/echo', {method: 'POST', headers: {'Content-Type': 'application/json'},
                                                         body: JSON.stringify({email, source: 'catalog'})});
      document.getElementById('msg').textContent = r.ok ? 'Subscribed ' + email : 'Subscription failed';
    };
    load();
  </script>
</body>
</html>

The page is served by Playwright itself: a route answers https://sqatools.in/pw-demo/catalog with this file, so the page runs on the sqatools.in origin and its fetch() calls go to the real practice API. Serving a test page through route.fulfill(path=...) is itself a useful technique for testing widgets in isolation.

📄 tests/conftest.py

from pathlib import Path

import pytest
from playwright.sync_api import Page

CATALOG_URL = "https://sqatools.in/pw-demo/catalog"
API = "**/wp-json/sqa-api/v1/products*"


@pytest.fixture
def open_catalog(page: Page):
    """Serve the demo page from a file; API calls still go to the real practice API unless a test mocks them."""
    page.route(CATALOG_URL, lambda route: route.fulfill(path=Path(__file__).parent / "catalog.html"))

    def _open():
        page.goto(CATALOG_URL)
        return page

    return _open

The baseline test runs against real data:

📄 tests/test_real_api.py

from playwright.sync_api import expect


def test_catalog_with_real_api(open_catalog):
    page = open_catalog()
    expect(page.get_by_test_id("product")).to_have_count(5)
    expect(page.get_by_test_id("status")).to_have_text("12 products")

⌨️ Terminal

pytest tests/test_real_api.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
rootdir: C:\Users\you\playwright-python
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_real_api.py::test_catalog_with_real_api[chromium] PASSED      [100%]

============================== 1 passed in 3.24s ==============================

🎭 Mock a Response with route.fulfill

Real data changes, and it rarely contains the cases you need, such as an out-of-stock item. Replace the response with your own JSON. Register the route before the page makes the request, so before goto():

📄 tests/test_mock_data.py

from playwright.sync_api import Page, expect

from tests.conftest import API

TWO_PRODUCTS = {
    "data": [
        {"id": 1, "name": "Test Laptop", "price": 50000, "in_stock": True},
        {"id": 2, "name": "Test Phone", "price": 20000, "in_stock": False},
    ],
    "meta": {"total": 2},
}


def test_mocked_products(page: Page, open_catalog):
    page.route(API, lambda route: route.fulfill(json=TWO_PRODUCTS))
    open_catalog()
    expect(page.get_by_test_id("product")).to_have_text(["Test Laptop — ₹50000", "Test Phone — ₹20000 (out of stock)"])
    expect(page.get_by_test_id("status")).to_have_text("2 products")


def test_empty_catalog(page: Page, open_catalog):
    page.route(API, lambda route: route.fulfill(json={"data": [], "meta": {"total": 0}}))
    open_catalog()
    expect(page.get_by_test_id("product")).to_have_count(0)
    expect(page.get_by_test_id("status")).to_have_text("0 products")

⌨️ Terminal

pytest tests/test_mock_data.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
rootdir: C:\Users\you\playwright-python
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_mock_data.py::test_mocked_products[chromium] PASSED           [ 50%]
tests/test_mock_data.py::test_empty_catalog[chromium] PASSED             [100%]

============================== 2 passed in 2.06s ==============================

route.fulfill(json=...) serialises the dictionary, sets Content-Type: application/json and status 200. Other useful arguments: status, headers, body (a string or bytes) and path (a file, as the conftest does).

The empty-list test found a small UX issue: the page shows “0 products” with no friendly message. Mocking makes such edge cases cheap to see.


💥 Errors, Network Failures and Slow APIs

📄 tests/test_failures.py

from playwright.sync_api import Page, expect

from tests.conftest import API


def test_server_error(page: Page, open_catalog):
    page.route(API, lambda route: route.fulfill(status=500, json={"error": "database down"}))
    open_catalog()
    expect(page.get_by_test_id("status")).to_have_text("Could not load products: HTTP 500")


def test_network_failure(page: Page, open_catalog):
    page.route(API, lambda route: route.abort())          # like a dropped connection
    open_catalog()
    expect(page.get_by_test_id("status")).to_contain_text("Could not load products")


def test_loading_state_then_data(page: Page, open_catalog):
    held = []
    page.route(API, lambda route: held.append(route))      # hold the request: no answer yet
    open_catalog()
    expect(page.get_by_test_id("status")).to_have_text("Loading…")

    held[0].continue_()                                     # now let it reach the real API
    expect(page.get_by_test_id("product")).to_have_count(5)

⌨️ Terminal

pytest tests/test_failures.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
rootdir: C:\Users\you\playwright-python
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 3 items

tests/test_failures.py::test_server_error[chromium] PASSED               [ 33%]
tests/test_failures.py::test_network_failure[chromium] PASSED            [ 66%]
tests/test_failures.py::test_loading_state_then_data[chromium] PASSED    [100%]

============================== 3 passed in 3.25s ==============================

The last test shows a powerful pattern: a handler that stores the route instead of answering keeps the request pending for as long as you like. You can assert the loading state at leisure, then release it with continue_() or fulfill(). This is deterministic, unlike adding real delays.

💡 Tip: route.abort() accepts an error code such as "failed" (default), "timedout", "connectionrefused" or "internetdisconnected", so you can simulate the exact failure your error handling distinguishes.


✏️ Modify a Real Response with route.fetch

Sometimes you want real data with one change, for example a price that triggers a formatting bug. route.fetch() performs the real request and returns the response; you edit its JSON and fulfil with it:

📄 tests/test_modify.py

from playwright.sync_api import Page, expect

from tests.conftest import API


def test_first_product_price_changed(page: Page, open_catalog):
    def handler(route):
        response = route.fetch()                   # the real API response
        body = response.json()
        body["data"][0]["price"] = 1234567
        route.fulfill(response=response, json=body)  # keep status and headers, replace the body

    page.route(API, handler)
    open_catalog()
    expect(page.get_by_test_id("product").first).to_have_text("Wireless Mouse — ₹1234567")

⌨️ Terminal

pytest tests/test_modify.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
rootdir: C:\Users\you\playwright-python
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_modify.py::test_first_product_price_changed[chromium] PASSED  [100%]

============================== 1 passed in 2.57s ==============================

The output exposes a real presentation issue: large prices are printed without digit grouping (₹1234567 rather than ₹12,34,567). That is exactly the kind of bug this technique is for.

route.continue_() can also change the request before it goes out, for example to add a header or point at another environment:

page.route("**/api/**", lambda route: route.continue_(headers={**route.request.headers, "X-Test-Run": "nightly"}))

🔎 Check What the Page Sends

Mocking responses is half of it; often you must verify the request: the right URL, method and body. page.expect_request() waits for a matching request while you trigger it:

📄 tests/test_requests.py

from playwright.sync_api import Page, expect


def test_subscribe_sends_email(page: Page, open_catalog):
    open_catalog()
    with page.expect_request("**/sqa-api/v1/echo") as request_info:
        page.get_by_role("button", name="Subscribe").click()
    request = request_info.value
    assert request.method == "POST"
    assert request.post_data_json == {"email": "tester@example.com", "source": "catalog"}
    expect(page.get_by_test_id("msg")).to_have_text("Subscribed tester@example.com")


def test_reload_calls_api_again(page: Page, open_catalog):
    open_catalog()
    expect(page.get_by_test_id("product")).to_have_count(5)
    with page.expect_response(lambda r: "/products" in r.url and r.status == 200) as response_info:
        page.get_by_role("button", name="Reload").click()
    body = response_info.value.json()
    assert body["meta"]["per_page"] == 5

⌨️ Terminal

pytest tests/test_requests.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
rootdir: C:\Users\you\playwright-python
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_requests.py::test_subscribe_sends_email[chromium] PASSED      [ 50%]
tests/test_requests.py::test_reload_calls_api_again[chromium] PASSED     [100%]

============================== 2 passed in 4.90s ==============================
  • expect_request / expect_response take a glob, a regex or a predicate function.
  • The with block starts listening before the click, so a fast response is never missed.
  • request.post_data_json parses the JSON body; response.json() parses the response.

For a log of everything, listen to events instead: page.on("request", ...), page.on("response", ...) and page.on("requestfailed", ...).


🚫 Block Ads, Analytics and Heavy Files

Third-party scripts (analytics, ads, chat widgets) slow tests down and make them flaky, and they are not what you are testing. Block them for the whole context:

📄 tests/test_block.py

import re

from playwright.sync_api import BrowserContext, Page, expect

THIRD_PARTY = re.compile(r"googlesyndication|google-analytics|googletagmanager|doubleclick|adtrafficquality")


def test_practice_page_without_third_parties(context: BrowserContext, page: Page):
    blocked = []

    def handler(route):
        blocked.append(route.request.url.split("/")[2])
        route.abort()

    context.route(THIRD_PARTY, handler)
    context.route("**/*.{png,jpg,jpeg,webp,gif}", lambda route: route.abort())   # skip images too
    page.goto("https://sqatools.in/automation-practice-page/")
    expect(page.locator("#username")).to_be_visible()
    print("\nblocked hosts:", sorted(set(blocked)))

⌨️ Terminal

pytest tests/test_block.py -q -s

🖥️ Output

blocked hosts: ['pagead2.googlesyndication.com', 'sqatools.in', 'www.googletagmanager.com']
.
1 passed in 1.98s

The sqatools.in entry is not a mistake: it is the site’s own copy of an analytics plugin script (.../google-analytics-for-wordpress/.../frontend-gtag.min.js), matched because the regex checks the whole URL, not only the host. That is usually what you want, but check the list once so you do not block something your test needs.

Blocking by host or URL with a regular expression and by file extension with a glob are the two most common patterns. Do not block resources your test checks, of course.


🧩 Patterns, Order, times and unroute

  • Glob: "**/api/products*" (* matches within a path segment, ** across segments, {a,b} alternatives).
  • Regex: re.compile(r"/api/products\?.*page=2") for query strings and alternatives.
  • Predicate: lambda url: "products" in url for anything else.
  • Order: when several routes match, the last registered handler runs first; it can pass the request on with route.fallback().
  • times: page.route(API, handler, times=1) handles only the first matching request, perfect for “fail once, then succeed” retry tests.
  • Removing: page.unroute(API) removes the handler; page.unroute_all() removes all.

📄 tests/test_times.py

from playwright.sync_api import Page, expect

from tests.conftest import API


def test_retry_after_one_failure(page: Page, open_catalog):
    page.route(API, lambda route: route.fulfill(status=503), times=1)   # only the first call fails
    open_catalog()
    expect(page.get_by_test_id("status")).to_have_text("Could not load products: HTTP 503")
    page.get_by_role("button", name="Reload").click()                    # second call reaches the real API
    expect(page.get_by_test_id("product")).to_have_count(5)

⌨️ Terminal

pytest tests/test_times.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
rootdir: C:\Users\you\playwright-python
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_times.py::test_retry_after_one_failure[chromium] PASSED       [100%]

============================== 1 passed in 6.57s ==============================

⚖️ When to Mock (and When Not To)

Mock it Do not mock it
Edge cases that are hard to create: empty lists, errors, timeouts The main happy path in your end-to-end smoke tests
Third-party services you do not control (payments, maps, ads) The API contract itself: test it with API tests (Module 9)
Slow or rate-limited dependencies in UI tests Behaviour that depends on real server logic you need to verify

A healthy suite has both: fast UI tests with mocked edge cases and a smaller set of end-to-end tests against real services. Keep mock data realistic (copy a real response and edit it), or your tests will pass against data the server never sends. The next lesson automates that copying with HAR files.


🏋️ 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 test that mocks the products API so it returns one product with a 300-character name, and checks the list shows exactly one item.

Show answer
def test_very_long_name(page, open_catalog):
    long_name = "Super " * 50
    page.route(API, lambda route: route.fulfill(json={"data": [{"id": 9, "name": long_name, "price": 1, "in_stock": True}], "meta": {"total": 1}}))
    open_catalog()
    expect(page.get_by_test_id("product")).to_have_count(1)

Follow it with a screenshot or a layout assertion to see whether the long name breaks the design.

Exercise 2: Write a route handler that adds an Authorization: Bearer test-token header to every request to **/sqa-api/** and lets it continue to the server.

Show answer
def add_token(route):
    route.continue_(headers={**route.request.headers, "Authorization": "Bearer test-token"})

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

Copy the original headers with {**route.request.headers, ...}; passing only the new header would drop the others.

Exercise 3: Test that the catalog shows the timeout error text when the products request times out. Use the right abort error code.

Show answer
def test_timeout(page, open_catalog):
    page.route(API, lambda route: route.abort("timedout"))
    open_catalog()
    expect(page.get_by_test_id("status")).to_contain_text("Could not load products")

The browser reports a network error to fetch, which rejects, so the page shows its error branch.

Exercise 4: Collect the URLs of every failed request during a test and print them at the end. Which event do you use?

Show answer
def test_log_failures(page):
    failed = []
    page.on("requestfailed", lambda request: failed.append(f"{request.url} {request.failure}"))
    page.goto("https://sqatools.in/automation-practice-page/")
    print("\n".join(failed))

requestfailed fires for aborted or network-failed requests; request.failure holds the error text. HTTP errors such as 404 are responses, so check those with page.on("response", ...) and response.status.


🧠 MCQ Quiz: Network Interception and API Mocking

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 route.fulfill(json={...}) do?
  2. When must you register a route that mocks the first API call of a page?
  3. How do you simulate a dropped network connection?
  4. What does a handler that only stores the route (and does not answer it) achieve?
  5. How do you change one field of a real API response?
  6. Which method verifies the body the page sent in a POST?
  7. Why is page.expect_response(...) used as a with block around the click?
  8. Several routes match the same URL. Which handler runs first?
  9. What does page.route(pattern, handler, times=1) do?
  10. Which is a good reason NOT to mock an API in a test?

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


❓ Frequently Asked Questions

🤔 Does page.route work for requests from service workers?

Requests made by a service worker are not seen by page.route(). Use context.route() or block service workers with browser_context_args = {..., "service_workers": "block"} when you need to mock them.

🤔 Can I mock WebSockets?

Yes. Playwright has page.route_web_socket(), which lets you intercept a WebSocket and send your own messages. It is a separate API from page.route().

🤔 Why is my route not called?

Usually the pattern does not match (check query strings: a glob such as **/products does not match /products?page=1; use **/products*), the route was registered after the request was made, or the request comes from a service worker.

🤔 Can I use route with the async API?

Yes. In the async API the handler is async def handler(route): await route.fulfill(...) and you await page.route(...). Lesson 69 covers the async API.

🤔 Should mocks live in the test or in fixtures?

Put reusable mocks (for example “catalog with an out-of-stock item”) in fixtures or a small helper module, and keep one-off edge cases in the test that needs them.


🏁 Summary

  • page.route(pattern, handler) intercepts matching requests; register it before the request happens.
  • route.fulfill(json=..., status=..., path=...) mocks responses; route.abort() simulates network failures.
  • Hold a route to test loading states; use route.fetch() to modify real responses and route.continue_() to change requests.
  • expect_request / expect_response verify traffic; context.route() blocks ads, analytics and heavy files for every page.
  • Mock edge cases and third parties, but keep real end-to-end tests and API contract tests.

🎬 Watch the Playwright tutorial series on YouTube!

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

Save and Reuse Login State in Playwright Python (storage_state)

Logging in through the UI before every test is slow and adds a point of failure to tests that are not about login. Playwright can save the browser’s logged-in state to a file once and load it into every new test context in milliseconds. In this lesson you will save and reuse login state with storage_state, see exactly what the file contains, discover the case where it does not work (session storage), build a pytest session fixture that logs in once per run, handle several user roles, refresh stale state, keep it working with pytest-xdist, and keep the file out of Git.

📖 What You’ll Learn: why reusing login saves time, what a storage state contains (cookies, localStorage, optional IndexedDB), context.storage_state(path=…), new_context(storage_state=…), set_storage_state, why sessionStorage logins are not saved and how to handle them, a session-scoped login fixture with browser_context_args, per-role state files, refreshing expired state, xdist-safe files with worker_id and a lock, and keeping auth files secret.


⏱️ Why Reuse Login?

A UI login takes 2 to 5 seconds. In a suite of 300 tests that need a logged-in user, that is 10 to 25 minutes spent typing the same username and password, and every one of those logins can fail for reasons unrelated to the test.

The fix: log in once, save the browser state, and start every test already logged in. Only your dedicated login tests go through the login form.

Approach Logins per run (300 tests) Isolation
UI login in every test 300 Full
Shared page across tests 1 None: tests leak into each other
Saved storage state 1 Full: every test gets a fresh context with the saved state

📦 What Is Storage State?

When a website logs you in, it remembers you in the browser, usually in cookies or localStorage. context.storage_state() takes a snapshot of both as JSON. Let’s log in to the SQA Shop with “Keep me logged in” ticked and save the state:

📄 save_state.py

import json

from playwright.sync_api import expect, sync_playwright

SHOP = "https://sqatools.in/dummy-ecommerce-website/"

with sync_playwright() as p:
    browser = p.chromium.launch()
    context = browser.new_context()
    page = context.new_page()
    page.goto(SHOP + "#/login")
    page.get_by_test_id("login-username").fill("testuser")
    page.get_by_test_id("login-password").fill("Test@123")
    page.get_by_test_id("remember-me").check()                 # store the login in localStorage
    page.get_by_test_id("login-button").click()
    expect(page.get_by_test_id("account-button")).to_contain_text("Hi, Test")

    context.storage_state(path=".auth/shopper.json")           # folders are created automatically
    browser.close()

state = json.load(open(".auth/shopper.json"))
print("cookies:", len(state["cookies"]))
for origin in state["origins"]:
    print(origin["origin"], "->", [(item["name"], item["value"]) for item in origin["localStorage"] if item["name"].startswith("sp")])

⌨️ Terminal

python save_state.py

🖥️ Output

cookies: 6
https://sqatools.in -> [('spUser', '"testuser"')]

The file holds every cookie and, per origin, every localStorage entry. The store remembers the user in localStorage under spUser.

Now load it into a brand-new context:

📄 reuse_state.py

from playwright.sync_api import expect, sync_playwright

SHOP = "https://sqatools.in/dummy-ecommerce-website/"

with sync_playwright() as p:
    browser = p.chromium.launch()
    context = browser.new_context(storage_state=".auth/shopper.json")
    page = context.new_page()
    page.goto(SHOP)
    expect(page.get_by_test_id("account-button")).to_contain_text("Hi, Test")
    print("Logged in without typing a password:", page.get_by_test_id("account-button").inner_text().strip())
    browser.close()

⌨️ Terminal

python reuse_state.py

🖥️ Output

Logged in without typing a password: Hi, Test

No login form, no password, and the store greets the user by name.

📌 Note: storage_state() also accepts indexed_db=True (for apps such as Firebase Authentication that keep tokens in IndexedDB), opfs=True (origin private file system) and credentials=True (virtual passkeys) in recent Playwright versions. Turn them on only if your app stores its login there.


⚠️ The Trap: sessionStorage Is Not Saved

Run the same experiment without ticking “Keep me logged in”:

📄 session_only.py

from playwright.sync_api import expect, sync_playwright

SHOP = "https://sqatools.in/dummy-ecommerce-website/"

with sync_playwright() as p:
    browser = p.chromium.launch()
    context = browser.new_context()
    page = context.new_page()
    page.goto(SHOP + "#/login")
    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()                # remember-me NOT ticked
    expect(page.get_by_test_id("account-button")).to_contain_text("Hi, Test")
    print("sessionStorage spUser:", page.evaluate("sessionStorage.getItem('spUser')"))
    print("localStorage spUser:  ", page.evaluate("localStorage.getItem('spUser')"))
    context.storage_state(path=".auth/session_only.json")

    fresh = browser.new_context(storage_state=".auth/session_only.json").new_page()
    fresh.goto(SHOP)
    print("New context shows:", fresh.get_by_test_id("account-button").inner_text().strip())
    browser.close()

⌨️ Terminal

python session_only.py

🖥️ Output

sessionStorage spUser: "testuser"
localStorage spUser:   None
New context shows: Login

The user was logged in, but the new context shows Login. Without “Keep me logged in”, the store keeps the login in sessionStorage, which lives only as long as the browser tab and is not part of a storage state.

When your application uses sessionStorage, you have two options:

  1. Log in with the option that persists the session (as here), if the product offers one.
  2. Save sessionStorage yourself and restore it with an init script before the page’s own scripts run:

📄 restore_session.py

import json

from playwright.sync_api import expect, sync_playwright

SHOP = "https://sqatools.in/dummy-ecommerce-website/"

with sync_playwright() as p:
    browser = p.chromium.launch()
    page = browser.new_page()
    page.goto(SHOP + "#/login")
    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("account-button")).to_contain_text("Hi, Test")
    saved = page.evaluate("JSON.stringify(sessionStorage)")                      # save

    context = browser.new_context()
    context.add_init_script(f"""
        if (location.hostname === 'sqatools.in') {{
            const data = JSON.parse({json.dumps(saved)});
            for (const [k, v] of Object.entries(data)) sessionStorage.setItem(k, v);
        }}""")                                                                   # restore before page scripts
    page2 = context.new_page()
    page2.goto(SHOP)
    print("Restored session shows:", page2.get_by_test_id("account-button").inner_text().strip())
    browser.close()

⌨️ Terminal

python restore_session.py

🖥️ Output

Restored session shows: Hi, Test

add_init_script runs in every page of the context before the site’s own JavaScript, so the app finds the session as if the user had never left.


🧪 Log In Once per Test Run with pytest

In a pytest suite, create the state in a session-scoped fixture and give it to every context through browser_context_args:

📄 pytest.ini

[pytest]
addopts = --base-url https://sqatools.in
markers =
    anonymous: run the test without the saved login

📄 tests/conftest.py

from pathlib import Path

import pytest
from playwright.sync_api import Browser, expect

AUTH_DIR = Path(__file__).parent.parent / ".auth"
SHOP = "/dummy-ecommerce-website/"


@pytest.fixture(scope="session")
def shopper_state(browser: Browser, base_url) -> Path:
    """Log in through the UI once per run and save the state."""
    path = AUTH_DIR / "shopper.json"
    context = browser.new_context(base_url=base_url)
    page = context.new_page()
    page.goto(SHOP + "#/login")
    page.get_by_test_id("login-username").fill("testuser")
    page.get_by_test_id("login-password").fill("Test@123")
    page.get_by_test_id("remember-me").check()
    page.get_by_test_id("login-button").click()
    expect(page.get_by_test_id("account-button")).to_contain_text("Hi, Test")   # fail setup if login breaks
    context.storage_state(path=path)
    context.close()
    return path


@pytest.fixture
def browser_context_args(browser_context_args, request):
    if request.node.get_closest_marker("anonymous"):
        return browser_context_args
    return {**browser_context_args, "storage_state": request.getfixturevalue("shopper_state")}

📄 tests/test_account.py

import pytest
from playwright.sync_api import Page, expect

SHOP = "/dummy-ecommerce-website/"


def test_greeting(page: Page):
    page.goto(SHOP)
    expect(page.get_by_test_id("account-button")).to_contain_text("Hi, Test")


def test_my_orders_link(page: Page):
    page.goto(SHOP)
    page.get_by_test_id("account-button").click()
    expect(page.get_by_test_id("menu-orders")).to_be_visible()


def test_checkout_uses_saved_account(page: Page):
    page.goto(SHOP + "#/search/earbuds")
    page.get_by_role("button", name="Add to cart").first.click()
    page.goto(SHOP + "#/checkout")
    expect(page.get_by_test_id("logged-in-note")).to_contain_text("Signed in as Test User")


@pytest.mark.anonymous
def test_guest_sees_login(page: Page):
    page.goto(SHOP)
    expect(page.get_by_test_id("account-button")).to_contain_text("Login")

⌨️ Terminal

pytest -v --durations=5

🖥️ 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 4 items

tests/test_account.py::test_greeting[chromium] PASSED                    [ 25%]
tests/test_account.py::test_my_orders_link[chromium] PASSED              [ 50%]
tests/test_account.py::test_checkout_uses_saved_account[chromium] PASSED [ 75%]
tests/test_account.py::test_guest_sees_login[chromium] PASSED            [100%]

============================= slowest 5 durations =============================
2.61s call     tests/test_account.py::test_guest_sees_login[chromium]
2.40s setup    tests/test_account.py::test_greeting[chromium]
1.92s call     tests/test_account.py::test_greeting[chromium]
1.82s call     tests/test_account.py::test_checkout_uses_saved_account[chromium]
1.64s call     tests/test_account.py::test_my_orders_link[chromium]
============================= 4 passed in 11.15s ==============================

How it works:

  • browser_context_args is normally session-scoped in pytest-playwright. Overriding it as a function-scoped fixture lets it look at each test’s markers, and pytest-playwright reads it for every new context.
  • request.getfixturevalue("shopper_state") triggers the login only when a test needs it, and only once per session.
  • The anonymous marker gives tests such as “guest sees Login” a clean context.
  • --durations=5 shows that only the first test paid for the login (its setup time); the other tests have no login in their setup and spend their time on the test itself.

💡 Tip: Each test still gets its own context loaded from the file. Adding items to the cart in one test does not affect the next one, unlike sharing one page.


👥 Several Roles

Most applications have more than one kind of user (customer, admin, support). Save one file per role and choose per test:

📄 tests/roles/conftest.py

from pathlib import Path

import pytest
from playwright.sync_api import Browser, expect

AUTH_DIR = Path(__file__).parent.parent.parent / ".auth"
USERS = {"shopper": ("testuser", "Test@123")}          # add "admin": (...) etc. for your app


@pytest.fixture(scope="session")
def state_for(browser: Browser, base_url):
    cache: dict[str, Path] = {}

    def _state(role: str) -> Path:
        if role not in cache:
            username, password = USERS[role]
            context = browser.new_context(base_url=base_url)
            page = context.new_page()
            page.goto("/dummy-ecommerce-website/#/login")
            page.get_by_test_id("login-username").fill(username)
            page.get_by_test_id("login-password").fill(password)
            page.get_by_test_id("remember-me").check()
            page.get_by_test_id("login-button").click()
            expect(page.get_by_test_id("account-button")).to_contain_text("Hi,")
            path = AUTH_DIR / f"{role}.json"
            context.storage_state(path=path)
            context.close()
            cache[role] = path
        return cache[role]

    return _state


@pytest.fixture
def page_as(browser: Browser, base_url, state_for):
    contexts = []

    def _page(role: str):
        context = browser.new_context(base_url=base_url, storage_state=state_for(role))
        contexts.append(context)
        return context.new_page()

    yield _page
    for context in contexts:
        context.close()

📄 tests/roles/test_roles.py

import pytest
from playwright.sync_api import expect


@pytest.mark.anonymous
def test_shopper_and_guest_side_by_side(page_as, page):
    shopper = page_as("shopper")
    shopper.goto("/dummy-ecommerce-website/")
    expect(shopper.get_by_test_id("account-button")).to_contain_text("Hi, Test")

    page.goto("/dummy-ecommerce-website/")                     # the normal page: a guest (anonymous marker)
    expect(page.get_by_test_id("account-button")).to_contain_text("Login")

⌨️ Terminal

pytest tests/roles -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/roles/test_roles.py::test_shopper_and_guest_side_by_side[chromium] PASSED [100%]

============================== 1 passed in 6.60s ==============================

page_as("admin") and page_as("shopper") in the same test is how you test interactions between users, for example an admin approving a customer’s request.


♻️ Expiry: Refresh Stale State

Saved sessions expire: cookies have dates and servers end sessions. Two practical rules:

  1. Create state at the start of every run (as the session fixture does). A file from yesterday is a source of mysterious failures.
  2. If you reuse files between runs locally to save time, check their age and log in again when they are old:

📄 state_age.py

import time
from pathlib import Path

MAX_AGE_MINUTES = 30


def is_fresh(path: Path) -> bool:
    return path.exists() and (time.time() - path.stat().st_mtime) < MAX_AGE_MINUTES * 60


print("shopper.json fresh:", is_fresh(Path(".auth/shopper.json")))
print("missing.json fresh:", is_fresh(Path(".auth/missing.json")))

⌨️ Terminal

python state_age.py

🖥️ Output

shopper.json fresh: True
missing.json fresh: False

In the session fixture: if is_fresh(path): return path before logging in.


⚡ Parallel Runs with pytest-xdist

With pytest -n 4, each worker is a separate process with its own session fixtures, so each worker logs in once. That is usually fine (4 logins instead of 300). Two things to get right:

  • Different file per worker, so workers never write the same file at the same time. pytest-xdist provides a worker_id fixture (gw0, gw1 …, or master without xdist):
path = AUTH_DIR / f"shopper-{worker_id}.json"
  • If the application allows only one active session per user, a second login logs out the first worker. Give each worker its own account (testuser1, testuser2 … chosen by worker_id), or log in once with a file lock (filelock library) and share the file read-only.

⌨️ Terminal

pytest tests/test_account.py -n 2 -q

🖥️ Output

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

....                                                                     [100%]
4 passed in 8.69s

🔒 Keep Auth Files Secret

A storage state file is a logged-in session: anyone with the file is logged in as that user until the session expires.

📄 .gitignore

.auth/
  • Never commit .auth/ and never upload it as a CI artifact.
  • Use dedicated test accounts with minimal permissions.
  • Do not print the file’s contents in logs.

🏋️ 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 short script that logs in to SQA Shop with “Keep me logged in”, saves the state to .auth/user.json, and prints how many localStorage entries were saved for https://sqatools.in.

Show answer
from playwright.sync_api import expect, sync_playwright

with sync_playwright() as p:
    browser = p.chromium.launch()
    context = browser.new_context()
    page = context.new_page()
    page.goto("https://sqatools.in/dummy-ecommerce-website/#/login")
    page.get_by_test_id("login-username").fill("testuser")
    page.get_by_test_id("login-password").fill("Test@123")
    page.get_by_test_id("remember-me").check()
    page.get_by_test_id("login-button").click()
    expect(page.get_by_test_id("account-button")).to_contain_text("Hi,")
    state = context.storage_state(path=".auth/user.json")
    origin = next(o for o in state["origins"] if o["origin"] == "https://sqatools.in")
    print(len(origin["localStorage"]), "localStorage entries")
    browser.close()

storage_state() both writes the file and returns the same data as a dictionary.

Exercise 2: A teammate saved storage state after logging in, but tests that load it still show the login page. List three possible causes.

Show answer

(1) The app keeps the session in sessionStorage, which storage state does not save (as SQA Shop does without “Keep me logged in”). (2) The session expired or was ended on the server (old file, or another login with the same account logged it out). (3) The state was saved before the login finished, for example right after click() without waiting for a logged-in element. Wait with expect(...) before saving.

Exercise 3: Change the browser_context_args override from the lesson so tests marked @pytest.mark.anonymous and tests in the folder tests/login/ start without saved state.

Show answer
@pytest.fixture
def browser_context_args(browser_context_args, request):
    anonymous = request.node.get_closest_marker("anonymous") or "tests/login/" in request.node.nodeid
    if anonymous:
        return browser_context_args
    return {**browser_context_args, "storage_state": request.getfixturevalue("shopper_state")}

A cleaner alternative is a conftest.py in tests/login/ that applies pytestmark = pytest.mark.anonymous-style behaviour by overriding browser_context_args there.

Exercise 4: Switch an existing context from a guest to the saved shopper without creating a new context.

Show answer
context.set_storage_state(".auth/shopper.json")   # clears cookies/storage, then loads the file
page.reload()

set_storage_state (added in recent Playwright versions) replaces everything in the context with the saved state.


🧠 MCQ Quiz: Save and Reuse Login State (storage_state)

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 context.storage_state() save by default?
  2. Why did the SQA Shop login without “Keep me logged in” not survive in a new context?
  3. How do you start a context with a saved state file?
  4. Why is the login fixture scoped to the session?
  5. What does add_init_script do?
  6. With pytest-xdist and four workers, how many times does the session login fixture run?
  7. Which fixture gives the current xdist worker name such as gw0?
  8. Why must .auth/ be in .gitignore?
  9. What should a login setup fixture do before saving the state?
  10. What does context.set_storage_state(path) do?

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


❓ Frequently Asked Questions

🤔 Is storage_state the same as reusing a browser profile?

No. A profile (launch_persistent_context(user_data_dir=...)) is a whole browser directory with history, cache and settings, and only one browser can use it at a time. A storage state is just cookies and storage, loaded into fresh, isolated contexts, which is what tests need.

🤔 Can I create the state through the API instead of the UI?

Yes, if your application issues session cookies or tokens from an API. Use Playwright’s APIRequestContext to log in, then call request_context.storage_state(path=...), which saves the cookies it received (Module 9).

🤔 Does storage_state work with Firefox and WebKit?

Yes. The file format is the same for all engines, so one file can be used in every browser, as long as the cookies’ domains match the site.

🤔 Should my login tests use the saved state?

No. Tests that check the login page itself (errors, lockout, remember-me) must start anonymous. Mark them, as the lesson does with anonymous.

🤔 What about HTTP Basic authentication?

That is not stored in cookies. Pass http_credentials={"username": ..., "password": ...} in browser_context_args instead.


🏁 Summary

  • context.storage_state(path=...) saves cookies and localStorage; new_context(storage_state=...) starts logged in.
  • sessionStorage is not saved: use a persistent login option or restore it with add_init_script.
  • Log in once in a session fixture, assert the login, and add the file to browser_context_args, with an opt-out marker for anonymous tests.
  • Save one file per role, refresh stale files, and use per-worker files (or accounts) with pytest-xdist.
  • Treat .auth/ files as secrets: never commit or upload them.

🎬 Watch the Playwright tutorial series on YouTube!

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

Mobile Device Emulation in Playwright Python (iPhone, Pixel, iPad)

More than half of web traffic comes from phones, and mobile layouts break in their own ways: menus collapse behind buttons, filters move into drawers, and touch replaces the mouse. Playwright can emulate hundreds of real devices in seconds, without an emulator or a phone. In this lesson you will run tests as an iPhone and a Pixel with one option, look inside a device descriptor, build your own device, use touch with tap(), emulate location, language, time zone and dark mode, and test the SQA Shop’s mobile filter drawer.

📖 What You’ll Learn: what device emulation does and does not cover, the –device option, the playwright.devices registry, viewport, user agent, device scale factor, is_mobile and has_touch, browser_context_args for devices, why iPhones should run in WebKit, tap() and touch, custom devices and landscape, set_viewport_size, geolocation with permissions, locale and timezone_id, dark mode with color_scheme and emulate_media, and the limits of emulation.


📱 What Device Emulation Means

Emulation tells a normal desktop browser engine to behave like a device. Playwright sets, for each new browser context:

Setting What it changes
viewport CSS width and height of the page (responsive layout, media queries)
user_agent The browser identification string servers and scripts read
device_scale_factor Pixel density (retina screens), which affects images and screenshots
is_mobile Mobile behaviour such as the meta viewport tag being honoured
has_touch Touch events and (pointer: coarse) media queries

What emulation does not give you: the real mobile operating system, real device performance, the on-screen keyboard, or browser quirks that exist only in the app shell (for example iOS Safari’s address-bar resizing). For those you need real devices or a device cloud. For layout and behaviour checks, which are most mobile bugs, emulation is fast and reliable.


⚡ The Quickest Way: –device

pytest-playwright has a --device option that applies a full device profile to every test:

📄 pytest.ini

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

📄 tests/test_mobile_layout.py

from playwright.sync_api import Page, expect

SHOP = "/dummy-ecommerce-website/"


def test_filters_live_in_a_drawer_on_phones(page: Page):
    page.goto(SHOP)
    expect(page.get_by_test_id("product-card").first).to_be_visible()

    filters = page.get_by_test_id("filters")
    toggle = page.get_by_role("button", name="Filters", exact=True)
    expect(filters).to_be_hidden()            # collapsed on small screens
    toggle.click()
    expect(filters).to_be_visible()           # opens as a drawer

⌨️ Terminal

pytest --device "Pixel 7" -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_mobile_layout.py::test_filters_live_in_a_drawer_on_phones[chromium] PASSED [100%]

============================== 1 passed in 7.44s ==============================

exact=True matters here: role names match substrings by default, so name="Filters" would also match the “Clear all filters” button whenever the filter panel is visible, and Playwright’s strict mode would refuse to click an ambiguous locator.

Without --device the desktop layout shows the filters in a sidebar and the same test fails at the first assertion, which proves it really tests the mobile layout:

⌨️ Terminal

pytest -q --tb=line

🖥️ Output

F                                                                        [100%]
================================== FAILURES ===================================
E   AssertionError: Locator expected to be hidden
    Actual value: visible 
    Call log:
      - Expect "to_be_hidden" get_by_test_id("filters") with timeout 5000ms
      - waiting for get_by_test_id("filters")
        13 × locator resolved to <aside id="filters" aria-label="Filters" data-testid="filters" class="sp-card sp-filters">…</aside>
           - unexpected value "visible"
    
    Aria snapshot:
    - complementary "Filters":
      - heading "Filters" [level=3]
      - text: Category
      - checkbox "T-shirts 6"
      - text: T-shirts
      - emphasis: "6"
      - checkbox "Shirts 6"
      - text: Shirts
      - emphasis: "6"
      - checkbox "Jeans and trousers 6"
      - text: Jeans and trousers
      - emphasis: "6"
      - checkbox "Dresses and kurtas 6"
      - text: Dresses and kurtas
      - emphasis: "6"
      - checkbox "Jackets and hoodies 6"
      - text: Jackets and hoodies
      - emphasis: "6"
      - checkbox "Footwear 6"
      - text: Footwear
      - emphasis: "6"
      - checkbox "Accessories 6"
      - text: Accessories
      - emphasis: "6"
      - checkbox "Mobiles 6"
      - text: Mobiles
      - emphasis: "6"
      - checkbox "Laptops 6"
      - text: Laptops
      - emphasis: "6"
      - checkbox "Audio 6"
      - text: Audio
      - emphasis: "6"
      - checkbox "Wearables 6"
      - text: Wearables
      - emphasis: "6"
      - checkbox "Chargers and power 6"
      - text: Chargers and power
      - emphasis: "6"
      - checkbox "TV and camera 6"
      - text: TV and camera
      - emphasis: "6"
      - checkbox "Gaming 6"
      - text: Gaming
      - emphasis: "6"
      - checkbox "Online courses 6"
      - text: Online courses
      - emphasis: "6"
      - checkbox "eBooks 6"
      - text: eBooks
      - emphasis: "6"
      - checkbox "Software licences 6"
      - text: Software licences
      - emphasis: "6"
      - checkbox "Music, photos and templates 6"
      - text: Music, photos and templates
      - emphasis: "6"
      - text: Price (₹) Minimum price
      - spinbutton "Minimum price"
      - text: Maximum price
      - spinbutton "Maximum price"
      - button "Apply price"
      - text: Customer rating
      - radio "4★ and above"
      - text: 4★ and above
      - radio "3★ and above"
      - text: 3★ and above
      - radio "Any rating" [checked]
      - text: Any rating Brand
      - checkbox "CodeCraft 3"
      - text: CodeCraft
      - emphasis: "3"
      - checkbox "Cotton Cove 9"
      - text: Cotton Cove
      - emphasis: "9"
      - checkbox "Loomline 11"
      - text: Loomline
      - emphasis: "11"
      - checkbox "Nexa 7"
      - text: Nexa
      - emphasis: "7"
      - checkbox "Northwind Apparel 10"
      - text: Northwind Apparel
      - emphasis: "10"
      - checkbox "PageTurn Books 4"
      - text: PageTurn Books
      - emphasis: "4"
      - checkbox "PixelPeak 6"
      - text: PixelPeak
      - emphasis: "6"
      - checkbox "PixelStock 6"
      - text: PixelStock
      - emphasis: "6"
      - checkbox "SQA Learn 5"
      - text: SQA Learn
      - emphasis: "5"
      - checkbox "Sonique 8"
      - text: Sonique
      - emphasis: "8"
      - checkbox "SoundWave Studio 6"
      - text: SoundWave Studio
      - emphasis: "6"
      - checkbox "Stride 8"
      - text: Stride
      - emphasis: "8"
      - checkbox "Urban Thread 4"
      - text: Urban Thread
      - emphasis: "4"
      - checkbox "Voltix 11"
      - text: Voltix
      - emphasis: "11"
      - checkbox "Zenbyte 10"
      - text: Zenbyte
      - emphasis: "10"
      - checkbox "In stock only"
      - text: In stock only
      - button "Clear all filters"
C:\Users\you\playwright-python\tests\test_mobile_layout.py:12: AssertionError: Locator expected to be hidden
=========================== short test summary info ===========================
FAILED tests/test_mobile_layout.py::test_filters_live_in_a_drawer_on_phones[chromium]
1 failed in 13.04s

🔎 Inside a Device Descriptor

Every name you can pass to --device is a key of playwright.devices, a dictionary of ready-made profiles (207 in Playwright 1.65):

📄 show_device.py

from playwright.sync_api import sync_playwright

with sync_playwright() as p:
    print(len(p.devices), "devices, for example:", [d for d in p.devices if d.startswith("iPhone 15")])
    for key, value in p.devices["iPhone 15"].items():
        print(f"  {key:20} {value}")

⌨️ Terminal

python show_device.py

🖥️ Output

207 devices, for example: ['iPhone 15', 'iPhone 15 landscape', 'iPhone 15 Plus', 'iPhone 15 Plus landscape', 'iPhone 15 Pro', 'iPhone 15 Pro landscape', 'iPhone 15 Pro Max', 'iPhone 15 Pro Max landscape']
  user_agent           Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/27.2 Mobile/15E148 Safari/604.1
  viewport             {'width': 393, 'height': 659}
  device_scale_factor  3
  is_mobile            True
  has_touch            True
  default_browser_type webkit
  screen               {'width': 393, 'height': 852}

Note default_browser_type: webkit: an iPhone profile describes Safari. pytest-playwright’s --device changes the context settings but not the engine, so for iPhones also pass --browser webkit:

⌨️ Terminal

pytest --device "iPhone 15" --browser webkit -q

🖥️ Output

.                                                                        [100%]
1 passed in 9.10s

🧩 Devices in Fixtures: browser_context_args

--device applies one device to the whole run. To choose devices in code, for example to run every test on a phone and a tablet, override browser_context_args. It is a session fixture whose dictionary is passed to browser.new_context():

📄 tests/devices/conftest.py

import pytest

DEVICES = ["Pixel 7", "iPad Mini"]


@pytest.fixture(scope="session", params=DEVICES, ids=lambda d: d.replace(" ", "-").lower())
def browser_context_args(browser_context_args, playwright, request):
    device = {k: v for k, v in playwright.devices[request.param].items() if k != "default_browser_type"}
    return {**browser_context_args, **device}

📄 tests/devices/test_devices.py

from playwright.sync_api import Page


def test_report_device(page: Page):
    page.goto("/dummy-ecommerce-website/")
    info = page.evaluate("({w: innerWidth, dpr: devicePixelRatio, touch: matchMedia('(pointer: coarse)').matches})")
    print(f"\n{page.viewport_size} -> {info}")
    assert info["touch"] is True

⌨️ Terminal

pytest tests/devices -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/devices/test_devices.py::test_report_device[pixel-7-chromium] 
{'width': 412, 'height': 839} -> {'w': 412, 'dpr': 2.625, 'touch': True}
PASSED
tests/devices/test_devices.py::test_report_device[ipad-mini-chromium] 
{'width': 768, 'height': 1024} -> {'w': 768, 'dpr': 2, 'touch': True}
PASSED

============================== 2 passed in 7.90s ==============================

Three things to notice:

  • {**browser_context_args, **device} keeps pytest-playwright’s defaults (such as base_url) and adds the device on top.
  • default_browser_type is removed because it is not a context option; passing it to new_context() raises an error.
  • Because the fixture is parametrized, every test runs once per device and the id shows which one (pixel-7, ipad-mini).

⚠️ Watch out: A browser_context_args override in a conftest.py changes every test in that folder and its sub-folders. That is why this one lives in tests/devices/: device-specific tests get their own folder and conftest.py, and desktop tests stay desktop.


👆 Touch: tap() Instead of click()

With has_touch=True you can send real touch events with tap(). Some mobile menus listen for touchstart and ignore mouse clicks entirely:

📄 tests/mobile/test_touch.py

import re

from playwright.sync_api import Page, expect


def test_tap_opens_filters(page: Page):
    page.goto("/dummy-ecommerce-website/")
    page.get_by_role("button", name="Filters", exact=True).tap()
    expect(page.get_by_test_id("filters")).to_be_visible()
    page.get_by_test_id("filter-sub-audio").tap()                 # tap a checkbox in the drawer
    expect(page.get_by_test_id("result-count")).to_have_text(re.compile(r"^6 products"))

📄 tests/mobile/conftest.py

import pytest


@pytest.fixture(scope="session")
def browser_context_args(browser_context_args, playwright):
    pixel = {k: v for k, v in playwright.devices["Pixel 7"].items() if k != "default_browser_type"}
    return {**browser_context_args, **pixel}

⌨️ Terminal

pytest tests/mobile -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/mobile/test_touch.py::test_tap_opens_filters[chromium] PASSED      [100%]

============================== 1 passed in 9.59s ==============================

tap() fails with “The page does not support tap” if the context was created without has_touch=True, which is a useful reminder that your test is not on a touch device.


📐 Custom Devices, Landscape and Resizing

You are not limited to the registry. A device is just a dictionary, so build one for a phone that is missing or for your company’s standard test size:

📄 custom_device.py

from playwright.sync_api import sync_playwright

BUDGET_ANDROID = {
    "viewport": {"width": 360, "height": 640},
    "device_scale_factor": 2,
    "is_mobile": True,
    "has_touch": True,
    "user_agent": "Mozilla/5.0 (Linux; Android 14; Budget) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0 Mobile Safari/537.36",
}

with sync_playwright() as p:
    browser = p.chromium.launch()
    for name, profile in [("budget-android", BUDGET_ANDROID), ("pixel-7-landscape", p.devices["Pixel 7 landscape"])]:
        profile = {k: v for k, v in profile.items() if k != "default_browser_type"}
        context = browser.new_context(**profile)
        page = context.new_page()
        page.goto("https://sqatools.in/dummy-ecommerce-website/")
        page.get_by_test_id("product-card").first.wait_for()
        print(f"{name:18} viewport={page.viewport_size} filters-button-visible={page.get_by_role("button", name="Filters", exact=True).is_visible()}")
        context.close()

    # resize an existing page, e.g. to test a breakpoint
    page = browser.new_page(viewport={"width": 1280, "height": 720})
    page.goto("https://sqatools.in/dummy-ecommerce-website/")
    page.get_by_test_id("product-card").first.wait_for()
    button, panel = page.get_by_role("button", name="Filters", exact=True), page.get_by_test_id("filters")
    for width in (1280, 1000, 980, 600):
        page.set_viewport_size({"width": width, "height": 720})
        print(f"width {width:4}: Filters button={button.is_visible()!s:5} filter panel={panel.is_visible()}")
    page.reload()
    page.get_by_test_id("product-card").first.wait_for()
    print(f"after reload at 600: Filters button={button.is_visible()!s:5} filter panel={panel.is_visible()}")
    browser.close()

⌨️ Terminal

python custom_device.py

🖥️ Output

budget-android     viewport={'width': 360, 'height': 640} filters-button-visible=True
pixel-7-landscape  viewport={'width': 863, 'height': 360} filters-button-visible=True
width 1280: Filters button=False filter panel=True
width 1000: Filters button=False filter panel=True
width  980: Filters button=True  filter panel=True
width  600: Filters button=True  filter panel=True
after reload at 600: Filters button=True  filter panel=False

Three lessons from the output:

  • In landscape the Pixel 7 is 863 px wide. That is still below the store’s 980 px breakpoint, so the phone layout (and the Filters button) stays. Always check where your own breakpoints are before assuming landscape means desktop.
  • page.set_viewport_size() resizes an open page, which makes breakpoint tests cheap: the Filters button appears exactly at 980 px.
  • After shrinking the window the filter panel is still open: the store decides “collapse the filters” only when the list is rendered (innerWidth <= 980). Only after a reload at 600 px does the panel start collapsed. A user who rotates a tablet sees the same thing. Resizing tests find this class of bug; device profiles that start at the final size never do.

📌 Note: is_mobile and has_touch cannot be changed after a context is created, and is_mobile is not supported in Firefox. To change them, create a new context.


🌍 Location, Language, Time Zone and Dark Mode

Real users are also somewhere, speak a language and may use dark mode. These are context options too:

📄 tests/test_context_emulation.py

import pytest
from playwright.sync_api import Page


@pytest.fixture(scope="session")
def browser_context_args(browser_context_args):
    return {
        **browser_context_args,
        "locale": "hi-IN",
        "timezone_id": "Asia/Kolkata",
        "geolocation": {"latitude": 18.5204, "longitude": 73.8567},   # Pune
        "permissions": ["geolocation"],
        "color_scheme": "dark",
    }


def test_user_environment(page: Page):
    page.goto("/dummy-ecommerce-website/")
    info = page.evaluate("""async () => ({
        language: navigator.language,
        timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,
        dark: matchMedia('(prefers-color-scheme: dark)').matches,
        position: await new Promise(ok => navigator.geolocation.getCurrentPosition(p => ok([p.coords.latitude, p.coords.longitude]))),
        price: (123456.5).toLocaleString(),
    })""")
    print("\n", info)
    assert info["timeZone"] in ("Asia/Kolkata", "Asia/Calcutta")   # Chromium reports the older alias
    assert info["dark"] is True

⌨️ Terminal

pytest tests/test_context_emulation.py -q -s

🖥️ Output

 {'language': 'hi-IN', 'timeZone': 'Asia/Calcutta', 'dark': True, 'position': [18.5204, 73.8567], 'price': '1,23,456.5'}
.
1 passed in 6.77s
  • Chromium reports the time zone as Asia/Calcutta, the older official name of Asia/Kolkata that its time-zone data still uses. Assertions on time-zone names should accept both.
  • locale changes navigator.language, the Accept-Language header and number and date formatting: note 1,23,456.5 (Indian grouping) from toLocaleString().
  • geolocation only works together with the geolocation permission; without it the page’s location request is denied.
  • color_scheme="dark" makes prefers-color-scheme: dark match. You can also switch during a test with page.emulate_media(color_scheme="light").

✅ A Practical Mobile Test Plan

  1. Pick three or four representative devices from your analytics (for example one iPhone, one mid-range Android, one tablet), not twenty.
  2. Run iPhone and iPad profiles in WebKit, Android profiles in Chromium.
  3. Test what changes on mobile: navigation menus, drawers, sticky headers, tap targets, forms with mobile keyboards (type="tel", inputmode), and images at high pixel density.
  4. Add breakpoint tests with set_viewport_size() for the widths where your layout changes.
  5. Keep visual screenshots per device (Lesson 40) and confirm critical journeys on a real device before major releases.

🏋️ 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 the command that runs tests/mobile as an iPhone 15 in the correct engine, headed, slowed down by 300 ms so you can watch it.

Show answer
pytest tests/mobile --device "iPhone 15" --browser webkit --headed --slowmo 300

An iPhone profile describes Safari, so it belongs in WebKit.

Exercise 2: Create a fixture phone_page that opens a new context as a Galaxy S24 in the existing browser and closes it after the test, without changing browser_context_args for other tests.

Show answer
import pytest


@pytest.fixture
def phone_page(browser, playwright, base_url):
    device = {k: v for k, v in playwright.devices["Galaxy S24"].items() if k != "default_browser_type"}
    context = browser.new_context(**device, base_url=base_url)
    page = context.new_page()
    yield page
    context.close()

Only tests that ask for phone_page get the device; page stays desktop.

Exercise 3: Write a breakpoint test that checks the SQA Shop “Filters” button is hidden at 1024 px and visible at 480 px, using one page.

Show answer
from playwright.sync_api import Page, expect


def test_filters_button_breakpoint(page: Page):
    page.goto("/dummy-ecommerce-website/")
    button = page.get_by_role("button", name="Filters", exact=True)
    page.set_viewport_size({"width": 1024, "height": 768})
    expect(button).to_be_hidden()
    page.set_viewport_size({"width": 480, "height": 800})
    expect(button).to_be_visible()

Exercise 4: Your geolocation test always gets “User denied Geolocation”. What is missing?

Show answer

The permission. Geolocation needs both options on the context:

browser.new_context(geolocation={"latitude": 51.5, "longitude": -0.12}, permissions=["geolocation"])

You can also grant it later with context.grant_permissions(["geolocation"]) and move the user with context.set_geolocation(...).


🧠 MCQ Quiz: Mobile Device Emulation

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 Playwright device emulation change?
  2. How do you run every test as a Pixel 7 with pytest-playwright?
  3. Why should iPhone profiles run with --browser webkit?
  4. Which key must you remove before passing a device dict to browser.new_context() yourself?
  5. What is required to use locator.tap()?
  6. How do you resize an already open page to test a breakpoint?
  7. Which context option makes prefers-color-scheme: dark match?
  8. Your geolocation test fails with a denied permission. What must you add?
  9. What does the locale option affect?
  10. Which is a real limit of device emulation?

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


❓ Frequently Asked Questions

🤔 How do I list all available devices?

Run python -c "from playwright.sync_api import sync_playwright as s; p = s().start(); print(sorted(p.devices)); p.stop()". The list is updated with each Playwright release (Pixel 10 and recent iPhones are included in 1.65).

🤔 Can I emulate a slow mobile network?

Playwright has no built-in throttling option for all browsers. In Chromium you can use a CDP session (Network.emulateNetworkConditions), or delay responses with page.route() (Lesson 52) to simulate slow APIs in every engine.

🤔 Is is_mobile supported in Firefox?

No. Firefox does not support is_mobile, so mobile profiles are meant for Chromium (Android) and WebKit (iOS). Use plain viewport changes if you need a narrow Firefox window.

🤔 Should I take screenshots on every device?

Only for key pages. Each device needs its own baseline, so screenshots multiply quickly. Lesson 40 explains how baselines are stored per browser and platform.

🤔 Does –device work together with browser_context_args?

Yes. pytest-playwright merges the device into browser_context_args, and your override receives that dictionary, so keep using {**browser_context_args, ...} to add your own options on top.


🏁 Summary

  • Device emulation sets viewport, user agent, scale factor, mobile mode and touch on a browser context.
  • --device "Pixel 7" applies a profile to the whole run; run iPhone profiles with --browser webkit.
  • Override browser_context_args (merging the defaults) to choose devices in code, and put mobile tests in their own folder.
  • Use tap() with has_touch, custom device dictionaries for missing devices, and set_viewport_size() for breakpoint tests.
  • Locale, time zone, geolocation (with permission) and color scheme are context options too; real devices are still needed for performance and OS behaviour.

🎬 Watch the Playwright tutorial series on YouTube!

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

Cross-Browser Testing with Playwright Python (Chromium, Firefox, WebKit)

Your users do not all use Chrome. Safari’s WebKit engine and Firefox’s Gecko engine render pages, handle events and implement web features differently, and bugs that only appear in one engine are common. Playwright ships all three engines, so one pytest suite can check them all. In this lesson you will run the same tests in Chromium, Firefox and WebKit, use real Chrome and Edge through channels, react to the current browser in fixtures and tests, give each browser its own launch options, and set up a cross-browser run that stays fast.

📖 What You’ll Learn: the three Playwright engines and which real browsers they represent, installing browsers, –browser and multiple browsers in one run, how test ids show the browser, Chrome and Edge with –browser-channel, the browser_name fixture, browser-specific expectations, browser_type_launch_args, skip_browser and only_browser, what usually differs between engines, and speeding up cross-browser runs.


🌐 Three Engines, Many Browsers

Every browser is built on a rendering engine. Playwright drives three of them directly:

Playwright browser Engine Represents
chromium Blink Chrome, Edge, Opera, Brave, Samsung Internet
firefox Gecko Firefox
webkit WebKit Safari on macOS and iOS

Playwright’s builds are patched versions of these engines, shipped with each Playwright release, so a test behaves the same on every machine. That is why Playwright can run WebKit on Windows and Linux, which is the easiest way to catch Safari bugs without a Mac.

Install the engines once (from Lesson 2):

⌨️ Terminal

playwright install                 # chromium, firefox and webkit
playwright install --with-deps     # also installs the system libraries on Linux/CI

▶️ Running in Another Browser

pytest-playwright runs Chromium by default. Choose another engine with --browser:

📄 pytest.ini

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

📄 tests/test_shop.py

import re

from playwright.sync_api import Page, expect

SHOP = "/dummy-ecommerce-website/"


def test_search_and_add_to_cart(page: Page):
    page.goto(SHOP)
    page.get_by_test_id("search-input").fill("earbuds")
    page.get_by_test_id("search-button").click()
    expect(page).to_have_url(re.compile(r"#/search/earbuds$"))
    page.get_by_role("button", name="Add to cart").first.click()
    expect(page.get_by_test_id("cart-count")).to_have_text("1")


def test_login_error_message(page: Page):
    page.goto(SHOP + "#/login")
    page.get_by_test_id("login-button").click()
    expect(page.get_by_test_id("login-error")).to_have_text("Username and password are required.")

⌨️ Terminal

pytest --browser firefox -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 2 items

tests/test_shop.py::test_search_and_add_to_cart[firefox] PASSED          [ 50%]
tests/test_shop.py::test_login_error_message[firefox] PASSED             [100%]

============================= 2 passed in 10.98s ==============================

Repeat the option to run every test in every listed browser:

⌨️ Terminal

pytest --browser chromium --browser firefox --browser webkit -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_shop.py::test_search_and_add_to_cart[chromium] PASSED         [ 16%]
tests/test_shop.py::test_login_error_message[chromium] PASSED            [ 33%]
tests/test_shop.py::test_search_and_add_to_cart[firefox] PASSED          [ 50%]
tests/test_shop.py::test_login_error_message[firefox] PASSED             [ 66%]
tests/test_shop.py::test_search_and_add_to_cart[webkit] PASSED           [ 83%]
tests/test_shop.py::test_login_error_message[webkit] PASSED              [100%]

============================= 6 passed in 22.19s ==============================

Two tests × three browsers = six results. The browser name is part of each test id ([chromium], [firefox], [webkit]), so you can select one with -k:

⌨️ Terminal

pytest --browser chromium --browser firefox --browser webkit -k webkit -q

🖥️ Output

..                                                                       [100%]
2 passed, 4 deselected in 7.22s

To make cross-browser runs the default for the whole project, put the options in addopts:

[pytest]
addopts = --base-url https://sqatools.in --browser chromium --browser firefox --browser webkit

🧭 Real Chrome and Edge: Channels

The chromium engine is the open-source base of Chrome and Edge, but not identical to them (codecs, some policies, auto-updates). To test with the branded browser installed on the machine, use a channel:

Channel Browser
chrome, chrome-beta, chrome-dev Google Chrome
msedge, msedge-beta, msedge-dev Microsoft Edge

⌨️ Terminal

pytest --browser-channel msedge -q

🖥️ Output

..                                                                       [100%]
2 passed in 10.95s

Edge is preinstalled on Windows; on other systems install the branded browser with playwright install chrome or playwright install msedge. A channel only applies to the Chromium engine.

📌 Note: Use the bundled chromium for everyday runs (it is pinned to your Playwright version, so results are reproducible) and a branded channel in a nightly job, or when a bug only shows in the real Chrome or Edge.


🔍 Knowing the Current Browser: browser_name

pytest-playwright provides a browser_name fixture ("chromium", "firefox" or "webkit"). Use it to log, to branch fixtures, or to explain an expected difference:

📄 tests/test_engine.py

from playwright.sync_api import Page


def test_engine_reports_itself(page: Page, browser_name):
    user_agent = page.evaluate("navigator.userAgent")
    print(f"\n{browser_name:9} -> {user_agent[:90]}")
    expected = {"chromium": "Chrome/", "firefox": "Firefox/", "webkit": "Safari/"}[browser_name]
    assert expected in user_agent

⌨️ Terminal

pytest tests/test_engine.py --browser chromium --browser firefox --browser webkit -q -s

🖥️ Output

chromium  -> Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) HeadlessC
.
firefox   -> Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:159.0) Gecko/20100101 Firefox/159.0
.
webkit    -> Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) V
.
3 passed in 5.74s

Each engine identifies itself differently, which is exactly why servers sometimes send different pages to different browsers.


⚖️ When Results Really Differ

Most well-written tests pass unchanged in all three engines. When a behaviour legitimately differs, encode the difference in one place, not with if statements scattered through tests. A dictionary keyed by browser_name keeps it explicit:

📄 tests/test_input_types.py

from playwright.sync_api import Page

# How each engine treats invalid text typed into <input type="number">
NUMBER_INPUT_VALUE = {"chromium": "", "firefox": "", "webkit": ""}


def test_number_input_rejects_letters(page: Page, browser_name):
    page.set_content('<input type="number" id="qty">')
    page.locator("#qty").press_sequentially("12abc")
    value = page.locator("#qty").input_value()
    print(f"\n{browser_name}: value={value!r}")
    assert value in ("12", NUMBER_INPUT_VALUE[browser_name])

⌨️ Terminal

pytest tests/test_input_types.py --browser chromium --browser firefox --browser webkit -q -s

🖥️ Output

chromium: value='12'
.
firefox: value=''
.
webkit: value='12'
.
3 passed in 5.99s

This is a real difference. Chromium and WebKit ignore the letters as you type, so the field holds 12. Firefox lets you type them, and because 12abc is not a valid number, the input’s value is an empty string. A form that reads the value without validating it would submit nothing in Firefox. The expected values live in one dictionary, so the difference is documented and tested instead of hidden.

page.set_content() loads a tiny HTML page directly into the browser, which is a quick way to compare engine behaviour without a server.

Common areas where engines differ in real projects:

  • Form controls: date, time and colour pickers look and behave differently; never automate the native picker UI, use fill() with an ISO value (2026-12-31).
  • Fonts and rendering: screenshots differ by a few pixels, so visual baselines are stored per browser (Lesson 40 does this automatically).
  • Media codecs: open-source Chromium lacks some proprietary codecs; use the chrome channel for video tests.
  • Downloads, clipboard and permissions: grant permissions explicitly per context; some permissions do not exist in every engine.
  • Timing: an engine may fire events in a slightly different order. Web-first assertions (expect) absorb this; time.sleep() does not.

🧰 Per-Browser Launch Options

Override the session fixture browser_type_launch_args to change how each browser starts. It receives the default arguments and browser_name is available too:

📄 tests/conftest.py

import pytest


@pytest.fixture(scope="session")
def browser_type_launch_args(browser_type_launch_args, browser_name):
    args = {**browser_type_launch_args}
    if browser_name == "chromium":
        args["args"] = ["--disable-features=Translate"]           # Chromium command-line switch
    if browser_name == "firefox":
        args["firefox_user_prefs"] = {"intl.accept_languages": "en-IN"}
    return args

⌨️ Terminal

pytest --browser chromium --browser firefox -q

🖥️ Output

........                                                                 [100%]
8 passed in 17.53s

Keep these overrides small. Each one is a difference between your tests and real users.


🏷️ Skipping a Browser for One Test

From Lesson 43: mark a test to skip or limit browsers, always with a reason.

📄 tests/test_markers.py

import pytest
from playwright.sync_api import Page


@pytest.mark.skip_browser("webkit")
def test_not_on_webkit(page: Page):
    page.set_content("<p>ok</p>")


@pytest.mark.only_browser("chromium")
def test_chromium_devtools_protocol(page: Page):
    cdp = page.context.new_cdp_session(page)        # the Chrome DevTools Protocol exists only in Chromium
    result = cdp.send("Runtime.evaluate", {"expression": "1 + 1"})
    assert result["result"]["value"] == 2

⌨️ Terminal

pytest tests/test_markers.py --browser chromium --browser firefox --browser webkit -v -rs

🖥️ 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_markers.py::test_not_on_webkit[chromium] PASSED               [ 16%]
tests/test_markers.py::test_chromium_devtools_protocol[chromium] PASSED  [ 33%]
tests/test_markers.py::test_not_on_webkit[firefox] PASSED                [ 50%]
tests/test_markers.py::test_chromium_devtools_protocol[firefox] SKIPPED  [ 66%]
tests/test_markers.py::test_not_on_webkit[webkit] SKIPPED (skipped f...) [ 83%]
tests/test_markers.py::test_chromium_devtools_protocol[webkit] SKIPPED   [100%]

=========================== short test summary info ===========================
SKIPPED [1] ..\..\.venv\Lib\site-packages\pytest_playwright\pytest_playwright.py:338: skipped for this browser: firefox
SKIPPED [2] ..\..\.venv\Lib\site-packages\pytest_playwright\pytest_playwright.py:338: skipped for this browser: webkit
======================== 3 passed, 3 skipped in 5.35s =========================

new_cdp_session is a real example of a Chromium-only API, so only_browser("chromium") is the honest marker here.


🚀 Keeping Cross-Browser Runs Fast

Three browsers triple the run time. Common strategies:

  1. Run in parallel with pytest-xdist: pytest -n auto --browser chromium --browser firefox --browser webkit (Lesson 65).
  2. Smoke in all, full in one: run the full suite in Chromium on every push, and a smoke subset in all browsers.
  3. CI matrix: one job per browser, so they run on separate machines in parallel and report separately (Lesson 66).
  4. Nightly full matrix: all tests × all browsers (and channels) once a day.

⌨️ Terminal

pytest tests/test_shop.py -n 3 --browser chromium --browser firefox --browser webkit -q

🖥️ Output

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

......                                                                   [100%]
6 passed in 19.03s

⚠️ Watch out: This project sets the base URL with addopts = --base-url ..., not with the base_url = ... ini key, on purpose. With pytest-xdist, the pytest-base-url plugin skips its setup on worker processes, so a base_url ini value never reaches the workers and every relative page.goto("/...") fails with Invalid url. A --base-url option (in addopts, on the command line or via PYTEST_BASE_URL) is passed to every worker and works.


🏋️ 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 is_safari_like that returns True when the current browser is WebKit, and use it in a test that prints a message only for WebKit.

Show answer
import pytest


@pytest.fixture
def is_safari_like(browser_name) -> bool:
    return browser_name == "webkit"


def test_message(page, is_safari_like):
    if is_safari_like:
        print("running the Safari engine")

Exercise 2: Your pytest.ini has addopts = --browser chromium --browser firefox --browser webkit. How do you run only Firefox for one quick check without editing the file?

Show answer

Options are additive, so adding --browser firefox would still run all three. Filter by the id instead:

pytest -k firefox

or override addopts for one run: pytest -o addopts="" --browser firefox (the -o flag replaces the ini value).

Exercise 3: Write the command that runs the whole suite in Google Chrome (installed on the machine) instead of the bundled Chromium, in headed mode.

Show answer
pytest --browser-channel chrome --headed

A channel only works with the Chromium engine, so --browser chromium is implied.

Exercise 4: A date-picker test passes in Chromium and fails in WebKit because it clicks the calendar popup. How should you rewrite it?

Show answer

Do not automate the native picker UI, which differs per engine. Fill the input with an ISO date and check the value:

page.locator("#datePicker").fill("2026-12-31")
expect(page.locator("#datePicker")).to_have_value("2026-12-31")

🧠 MCQ Quiz: Cross-Browser Testing in Python

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 Playwright browser represents Safari?
  2. How do you run every test in both Chromium and Firefox?
  3. How can you tell in the report which browser a result belongs to?
  4. What does --browser-channel msedge do?
  5. Which fixture tells a test which engine is running?
  6. Which fixture should you override to pass launch arguments per browser?
  7. Why is page.context.new_cdp_session() a good reason for only_browser("chromium")?
  8. Can Playwright run WebKit tests on Windows?
  9. What is the safest way to set a value in a native date input across browsers?
  10. Which strategy keeps cross-browser runs fast?

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


❓ Frequently Asked Questions

🤔 Is testing in Playwright’s WebKit the same as testing in Safari?

Very close, but not identical: it is the same engine with Playwright’s patches, without Safari’s browser shell and macOS integrations. It catches the vast majority of Safari engine bugs; for final sign-off on iOS, teams still use a real device or a device cloud.

🤔 Do I need to test in both Chrome and Edge?

Usually not: both use the Blink engine and behave almost identically. Run the bundled Chromium routinely and add an msedge channel run if many of your users use Edge or your app relies on enterprise policies.

🤔 Why does my test pass in Chromium but time out in Firefox?

Common causes: a locator that relies on browser-specific markup, a hard-coded wait that is too short for the slower first navigation, or a feature the engine does not support. Open the trace for the Firefox run (Lesson 62) and compare it with the Chromium trace.

🤔 Can I set the browser in pytest.ini instead of the command line?

Yes, through addopts = --browser firefox (or several --browser options). There is no separate ini key for it.

🤔 How do mobile browsers fit in?

Mobile Safari and Chrome on Android are covered by device emulation in WebKit and Chromium: viewport, touch, user agent and device scale factor. That is the next lesson.


🏁 Summary

  • Playwright drives three engines: Chromium (Chrome, Edge), Firefox and WebKit (Safari), on every OS.
  • --browser selects an engine and can be repeated; the browser name appears in each test id.
  • --browser-channel chrome or msedge runs the installed branded browser.
  • Use browser_name to log or encode real differences in one place, and browser_type_launch_args for per-browser launch options.
  • Mark engine-specific tests with skip_browser / only_browser, and keep runs fast with xdist, CI matrices and a smoke-vs-full split.

🎬 Watch the Playwright tutorial series on YouTube!

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