Run Playwright Python Tests Against Multiple Environments

The same test suite usually has to run against several copies of an application: a QA server, a staging server before release and, carefully, production after release. Copying tests per environment is a maintenance trap. In this lesson you will run one suite anywhere by changing a single command-line option: use --base-url and relative URLs, add a custom --env option with pytest_addoption, keep each environment’s URL, users and flags in one config file, load per-environment .env secrets, and stop destructive tests from ever touching production.

📖 What You’ll Learn: why environments need configuration not code, relative URLs with base_url, the –base-url option and pytest.ini, a custom –env option with pytest_addoption, an environments.json config file, an env_config fixture that also drives base_url, per-environment .env files, markers that skip tests by environment, a production safety guard, and printing the environment in the report header.


🌍 One Suite, Many Environments

A typical company has at least these environments:

Environment Purpose What tests may do
local / dev A developer’s machine Anything
QA Shared test server Create and delete test data
staging Copy of production before a release Mostly read; limited test data
production Real users Read-only smoke tests only

The URLs, accounts and rules differ; the tests stay the same. The goal of this lesson is a command like:

⌨️ Terminal

pytest --env qa
pytest --env staging -m smoke
pytest --env prod -m smoke

🔗 Step 1: Relative URLs and –base-url

pytest-playwright (through the pytest-base-url plugin) gives every test a base_url. When it is set, page.goto() accepts relative URLs and joins them to it:

📄 pytest.ini

[pytest]
base_url = https://sqatools.in
markers =
    smoke: quick checks that are safe on every environment
    destructive: creates, changes or deletes data
    only_env(*names): run only on the named environments

📄 tests/test_relative.py

from playwright.sync_api import Page, expect


def test_store_home(page: Page, base_url):
    page.goto("/dummy-ecommerce-website/")          # becomes https://sqatools.in/dummy-ecommerce-website/
    print("\nopened", page.url, "with base_url", base_url)
    expect(page.get_by_test_id("logo")).to_be_visible()

⌨️ Terminal

pytest tests/test_relative.py -q -s

🖥️ Output

opened https://sqatools.in/dummy-ecommerce-website/ with base_url https://sqatools.in
.
1 passed in 2.52s

The command line beats the ini file, so pytest --base-url https://staging.example.com would run the same test on another host. Rule number one for multi-environment suites: never hard-code a host name in a test.

📌 Note: The base_url value from pytest.ini is also applied to context.new_page() and to the page fixture through browser_context_args, so every page in the test uses it.


⚙️ Step 2: A Custom –env Option

A URL alone is not enough: environments also differ in accounts, feature flags and what is allowed. Add a single --env option and keep the details in a config file.

📄 environments.json

{
  "qa": {
    "base_url": "https://sqatools.in",
    "shop_path": "/dummy-ecommerce-website/",
    "user": "testuser",
    "read_only": false
  },
  "staging": {
    "base_url": "https://sqatools.in",
    "shop_path": "/dummy-ecommerce-website/",
    "user": "testuser",
    "read_only": false
  },
  "prod": {
    "base_url": "https://sqatools.in",
    "shop_path": "/dummy-ecommerce-website/",
    "user": "testuser",
    "read_only": true
  }
}

📌 Note: SQA Tools has a single public practice site, so all three entries point at it and you can run every command in this lesson. In your project each entry would have its own host, for example https://qa.shop.example.com.

Since the host now comes from the config file, remove base_url from pytest.ini (otherwise pytest-base-url copies it into the --base-url option, and the option would always win):

📄 pytest.ini

[pytest]
markers =
    smoke: quick checks that are safe on every environment
    destructive: creates, changes or deletes data
    only_env(*names): run only on the named environments

The root conftest.py registers the option, loads the matching entry once per session, and overrides the base_url fixture so the URL comes from the config:

📄 conftest.py

import json
import os
from dataclasses import dataclass
from pathlib import Path

import pytest
from dotenv import load_dotenv

ROOT = Path(__file__).parent


def pytest_addoption(parser):
    parser.addoption("--env", default=os.getenv("TEST_ENV", "qa"), choices=["qa", "staging", "prod"],
                     help="target environment (default: qa, or $TEST_ENV)")


@dataclass(frozen=True)
class EnvConfig:
    name: str
    base_url: str
    shop_path: str
    user: str
    read_only: bool
    password: str


@pytest.fixture(scope="session")
def env_config(pytestconfig) -> EnvConfig:
    name = pytestconfig.getoption("--env")
    data = json.loads((ROOT / "environments.json").read_text(encoding="utf-8"))[name]
    load_dotenv(ROOT / f".env.{name}")                     # per-environment secrets, if the file exists
    password = os.getenv("SHOP_PASSWORD", "")
    return EnvConfig(name=name, password=password, **data)


@pytest.fixture(scope="session")
def base_url(env_config, pytestconfig) -> str:
    # an explicit --base-url still wins, which is handy for one-off runs
    return pytestconfig.getoption("base_url") or env_config.base_url


def pytest_report_header(config):
    return f"target environment: {config.getoption('--env')}"

Two details matter:

  • default=os.getenv("TEST_ENV", "qa") lets CI choose the environment with a variable instead of editing the command.
  • choices=[...] makes a typo such as --env stagin fail immediately with a clear argparse error.

Secrets come from .env.qa, .env.staging and .env.prod (all git-ignored, see Lesson 47):

📄 .env.qa

SHOP_PASSWORD=Test@123

📄 .env.staging

SHOP_PASSWORD=Test@123

📄 .env.prod

SHOP_PASSWORD=Test@123

🧪 Step 3: Tests That Use the Config

📄 tests/test_shop.py

import pytest
from playwright.sync_api import Page, expect


@pytest.mark.smoke
def test_store_loads(page: Page, env_config):
    page.goto(env_config.shop_path)
    expect(page.get_by_test_id("product-card").first).to_be_visible()


@pytest.mark.smoke
def test_user_can_log_in(page: Page, env_config):
    page.goto(env_config.shop_path + "#/login")
    page.get_by_test_id("login-username").fill(env_config.user)
    page.get_by_test_id("login-password").fill(env_config.password)
    page.get_by_test_id("login-button").click()
    expect(page.get_by_test_id("account-button")).to_contain_text("Hi,")


@pytest.mark.destructive
def test_place_order(page: Page, env_config):
    page.goto(env_config.shop_path + "#/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")


@pytest.mark.only_env("qa")
def test_qa_only_feature(page: Page, env_config):
    page.goto(env_config.shop_path + "#/deals")
    expect(page.get_by_test_id("product-card").first).to_be_visible()

⌨️ Terminal

pytest tests/test_shop.py --env qa -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
target environment: qa
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_shop.py::test_store_loads[chromium] PASSED                    [ 25%]
tests/test_shop.py::test_user_can_log_in[chromium] PASSED                [ 50%]
tests/test_shop.py::test_place_order[chromium] PASSED                    [ 75%]
tests/test_shop.py::test_qa_only_feature[chromium] PASSED                [100%]

============================= 4 passed in 10.29s ==============================

The header line target environment: qa comes from pytest_report_header. It makes every CI log and HTML report state which environment was tested.


🛡️ Step 4: Protect Production

Nobody should be able to place orders or delete data on production by running the wrong command. A collection hook skips destructive tests on read-only environments and applies only_env markers:

📄 tests/conftest.py

import json
from pathlib import Path

import pytest

ENVIRONMENTS = json.loads((Path(__file__).parent.parent / "environments.json").read_text(encoding="utf-8"))


def pytest_collection_modifyitems(config, items):
    env = config.getoption("--env")
    read_only = ENVIRONMENTS[env]["read_only"]
    for item in items:
        if read_only and item.get_closest_marker("destructive"):
            item.add_marker(pytest.mark.skip(reason=f"destructive test blocked on read-only environment '{env}'"))
        only = item.get_closest_marker("only_env")
        if only and env not in only.args:
            item.add_marker(pytest.mark.skip(reason=f"runs only on {', '.join(only.args)}"))

⌨️ Terminal

pytest tests/test_shop.py --env prod -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
target environment: prod
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_shop.py::test_store_loads[chromium] PASSED                    [ 25%]
tests/test_shop.py::test_user_can_log_in[chromium] PASSED                [ 50%]
tests/test_shop.py::test_place_order[chromium] SKIPPED (destructive ...) [ 75%]
tests/test_shop.py::test_qa_only_feature[chromium] SKIPPED (runs onl...) [100%]

=========================== short test summary info ===========================
SKIPPED [1] tests\test_shop.py:20: destructive test blocked on read-only environment 'prod'
SKIPPED [1] tests\test_shop.py:27: runs only on qa
======================== 2 passed, 2 skipped in 6.59s =========================

On prod the order test and the QA-only test are skipped with clear reasons (-rs prints them), and the smoke tests still run. The guard lives in one place, so a new destructive test is protected as soon as it is marked.

⚠️ Watch out: Skipping is a safety net, not a permission system. Production test accounts should also be restricted on the server side, so a mistake in the hook cannot do real damage.


🔀 Choosing the Environment Without the Option

Because the default comes from TEST_ENV, these are equivalent:

⌨️ Terminal

pytest --env staging
$env:TEST_ENV = "staging"; pytest          # PowerShell
TEST_ENV=staging pytest                    # macOS / Linux

⌨️ Terminal

$env:TEST_ENV = "staging"; pytest tests/test_shop.py -m smoke

🖥️ Output

============================= test session starts =============================
platform win32 -- Python 3.15.1, pytest-9.2.0, pluggy-1.7.0
target environment: staging
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
collected 4 items / 2 deselected / 2 selected

tests\test_shop.py ..                                                    [100%]

======================= 2 passed, 2 deselected in 4.50s =======================

The report header shows target environment: staging. A one-off override of only the host also still works, because the base_url fixture checks --base-url first:

⌨️ Terminal

pytest --env qa --base-url https://qa2.shop.example.com

🧭 What Belongs Where

Kind of value Where it lives
Host names, paths, feature flags, read-only flag environments.json (committed)
Passwords, API keys, tokens .env.<env> locally, CI secrets in pipelines (never committed)
Which environment to test --env option or TEST_ENV variable
Test inputs and expected results data files (Lesson 46)

🏋️ 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 boolean field slow_network to each environment in environments.json and a fixture that sets the default navigation timeout to 60 seconds when it is true. Write the fixture.

Show answer
import pytest
from playwright.sync_api import Page


@pytest.fixture(autouse=True)
def env_timeouts(page: Page, env_config):
    if getattr(env_config, "slow_network", False):
        page.set_default_navigation_timeout(60_000)
    yield

Add slow_network: bool = False to the EnvConfig dataclass so the JSON field is accepted. autouse=True applies it to every test without changing them.

Exercise 2: Write a test marker prod_only and the hook code that skips such tests on every environment except prod.

Show answer
# pytest.ini: markers = prod_only: runs only against production

def pytest_collection_modifyitems(config, items):
    env = config.getoption("--env")
    for item in items:
        if item.get_closest_marker("prod_only") and env != "prod":
            item.add_marker(pytest.mark.skip(reason="production-only check"))

(This is a special case of only_env("prod"); prefer the general marker when you already have it.)

Exercise 3: A teammate runs pytest --env Staging and gets argument --env: invalid choice: 'Staging'. Change the option so the value is case-insensitive.

Show answer
parser.addoption("--env", default=os.getenv("TEST_ENV", "qa"), type=str.lower,
                 choices=["qa", "staging", "prod"], help="target environment")

argparse applies type before checking choices, so Staging becomes staging.

Exercise 4: Why does the lesson override the base_url fixture instead of writing page.goto(env_config.base_url + "/path") in every test?

Show answer

Overriding base_url makes relative goto() calls work everywhere (the page and every new context use it), keeps host names out of tests, and still lets an explicit --base-url win. Concatenating strings in tests repeats the host logic in hundreds of places and breaks easily (double or missing slashes).


🧠 MCQ Quiz: Run Against Multiple Environments

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 page.goto("/login") do when base_url is https://qa.example.com?
  2. Which wins: --base-url on the command line or base_url in pytest.ini?
  3. Which hook registers a custom option such as --env?
  4. What does choices=["qa", "staging", "prod"] on the option give you?
  5. Where should production passwords used by smoke tests live?
  6. What is the purpose of pytest_report_header in this lesson?
  7. How does the lesson stop destructive tests from running on production?
  8. What does item.get_closest_marker("only_env") return?
  9. Why give --env a default of os.getenv("TEST_ENV", "qa")?
  10. Why is skipping destructive tests on prod not enough on its own?

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


❓ Frequently Asked Questions

🤔 Should I use separate test folders per environment?

No. Separate copies drift apart. Keep one suite and let configuration (and markers such as smoke or destructive) decide what runs where.

🤔 Can I run the suite against two environments in one command?

Not with one session-scoped env_config. Run pytest twice (for example as two CI jobs in a matrix), which also keeps the reports separate. Lesson 66 shows a GitHub Actions matrix.

🤔 Where do I put environment-specific test data, such as product IDs?

Add it to the environment entry in environments.json (or a data file per environment, such as test_data/qa/products.csv) and read it through env_config.

🤔 What is the difference between base_url and env_config.base_url here?

env_config.base_url is the value from the config file. The base_url fixture is what pytest-playwright uses for relative navigation; the lesson’s override returns --base-url if given, otherwise the config value.

🤔 How do I make API tests use the same environment?

Use env_config (or base_url) when you create the API request context: playwright.request.new_context(base_url=env_config.base_url). Module 9 covers API testing.


🏁 Summary

  • Never hard-code hosts: use relative page.goto() with base_url, which --base-url can override.
  • Add one --env option with pytest_addoption (default from TEST_ENV, validated with choices).
  • Keep URLs and flags in a committed environments.json; keep secrets in git-ignored .env.<env> files or CI secrets.
  • Override the base_url fixture from the environment config and print the environment with pytest_report_header.
  • Guard production with destructive and only_env markers in pytest_collection_modifyitems, plus server-side restrictions.

🎬 Watch the Playwright tutorial series on YouTube!

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

Environment Variables and .env Files in Playwright Python

A test that contains password = "Test@123" works on your laptop and is a security problem everywhere else. Passwords, API keys and environment URLs belong outside the code, in environment variables. In this lesson you will read environment variables in pytest, load them from a .env file with python-dotenv, commit a safe .env.example instead of the real file, build one validated settings object that fails fast when something is missing, and pass the same values from a CI pipeline.

📖 What You’ll Learn: what environment variables are and why tests need them, os.environ and os.getenv with defaults, setting variables in PowerShell, macOS and Linux, python-dotenv and load_dotenv in conftest.py, .env vs .env.example and .gitignore, precedence and override, a frozen Settings dataclass with validation, PYTEST_BASE_URL and PYTEST_ADDOPTS, masking secrets, and CI secrets.


🔐 Why Environment Variables?

Hard-coded values cause three problems in a test framework:

  1. Secrets leak. Anything committed to Git stays in its history forever, even after you delete the line.
  2. Environments differ. The QA server, staging and production have different URLs and accounts.
  3. People differ. Each tester and the CI server may use their own test account.

An environment variable is a named value that the operating system passes to every program it starts. Your test reads SHOP_USER and gets testuser on your laptop and ci-bot on the build server, with no code change.


🐍 Reading Variables in Python

os.environ is a dictionary-like object with all variables of the current process.

📄 read_env.py

import os

print("HOME or USERPROFILE set:", bool(os.getenv("HOME") or os.getenv("USERPROFILE")))
print("SHOP_USER =", os.getenv("SHOP_USER"))                      # None when missing
print("SHOP_TIMEOUT =", os.getenv("SHOP_TIMEOUT", "5000"))         # default when missing
try:
    os.environ["SHOP_PASSWORD"]                                     # KeyError when missing
except KeyError as e:
    print("missing:", e)

⌨️ Terminal

python read_env.py

🖥️ Output

HOME or USERPROFILE set: True
SHOP_USER = None
SHOP_TIMEOUT = 5000
missing: 'SHOP_PASSWORD'
Call When the variable is missing
os.environ["NAME"] raises KeyError (good for required values)
os.getenv("NAME") returns None
os.getenv("NAME", "default") returns the default (good for optional values)

⚠️ Watch out: Environment variables are always strings. os.getenv("SHOP_TIMEOUT", "5000") returns "5000", and os.getenv("HEADLESS") == "false" is the only safe way to read a flag: bool("false") is True.


⌨️ Setting Variables for One Run

How you set a variable depends on your shell. The value exists only for that terminal window (or that one command).

Windows PowerShell:

⌨️ Terminal

$env:SHOP_USER = "testuser"
$env:SHOP_PASSWORD = "Test@123"
pytest -q

macOS and Linux (bash or zsh):

⌨️ Terminal

export SHOP_USER=testuser
export SHOP_PASSWORD='Test@123'
pytest -q
# or for a single command only:
SHOP_USER=testuser SHOP_PASSWORD='Test@123' pytest -q

Typing these every day is tedious and error-prone, which is where .env files come in.


📄 .env Files with python-dotenv

A .env file is a plain text file of NAME=value lines. The python-dotenv library reads it and puts the values into os.environ.

⌨️ Terminal

pip install python-dotenv

Create the project files:

📄 pytest.ini

[pytest]
base_url = https://sqatools.in

📄 .env

# Local settings for this machine. Never commit this file.
SHOP_USER=testuser
SHOP_PASSWORD=Test@123
SHOP_PATH=/dummy-ecommerce-website/
EXPECT_TIMEOUT=7000

Load the file as early as possible: in the root conftest.py, at import time, so every fixture and test sees the values.

📄 conftest.py

import os
from pathlib import Path

from dotenv import load_dotenv
from playwright.sync_api import expect

load_dotenv(Path(__file__).parent / ".env")          # explicit path: works from any folder

expect.set_options(timeout=int(os.getenv("EXPECT_TIMEOUT", "5000")))

Now a test can log in without any secret in the code:

📄 tests/test_login_env.py

import os

from playwright.sync_api import Page, expect


def test_login_with_env_credentials(page: Page):
    page.goto(os.environ["SHOP_PATH"] + "#/login")
    page.get_by_test_id("login-username").fill(os.environ["SHOP_USER"])
    page.get_by_test_id("login-password").fill(os.environ["SHOP_PASSWORD"])
    page.get_by_test_id("login-button").click()
    expect(page.get_by_test_id("account-button")).to_contain_text("Hi,")

⌨️ Terminal

pytest tests/test_login_env.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_login_env.py::test_login_with_env_credentials[chromium] PASSED [100%]

============================== 1 passed in 3.25s ==============================

expect.set_options(timeout=...) changes the default timeout of every expect() assertion, here from 5 to 7 seconds, controlled by the .env file.


🙈 .env, .env.example and .gitignore

The real .env must never be committed. Add it to .gitignore and commit a template with the same names and safe placeholder values:

📄 .gitignore

.env
.env.*
!.env.example

📄 .env.example

# Copy this file to .env and fill in your own values.
SHOP_USER=
SHOP_PASSWORD=
SHOP_PATH=/dummy-ecommerce-website/
EXPECT_TIMEOUT=5000

A new team member runs copy .env.example .env (Windows) or cp .env.example .env (macOS/Linux), fills in their account, and is ready. The !.env.example line re-includes the template that .env.* would otherwise ignore. See the Git and GitHub tutorial for more .gitignore patterns.

⚠️ Watch out: If a secret was ever committed, deleting it in a new commit is not enough: it is still in the history. Change the password or rotate the key, then clean the history if your policy requires it.


⚖️ Which Value Wins? Precedence and override

By default load_dotenv() does not overwrite variables that already exist. So a value set in the terminal or by CI beats the .env file, which is exactly what you want: CI can inject its own credentials while developers rely on .env.

📄 precedence.py

import os

from dotenv import load_dotenv

os.environ["SHOP_USER"] = "ci-bot"                 # pretend CI already set it
load_dotenv(".env")
print("default:", os.environ["SHOP_USER"])          # ci-bot: existing value kept

load_dotenv(".env", override=True)
print("override=True:", os.environ["SHOP_USER"])    # testuser: the file wins

⌨️ Terminal

python precedence.py

🖥️ Output

default: ci-bot
override=True: testuser

Use override=True only when the file must win, for example when you load a specific environment file on purpose (next lesson).


🧱 One Validated Settings Object

Scattering os.environ[...] across fifty tests makes it hard to see what the framework needs, and a missing variable fails deep inside a test. Collect everything in one place and check it once, at startup:

📄 settings.py

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

from dotenv import load_dotenv

load_dotenv(Path(__file__).parent / ".env")


@dataclass(frozen=True)
class Settings:
    shop_user: str
    shop_password: str = field(repr=False)          # never printed in logs or reports
    shop_path: str = "/dummy-ecommerce-website/"
    expect_timeout: int = 5000
    headless: bool = True


def load_settings() -> Settings:
    required = ["SHOP_USER", "SHOP_PASSWORD"]
    missing = [name for name in required if not os.getenv(name)]
    if missing:
        raise RuntimeError(f"Missing environment variables: {', '.join(missing)}. Copy .env.example to .env and fill them in.")
    return Settings(
        shop_user=os.environ["SHOP_USER"],
        shop_password=os.environ["SHOP_PASSWORD"],
        shop_path=os.getenv("SHOP_PATH", "/dummy-ecommerce-website/"),
        expect_timeout=int(os.getenv("EXPECT_TIMEOUT", "5000")),
        headless=os.getenv("HEADLESS", "true").lower() != "false",
    )


if __name__ == "__main__":
    print(load_settings())

⌨️ Terminal

python settings.py

🖥️ Output

Settings(shop_user='testuser', shop_path='/dummy-ecommerce-website/', expect_timeout=7000, headless=True)

The password is filled in but not printed: field(repr=False) hides it from repr(), so it never appears in a log, a pytest failure message or an HTML report.

Expose it as a session fixture:

📄 tests/conftest.py

import pytest

from settings import Settings, load_settings


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

📄 tests/test_login_settings.py

from playwright.sync_api import Page, expect

from settings import Settings


def test_login_with_settings(page: Page, settings: Settings):
    page.goto(settings.shop_path + "#/login")
    page.get_by_test_id("login-username").fill(settings.shop_user)
    page.get_by_test_id("login-password").fill(settings.shop_password)
    page.get_by_test_id("login-button").click()
    expect(page.get_by_test_id("account-button")).to_contain_text("Hi,")

⌨️ Terminal

pytest tests/test_login_settings.py -q

🖥️ Output

.                                                                        [100%]
1 passed in 2.66s

What happens when a variable is missing? Rename the .env file away and run again:

⌨️ Terminal

move .env .env.bak
pytest tests/test_login_settings.py -q

🖥️ Output

E                                                                        [100%]
=================================== ERRORS ====================================
____________ ERROR at setup of test_login_with_settings[chromium] _____________

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

tests\conftest.py:8: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

    def load_settings() -> Settings:
        required = ["SHOP_USER", "SHOP_PASSWORD"]
        missing = [name for name in required if not os.getenv(name)]
        if missing:
>           raise RuntimeError(f"Missing environment variables: {', '.join(missing)}. Copy .env.example to .env and fill them in.")
E           RuntimeError: Missing environment variables: SHOP_USER, SHOP_PASSWORD. Copy .env.example to .env and fill them in.

settings.py:23: RuntimeError
=========================== short test summary info ===========================
ERROR tests/test_login_settings.py::test_login_with_settings[chromium] - Runt...
1 error in 0.88s

The test errors in setup with a message that says exactly what to do, instead of typing None into a login form.


🌐 Variables pytest Itself Understands

Some tools read environment variables directly, which is handy in CI:

Variable Read by Effect
PYTEST_BASE_URL pytest-base-url Default for --base-url (beats base_url in pytest.ini)
PYTEST_ADDOPTS pytest Extra command-line options added to every run
PWDEBUG=1 Playwright Opens the Playwright Inspector and runs headed (Lesson 61)
DEBUG=pw:api Playwright Logs every Playwright API call to the terminal

📄 tests/test_base_url.py

def test_print_base_url(base_url):
    print("base_url =", base_url)

⌨️ Terminal

$env:PYTEST_BASE_URL = "https://sqatools.in/"
pytest tests/test_base_url.py -q -s

🖥️ Output

base_url = https://sqatools.in/
.
1 passed in 0.01s

The value from the environment replaced the base_url in pytest.ini (notice the trailing slash). The next lesson uses this to switch between environments.


🚀 Environment Variables in CI

In CI you do not create a .env file. The pipeline stores secrets encrypted and exposes them as environment variables to the test step. In GitHub Actions:

- name: Run Playwright tests
  env:
    SHOP_USER: ${{ secrets.SHOP_USER }}
    SHOP_PASSWORD: ${{ secrets.SHOP_PASSWORD }}
    EXPECT_TIMEOUT: "10000"
  run: pytest

Because load_dotenv() does not override existing variables, the same conftest.py works locally (values from .env) and in CI (values from secrets). Lesson 66 builds the full workflow, and Lesson 67 does the same in Jenkins with withCredentials.


🏋️ 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 credentials that returns a (username, password) tuple from SHOP_USER and SHOP_PASSWORD, and calls pytest.fail() with a helpful message when either is missing.

Show answer
import os

import pytest


@pytest.fixture(scope="session")
def credentials() -> tuple[str, str]:
    user, password = os.getenv("SHOP_USER"), os.getenv("SHOP_PASSWORD")
    if not user or not password:
        pytest.fail("Set SHOP_USER and SHOP_PASSWORD (copy .env.example to .env)", pytrace=False)
    return user, password

pytrace=False prints only the message, without a long traceback.

Exercise 2: A teammate writes headless = bool(os.getenv("HEADLESS", "true")) and is surprised that HEADLESS=false still runs headless. Explain and fix it.

Show answer

Environment variables are strings, and every non-empty string is truthy, so bool("false") is True. Compare the text instead:

headless = os.getenv("HEADLESS", "true").strip().lower() not in ("false", "0", "no")

Exercise 3: CI sets SHOP_USER=ci-bot, and the repository also contains a .env with SHOP_USER=testuser (by mistake). Which value do the tests use with load_dotenv(), and with load_dotenv(override=True)?

Show answer

With the default load_dotenv() the existing value wins, so tests use ci-bot. With override=True the file wins and tests use testuser. Keep the default for local .env files, and make sure .env is in .gitignore so it never reaches CI.

Exercise 4: Add an api_key field to the Settings dataclass so that it is required but never appears in logs or in pytest failure output.

Show answer
@dataclass(frozen=True)
class Settings:
    shop_user: str
    shop_password: str = field(repr=False)
    api_key: str = field(repr=False, default="")

and in load_settings() add "API_KEY" to required and pass api_key=os.environ["API_KEY"]. repr=False keeps it out of repr(), which is what pytest and loggers print.


🧠 MCQ Quiz: Environment Variables and .env Files

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 os.getenv("NAME") return when the variable is not set?
  2. What is bool(os.getenv("HEADLESS")) when HEADLESS=false?
  3. Which file should be committed to Git?
  4. By default, does load_dotenv() overwrite a variable that is already set in the environment?
  5. Where is the best place to call load_dotenv() in a pytest project?
  6. What does field(repr=False) on a dataclass field do?
  7. Which environment variable sets the default for pytest-playwright’s --base-url?
  8. How do you set a variable for the current PowerShell session?
  9. A password was committed to Git and removed in the next commit. What must you do?
  10. How should CI provide secrets to Playwright tests?

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


❓ Frequently Asked Questions

🤔 Is there a pytest plugin that loads .env automatically?

Yes, pytest-dotenv loads .env files listed in pytest.ini. Calling load_dotenv() yourself in conftest.py does the same with one line and no extra plugin, and makes the precedence explicit.

🤔 Can I keep several .env files, one per environment?

Yes, for example .env.qa and .env.staging, and choose one with a command-line option or an ENV variable. The next lesson builds exactly that.

🤔 Do environment variables work with pytest-xdist workers?

Yes. Worker processes inherit the environment of the main pytest process, and each worker imports conftest.py, so load_dotenv() runs there too.

🤔 Should test data like usernames go in .env?

Only values that differ per machine or environment, or that are secret. Shared test data (search terms, expected messages) belongs in data files (previous lesson).

🤔 How do I see which variables are set?

In PowerShell run Get-ChildItem env:; on macOS or Linux run env or printenv. In Python, print(sorted(os.environ)) lists the names. Never print the values of secrets.


🏁 Summary

  • Keep secrets and per-environment values in environment variables, not in test code.
  • os.environ["X"] for required values, os.getenv("X", default) for optional ones; every value is a string.
  • python-dotenv loads .env into the environment; commit .env.example, ignore .env.
  • Existing variables beat the file unless override=True, so CI secrets win over local files.
  • Validate everything once in a Settings object, hide secrets with repr=False, and use PYTEST_BASE_URL / PYTEST_ADDOPTS in CI.

🎬 Watch the Playwright tutorial series on YouTube!

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

Read Test Data from JSON, CSV and Excel in Playwright Python

In the previous lesson the test data lived inside the test file. Real teams keep it in files that testers, analysts and even business users can edit: JSON for structured data, CSV for simple tables and Excel because that is where the requirements already are. In this lesson you will build a small, reusable data loader that reads all three formats, turns every row into a named pytest case, validates the rows before any browser starts, and drives real Playwright tests on the SQA Shop practice store.

📖 What You’ll Learn: when to use JSON, CSV or Excel for test data, a test_data folder and paths that work from anywhere, a JSON loader with nested data, csv.DictReader and type conversion, reading .xlsx with openpyxl, turning rows into pytest.param ids, validating rows with a dataclass, caching loaded files, and the encoding and empty-cell traps.


📁 Choosing a Format

Format Good for Watch out for
JSON Nested data (a user with an address and a cart), typed values (numbers, booleans, null) Hard for non-programmers to edit; no comments
CSV Flat tables, easy diffs in Git, editable in any spreadsheet Every value is a string; commas and encodings
Excel (.xlsx) Data owned by business users or copied from requirements Binary file (poor Git diffs), needs openpyxl, empty cells become None

A common, healthy setup: JSON for framework data (users, environments), CSV or Excel for large tables of cases that someone else maintains.


🗂️ Project Layout

project/
├── pytest.ini
├── test_data/
│   ├── login_cases.json
│   ├── search_cases.csv
│   └── coupon_cases.xlsx
└── tests/
    ├── __init__.py
    ├── data_loader.py
    ├── test_login_json.py
    ├── test_search_csv.py
    └── test_coupon_excel.py

📄 pytest.ini

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

Install the Excel library once (pytest-playwright is already installed from Lesson 2):

⌨️ Terminal

pip install openpyxl

📍 Paths That Work from Anywhere

The most common data-file bug is a relative path such as open("test_data/login_cases.json"). It works when you run pytest from the project root and fails from an IDE, from a sub-folder or in CI. Build paths from the location of the Python file instead:

from pathlib import Path

DATA_DIR = Path(__file__).resolve().parent.parent / "test_data"   # tests/ -> project/ -> test_data/

Path(__file__) is the loader file itself, so DATA_DIR is correct no matter where pytest was started.


🧾 JSON Test Data

JSON keeps types: true becomes True, null becomes None, numbers stay numbers. It also nests, so one case can hold several related values.

📄 test_data/login_cases.json

[
  {"id": "valid-user", "username": "testuser", "password": "Test@123", "error": null},
  {"id": "wrong-password", "username": "testuser", "password": "nope", "error": "Invalid username or password."},
  {"id": "locked-user", "username": "lockeduser", "password": "Test@123", "error": "This account is locked. Please contact support."},
  {"id": "missing-password", "username": "testuser", "password": "", "error": "Password is required."}
]

The loader reads the file once and turns each object into a pytest.param whose id comes from the data:

📄 tests/data_loader.py

import csv
import json
from functools import cache
from pathlib import Path

import pytest
from openpyxl import load_workbook

DATA_DIR = Path(__file__).resolve().parent.parent / "test_data"


@cache
def read_json(name: str) -> list[dict]:
    with open(DATA_DIR / name, encoding="utf-8") as f:
        return json.load(f)


@cache
def read_csv(name: str) -> list[dict]:
    # utf-8-sig also accepts files saved by Excel, which start with a byte-order mark
    with open(DATA_DIR / name, encoding="utf-8-sig", newline="") as f:
        return list(csv.DictReader(f))


@cache
def read_excel(name: str, sheet: str | None = None) -> list[dict]:
    wb = load_workbook(DATA_DIR / name, read_only=True, data_only=True)
    ws = wb[sheet] if sheet else wb.active
    rows = ws.iter_rows(values_only=True)
    header = [str(h).strip() for h in next(rows)]
    data = [dict(zip(header, row)) for row in rows if any(v is not None for v in row)]
    wb.close()
    return data


def as_params(rows: list[dict], fields: list[str], id_field: str = "id") -> list:
    """Rows -> pytest.param objects with the given fields, named by id_field. Rows with run = no are skipped."""
    params = []
    for row in rows:
        marks = []
        if str(row.get("run", "yes")).strip().lower() in ("no", "false", "0"):
            marks.append(pytest.mark.skip(reason="disabled in the data file"))
        params.append(pytest.param(*(row[f] for f in fields), id=str(row[id_field]), marks=marks))
    return params

Three details are worth copying into your own framework:

  • @cache (from functools) reads each file once per test session, even if 50 tests use it.
  • encoding="utf-8-sig" silently drops the invisible byte-order mark that Excel puts at the start of “CSV UTF-8” files. Without it the first column header becomes 'id' and row["id"] raises KeyError.
  • A run column lets the data owner switch a case off without touching Python code.

Now the test:

📄 tests/test_login_json.py

import pytest
from playwright.sync_api import Page, expect

from tests.data_loader import as_params, read_json

SHOP = "/dummy-ecommerce-website/"


@pytest.mark.parametrize("username, password, error", as_params(read_json("login_cases.json"), ["username", "password", "error"]))
def test_login_from_json(page: Page, username, password, error):
    page.goto(SHOP + "#/login")
    page.get_by_test_id("login-username").fill(username)
    page.get_by_test_id("login-password").fill(password)
    page.get_by_test_id("login-button").click()
    if error is None:
        expect(page.get_by_test_id("account-button")).to_contain_text("Hi, Test")
    else:
        expect(page.get_by_test_id("login-error")).to_have_text(error)

⌨️ Terminal

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

tests/test_login_json.py::test_login_from_json[chromium-valid-user] PASSED [ 25%]
tests/test_login_json.py::test_login_from_json[chromium-wrong-password] PASSED [ 50%]
tests/test_login_json.py::test_login_from_json[chromium-locked-user] PASSED [ 75%]
tests/test_login_json.py::test_login_from_json[chromium-missing-password] PASSED [100%]

============================== 4 passed in 8.73s ==============================

The ids (valid-user, locked-user …) come straight from the JSON file, so a failure report tells you exactly which row broke.


📊 CSV Test Data

CSV is the simplest format for a table of cases. This file drives search tests: a search term, the minimum number of results and a word that at least one product name must contain.

📄 test_data/search_cases.csv

id,term,min_results,name_contains,run
earbuds,earbuds,1,Earbuds,yes
jeans,jeans,3,Jeans,yes
course,course,3,Course,yes
smart-tv,smart tv,1,Smart TV,yes
not-ready,hoverboard,1,Hoverboard,no

⚠️ Watch out: Every CSV value is a string. min_results arrives as "3", not 3, and "no" is a non-empty string, which is truthy in Python. Convert types explicitly, as the test below does with int(...), and compare flags as text (== "yes"), never with if row["run"]:.

📄 tests/test_search_csv.py

import re

import pytest
from playwright.sync_api import Page, expect

from tests.data_loader import as_params, read_csv

SHOP = "/dummy-ecommerce-website/"


@pytest.mark.parametrize("term, min_results, name_contains", as_params(read_csv("search_cases.csv"), ["term", "min_results", "name_contains"]))
def test_search_from_csv(page: Page, term, min_results, name_contains):
    page.goto(SHOP + "#/")
    page.get_by_test_id("search-input").fill(term)
    page.get_by_test_id("search-button").click()

    cards = page.get_by_test_id("product-card")
    expect(cards.first).to_be_visible()
    assert cards.count() >= int(min_results)          # CSV gives "3"; convert before comparing
    names = page.get_by_test_id("product-name").filter(has_text=re.compile(name_contains, re.IGNORECASE))
    expect(names.first).to_be_visible()                # search also matches categories, so not every card has the word

⌨️ Terminal

pytest tests/test_search_csv.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 5 items

tests/test_search_csv.py::test_search_from_csv[chromium-earbuds] PASSED  [ 20%]
tests/test_search_csv.py::test_search_from_csv[chromium-jeans] PASSED    [ 40%]
tests/test_search_csv.py::test_search_from_csv[chromium-course] PASSED   [ 60%]
tests/test_search_csv.py::test_search_from_csv[chromium-smart-tv] PASSED [ 80%]
tests/test_search_csv.py::test_search_from_csv[chromium-not-ready] SKIPPED [100%]

======================== 4 passed, 1 skipped in 9.74s =========================

The not-ready row shows as SKIPPED with the reason “disabled in the data file”, because its run column is no.


📗 Excel Test Data with openpyxl

Excel is common when manual testers or product owners write the cases. To keep this lesson repeatable, a short script creates the workbook. In a real project someone would create it in Excel or Google Sheets and save it as .xlsx.

📄 make_coupon_workbook.py

from openpyxl import Workbook

wb = Workbook()
ws = wb.active
ws.title = "coupons"
ws.append(["id", "product", "code", "message", "discount"])
ws.append(["save10-capped", "Wireless Earbuds", "SAVE10", "Coupon SAVE10 applied.", 500])
ws.append(["flat200", "Wireless Earbuds", "FLAT200", "Coupon FLAT200 applied.", 200])
ws.append(["save10-below-minimum", "Agile Testing Handbook", "SAVE10", "Add ₹500 more to use SAVE10.", None])
ws.append(["unknown-code", "Wireless Earbuds", "BOGUS", "This coupon code is not valid.", None])
wb.save("test_data/coupon_cases.xlsx")
print("saved", ws.max_row - 1, "cases")

⌨️ Terminal

python make_coupon_workbook.py

🖥️ Output

saved 4 cases

Two Excel facts show up immediately:

  • The discount column holds numbers (500), not text, because openpyxl reads real cell types.
  • Empty cells come back as None. In this workbook None means “no discount line is shown”.

Look at the rows the loader returns:

📄 show_rows.py

from tests.data_loader import read_excel

for row in read_excel("coupon_cases.xlsx", "coupons"):
    print(row)

⌨️ Terminal

python show_rows.py

🖥️ Output

{'id': 'save10-capped', 'product': 'Wireless Earbuds', 'code': 'SAVE10', 'message': 'Coupon SAVE10 applied.', 'discount': 500}
{'id': 'flat200', 'product': 'Wireless Earbuds', 'code': 'FLAT200', 'message': 'Coupon FLAT200 applied.', 'discount': 200}
{'id': 'save10-below-minimum', 'product': 'Agile Testing Handbook', 'code': 'SAVE10', 'message': 'Add ₹500 more to use SAVE10.', 'discount': None}
{'id': 'unknown-code', 'product': 'Wireless Earbuds', 'code': 'BOGUS', 'message': 'This coupon code is not valid.', 'discount': None}

The test adds the product to the cart, applies the coupon and checks both the message and the discount line:

📄 tests/test_coupon_excel.py

import pytest
from playwright.sync_api import Page, expect

from tests.data_loader import as_params, read_excel

SHOP = "/dummy-ecommerce-website/"
CASES = as_params(read_excel("coupon_cases.xlsx", "coupons"), ["product", "code", "message", "discount"])


@pytest.mark.parametrize("product, code, message, discount", CASES)
def test_coupon_from_excel(page: Page, product, code, message, discount):
    page.goto(SHOP + "#/search/" + product)
    card = page.get_by_test_id("product-card").filter(has_text=product).first
    card.get_by_role("button", name="Add to cart").click()
    expect(page.get_by_test_id("cart-count")).to_have_text("1")

    page.goto(SHOP + "#/cart")
    page.get_by_test_id("coupon-input").fill(code)
    page.get_by_test_id("apply-coupon").click()

    expect(page.get_by_test_id("coupon-message")).to_have_text(message)
    discount_line = page.get_by_test_id("coupon-discount")
    if discount is None:
        expect(discount_line).to_have_count(0)
    else:
        expect(discount_line).to_have_text(f"−₹{discount:,}")

⌨️ Terminal

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

tests/test_coupon_excel.py::test_coupon_from_excel[chromium-save10-capped] PASSED [ 25%]
tests/test_coupon_excel.py::test_coupon_from_excel[chromium-flat200] PASSED [ 50%]
tests/test_coupon_excel.py::test_coupon_from_excel[chromium-save10-below-minimum] PASSED [ 75%]
tests/test_coupon_excel.py::test_coupon_from_excel[chromium-unknown-code] PASSED [100%]

============================== 4 passed in 8.94s ==============================

Note f"−₹{discount:,}": the store prints a real minus sign (−, not a hyphen) and Indian-style digit grouping. Copy expected text from the page, not from memory.

💡 Tip: data_only=True makes openpyxl return the calculated value of formula cells (=A2*2 gives the number) instead of the formula text. It only works if the file was last saved by Excel or LibreOffice, which store the computed values.


🛡️ Validate Rows Before the Browser Starts

A typo in a data file (usrname instead of username) should fail fast with a clear message, not 30 seconds later inside a browser. A frozen dataclass checks every row at collection time:

📄 tests/test_validated.py

from dataclasses import dataclass, fields

import pytest

from tests.data_loader import read_json


@dataclass(frozen=True)
class LoginRow:
    id: str
    username: str
    password: str
    error: str | None

    @classmethod
    def from_row(cls, row: dict) -> "LoginRow":
        expected = {f.name for f in fields(cls)}
        missing, extra = expected - row.keys(), row.keys() - expected
        if missing or extra:
            raise ValueError(f"row {row.get('id', '?')}: missing {sorted(missing)}, unexpected {sorted(extra)}")
        return cls(**row)


ROWS = [LoginRow.from_row(r) for r in read_json("login_cases.json")]


@pytest.mark.parametrize("row", ROWS, ids=lambda r: r.id)
def test_rows_are_valid(row: LoginRow):
    assert row.username or row.error, "a row with no username must expect an error"

⌨️ Terminal

pytest tests/test_validated.py -q

🖥️ Output

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

Now break the file on purpose: add a row with a misspelt key and run again.

📄 break_data.py

import json
from pathlib import Path

path = Path("test_data/login_cases_broken.json")
rows = json.loads(Path("test_data/login_cases.json").read_text(encoding="utf-8"))
rows.append({"id": "typo", "usrname": "testuser", "password": "x", "error": None})
path.write_text(json.dumps(rows, indent=1), encoding="utf-8")

from tests.test_validated import LoginRow  # noqa: E402

for r in rows:
    try:
        LoginRow.from_row(r)
    except ValueError as e:
        print("Invalid data:", e)

⌨️ Terminal

python break_data.py

🖥️ Output

Invalid data: row typo: missing ['username'], unexpected ['usrname']

The error names the row and the exact problem before any browser opens.


⚖️ Data Files: Good Practices

  1. One loader module for the whole framework, so encoding, paths and skipping work the same everywhere.
  2. An id column in every file. Readable ids are the difference between “row 37 failed” and “save10-capped failed”.
  3. Keep expected results in the data, next to the inputs.
  4. Never put real passwords or personal data in data files. Use test accounts, and read secrets from environment variables (next lesson).
  5. Prefer CSV or JSON in Git, because reviewers can see changes line by line. If business users own an Excel file, export it to CSV in CI or review it with a script.
  6. Validate rows at collection time so broken data fails in milliseconds with a clear message.

🏋️ 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 read_json call and a parametrized test that loads test_data/users.json (a list of objects with id, username and display_name) and checks that after logging in, the account button contains "Hi, " + display_name.split()[0]. Assume the password is always Test@123.

Show answer
import pytest
from playwright.sync_api import Page, expect

from tests.data_loader import as_params, read_json


@pytest.mark.parametrize("username, display_name", as_params(read_json("users.json"), ["username", "display_name"]))
def test_greeting(page: Page, username, display_name):
    page.goto("/dummy-ecommerce-website/#/login")
    page.get_by_test_id("login-username").fill(username)
    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, " + display_name.split()[0])

Exercise 2: A CSV file saved from Excel makes row["id"] raise KeyError: 'id', although the header clearly says id. What is wrong and how do you fix it?

Show answer

Excel’s “CSV UTF-8” format starts the file with a byte-order mark (BOM), so the first header is read as 'id'. Open the file with encoding="utf-8-sig", which removes the BOM:

with open(path, encoding="utf-8-sig", newline="") as f:
    rows = list(csv.DictReader(f))

Exercise 3: Your CSV has a column expected_count and a column active with values yes/no. Write the two conversions you need before using them in a test.

Show answer
count = int(row["expected_count"])               # "3" -> 3
active = row["active"].strip().lower() == "yes"  # never `if row["active"]:` - "no" is truthy

Every value from csv.DictReader is a string, so numbers and flags must be converted explicitly.

Exercise 4: Extend read_excel so it raises a clear error when a required column is missing from the header row. The function should take required: set[str].

Show answer
def read_excel(name: str, sheet: str | None = None, required: set[str] = frozenset()) -> list[dict]:
    wb = load_workbook(DATA_DIR / name, read_only=True, data_only=True)
    ws = wb[sheet] if sheet else wb.active
    rows = ws.iter_rows(values_only=True)
    header = [str(h).strip() for h in next(rows)]
    missing = required - set(header)
    if missing:
        wb.close()
        raise ValueError(f"{name}: missing columns {sorted(missing)}")
    data = [dict(zip(header, row)) for row in rows if any(v is not None for v in row)]
    wb.close()
    return data

(Remove @cache or make required a frozenset, because cached functions need hashable arguments.)


🧠 MCQ Quiz: Read Test Data from JSON, CSV and Excel

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

  1. Why build data paths with Path(__file__).resolve().parent?
  2. What type does csv.DictReader return for a cell containing 42?
  3. What does encoding="utf-8-sig" fix when reading CSV files?
  4. In openpyxl, what does an empty cell return with iter_rows(values_only=True)?
  5. What does load_workbook(..., data_only=True) do?
  6. What is the benefit of decorating a loader with functools.cache?
  7. A CSV column run contains no. Why is if row["run"]: wrong?
  8. Which format keeps nested data and real types such as booleans and null?
  9. Why validate data rows at collection time with a dataclass?
  10. Which is the best place for a real production password used by tests?

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


❓ Frequently Asked Questions

🤔 Should I use pandas to read test data?

You can, but it is a large dependency for reading a few hundred rows, and it converts types in ways that surprise testers (for example, IDs such as 007 become 7). csv, json and openpyxl are enough for test data and keep values predictable.

🤔 Can I read Google Sheets directly?

Yes, through the Google Sheets API (for example with the gspread library), but tests then depend on the network and on credentials. A safer pattern is to export the sheet to CSV in a pipeline step and commit or cache the file.

🤔 How do I read the old .xls format?

openpyxl reads only .xlsx. Save old files as .xlsx, or use the xlrd library, which still supports .xls.

🤔 Where should the data loader live?

In a shared module such as utils/data_loader.py or tests/data_loader.py, imported by every test. Lesson 57 shows a full framework folder structure.

🤔 How do I parametrize with YAML?

Install PyYAML, read the file with yaml.safe_load(f) and pass the resulting list to as_params exactly like JSON. Always use safe_load, never load, for files you did not write.


🏁 Summary

  • Use JSON for typed or nested data, CSV for flat tables in Git, Excel when business users own the cases.
  • Build paths from Path(__file__), read files once with @cache, and use utf-8-sig for CSV from Excel.
  • CSV values are strings; openpyxl returns real types and None for empty cells.
  • Turn rows into pytest.param with ids from an id column, and let a run column skip cases.
  • Validate rows at collection time so broken data fails fast and clearly.

🎬 Watch the Playwright tutorial series on YouTube!

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

Data-Driven Testing in Playwright Python with pytest parametrize

Most bugs hide in the inputs you did not try. Data-driven testing runs the same Playwright test with many sets of data, so one well-written test checks a valid login, a wrong password, a locked account and empty fields. In this lesson you will turn a single login test into a data-driven suite with @pytest.mark.parametrize, give every case a readable id, mark known failures with pytest.param, keep test data in dataclasses, combine parameters, and parametrize fixtures so the same test runs against different setups.

📖 What You’ll Learn: what data-driven testing is, a login test matrix with @pytest.mark.parametrize, readable ids, pytest.param with marks, stacking parametrize for combinations, dataclass test cases, parametrized fixtures with params=, generating cases with pytest_generate_tests, and when not to parametrize.


🧩 What Is Data-Driven Testing?

Data-driven testing separates the steps of a test from the data it uses. You write the steps once (open the login page, type a username and password, click Log in, check the result) and feed them a table of inputs and expected results.

Username Password Expected result
testuser Test@123 Logged in, header shows “Hi, Test”
testuser wrong “Invalid username or password.”
lockeduser Test@123 “This account is locked. Please contact support.”
(empty) Test@123 “Username is required.”
testuser (empty) “Password is required.”

Without data-driven tests you would copy the same test five times. With it, adding a sixth case is one more line of data.

In pytest the main tool is @pytest.mark.parametrize, which you met in Lesson 27. This lesson applies it to real browser tests and adds the techniques that matter in a Playwright framework.

📌 Note: All examples in this lesson run against SQA Shop, the dummy e-commerce website on SQA Tools. Its login page lists the test data: testuser / Test@123 (valid) and lockeduser / Test@123 (locked). Everything runs in your browser, so you can run these tests as often as you like.


🛠️ Project Setup

Create a folder with this pytest.ini. --base-url lets tests call page.goto("/dummy-ecommerce-website/") with a relative URL (the base_url option comes from the pytest-base-url plugin that pytest-playwright installs).

📄 pytest.ini

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

The store is a single-page app: its views live after the # in the URL. The login view is #/login. A small helper keeps the URL in one place:

📄 tests/shop.py

SHOP = "/dummy-ecommerce-website/"


def open_login(page):
    page.goto(SHOP + "#/login")

🔁 From One Test to a Data-Driven Test

Here is a plain test for the error message when the password is wrong:

📄 tests/test_login_single.py

from playwright.sync_api import Page, expect

from tests.shop import open_login


def test_wrong_password(page: Page):
    open_login(page)
    page.get_by_test_id("login-username").fill("testuser")
    page.get_by_test_id("login-password").fill("wrong")
    page.get_by_test_id("login-button").click()
    expect(page.get_by_test_id("login-error")).to_have_text("Invalid username or password.")

To test the other error cases you only change three values: username, password and the expected message. Move them into @pytest.mark.parametrize:

📄 tests/test_login_errors.py

import pytest
from playwright.sync_api import Page, expect

from tests.shop import open_login


@pytest.mark.parametrize(
    "username, password, message",
    [
        ("testuser", "wrong", "Invalid username or password."),
        ("nobody", "Test@123", "Invalid username or password."),
        ("lockeduser", "Test@123", "This account is locked. Please contact support."),
        ("", "Test@123", "Username is required."),
        ("testuser", "", "Password is required."),
        ("", "", "Username and password are required."),
    ],
)
def test_login_error(page: Page, username, password, message):
    open_login(page)
    page.get_by_test_id("login-username").fill(username)
    page.get_by_test_id("login-password").fill(password)
    page.get_by_test_id("login-button").click()
    expect(page.get_by_test_id("login-error")).to_have_text(message)

⌨️ Terminal

pytest tests/test_login_errors.py -v

🖥️ Output

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

tests/test_login_errors.py::test_login_error[chromium-testuser-wrong-Invalid username or password.] PASSED [ 16%]
tests/test_login_errors.py::test_login_error[chromium-nobody-Test@123-Invalid username or password.] PASSED [ 33%]
tests/test_login_errors.py::test_login_error[chromium-lockeduser-Test@123-This account is locked. Please contact support.] PASSED [ 50%]
tests/test_login_errors.py::test_login_error[chromium--Test@123-Username is required.] PASSED [ 66%]
tests/test_login_errors.py::test_login_error[chromium-testuser--Password is required.] PASSED [ 83%]
tests/test_login_errors.py::test_login_error[chromium---Username and password are required.] PASSED [100%]

============================= 6 passed in 10.40s ==============================

pytest created six tests from one function. Notice the chromium- at the start of every id: pytest-playwright parametrizes each test by browser too, so with --browser firefox --browser webkit you would get 18 tests. Each case gets a fresh page (and a fresh browser context), so a failed login in one case can never leak into the next.

💡 Tip: fill("") is valid: it clears the field. That is how the empty-field cases work without any special code.


🏷️ Readable Test IDs

The generated names such as test_login_error[testuser-wrong-Invalid username or password.] are long, and an empty string gives an ugly id like -Test@123-.... Give every case a short name with ids=:

📄 tests/test_login_ids.py

import pytest
from playwright.sync_api import Page, expect

from tests.shop import open_login

CASES = [
    ("testuser", "wrong", "Invalid username or password."),
    ("lockeduser", "Test@123", "This account is locked. Please contact support."),
    ("", "Test@123", "Username is required."),
]


@pytest.mark.parametrize("username, password, message", CASES, ids=["wrong-password", "locked-user", "empty-username"])
def test_login_error(page: Page, username, password, message):
    open_login(page)
    page.get_by_test_id("login-username").fill(username)
    page.get_by_test_id("login-password").fill(password)
    page.get_by_test_id("login-button").click()
    expect(page.get_by_test_id("login-error")).to_have_text(message)

⌨️ Terminal

pytest tests/test_login_ids.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_login_ids.py::test_login_error[chromium-wrong-password] PASSED [ 33%]
tests/test_login_ids.py::test_login_error[chromium-locked-user] PASSED   [ 66%]
tests/test_login_ids.py::test_login_error[chromium-empty-username] PASSED [100%]

============================== 3 passed in 5.36s ==============================

Now you can run one case by its id with -k:

⌨️ Terminal

pytest tests/test_login_ids.py -k locked -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 / 2 deselected / 1 selected

tests/test_login_ids.py::test_login_error[chromium-locked-user] PASSED   [100%]

======================= 1 passed, 2 deselected in 2.38s =======================

ids= also accepts a function that receives each value and returns a string (or None to keep the default). That is handy when the data has a natural name field.


🎯 pytest.param: Per-Case IDs and Marks

A list of ids must stay in the same order as the data, which is easy to break. pytest.param keeps the id next to its data, and it can carry marks such as skip or xfail for a single case:

📄 tests/test_login_param.py

import pytest
from playwright.sync_api import Page, expect

from tests.shop import open_login


@pytest.mark.parametrize(
    "username, password, message",
    [
        pytest.param("testuser", "wrong", "Invalid username or password.", id="wrong-password"),
        pytest.param("TESTUSER", "Test@123", "Invalid username or password.", id="username-is-case-sensitive"),
        pytest.param(" testuser ", "Test@123", None, id="spaces-are-trimmed"),
        pytest.param(
            "testuser", "test@123", None, id="password-case-insensitive",
            marks=pytest.mark.xfail(reason="passwords are case-sensitive by design", strict=True),
        ),
    ],
)
def test_login(page: Page, username, password, message):
    open_login(page)
    page.get_by_test_id("login-username").fill(username)
    page.get_by_test_id("login-password").fill(password)
    page.get_by_test_id("login-button").click()
    if message is None:  # None means "login should succeed"
        expect(page.get_by_test_id("account-button")).to_contain_text("Hi, Test")
    else:
        expect(page.get_by_test_id("login-error")).to_have_text(message)

⌨️ Terminal

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

tests/test_login_param.py::test_login[chromium-wrong-password] PASSED    [ 25%]
tests/test_login_param.py::test_login[chromium-username-is-case-sensitive] PASSED [ 50%]
tests/test_login_param.py::test_login[chromium-spaces-are-trimmed] PASSED [ 75%]
tests/test_login_param.py::test_login[chromium-password-case-insensitive] XFAIL [100%]

======================== 3 passed, 1 xfailed in 12.95s ========================

Read the result line by line:

  • spaces-are-trimmed passed: the app trims the username, which is a behaviour worth pinning down with a test.
  • password-case-insensitive is XFAIL: we expected it to fail, and it did. With strict=True, if someone ever made passwords case-insensitive, the test would turn into a hard FAIL (XPASS strict), which is exactly the alarm you want.

⚠️ Watch out: Keep the if message is None style for small variations only. If the two branches grow into different flows, split them into two tests: one for successful logins and one for errors. A test full of if statements is hard to read when it fails.


✖️ Combinations: Stacking parametrize

Stack two parametrize decorators and pytest runs every combination (a cross product). Here 2 search terms × 2 sort orders = 4 tests, each checking that the prices on the first results page are sorted:

📄 tests/test_search_sort.py

import re

import pytest
from playwright.sync_api import Page, expect

from tests.shop import SHOP


def prices(page: Page) -> list[int]:
    texts = page.get_by_test_id("product-price").all_inner_texts()
    return [int(re.sub(r"[^\d]", "", t)) for t in texts]


@pytest.mark.parametrize("term", ["shirt", "watch"])
@pytest.mark.parametrize("sort, reverse", [("price-asc", False), ("price-desc", True)], ids=["low-to-high", "high-to-low"])
def test_search_results_are_sorted(page: Page, term, sort, reverse):
    page.goto(SHOP + "#/search/" + term)
    expect(page.get_by_test_id("product-card").first).to_be_visible()
    page.get_by_test_id("sort-by").select_option(sort)
    expect(page.get_by_test_id("product-card").first).to_be_visible()
    found = prices(page)
    assert len(found) > 1
    assert found == sorted(found, reverse=reverse)

⌨️ Terminal

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

tests/test_search_sort.py::test_search_results_are_sorted[chromium-low-to-high-shirt] PASSED [ 25%]
tests/test_search_sort.py::test_search_results_are_sorted[chromium-low-to-high-watch] PASSED [ 50%]
tests/test_search_sort.py::test_search_results_are_sorted[chromium-high-to-low-shirt] PASSED [ 75%]
tests/test_search_sort.py::test_search_results_are_sorted[chromium-high-to-low-watch] PASSED [100%]

============================== 4 passed in 8.04s ==============================

⚠️ Watch out: Combinations grow fast: 5 browsers-worth of data × 4 × 6 is already 120 tests. Stack decorators only when every combination is a meaningful test. Otherwise list the combinations you care about in one parametrize.


📦 Test Cases as Dataclasses

Tuples are fine for three values. When a case has six or seven fields, positional tuples become hard to read and easy to get wrong. A dataclass gives every field a name, a type and an optional default:

📄 tests/test_login_cases.py

from dataclasses import dataclass

import pytest
from playwright.sync_api import Page, expect

from tests.shop import open_login


@dataclass(frozen=True)
class LoginCase:
    name: str
    username: str
    password: str = "Test@123"
    error: str | None = None          # None = the login must succeed
    remember: bool = False


CASES = [
    LoginCase("valid-user", "testuser"),
    LoginCase("valid-user-remember-me", "testuser", remember=True),
    LoginCase("locked-user", "lockeduser", error="This account is locked. Please contact support."),
    LoginCase("unknown-user", "ghost", error="Invalid username or password."),
]


@pytest.mark.parametrize("case", CASES, ids=lambda c: c.name)
def test_login(page: Page, case: LoginCase):
    open_login(page)
    page.get_by_test_id("login-username").fill(case.username)
    page.get_by_test_id("login-password").fill(case.password)
    if case.remember:
        page.get_by_test_id("remember-me").check()
    page.get_by_test_id("login-button").click()

    if case.error:
        expect(page.get_by_test_id("login-error")).to_have_text(case.error)
    else:
        expect(page.get_by_test_id("account-button")).to_contain_text("Hi, Test")
        stored = page.evaluate("localStorage.getItem('spUser')")
        assert (stored == '"testuser"') is case.remember

⌨️ Terminal

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

tests/test_login_cases.py::test_login[chromium-valid-user] PASSED        [ 25%]
tests/test_login_cases.py::test_login[chromium-valid-user-remember-me] PASSED [ 50%]
tests/test_login_cases.py::test_login[chromium-locked-user] PASSED       [ 75%]
tests/test_login_cases.py::test_login[chromium-unknown-user] PASSED      [100%]

============================== 4 passed in 7.35s ==============================

Three things make this version strong:

  1. ids=lambda c: c.name takes the id from the data itself, so ids and data can never drift apart.
  2. Defaults (password="Test@123") keep each case short: you only write what is special about it.
  3. The “remember me” case checks a real side effect: the store saves spUser in localStorage only when the box is ticked. You will use exactly this in Lesson 51 to save and reuse a login.

🧪 Parametrized Fixtures

Sometimes the setup varies rather than the inputs. A fixture with params= runs every test that uses it once per parameter. Here each test runs once for a guest and once for a logged-in shopper:

📄 tests/test_fixture_params.py

import pytest
from playwright.sync_api import Page, expect

from tests.shop import SHOP, open_login


@pytest.fixture(params=["guest", "testuser"])
def shopper(request, page: Page) -> Page:
    """A page on the store home, as a guest or after logging in."""
    if request.param != "guest":
        open_login(page)
        page.get_by_test_id("login-username").fill(request.param)
        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,")
    page.goto(SHOP + "#/")
    return page


def test_cart_starts_empty(shopper: Page):
    expect(shopper.get_by_test_id("cart-count")).to_have_text("0")


def test_add_to_cart_updates_badge(shopper: Page):
    shopper.get_by_test_id("search-input").fill("earbuds")
    shopper.get_by_test_id("search-button").click()
    shopper.get_by_role("button", name="Add to cart").first.click()
    expect(shopper.get_by_test_id("cart-count")).to_have_text("1")

⌨️ Terminal

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

tests/test_fixture_params.py::test_cart_starts_empty[guest-chromium] PASSED [ 25%]
tests/test_fixture_params.py::test_cart_starts_empty[testuser-chromium] PASSED [ 50%]
tests/test_fixture_params.py::test_add_to_cart_updates_badge[guest-chromium] PASSED [ 75%]
tests/test_fixture_params.py::test_add_to_cart_updates_badge[testuser-chromium] PASSED [100%]

============================== 4 passed in 8.60s ==============================

Two tests × two fixture params = four results. Use parametrized fixtures when many tests need to run under each setup (each user role, each locale, each environment); use @pytest.mark.parametrize when one test needs many inputs.


⚙️ Generating Cases with pytest_generate_tests

For full control, pytest calls the hook pytest_generate_tests for every test function. You can read a command-line option, a file or an environment variable and decide the parameters at collection time. This conftest.py adds a --users option:

📄 tests/conftest.py

def pytest_addoption(parser):
    parser.addoption("--users", default="testuser", help="comma-separated usernames for test_user_can_log_in")


def pytest_generate_tests(metafunc):
    if "username" in metafunc.fixturenames and metafunc.function.__name__ == "test_user_can_log_in":
        users = metafunc.config.getoption("--users").split(",")
        metafunc.parametrize("username", users, ids=users)

📄 tests/test_generated.py

from playwright.sync_api import Page, expect

from tests.shop import open_login


def test_user_can_log_in(page: Page, username):
    open_login(page)
    page.get_by_test_id("login-username").fill(username)
    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,")

⌨️ Terminal

pytest tests/test_generated.py --users testuser,lockeduser -q

🖥️ Output

.F                                                                       [100%]
================================== FAILURES ===================================
__________________ test_user_can_log_in[lockeduser-chromium] __________________

page = <Page url='https://sqatools.in/dummy-ecommerce-website/#/login'>
username = 'lockeduser'

    def test_user_can_log_in(page: Page, username):
        open_login(page)
        page.get_by_test_id("login-username").fill(username)
        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,")
E       AssertionError: Locator expected to contain text 'Hi,'
E       Actual value: Login 
E       Call log:
E         - Expect "to_contain_text" get_by_test_id("account-button") with timeout 5000ms
E         - waiting for get_by_test_id("account-button")
E           14 × locator resolved to <button type="button" class="sp-tool" id="account-btn" aria-haspopup="true" aria-expanded="false" data-testid="account-button">…</button>
E              - unexpected value "Login"
E       
E       Aria snapshot:
E       - button "Login"

tests\test_generated.py:11: AssertionError
=========================== short test summary info ===========================
FAILED tests/test_generated.py::test_user_can_log_in[lockeduser-chromium] - A...
1 failed, 1 passed in 9.86s

The lockeduser case fails, as it should: the generated test expects a successful login. In the next lesson you will use the same idea to load cases from JSON, CSV and Excel files.


✅ Good Practices for Data-Driven Tests

  1. One behaviour per test function. Parametrize the data, not the flow. Successful and failing logins are two behaviours: two functions.
  2. Always give readable ids, either with pytest.param(..., id=...) or ids=lambda case: case.name.
  3. Keep the expected result in the data. A case without an expected value is not a test case.
  4. Prefer named data (dataclasses, dictionaries) once a case has more than three fields.
  5. Watch the count. Each case starts a fresh browser context; 200 cases × 3 browsers is 600 browser tests. Test the edges in the UI and the bulk of combinations through the API (Module 9).
  6. Never share state between cases. Every case must pass when run alone with -k.

🏋️ 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 parametrized test for the SQA Shop search box. For the terms "jeans", "earbuds" and "course", search and assert that at least one product name contains the term (case-insensitive). Give each case the term as its id.

Show answer
import re

import pytest
from playwright.sync_api import Page, expect

SHOP = "/dummy-ecommerce-website/"


@pytest.mark.parametrize("term", ["jeans", "earbuds", "course"], ids=str)
def test_search_finds_term(page: Page, term):
    page.goto(SHOP + "#/")
    page.get_by_test_id("search-input").fill(term)
    page.get_by_test_id("search-button").click()
    names = page.get_by_test_id("product-name").filter(has_text=re.compile(term, re.IGNORECASE))
    expect(names.first).to_be_visible()

ids=str turns each value into its own id. Checking at least one name matters: the store’s search also matches category names, so a search for “jeans” can list “Chino Trousers” first.

Exercise 2: The test below uses a list of ids. Rewrite it with pytest.param so the id sits next to each case, and mark the "FLAT200" case on a small cart as xfail with a reason.

@pytest.mark.parametrize("code, ok", [("SAVE10", True), ("BOGUS", False), ("FLAT200", True)],
                         ids=["save10", "bogus", "flat200-small-cart"])
def test_coupon(page, code, ok): ...
Show answer
@pytest.mark.parametrize("code, ok", [
    pytest.param("SAVE10", True, id="save10"),
    pytest.param("BOGUS", False, id="bogus"),
    pytest.param("FLAT200", True, id="flat200-small-cart",
                 marks=pytest.mark.xfail(reason="FLAT200 needs a cart over ₹1,499", strict=True)),
])
def test_coupon(page, code, ok): ...

Each id now lives with its data, so reordering cases can never attach the wrong name.

Exercise 3: Model this table as a dataclass and a parametrized test: product search term, sort option value (price-asc / price-desc), and whether prices must be ascending. Use ids=lambda c: c.name.

Show answer
from dataclasses import dataclass

import pytest


@dataclass(frozen=True)
class SortCase:
    name: str
    term: str
    sort: str
    ascending: bool


CASES = [
    SortCase("shirts-cheapest-first", "shirt", "price-asc", True),
    SortCase("laptops-dearest-first", "laptop", "price-desc", False),
]


@pytest.mark.parametrize("case", CASES, ids=lambda c: c.name)
def test_sorting(page, case: SortCase):
    ...  # search case.term, select case.sort, compare prices with sorted(..., reverse=not case.ascending)

Exercise 4: You want every test in tests/test_header.py to run twice: once at desktop size (1280×720) and once at phone size (390×844). Write a parametrized fixture sized_page that sets the viewport.

Show answer
import pytest
from playwright.sync_api import Page

SIZES = {"desktop": (1280, 720), "phone": (390, 844)}


@pytest.fixture(params=list(SIZES), ids=list(SIZES))
def sized_page(request, page: Page) -> Page:
    width, height = SIZES[request.param]
    page.set_viewport_size({"width": width, "height": height})
    return page

Every test that asks for sized_page now runs once per size. For full device emulation (user agent, touch, device scale factor) see Lesson 50.


🧠 MCQ Quiz: Data-Driven Tests with parametrize

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 @pytest.mark.parametrize("a, b", [(1, 2), (3, 4)]) do?
  2. Two @pytest.mark.parametrize decorators are stacked on one test, with 3 and 4 values. How many tests run?
  3. Which is the best way to keep a case id next to its data?
  4. How do you mark only one parametrized case as an expected failure?
  5. With xfail(strict=True), what happens if the case unexpectedly passes?
  6. Does each parametrized case of a Playwright test get its own page?
  7. When should you prefer a parametrized fixture (@pytest.fixture(params=...)) over @pytest.mark.parametrize?
  8. What does ids=lambda c: c.name do?
  9. Which hook lets you decide parameters at collection time, for example from a command-line option?
  10. Why should successful and failing logins usually be two test functions instead of one test with an if?

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


❓ Frequently Asked Questions

🤔 Is data-driven testing the same as parametrization?

Parametrization is how pytest implements data-driven testing. The idea (same steps, many data rows with expected results) is tool-independent; @pytest.mark.parametrize, parametrized fixtures and pytest_generate_tests are the pytest mechanisms.

🤔 How many parameters are too many for a UI test?

There is no fixed number, but every case costs a browser context and several seconds. Keep UI cases to the meaningful edges (valid, each error type, boundaries) and push large combinatorial data sets to API tests, which run in milliseconds.

🤔 Can I parametrize with data from a file?

Yes. Load the file in a helper function and pass the result to parametrize, or use pytest_generate_tests. The next lesson shows JSON, CSV and Excel loaders step by step.

🤔 Why does my parametrized test id contain strange characters?

pytest builds ids from the values. Strings with spaces, symbols or non-ASCII characters are escaped, and empty strings make ids like -Test@123. Pass ids= or use pytest.param(..., id=...) for clean names.

🤔 Do parametrized tests run in parallel?

Not by default. Each case is a separate test, so with pytest-xdist (pytest -n 4) the cases are spread across workers automatically. Lesson 65 covers parallel runs.


🏁 Summary

  • Data-driven testing runs one set of steps with many rows of data and expected results.
  • @pytest.mark.parametrize turns one Playwright test into many; each case gets a fresh page.
  • Use ids= or pytest.param(..., id=...) for readable names, and pytest.param(..., marks=...) to skip or xfail single cases.
  • Stacked parametrize decorators create every combination; use them only when every combination matters.
  • Dataclasses give test cases names, types and defaults; parametrized fixtures vary the setup for many tests; pytest_generate_tests builds cases at collection time.

🎬 Watch the Playwright tutorial series on YouTube!

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

Playwright Test Data, Configuration and Cross-Browser Interview Questions

These Playwright test data and configuration interview questions cover what interviewers ask after “what is Playwright”: data-driven tests, environments and secrets, multiple configs, cross-browser and mobile runs. Each question is a real scenario with a step-by-step answer and TypeScript code that was run on Chromium, Firefox, WebKit and a Pixel 7 emulation against the SQA Tools practice shop. They follow Module 7 of the Playwright TypeScript tutorial.

📖 How to use this page: answer each scenario out loud first, then compare with the steps. Questions 1 to 5 suit 0 to 2 years of experience; the rest are common for 3+ years.


📊 Data-Driven Tests

Q1. Scenario: You have 30 invalid-login cases in a spreadsheet. A colleague wrote one test with a loop inside it; when case 4 fails, cases 5 to 30 never run.

What the interviewer is checking: generating one test per data row so each case passes or fails on its own.

Answer:

  1. Export the cases to JSON (or CSV) and keep them in the repo next to the tests.
  2. Loop outside test() so Playwright registers one test per row.
  3. Put the case name in the title so the report shows exactly which row failed.
  4. Each generated test runs in parallel and retries on its own.

📄 tests/data/login-cases.json and tests/login-data.spec.ts

// tests/data/login-cases.json
[
  { "case": "wrong password", "username": "testuser", "password": "wrong", "error": "Invalid username or password." },
  { "case": "locked account", "username": "lockeduser", "password": "Test@123", "error": "This account is locked. Please contact support." },
  { "case": "empty fields", "username": "", "password": "", "error": "Username and password are required." }
]

// tests/login-data.spec.ts
import { test, expect } from '@playwright/test';
import cases from './data/login-cases.json';

for (const c of cases) {
  test(`login fails: ${c.case}`, async ({ page }) => {
    await page.goto('#/login');
    await page.getByTestId('login-username').fill(c.username);
    await page.getByTestId('login-password').fill(c.password);
    await page.getByTestId('login-button').click();
    await expect(page.getByTestId('login-error')).toHaveText(c.error);
  });
}

🖥️ Output

  ok 11 [chromium] › interview\data.spec.ts:6:3 › login fails: wrong password (3.2s)
  ok 12 [chromium] › interview\data.spec.ts:6:3 › login fails: locked account (3.9s)
  ok 13 [chromium] › interview\data.spec.ts:6:3 › login fails: empty fields (3.3s)

Follow-up they may ask: How do you read a CSV instead of JSON? Read the file with fs.readFileSync and parse it with a library such as csv-parse/sync (parse(text, { columns: true })), then loop the same way. See reading CSV data in Playwright.

Red flag answer: “I loop inside one test.” One failure hides the rest, and the report shows a single result for 30 cases.

Q2. Scenario: After adding data rows, the whole suite stops before running anything, with an error about a duplicate title.

What the interviewer is checking: that you have seen this real error and know test titles must be unique in a file.

Answer:

  1. Read the error: Playwright refuses to run when two tests in one file have the same title.
  2. It happens when the loop variable is not in the title, or when two data rows are identical.
  3. Fix it by putting a unique field (case name or id) in the title, and remove duplicated rows from the data.

📄 dup.spec.ts (the mistake)

const users = ['testuser', 'testuser'];
for (const u of users) {
  test('login works', async () => {});
}

🖥️ Output

Error: duplicate test title "login works", first declared in dup.spec.ts:4

   at dup.spec.ts:4

Follow-up they may ask: Can two tests have the same title in different describe blocks? Yes. The full title includes the describe names, so describe('admin') and describe('viewer') can each contain test('login works').

Red flag answer: “Add a random number to the title.” Titles then change every run, which breaks test history, retries and --grep.

Q3. Scenario: Two parallel workers create a user with the same email, and one test fails with “email already exists” about once in five runs.

What the interviewer is checking: unique test data per worker and per retry.

Answer:

  1. Recognise the pattern: intermittent failures that disappear with --workers=1 point to shared data.
  2. Build unique values from testInfo.workerIndex, testInfo.retry and a timestamp, for example `qa+w${testInfo.workerIndex}-${Date.now()}@example.com`.
  3. Create the data in a fixture and delete it in teardown.
  4. For data that must be shared (a reference product), make it read-only for tests.

Follow-up they may ask: What is the difference between workerIndex and parallelIndex? workerIndex is unique for every worker process ever started (it grows when a worker restarts after a failure); parallelIndex is between 0 and workers-1, good for picking one of N pre-created accounts.

Red flag answer: “Turn off parallel mode.” The suite gets slower and the bug in the test design stays.


⚙️ Environments, Secrets and Config Files

Q4. Scenario: The same suite must run against QA, staging and a developer’s local server. Today the URL is hard-coded in 40 files.

What the interviewer is checking: a single source of configuration: baseURL plus environment files.

Answer:

  1. Set use.baseURL in playwright.config.ts and use relative paths in tests (page.goto('/login')).
  2. Keep one .env.qa, .env.staging file per environment and load the right one with dotenv based on a variable such as TEST_ENV.
  3. Fail fast if a required variable is missing, instead of running against undefined.
  4. In CI, set the same variables from the pipeline’s variables and secrets.

📄 playwright.config.ts

import { defineConfig } from '@playwright/test';
import dotenv from 'dotenv';

const env = process.env.TEST_ENV ?? 'qa';
dotenv.config({ path: `.env.${env}` });

if (!process.env.BASE_URL) {
  throw new Error(`BASE_URL is missing in .env.${env}`);
}

export default defineConfig({
  use: { baseURL: process.env.BASE_URL },
});

Follow-up they may ask: How do you run against staging from the command line on Windows PowerShell? Set the variable first: $env:TEST_ENV="staging"; npx playwright test. On macOS and Linux: TEST_ENV=staging npx playwright test.

Red flag answer: “I change the URL in the config before each run.” Someone will forget, and tests will run against the wrong environment.

Q5. Scenario: A test account password was found in the Git history of your automation repo.

What the interviewer is checking: secret handling, and what to do after a leak.

Answer:

  1. Treat it as leaked: ask for the password to be changed immediately. Deleting the line does not remove it from history.
  2. Move credentials to environment variables; commit only a .env.example with dummy values and add .env* to .gitignore.
  3. Store real values in the CI secret store and in a password manager for local runs.
  4. Add a secret scanner (for example GitHub secret scanning or gitleaks) to the pipeline.
  5. Mask secrets in reports: avoid logging them and do not put them in test titles.

Follow-up they may ask: Can secrets still leak into the Playwright HTML report? Yes. fill() steps, traces and screenshots can contain them. Use dedicated low-privilege test accounts, and do not publish traces from production-like environments publicly.

Red flag answer: “It is only a test account.” Test accounts often have real access to shared environments.

Q6. Scenario: Smoke tests should run in 2 minutes on every commit with no retries; the nightly regression needs 3 browsers, retries and video.

What the interviewer is checking: using multiple config files that share one base instead of copy-paste.

Answer:

  1. Keep shared settings in playwright.config.ts (base URL, reporters, timeouts).
  2. Create playwright.smoke.config.ts that imports the base and overrides grep, retries and projects.
  3. Run with npx playwright test -c playwright.smoke.config.ts.
  4. Alternatively, use one config with different projects and pick with --project.

📄 playwright.smoke.config.ts

import { defineConfig, devices } from '@playwright/test';
import base from './playwright.config';

export default defineConfig({
  ...base,
  grep: /@smoke/,
  retries: 0,
  use: { ...base.use, video: 'off' },
  projects: [{ name: 'chromium', use: { ...devices['Desktop Chrome'] } }],
});

Follow-up they may ask: Why spread base.use instead of replacing it? Replacing use drops the shared baseURL and other options; spreading keeps them and changes only what you list.

Red flag answer: “We keep two full copies of the config.” They drift apart within weeks.

Q7. Scenario: Admin and viewer users need to run the same tests with different credentials and expected permissions.

What the interviewer is checking: custom options: values set per project and read in fixtures.

Answer:

  1. Declare an option fixture with { option: true }, for example role.
  2. Create one project per role in the config and set use: { role: 'admin' }.
  3. Read role in a fixture that logs in as that user, and in tests that expect different outcomes.
  4. The report then shows each test once per role, labelled with the project name.

📄 fixtures/role.ts

import { test as base } from '@playwright/test';

export type Role = 'admin' | 'viewer';
export const test = base.extend<{ role: Role }>({
  role: ['viewer', { option: true }],
});

// playwright.config.ts
// projects: [
//   { name: 'admin',  use: { role: 'admin' } },
//   { name: 'viewer', use: { role: 'viewer' } },
// ]

Follow-up they may ask: How is this different from reading process.env.ROLE? Options are typed, visible in the config, and let both roles run in the same command; an environment variable gives one role per run.

Red flag answer: “I duplicate the test files for each role.”


🌐 Cross-Browser and Mobile

Q8. Scenario: A checkout test passes in Chromium and Firefox but fails only in WebKit. The release is tomorrow.

What the interviewer is checking: a calm, evidence-based process for browser-specific failures.

Answer:

  1. Reproduce with npx playwright test --project=webkit --headed and open the trace.
  2. Decide whether it is an app bug (real Safari users are affected) or a test issue (timing, a locator that depends on layout).
  3. If it is an app bug, raise it with the trace and keep the test failing or mark it test.fail() with the ticket number.
  4. If it is a known issue the team accepts, skip it only for that browser with a reason, so it still runs elsewhere.
  5. Remember WebKit in Playwright is close to Safari but not identical; confirm important bugs on a real Safari.

📄 tests/search.spec.ts

test('search works in every browser', async ({ page, browserName }) => {
  test.skip(browserName === 'webkit' && !!process.env.SKIP_WEBKIT, 'Known WebKit issue: JIRA-123');
  await page.goto('');
  await page.getByTestId('search-input').fill('earbuds');
  await page.getByTestId('search-button').click();
  await expect(page.getByTestId('result-count')).toContainText('1 product');
});

Follow-up they may ask: What is the difference between test.skip, test.fixme and test.fail? skip does not run the test; fixme also skips it but marks it as needing a fix; fail runs it and expects it to fail, so you notice when the bug is fixed.

Red flag answer: “Remove WebKit from the config.” You stop testing a browser your users use.

Q9. Scenario: Your app shows prices in Indian format and dates in local time. Tests pass in India and fail on the CI server in the US.

What the interviewer is checking: controlling locale and time zone instead of depending on the machine.

Answer:

  1. Set locale and timezoneId in the config or with test.use(), so every machine behaves the same.
  2. Verify what the browser actually reports, then assert the formatted values.
  3. Add a second project with another locale if the product supports it.
  4. Watch the browser differences: Chromium reports the old name Asia/Calcutta for Asia/Kolkata, so do not assert the zone name exactly.

📄 tests/locale.spec.ts

test.describe('Indian locale', () => {
  test.use({ locale: 'en-IN', timezoneId: 'Asia/Kolkata' });
  test('browser reports the emulated locale and time zone', async ({ page }) => {
    await page.goto('');
    const env = await page.evaluate(() => ({
      lang: navigator.language,
      tz: Intl.DateTimeFormat().resolvedOptions().timeZone,
      price: new Intl.NumberFormat(navigator.language).format(119399),
    }));
    expect(env.lang).toBe('en-IN');
    expect(env.price).toBe('1,19,399');
    // Chromium reports the old ICU name Asia/Calcutta; Firefox and WebKit say Asia/Kolkata
    expect(env.tz).toMatch(/^Asia\/(Kolkata|Calcutta)$/);
  });
});

🖥️ Output

  ok 15 [chromium] › interview\data.spec.ts:27:3 › Indian locale › browser reports the emulated locale and time zone
  ok 20 [firefox] › interview\data.spec.ts:27:3 › Indian locale › browser reports the emulated locale and time zone
  ok 25 [webkit] › interview\data.spec.ts:27:3 › Indian locale › browser reports the emulated locale and time zone

Follow-up they may ask: What did the first version of this test do in Chromium? It asserted tz: 'Asia/Kolkata' and failed with + "tz": "Asia/Calcutta". Both names are the same zone; the fix is the regular expression above.

Red flag answer: “Set the CI server’s time zone to India.” The next server or developer will break it again.

Q10. Scenario: Product asks for mobile coverage. A teammate suggests just setting a small viewport.

What the interviewer is checking: knowing what device emulation includes, and its limits.

Answer:

  1. Use a device descriptor such as devices['Pixel 7']: it sets viewport, device scale factor, user agent, isMobile and touch, not only the size.
  2. Add it as a project so the same tests run on desktop and mobile, or write mobile-only tests for different layouts.
  3. Test what really changes on phones: menus, collapsed filters, sticky buttons, touch targets.
  4. Be clear about the limits: emulation runs desktop browser engines, so use real devices or a device cloud for final checks.

📄 tests/mobile-filters.spec.ts

// playwright.config.ts → projects: [{ name: 'mobile-chrome', use: { ...devices['Pixel 7'] } }]

test('filters open from the Filters button on a phone', async ({ page, isMobile }) => {
  expect(isMobile).toBe(true);
  await page.goto('');
  const toggle = page.getByRole('button', { name: 'Filters' });
  await expect(toggle).toBeVisible();
  await expect(page.getByTestId('apply-price')).toBeHidden();
  await toggle.click();
  await expect(page.getByTestId('apply-price')).toBeVisible();
});

🖥️ Output

  ok 26 [mobile-chrome] › interview\mobile.spec.ts:4:1 › filters open from the Filters button on a phone (2.4s)

Follow-up they may ask: Can Playwright test a native Android app? No. It tests web apps in mobile browsers (and has experimental Android Chrome support over ADB). Native apps need tools like Appium.

Red flag answer: “Mobile testing is just a small viewport.”

Q11. Scenario: Running 3 browsers tripled CI time to 45 minutes. The team wants to drop Firefox and WebKit.

What the interviewer is checking: balancing coverage and speed with data, not removing coverage.

Answer:

  1. Check analytics: which browsers do your users actually use?
  2. Run the full suite on Chromium on every pull request, and the cross-browser projects nightly or before release.
  3. Tag a small @cross-browser subset (rendering, forms, uploads, dates) to run on all browsers per pull request.
  4. Shard the nightly run across machines with --shard=1/3 and merge the reports.

Follow-up they may ask: How do you run one project only? npx playwright test --project=firefox. You can pass --project several times.

Red flag answer: “Browsers are all the same now, Chromium is enough.”


❓ Frequently Asked Questions

🤔 How do I run Playwright tests with different data?

Loop over the data outside test() and put a unique value in each title, so every row becomes its own test. Data can come from JSON, CSV, Excel or an API.

🤔 How do I use environment variables in Playwright?

Read them with process.env.NAME. Load a .env file with dotenv at the top of playwright.config.ts, and set the same variables as secrets in CI.

🤔 How do I run Playwright tests in all browsers?

Define one project per browser in the config (devices['Desktop Chrome'], 'Desktop Firefox', 'Desktop Safari') and run npx playwright test. Install browsers with npx playwright install.

🤔 Is Playwright mobile emulation enough for mobile testing?

It is good for layout and behaviour of responsive web apps, and fast enough for every build. It is not a real device, so confirm critical flows on real phones or a device cloud.


🔗 More Playwright Interview Preparation

🎬 Watch the full Playwright tutorial series on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

Playwright API Testing Interview Questions (Scenario-Based, TypeScript)

These Playwright API testing interview questions are real situations an interviewer gives you, not definitions to memorise. Each answer shows how to investigate and fix the problem step by step, with TypeScript code that was run against the free SQA Tools practice REST API. They follow Module 9 of the Playwright TypeScript tutorial.

📖 How to use this page: read the scenario, answer it out loud in 60 to 90 seconds, then compare with the steps. The follow-up and red-flag lines show where interviewers push and where candidates lose marks.


🧪 API Test Design and Assertions

Q1. Scenario: You are asked to automate a create-update-delete flow for an /objects endpoint. The manual testers only check that each call returns 2xx.

What the interviewer is checking: whether you test the whole resource lifecycle and the data, not just status codes.

Answer:

  1. Create the object with a unique name so parallel runs never collide.
  2. Assert 201 and the Location header that points to the new resource.
  3. Update one field and assert the response contains the new value.
  4. Delete it and accept the documented success code (200 or 204).
  5. Prove the delete worked: a GET on the same id must now return 404.

📄 tests/api/objects.spec.ts

import { test, expect } from '@playwright/test';

const API = 'https://sqatools.in/wp-json/sqa-api/v1';

test('object CRUD lifecycle', async ({ request }) => {
  const created = await request.post(`${API}/objects`, {
    data: { name: `pw-crud-${Date.now()}`, data: { price: 10 } },
  });
  expect(created.status()).toBe(201);
  const obj = await created.json();
  expect(created.headers()['location']).toContain(`/objects/${obj.id}`);

  const patched = await request.patch(`${API}/objects/${obj.id}`, { data: { data: { price: 12 } } });
  expect(patched.ok()).toBeTruthy();
  expect((await patched.json()).data.price).toBe(12);

  const deleted = await request.delete(`${API}/objects/${obj.id}`);
  expect([200, 204]).toContain(deleted.status());

  const gone = await request.get(`${API}/objects/${obj.id}`);
  expect(gone.status()).toBe(404);
});

Follow-up they may ask: Why not reuse one fixed object id for all tests? Shared data couples tests: one failure or a parallel worker changes the state for every other test. Each test should create and own its data.

Red flag answer: “I check that every call returns 200.” That misses wrong bodies, wrong codes like 200 instead of 201, and deletes that silently do nothing.

Q2. Scenario: A backend change renamed email to emailAddress. All your API tests still passed, and the UI broke in production.

What the interviewer is checking: contract thinking: asserting the shape and types of the response, not just one or two values.

Answer:

  1. Explain why the tests passed: they checked the status and maybe id, never the full shape.
  2. Assert the fields consumers depend on with toMatchObject and asymmetric matchers such as expect.any(String).
  3. For wide coverage, validate against a JSON Schema (the practice API publishes them at /schema/{name}) with a library like Ajv.
  4. Agree with the backend team on contract tests in their pipeline so renames are caught before deploy.

📄 tests/api/users.spec.ts

test('user has the expected shape', async ({ request }) => {
  const res = await request.get(`${API}/users/1`);
  expect(res.status()).toBe(200);
  const { data } = await res.json();
  expect(data).toMatchObject({
    id: 1,
    username: 'asha',
    email: expect.stringContaining('@'),
    role: expect.any(String),
    active: expect.any(Boolean),
  });
});

Follow-up they may ask: Why toMatchObject and not toEqual? toEqual fails when the API adds a new optional field, which is not a breaking change. toMatchObject checks only the fields you list.

Red flag answer: “We compare the whole response to a saved JSON file.” That breaks on every timestamp or new field and trains the team to ignore failures.

Q3. Scenario: The product owner says error responses are “random”. Mobile developers cannot show proper messages to users.

What the interviewer is checking: that you treat error responses as part of the contract and test them as carefully as success paths.

Answer:

  1. List the documented errors: 400 invalid input, 401 no credentials, 403 not allowed, 404 not found, 422 validation, 429 rate limit.
  2. Write one test per error that checks the status, the machine-readable code and the message.
  3. For validation, send several bad fields at once and check that every field is reported, not just the first.

📄 tests/api/errors.spec.ts

test('unknown user returns a clear 404', async ({ request }) => {
  const res = await request.get(`${API}/users/999`);
  expect(res.status()).toBe(404);
  expect(await res.json()).toEqual({
    error: { status: 404, code: 'not_found', message: 'User 999 does not exist. Valid ids are 1 to 12.' },
  });
});

test('invalid user payload lists every field error', async ({ request }) => {
  const res = await request.post(`${API}/validate/user`, { data: { name: '', email: 'not-an-email', age: -1 } });
  expect(res.status()).toBe(422);
  const body = await res.json();
  console.log(JSON.stringify(body));
  expect(body.error.code).toBe('validation_failed');
});

🖥️ Output

{"error":{"status":422,"code":"validation_failed","message":"3 field(s) failed validation.","details":[{"field":"name","message":"name is required: text of 2 to 50 characters."},{"field":"email","message":"email is required and must be a valid email address."},{"field":"age","message":"age is required: a whole number from 18 to 100 (not a string)."}]}}

Follow-up they may ask: Would you assert the exact error message text? Assert the stable code always; assert the message only when it is shown to users or documented, because wording changes are common.

Red flag answer: “Negative testing is just checking for 500 errors.” A 500 is a bug; the interesting cases are the correct 4xx responses.

Q4. Scenario: A product listing supports category, sort and order parameters. A bug made order=asc return items in database order.

What the interviewer is checking: whether you assert the behaviour a parameter promises (filtering, ordering), not just that the call succeeds.

Answer:

  1. Pass parameters with the params option, so Playwright encodes them correctly.
  2. Check the filter: every item must have the requested category.
  3. Check the order: compare the returned list with a sorted copy.
  4. Add one invalid value to prove the API rejects it with 400 and names the field.

📄 tests/api/products.spec.ts

test('electronics sorted by price, cheapest first', async ({ request }) => {
  const res = await request.get(`${API}/products`, {
    params: { category: 'electronics', sort: 'price', order: 'asc' },
  });
  expect(res.status()).toBe(200);
  const { data } = await res.json();
  const prices = data.map((p: { price: number }) => p.price);
  expect(data.every((p: { category: string }) => p.category === 'electronics')).toBe(true);
  expect(prices).toEqual([...prices].sort((a, b) => a - b));
});

test('an invalid filter value returns 400 with details', async ({ request }) => {
  const res = await request.get(`${API}/products`, { params: { category: 'audio' } });
  expect(res.status()).toBe(400);
  const body = await res.json();
  expect(body.error.code).toBe('invalid_parameter');
  expect(body.error.details[0].field).toBe('category');
});

Follow-up they may ask: How would you test pagination? Request page 1 and page 2 with the same page size and assert there is no overlap and no gap in ids, plus the total-count header if the API provides one.

Red flag answer: “I check the first item only.” The bug is usually in the middle or the last page.


🔐 Authentication and Authorisation

Q5. Scenario: Every API test logs in first, so the suite takes 6 minutes and sometimes hits the login rate limit.

What the interviewer is checking: fixture design: logging in once and reusing a ready, authenticated request context.

Answer:

  1. Move login into a fixture that returns an APIRequestContext with the Authorization header already set.
  2. Create one fixture per role (admin, viewer) so tests ask for the role they need by name.
  3. If tokens are long-lived, make the fixture worker-scoped so each worker logs in once.
  4. Dispose contexts in the fixture teardown to avoid leaking connections.

📄 tests/api/auth.spec.ts

import { test as base, expect, request as pwRequest, APIRequestContext } from '@playwright/test';

const API = 'https://sqatools.in/wp-json/sqa-api/v1';

type ApiFixtures = { adminApi: APIRequestContext; viewerApi: APIRequestContext; tempObject: { id: string } };
async function loginAs(username: string, password: string) {
  const anon = await pwRequest.newContext();
  const res = await anon.post(`${API}/auth/login`, { data: { username, password } });
  expect(res.ok()).toBeTruthy();
  const { access_token } = await res.json();
  await anon.dispose();
  return pwRequest.newContext({ extraHTTPHeaders: { Authorization: `Bearer ${access_token}` } });
}
const test = base.extend<ApiFixtures, { adminToken: string }>({
  adminApi: async ({}, use) => {
    const ctx = await loginAs('admin', 'admin@123');
    await use(ctx);
    await ctx.dispose();
  },
  viewerApi: async ({}, use) => {
    const ctx = await loginAs('viewer', 'viewer@123');
    await use(ctx);
    await ctx.dispose();
  },
  tempObject: async ({ adminApi }, use, testInfo) => {
    const res = await adminApi.post(`${API}/token/objects`, {
      data: { name: `pw-${testInfo.workerIndex}-${Date.now()}` },
    });
    const obj = await res.json();
    await use(obj);
    await adminApi.delete(`${API}/token/objects/${obj.id}`); // cleanup even if the test failed
  },
});

test('viewer can read but not delete', async ({ viewerApi, tempObject }) => {
  expect((await viewerApi.get(`${API}/token/objects/${tempObject.id}`)).status()).toBe(200);
  const del = await viewerApi.delete(`${API}/token/objects/${tempObject.id}`);
  expect(del.status()).toBe(403);
});

test('token identifies the user', async ({ adminApi }) => {
  const me = await (await adminApi.get(`${API}/auth/me`)).json();
  console.log(JSON.stringify(me));
  expect(JSON.stringify(me)).toContain('admin');
});

🖥️ Output

{"data":{"username":"admin","name":"Admin User","role":"admin","issued_at":"2026-11-24T05:20:16Z","expires_at":"2026-11-24T05:35:16Z","can_write":true}}

Follow-up they may ask: The token expires after 15 minutes. What happens in a 40-minute run? Keep the fixture test-scoped (a fresh token per test, as above), or refresh it when a request returns 401. The practice API has /auth/refresh for exactly this.

Red flag answer: “I hard-code a token copied from Postman.” It expires, leaks in Git, and hides login bugs.

Q6. Scenario: A security review finds that read-only users can delete records through the API, although the UI hides the Delete button.

What the interviewer is checking: that you test authorisation on the server, per role, and not only through the UI.

Answer:

  1. Explain that hiding a button is not security; the API must refuse the call.
  2. Create test data as an admin in a fixture, then call the write endpoint as the viewer.
  3. Assert 403 (authenticated but not allowed), not 401 (not authenticated).
  4. Turn this into a role-by-endpoint matrix and run it on every build.

📄 tests/api/auth.spec.ts (uses the fixtures above)

test('viewer can read but not delete', async ({ viewerApi, tempObject }) => {
  expect((await viewerApi.get(`${API}/token/objects/${tempObject.id}`)).status()).toBe(200);
  const del = await viewerApi.delete(`${API}/token/objects/${tempObject.id}`);
  expect(del.status()).toBe(403);
});

Follow-up they may ask: What is the difference between 401 and 403? 401 means “who are you?”: missing or invalid credentials. 403 means “I know who you are, and you may not do this.”

Red flag answer: “The UI does not allow it, so it is covered by UI tests.”

Q7. Scenario: Your service supports HTTP Basic auth for partners and an API key for internal tools. You need tests for both, plus a test that a missing key is rejected.

What the interviewer is checking: knowledge of request.newContext() options for different auth types.

Answer:

  1. Use httpCredentials for Basic auth; Playwright builds the header for you.
  2. Use extraHTTPHeaders for an API key or any custom header.
  3. Always include the negative case: no credentials must return 401.
  4. Keep credentials in environment variables in real projects; these are public practice values.

📄 tests/api/auth-types.spec.ts

import { test, expect, request as pwRequest } from '@playwright/test';

const API = 'https://sqatools.in/wp-json/sqa-api/v1';

test('basic auth and API key', async () => {
  const basic = await pwRequest.newContext({ httpCredentials: { username: 'sqa_user', password: 'sqa@123' } });
  expect((await basic.get(`${API}/basic/profile`)).status()).toBe(200);
  const keyed = await pwRequest.newContext({ extraHTTPHeaders: { 'X-API-Key': 'sqa-key-12345' } });
  expect((await keyed.get(`${API}/apikey/profile`)).status()).toBe(200);
  const noKey = await pwRequest.newContext();
  expect((await noKey.get(`${API}/apikey/profile`)).status()).toBe(401);
  await Promise.all([basic.dispose(), keyed.dispose(), noKey.dispose()]);
});

Follow-up they may ask: How do you share an API login with UI tests? After logging in with request, call request.storageState({ path }) and load that file in the browser context with storageState, if the app uses cookies.

Red flag answer: “I put the password in the test file.” Secrets belong in CI secrets and .env files that are not committed.


⏱️ Timeouts, Caching and Reliability

Q8. Scenario: One slow endpoint sometimes takes 40 seconds. When it does, the whole test times out and the report says nothing useful.

What the interviewer is checking: whether you set request-level timeouts and make the failure message point at the real cause.

Answer:

  1. Set a per-request timeout that matches the service level agreement, for example 2 seconds.
  2. Assert the timeout explicitly in a test for the slow path, so the report names the slow call.
  3. Log the response time header (X-Response-Time here) for trend tracking.
  4. Raise it with the backend team as a performance bug; do not just raise the test timeout.

📄 tests/api/timeouts.spec.ts

test('a slow endpoint fails fast with a per-request timeout', async ({ request }) => {
  await expect(request.get(`${API}/delay/5`, { timeout: 2000 })).rejects.toThrow(/Timeout 2000ms exceeded/);
});

Follow-up they may ask: Where else can you set API timeouts? In request.newContext({ timeout }) for a whole context, or use.actionTimeout in the config. The per-call option wins.

Red flag answer: “I increase the test timeout to 2 minutes.” The suite gets slower and the slow endpoint is never fixed.

Q9. Scenario: The API team added ETags to cut bandwidth. You are asked to prove caching works.

What the interviewer is checking: HTTP knowledge beyond status 200: conditional requests and 304.

Answer:

  1. Make a first GET and read the ETag header.
  2. Repeat the GET with If-None-Match set to that value.
  3. Assert 304 Not Modified with no body.
  4. Update the resource, then prove the old ETag now returns 200 with a new ETag.

📄 tests/api/etag.spec.ts

test('ETag returns 304 when nothing changed', async ({ request }) => {
  const first = await request.get(`${API}/products/101`);
  const etag = first.headers()['etag'];
  expect(etag).toBeTruthy();
  const second = await request.get(`${API}/products/101`, { headers: { 'If-None-Match': etag } });
  expect(second.status()).toBe(304);
});

Follow-up they may ask: Why might the ETag header be missing in your test but present in Postman? A proxy or CDN may strip or rewrite it, or you hit a different URL (for example an id that does not exist returns 404 without an ETag). Print response.headers() and the status first.

Red flag answer: “304 is an error code.”

Q10. Scenario: Your API tests pass on your laptop, but every request returns 403 with an HTML page in CI.

What the interviewer is checking: debugging from evidence: reading the body and headers, and knowing about firewalls and CDNs in front of APIs.

Answer:

  1. Print the status, headers and the first part of the body. An HTML 403 page means something in front of the API answered, not the API itself (which returns JSON).
  2. Check the headers for the proxy, WAF or CDN name (for example server or a request-id header).
  3. Compare what differs in CI: IP range, missing VPN, user agent, or a query pattern the firewall blocks.
  4. Fix it at the source: allow-list the CI runners or the endpoint pattern with the platform team. Do not fake a browser user agent to sneak past security.

Follow-up they may ask: How do you make this failure obvious next time? Assert the content-type is JSON before calling response.json(), so the error says “got text/html” instead of “Unexpected token <“.

Red flag answer: “I add retries.” A firewall block will fail on every retry.

⚠️ Watch out: Calling response.json() on an HTML error page throws SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON. When you see that error, the request reached the wrong thing: read await response.text() to see what answered.


🏗️ Framework Design for API Tests

Q11. Scenario: Tests running in parallel delete each other’s data, and the shared test environment fills up with thousands of leftover records.

What the interviewer is checking: test data ownership and cleanup that runs even when a test fails.

Answer:

  1. Each test creates its own data with a unique name (worker index plus timestamp).
  2. Create the data in a fixture, and delete it after use(): fixture teardown runs even if the test fails.
  3. Never depend on data created by another test or on test order.
  4. Add a nightly job that removes anything older than a day with your test prefix, as a safety net.

📄 tempObject fixture (from tests/api/auth.spec.ts above)

  tempObject: async ({ adminApi }, use, testInfo) => {
    const res = await adminApi.post(`${API}/token/objects`, {
      data: { name: `pw-${testInfo.workerIndex}-${Date.now()}` },
    });
    const obj = await res.json();
    await use(obj);
    await adminApi.delete(`${API}/token/objects/${obj.id}`); // cleanup even if the test failed
  },

Follow-up they may ask: Why not clean up in afterEach? It works, but a fixture keeps setup and cleanup together, runs only for tests that use it, and can be shared across files.

Red flag answer: “We reset the database before the run.” That does not stop parallel workers clashing during the run.

Q12. Scenario: Your manager asks why you use Playwright for API tests instead of a separate tool like Postman or REST Assured.

What the interviewer is checking: a balanced view of tool choice, not tool loyalty.

Answer:

  1. One language, one runner and one report for UI and API tests, so the team maintains one framework.
  2. API calls can prepare data for UI tests (create a user, then log in through the UI) in the same test.
  3. Built-in retries, parallel workers, traces and CI integration already exist.
  4. Be honest about limits: Postman is better for exploratory checks and sharing collections; dedicated tools are better for load testing.

Follow-up they may ask: What is APIRequestContext? Playwright’s HTTP client. The built-in request fixture gives you one per test that uses the config’s baseURL and extraHTTPHeaders; request.newContext() creates extra ones with their own settings.

Red flag answer: “Playwright is a UI tool, so API tests are a workaround.”

Q13. Scenario: A UI test for “order history” is slow and flaky because it first places three orders through the checkout UI.

What the interviewer is checking: hybrid tests: using the API for setup and the UI only for what you are testing.

Answer:

  1. Create the three orders through the API in a fixture: seconds instead of minutes.
  2. Log in with saved storage state, then open only the order history page in the UI.
  3. Assert in the UI what the user sees, and optionally cross-check totals against the API response.
  4. Keep one separate end-to-end checkout test so the full UI flow is still covered once.

Follow-up they may ask: When would you mock the API instead of calling it? With page.route() when you need states that are hard to create (empty list, server error, slow response) or when the backend is not ready. Never mock in the one test that proves the integration works.

Red flag answer: “Every test should go through the UI because that is what users do.”


❓ Frequently Asked Questions

🤔 Can Playwright be used only for API testing?

Yes. Tests that use only the request fixture never start a browser, so a pure API suite runs fast and needs no browser download in CI beyond the Playwright package.

🤔 How do I send query parameters with Playwright request?

Use the params option, for example request.get(url, { params: { category: 'electronics' } }). Playwright encodes the values for you.

🤔 How do I validate a JSON schema in Playwright?

Playwright has no built-in schema validator. Fetch or store the schema, compile it with a library such as Ajv, and assert that validate(body) is true, printing validate.errors on failure.

🤔 Where can I practise Playwright API testing for free?

Use the SQA Tools practice REST API: users, products, orders, temporary objects you can create and delete, and Basic, API key and Bearer token auth.


🔗 More Playwright Interview Preparation

🎬 Watch the full Playwright tutorial series on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

Retries and Flaky Tests in Playwright Python with pytest-rerunfailures

A flaky test passes on one run and fails on the next, with no change in the code. Flaky tests destroy trust in a test suite: people stop believing red builds. The Playwright TypeScript runner has retries built in; in Python, the pytest-rerunfailures plugin provides them. In this lesson you will learn what makes Playwright tests flaky and how to fix the cause, then use retries correctly: –reruns, delays, the flaky marker, rerunning only specific errors, failing the build on flaky passes, artifacts per attempt, and finding flaky tests with pytest-repeat.

📖 What You’ll Learn: what a flaky test is and why it matters, common causes in browser tests and their fixes, installing pytest-rerunfailures, –reruns and the R progress letter, –reruns-delay, the flaky marker, –only-rerun and –rerun-except, why expect() timeouts are AssertionErrors, –fail-on-flaky, reruns in pytest.ini, screenshots and traces for each attempt, and repeating tests with pytest-repeat to expose flakiness.


🎲 What Is a Flaky Test?

A flaky test gives different results on different runs of the same code: green on your laptop, red in CI, green again when someone clicks “re-run”. It is one of the most expensive problems in test automation:

  • Real bugs hide among the “probably flaky again” failures.
  • Teams waste hours re-running pipelines and investigating ghosts.
  • People stop trusting the suite, and a suite nobody trusts is worth nothing.

A real example from this course: while Lesson 42 was being prepared, about one in six navigations to the public SauceDemo site stalled for more than 30 seconds, and the same unchanged tests failed with Page.goto: Timeout 30000ms exceeded in some runs and passed in others.


🔍 Common Causes and Their Real Fixes

Retries hide symptoms. Before you add them, look for the cause:

CauseSymptomReal fix
Checking too earlyPasses locally, fails on slow CIUse expect() assertions, never time.sleep() or one-shot reads like inner_text() (Module 5)
Shared state between testsFails only in a certain order or in parallelFresh context per test (the default), unique test data, no module-level globals
Animations and transitionsClicks land on a moving elementLet actionability checks work; disable animations for screenshots
Dependence on live third-party servicesRandom timeoutsMock the network (Module 8), or use a stable test environment
Dates, times and random dataFails around midnight or on certain valuesFix the time zone with timezone_id, control test data
Fragile locatorsFails after small UI changes or with A/B testsRole-based locators and test ids (Module 4)
Too-short timeoutsFails under loadTimeouts based on real requirements, not guesses

💡 Tip: The Trace Viewer (Module 5) is the best tool for flaky failures: run CI with --tracing retain-on-failure and compare the trace of a failed attempt with a passing one.


🔁 Retries with pytest-rerunfailures

Install the plugin:

⌨️ Terminal

pip install pytest-rerunfailures

This lesson uses version 16.7. To make the demonstrations repeatable, the test below simulates a flaky server. It shows a search result after a delay: 6 seconds on the first attempt (longer than expect()‘s 5-second timeout) and 1 second on later attempts. pytest-rerunfailures numbers the attempts in request.node.execution_count (1, 2, 3, …).

📄 flaky/test_flaky.py

from playwright.sync_api import Page, expect

RESULT_PAGE = """
<p id="result">Searching...</p>
<script>
  setTimeout(() => document.getElementById('result').textContent = '3 products found', {delay});
</script>
"""


def test_search_results(page: Page, request):
    attempt = getattr(request.node, "execution_count", 1)   # 1 = first try, 2 = first retry, ...
    delay = 6_000 if attempt == 1 else 1_000                # simulated slow server on the first try
    page.set_content(RESULT_PAGE.replace("{delay}", str(delay)))

    expect(page.locator("#result")).to_have_text("3 products found")
  • getattr(..., 1) returns 1 when the plugin is not active, so the test also runs without it.
  • In a real suite the delay comes from the server, not from your test. The simulation only makes the behaviour predictable for this lesson.

Without retries, the first attempt fails:

⌨️ Terminal

pytest -q flaky

🖥️ Output

F                                                                        [100%]
================================== FAILURES ===================================
________________________ test_search_results[chromium] ________________________

page = <Page url='about:blank'>
request = <FixtureRequest for <Function test_search_results[chromium]>>

    def test_search_results(page: Page, request):
        attempt = getattr(request.node, "execution_count", 1)   # 1 = first try, 2 = first retry, ...
        delay = 6_000 if attempt == 1 else 1_000                # simulated slow server on the first try
        page.set_content(RESULT_PAGE.replace("{delay}", str(delay)))
    
>       expect(page.locator("#result")).to_have_text("3 products found")
E       AssertionError: Locator expected to have text '3 products found'
E       Actual value: Searching... 
E       Call log:
E         - Expect "to_have_text" locator("#result") with timeout 5000ms
E         - waiting for locator("#result")
E           14 × locator resolved to <p id="result">Searching...</p>
E              - unexpected value "Searching..."
E       
E       Aria snapshot:
E       - paragraph: Searching...

flaky\test_flaky.py:16: AssertionError
=========================== short test summary info ===========================
FAILED flaky/test_flaky.py::test_search_results[chromium] - AssertionError: L...
1 failed, 1 warning in 5.56s

With retries, --reruns 2 allows up to two more attempts for a failed test:

⌨️ Terminal

pytest -q -rR flaky --reruns 2

🖥️ Output

R.                                                                       [100%]
=========================== rerun test summary info ===========================
RERUN flaky/test_flaky.py::test_search_results[chromium]
PASSED flaky/test_flaky.py::test_search_results[chromium]
1 passed, 1 warning, 1 rerun in 6.95s
  • R in the progress line means “failed, then rerun”; the final . is the passing attempt.
  • The summary counts reruns separately: 1 passed, 1 rerun. The run’s exit code is 0.
  • -rR adds the “rerun test summary info” section that lists which tests needed a rerun. Keep an eye on this list: every entry is a flaky test to investigate.
  • Each attempt runs the test’s fixtures again: a new context and a new page.

⚙️ Retry Options

OptionMeaning
--reruns NRerun a failed test up to N times
--reruns-delay SWait S seconds before each rerun (for example, to let a service recover)
--only-rerun REGEXRerun only failures whose error matches the regex; repeatable
--rerun-except REGEXDo not rerun failures that match the regex; repeatable
--fail-on-flakyFail the run with exit code 7 if any test passed only after a rerun
--max-suite-reruns NLimit the total number of reruns in the whole run
--force-reruns NUse N reruns for every test, ignoring markers

The same settings work in pytest.ini:

[pytest]
addopts = --reruns 2 --reruns-delay 1

pytest-rerunfailures 16.7 also has its own ini keys, such as reruns = 2, reruns_delay = 1, only_rerun and rerun_except.

Retry only infrastructure errors: –only-rerun

A retry makes sense for problems outside your application, such as a slow network. It makes no sense for a wrong text, which will be wrong again on the next attempt. Here is a real bug and a slow page in one file:

📄 filters/test_filters.py

from playwright.sync_api import Page, expect

SLOW_BUTTON = """
<script>
  setTimeout(() => document.body.innerHTML = '<button>Checkout</button>', {delay});
</script>
"""


def test_wrong_heading(page: Page):
    page.set_content("<h1>Cart</h1>")
    expect(page.locator("h1")).to_have_text("Basket", timeout=1_000)   # a real bug: wrong text


def test_slow_button(page: Page, request):
    attempt = getattr(request.node, "execution_count", 1)
    page.set_content(SLOW_BUTTON.replace("{delay}", "3000" if attempt == 1 else "200"))
    page.get_by_role("button", name="Checkout").click(timeout=2_000)       # an action timeout

⌨️ Terminal

pytest -q filters --reruns 2 --only-rerun TimeoutError

🖥️ Output

FR.                                                                      [100%]
================================== FAILURES ===================================
________________________ test_wrong_heading[chromium] _________________________

page = <Page url='about:blank'>

    def test_wrong_heading(page: Page):
        page.set_content("<h1>Cart</h1>")
>       expect(page.locator("h1")).to_have_text("Basket", timeout=1_000)   # a real bug: wrong text
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
E       AssertionError: Locator expected to have text 'Basket'
E       Actual value: Cart 
E       Call log:
E         - Expect "to_have_text" locator("h1") with timeout 1000ms
E         - waiting for locator("h1")
E           11 × locator resolved to <h1>Cart</h1>
E              - unexpected value "Cart"
E       
E       Aria snapshot:
E       - heading "Cart" [level=1]

filters\test_filters.py:12: AssertionError
=========================== short test summary info ===========================
FAILED filters/test_filters.py::test_wrong_heading[chromium] - AssertionError...
1 failed, 1 passed, 1 warning, 1 rerun in 4.07s
  • test_slow_button failed with Playwright’s TimeoutError on the first attempt, matched TimeoutError, was rerun and passed.
  • test_wrong_heading failed without a rerun. A failed expect() raises an AssertionError, even when it waited for its timeout, so it does not match TimeoutError.

📝 Note: This difference is useful. Action and navigation timeouts (click, fill, goto) raise TimeoutError, often caused by the environment. Failed expect() checks raise AssertionError, more often a real difference in the application. --only-rerun TimeoutError therefore retries infrastructure problems while real assertion failures fail at once.

Failing the build on flaky passes: –fail-on-flaky

Some teams want retries to keep the pipeline moving, but still want to know about flakiness. --fail-on-flaky lets the tests pass on retry but ends the run with exit code 7:

⌨️ Terminal

pytest -q flaky --reruns 2 --fail-on-flaky

🖥️ Output

R.                                                                       [100%]
1 passed, 1 warning, 1 rerun in 6.96s

The summary still says 1 passed, 1 rerun, but pytest exited with code 7 (in our run, the verification script recorded exit 7), so CI marks the job as failed and someone has to look at the flaky test.


🏷️ The flaky Marker: Retries for Specific Tests

Instead of retrying the whole suite, mark only the tests you know are affected:

📄 marker/test_marker.py

import pytest
from playwright.sync_api import Page, expect

RESULT_PAGE = """
<p id="result">Searching...</p>
<script>
  setTimeout(() => document.getElementById('result').textContent = 'done', {delay});
</script>
"""


@pytest.mark.flaky(reruns=3, reruns_delay=1, only_rerun=["AssertionError"])
def test_known_slow_search(page: Page, request):
    attempt = request.node.execution_count
    print(f"\nattempt {attempt}")
    page.set_content(RESULT_PAGE.replace("{delay}", "4000" if attempt < 3 else "100"))
    expect(page.locator("#result")).to_have_text("done", timeout=2_000)

⌨️ Terminal

pytest -q -s marker

🖥️ Output

attempt 1
R
attempt 2
R
attempt 3
.
1 passed, 1 warning, 2 rerun in 6.89s
  • reruns=3 allows three reruns for this test only, without any command-line option.
  • reruns_delay=1 waits one second between attempts.
  • only_rerun= (and rerun_except=) work in the marker too. Here the test’s failures are AssertionErrors from expect(), so they are listed explicitly.
  • The test failed twice (each R) and passed on attempt 3; the summary counts 2 rerun.
  • When both the marker and --reruns are given, the marker wins by default (--reruns-mode strict).

⚠️ Watch out: A flaky marker is a temporary measure. Add a comment with the reason and a ticket number, and remove the marker once the cause is fixed. A suite where many tests carry it has a flakiness problem that retries only hide.


📸 Artifacts for Each Attempt

When you combine retries with pytest-playwright’s artifacts, each failed attempt keeps its own evidence. Run the simulated flaky test with one rerun and screenshots on failure:

⌨️ Terminal

pytest -q flaky --reruns 1 --screenshot only-on-failure

🖥️ Output

R.                                                                       [100%]
1 passed, 1 warning, 1 rerun in 7.00s

The output folder now contains:

🖥️ Output

test-results/flaky-test-flaky-py-test-search-results-chromium/test-failed-1.png
  • The screenshot of the first, failed attempt is kept, which is exactly the evidence you need to understand the flaky failure.
  • The retry passed, so it kept nothing. A failed retry would have its own folder ending in -retry1, as you saw in Module 5.
  • With --tracing retain-on-failure, you get a trace of the failed attempt too: the best way to see why it was slow.

🔂 Finding Flaky Tests: pytest-repeat

To check whether a test is stable before it causes trouble in CI, run it many times. The pytest-repeat plugin (version 0.9.4 here) adds --count:

⌨️ Terminal

pip install pytest-repeat

📄 repeat/test_repeat.py

from playwright.sync_api import Page, expect


def test_practice_page_title(page: Page):
    page.goto("https://sqatools.in/automation-practice-page/")
    expect(page).to_have_title("Automation Practice Page - SQA Tools")

⌨️ Terminal

pytest repeat --count 3 -v

🖥️ Output

============================= test session starts =============================
platform win32 -- Python 3.15.1, pytest-9.2.0, pluggy-1.7.0 -- C:\pwv\_venv\Scripts\python.exe
...
plugins: html-4.2.0, metadata-3.1.1, playwright-0.10.0, repeat-0.9.4, rerunfailures-16.7, xdist-3.8.0
collecting ... collected 3 items

repeat/test_repeat.py::test_practice_page_title[chromium-1-3] PASSED     [ 33%]
repeat/test_repeat.py::test_practice_page_title[chromium-2-3] PASSED     [ 66%]
repeat/test_repeat.py::test_practice_page_title[chromium-3-3] PASSED     [100%]

======================== 3 passed, 1 warning in 6.59s =========================
  • Each repetition gets its own test id (1-3, 2-3, 3-3) and a fresh context.
  • For a real stability check, use a higher count, such as --count 50, and add -x to stop at the first failure. Combine it with pytest-xdist (Module 12) to finish faster.
  • Do not combine --count with --reruns for this purpose: retries would hide exactly the failures you are looking for.

✅ A Sensible Retry Policy

  1. Locally: no retries. You want to see every failure while you work.
  2. In CI: a small number, such as --reruns 1 or --reruns 2, ideally with --only-rerun TimeoutError for infrastructure problems.
  3. Always keep evidence: --tracing retain-on-failure and --screenshot only-on-failure.
  4. Track every rerun. Use -rR or the report to list flaky tests, and fix them like bugs; consider --fail-on-flaky once the suite is mostly stable.
  5. Never use retries to hide a real failure. A test that fails 1 time in 10 because of the application is a bug report, not noise.

🏋️ 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 reruns failed tests up to twice with a 2-second delay, but only for Playwright TimeoutError failures.

Show answer
pytest --reruns 2 --reruns-delay 2 --only-rerun TimeoutError

Exercise 2: Mark one known-flaky test with three reruns using the marker, and explain why fixing the cause is still the goal.

Show answer
@pytest.mark.flaky(reruns=3, reruns_delay=1)
def test_slow_third_party_widget(page): ...

Reruns only hide the symptom: the test can still fail, wastes time, and may hide a real intermittent bug. Find the cause (timing, shared data, unstable dependency) with traces and fix it, then remove the marker.

Exercise 3: How do you find out whether a test is flaky before it bothers the team? Write the command.

Show answer
pip install pytest-repeat
pytest tests/test_checkout.py --count 20 -x

Repeating a test many times (optionally in parallel with -n) exposes intermittent failures early.


🧠 MCQ Quiz: Retries and Flaky Tests (pytest-rerunfailures)

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 flaky test?
  2. Which plugin adds --reruns?
  3. What does the letter R mean in pytest’s progress line?
  4. What exception does a failed expect() raise?
  5. What does --fail-on-flaky do?
  6. Which is the best first fix for a test that fails because it checks too early?
  7. Do function-scoped fixtures run again on a rerun?
  8. Which plugin repeats a test N times to expose flakiness?
  9. What is a common cause of flakiness in parallel runs?
  10. What should a team track about retries?

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


❓ Frequently Asked Questions

🤔 Does Playwright Python have built-in retries like playwright.config.ts?

No. The TypeScript test runner has a retries setting. In Python, retries come from the pytest-rerunfailures plugin: --reruns N or the flaky marker.

🤔 Are fixtures run again on a rerun?

Yes. Each attempt is a complete run of the test, with its function-scoped fixtures (including page and context) set up and torn down again. Session-scoped fixtures, such as the browser, are reused.

🤔 Why is my expect() failure not retried with –only-rerun TimeoutError?

A failed expect() raises AssertionError, not TimeoutError. Only actions and navigations (click, fill, goto) raise Playwright’s TimeoutError. Use --only-rerun AssertionError if you really want to retry assertion failures.

🤔 How do I know which tests are flaky?

Look for R in the progress line and use -rR to list rerun tests in the summary. Run suspicious tests many times with pytest-repeat’s --count.

🤔 Can I use –reruns together with pytest-xdist?

Yes. Each worker reruns its own failed tests. Parallel runs are covered in Module 12.


🏁 Summary

  • Flaky tests pass and fail on the same code; fix their causes first: waits, shared state, live dependencies, data and locators.
  • pytest-rerunfailures adds retries: --reruns N, --reruns-delay, the flaky marker, and filters with --only-rerun and --rerun-except.
  • Failed expect() checks raise AssertionError; action and navigation timeouts raise TimeoutError.
  • --fail-on-flaky exits with code 7 when a test only passed on retry; -rR lists rerun tests.
  • Failed attempts keep their screenshots and traces; pytest-repeat’s --count exposes flakiness before CI does.

You have finished Module 6. Test yourself with the Module 6 mock interview, then continue to Module 7: test data, configuration and cross-browser testing at scale.

🎬 Watch the Playwright tutorial series on YouTube!

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

Browser Markers in pytest-playwright: skip_browser, only_browser and browser_context_args

One of Playwright’s biggest strengths is real cross-browser testing: the same test runs on Chromium, Firefox and WebKit. Sometimes, though, a test should not run everywhere: a feature is missing in one engine, or the test uses a Chromium-only API. pytest-playwright gives you markers for exactly that. In this lesson you will run a suite on all three engines, find a real browser difference on the practice page, and control where each test runs with skip_browser, only_browser, browser_context_args, browser channels and per-test launch options.

📖 What You’ll Learn: running tests on several browsers with –browser, reading the parametrized test ids, a real WebKit difference on the practice page, skip_browser and only_browser, showing skip reasons with -rs, markers on classes and modules, branching on browser_name, the browser_context_args marker for per-test context options, browser channels for Google Chrome and Microsoft Edge, and per-test launch options with indirect parametrization of browser_type_launch_args.


🌍 Running on Several Browsers

By default pytest-playwright runs every test on Chromium. Pass --browser once per engine to run on more:

⌨️ Terminal

pytest --browser chromium --browser firefox --browser webkit

Each --browser creates one copy of every browser test, with the engine in the test id: test_title[chromium], test_title[firefox], test_title[webkit]. Each engine gets its own browser process; every test still gets a fresh context.

EngineUsed byNotes
ChromiumGoogle Chrome, Microsoft Edge, OperaPlaywright’s default
FirefoxMozilla FirefoxPlaywright’s patched build
WebKitApple SafariPlaywright’s WebKit build runs on Windows, Linux and macOS

📝 Note: Playwright’s WebKit is close to Safari but not identical: the real Safari also depends on the Apple operating system it runs on. It is still the best way to catch WebKit-specific problems without a Mac.


🔎 A Real Difference Between Engines

All tests in this lesson use the SQA Tools practice page:

📄 tests/conftest.py

import pytest
from playwright.sync_api import Page


@pytest.fixture
def practice(page: Page) -> Page:
    page.goto("https://sqatools.in/automation-practice-page/")
    return page

The page has a date picker, <input type="date" id="datePicker">. This test asks each browser what kind of input it actually created:

📄 tests/test_cross_browser.py

import pytest
from playwright.sync_api import Page, expect


def test_title(practice: Page, browser_name):
    print(f"\n{browser_name} {practice.context.browser.version}")
    expect(practice).to_have_title("Automation Practice Page - SQA Tools")


def test_what_is_the_date_input(practice: Page, browser_name):
    input_type = practice.locator("#datePicker").evaluate("el => el.type")
    print(f"\n{browser_name}: #datePicker has type '{input_type}'")
  • practice.context.browser.version is the version of the browser that runs the test.
  • el.type returns the type the browser supports: a browser without a date control falls back to a plain text box and reports "text".

When this lesson was run on Windows, Chromium and Firefox reported date, but **WebKit reported text**: Playwright’s WebKit build on Windows has no native date picker (you will see this in the output below). A test that fills the date picker in the YYYY-MM-DD format and expects a date control would fail there for a reason that has nothing to do with your application.


⏭️ skip_browser and only_browser

pytest-playwright registers two markers for such cases:

📄 tests/test_cross_browser.py

@pytest.mark.skip_browser("webkit")
def test_date_picker(practice: Page):
    practice.locator("#datePicker").fill("2026-11-01")
    expect(practice.locator("#datePicker")).to_have_value("2026-11-01")


@pytest.mark.only_browser("chromium")
def test_chromium_devtools_protocol(practice: Page):
    # CDP sessions exist only in Chromium-based browsers
    cdp = practice.context.new_cdp_session(practice)
    version = cdp.send("Browser.getVersion")
    print("\nCDP product:", version["product"].split("/")[0])
  • @pytest.mark.skip_browser("webkit"): run on every browser except WebKit.
  • @pytest.mark.only_browser("chromium"): run only on Chromium; all other browsers are skipped.
  • new_cdp_session() talks to the Chrome DevTools Protocol, which only Chromium-based browsers support. That makes it a genuine reason for only_browser.
  • Skipped copies appear as s in the progress line. Add -rs to the pytest command to list each skip with its reason.

⚠️ Watch out: Use these markers for real engine limitations, not to hide bugs. If your application is broken in Safari, a skipped test means your users find the bug instead of you. Mark such tests with xfail and a ticket number, or fix the application.

Markers on a whole class or module

Markers can be applied to a class, and to a whole file with pytestmark:

📄 tests/test_firefox_suite.py

import pytest
from playwright.sync_api import Page, expect


@pytest.mark.only_browser("firefox")
class TestFirefoxSpecific:
    def test_user_agent(self, practice: Page):
        expect(practice.locator("body")).to_be_visible()
        assert "Firefox" in practice.evaluate("navigator.userAgent")

    def test_engine_name(self, practice: Page, browser_name):
        assert browser_name == "firefox"

For a whole module, write pytestmark = pytest.mark.skip_browser("webkit") at the top of the file.

Branching inside a test with browser_name

When only one step differs, skip that part or adapt the expected value instead of skipping the whole test:

📄 tests/test_cross_browser.py

ENGINE_IN_USER_AGENT = {"chromium": "Chrome", "firefox": "Firefox", "webkit": "AppleWebKit"}


def test_user_agent_matches_engine(practice: Page, browser_name):
    user_agent = practice.evaluate("navigator.userAgent")
    assert ENGINE_IN_USER_AGENT[browser_name] in user_agent
  • A dictionary keyed by browser_name keeps browser-specific expectations in one readable place.
  • You can also call pytest.skip("reason") inside the test after checking browser_name or is_webkit. Prefer the markers when the whole test does not apply: the decision is then visible without reading the test body.

🎛️ The browser_context_args Marker

You met this marker in Lesson 6. It adds or overrides context options for one test (or one class), on top of the browser_context_args fixture:

📄 tests/test_context_marker.py

import pytest
from playwright.sync_api import Page


@pytest.mark.browser_context_args(locale="de-DE", timezone_id="Europe/Berlin")
def test_german_user(page: Page):
    page.goto("https://sqatools.in/automation-practice-page/")
    language = page.evaluate("navigator.language")
    zone = page.evaluate("Intl.DateTimeFormat().resolvedOptions().timeZone")
    print(f"\nlanguage={language} timezone={zone}")
    assert (language, zone) == ("de-DE", "Europe/Berlin")
  • The marker’s keyword arguments are passed to browser.new_context() for this test’s context.
  • Typical uses: a different locale or time zone, color_scheme="dark", permissions=["geolocation"], a mobile viewport, or storage_state for a test that should start logged in.

Now run the whole tests folder on all three engines, with -rs to show skip reasons:

⌨️ Terminal

pytest -q -s -rs tests --browser chromium --browser firefox --browser webkit

🖥️ Output

language=de-DE timezone=Europe/Berlin
.
chromium 156.0.8078.4
.
chromium: #datePicker has type 'date'
..
CDP product: HeadlessChrome
..ss
language=de-DE timezone=Europe/Berlin
.
firefox 157.0
.
firefox: #datePicker has type 'date'
..s...
language=de-DE timezone=Europe/Berlin
.
webkit 27.2
.
webkit: #datePicker has type 'text'
.ss.ss
=========================== short test summary info ===========================
SKIPPED [2] ..\_venv0\Lib\site-packages\pytest_playwright\pytest_playwright.py:338: skipped for this browser: chromium
SKIPPED [1] ..\_venv0\Lib\site-packages\pytest_playwright\pytest_playwright.py:338: skipped for this browser: firefox
SKIPPED [4] ..\_venv0\Lib\site-packages\pytest_playwright\pytest_playwright.py:338: skipped for this browser: webkit
17 passed, 7 skipped, 1 warning in 38.09s

Read the result:

  • The #datePicker lines show the real engine difference: date in Chromium and Firefox, text in WebKit.
  • test_date_picker[webkit] was skipped by skip_browser; the CDP test and the Firefox class were skipped on the other engines by only_browser. The reason for each skip is listed in the short test summary, because of -rs.
  • pytest groups the run by browser: all Chromium tests first, then Firefox, then WebKit, because each engine’s browser is a separate session fixture.
  • The skips add up: Chromium skipped the two Firefox-only tests, Firefox skipped the CDP test, and WebKit skipped the date picker, the CDP test and the two Firefox-only tests.
  • The reason text is fixed by the plugin (“skipped for this browser: …”) and points at the plugin’s code line, not at your test.

🏷️ Browser Channels: Google Chrome and Microsoft Edge

Playwright’s Chromium is an open-source build. To test with the branded browsers installed on the machine, pass a channel:

⌨️ Terminal

pytest -q -s tests/test_cross_browser.py::test_title --browser-channel msedge

🖥️ Output

chromium 156.0.4314.42
.
1 passed, 1 warning in 2.70s
  • --browser-channel msedge launched the Microsoft Edge installed on this Windows machine, so the version is Edge’s own version number. chrome selects Google Chrome; beta and dev channels exist too (chrome-beta, msedge-beta, …).
  • The test id still says [chromium], because a channel is a Chromium-based browser.
  • A channel uses the browser installed on the machine. Install it there first (for Chrome you can also run playwright install chrome).

🚀 Per-Test Launch Options

Context options change the page environment (locale, viewport, permissions). Launch options change the browser process itself: command-line arguments, slow_mo, headless, channel. The suite-wide way to set them is overriding the browser_type_launch_args fixture (Lesson 6). For a single test, parametrize that fixture indirectly:

📄 launch/test_launch_args.py

import pytest
from playwright.sync_api import Page


@pytest.mark.only_browser("chromium")
@pytest.mark.parametrize(
    "browser_type_launch_args",
    [{"args": ["--lang=de-DE"]}],
    indirect=True,
)
def test_browser_started_in_german(page: Page, browser_type_launch_args):
    print("\nlaunch args:", browser_type_launch_args)
    print("navigator.language:", page.evaluate("navigator.language"))
  • indirect=True sends the value to the browser_type_launch_args fixture instead of passing it straight to the test. In pytest-playwright 0.10, the fixture merges it over the command-line launch options.
  • --lang=de-DE is a Chromium command-line switch, so the test is limited to Chromium with only_browser.
  • Because browser_type_launch_args and browser are session-scoped, each distinct value launches its own browser. That is slower, so keep per-test launch options for the few tests that really need them.

⌨️ Terminal

pytest -q -s -rs launch --browser chromium --browser firefox

🖥️ Output

launch args: {'args': ['--lang=de-DE']}
navigator.language: de
.s
=========================== short test summary info ===========================
SKIPPED [1] ..\_venv0\Lib\site-packages\pytest_playwright\pytest_playwright.py:338: skipped for this browser: firefox
1 passed, 1 skipped, 1 warning in 0.57s
  • The browser started with --lang=de-DE, so navigator.language is de, without any context option.
  • On Firefox the test was skipped by the only_browser marker.
  • The test id is test_browser_started_in_german[chromium-browser_type_launch_args0]: the parameter gets an automatic id. Pass ids=["german"] to parametrize for a readable one.

📋 Which Tool for Which Need?

NeedUse
Run the suite on several engines--browser chromium --browser firefox --browser webkit
A test that cannot work on one engine@pytest.mark.skip_browser("webkit")
A test that uses an engine-specific API@pytest.mark.only_browser("chromium")
One step that differs per enginebrowser_name, is_webkit and friends inside the test
Locale, time zone, viewport, permissions for one test@pytest.mark.browser_context_args(...)
The same for every testOverride the browser_context_args fixture
Branded Chrome or Edge--browser-channel chrome or msedge
Browser command-line switches for one testIndirect parametrization of browser_type_launch_args

🏋️ 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: Mark a test so it never runs in WebKit, and another so it runs only in Chromium. Then show the command that runs all browsers and prints the skip reasons.

Show answer
@pytest.mark.skip_browser("webkit")
def test_not_on_webkit(page): ...


@pytest.mark.only_browser("chromium")
def test_cdp_feature(page): ...
pytest --browser chromium --browser firefox --browser webkit -rs

Exercise 2: Give one test a German locale and a 400×800 viewport without affecting other tests.

Show answer
@pytest.mark.browser_context_args(locale="de-DE", viewport={"width": 400, "height": 800})
def test_german_mobile(page):
    assert page.evaluate("navigator.language") == "de-DE"

Exercise 3: Mark every test in a module to skip Firefox.

Show answer
import pytest

pytestmark = pytest.mark.skip_browser("firefox")

🧠 MCQ Quiz: Browser Markers and browser_context_args

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 @pytest.mark.skip_browser("webkit") do?
  2. What does @pytest.mark.only_browser("chromium") do?
  3. How do you see why tests were skipped?
  4. Which marker changes context options for one test?
  5. How do you apply a browser marker to a whole class?
  6. When is branching on browser_name inside a test acceptable?
  7. How do you run tests in Microsoft Edge?
  8. How many results does one test produce with --browser chromium --browser firefox?
  9. Which module-level variable applies markers to all tests in a file?
  10. Why always give a reason when skipping a browser?

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


❓ Frequently Asked Questions

🤔 How do I run Playwright Python tests on all browsers?

Pass --browser once per engine: pytest --browser chromium --browser firefox --browser webkit. Put it in addopts in pytest.ini to make it the default.

🤔 What is the difference between skip_browser and only_browser?

skip_browser("webkit") excludes one engine and runs on the rest. only_browser("chromium") runs on one engine and skips all others.

🤔 Why is my only_browser test always skipped?

It only runs when that browser is part of the run. With only_browser("firefox") and no --browser firefox, every copy of the test is skipped.

🤔 Is WebKit on Windows the same as Safari?

No. It is Playwright’s build of the WebKit engine, so it behaves like Safari in most respects but not all, as the date input in this lesson shows. Run important Safari checks on macOS as well.

🤔 Can I set a different viewport for one test?

Yes: @pytest.mark.browser_context_args(viewport={"width": 390, "height": 844}), or create a context with new_context(viewport=...) inside the test.


🏁 Summary

  • --browser runs every browser test once per engine; the engine appears in the test id.
  • Engines differ: on Windows, WebKit has no native date input on the practice page.
  • skip_browser and only_browser decide where a test runs; -rs shows why tests were skipped.
  • Apply markers to classes or whole modules (pytestmark), and branch on browser_name for small differences.
  • The browser_context_args marker changes context options for one test; --browser-channel runs branded Chrome or Edge.
  • Indirect parametrization of browser_type_launch_args sets launch options for one test, at the cost of a separate browser launch.

Next, you will deal with tests that fail only sometimes: why tests become flaky, and how to retry them with pytest-rerunfailures without hiding real problems.

🎬 Watch the Playwright tutorial series on YouTube!

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

Custom Fixtures for Playwright Python Tests (Page Objects, Login, Factories)

The built-in page fixture gives every test an empty browser tab. Real tests need more: an opened login page, a user who is already logged in, products in the cart, a check that no JavaScript errors happened. Custom fixtures turn that preparation into one reusable word in the test’s parameter list. In this lesson you will build a small fixture library for the SauceDemo shop on top of pytest-playwright’s fixtures, including a session-scoped login that is reused by every test.

📖 What You’ll Learn: why custom fixtures keep Playwright tests short, a page object fixture, chaining fixtures into a logged-in page, logging in once per session with storage_state and new_context, factory fixtures that take arguments, yield teardown, a fixture that collects console and page errors, parametrized fixtures for desktop and mobile, the ScopeMismatch error and the scope rules for fixtures that use page.


🧩 Why Custom Fixtures?

Compare two versions of the same test. Without fixtures, every test repeats the setup:

def test_cart_badge(page):
    page.goto("https://www.saucedemo.com/")
    page.get_by_placeholder("Username").fill("standard_user")
    page.get_by_placeholder("Password").fill("secret_sauce")
    page.get_by_role("button", name="Login").click()
    # ... and only now the actual test starts

With fixtures, the test says only what it is about:

def test_cart_badge(add_to_cart):
    page = add_to_cart("Sauce Labs Backpack")
    expect(page.locator(".shopping_cart_badge")).to_have_text("1")

You already know how fixtures work (Module 3). This lesson is about Playwright-specific fixtures: building on page, new_context and browser, choosing the right scope, and keeping tests isolated.

All examples use SauceDemo (www.saucedemo.com), a public practice shop. Its login page lists the demo user names and the shared password secret_sauce.

📝 Note: SauceDemo is a shared public site. While this lesson was being prepared, roughly one navigation in six stalled for more than 30 seconds, and the tests then failed with Page.goto: Timeout 30000ms exceeded. If that happens to you, simply run the tests again. Lesson 44 shows how to handle such flaky failures with automatic retries.


🏗️ The Fixture Library: conftest.py

Here is the start of conftest.py. The rest of the file follows in the next sections.

📄 conftest.py

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

SAUCE = "https://www.saucedemo.com/"
USER = {"username": "standard_user", "password": "secret_sauce"}   # public demo account


class LoginPage:
    """A tiny page object for the SauceDemo login page."""

    def __init__(self, page: Page):
        self.page = page
        self.username = page.get_by_placeholder("Username")
        self.password = page.get_by_placeholder("Password")
        self.button = page.get_by_role("button", name="Login")
        self.error = page.locator("[data-test='error']")

    def open(self) -> "LoginPage":
        self.page.goto(SAUCE, wait_until="domcontentloaded")
        return self

    def login(self, username: str, password: str) -> None:
        self.username.fill(username)
        self.password.fill(password)
        self.button.click()


# 1. A page object fixture: the login page, already opened
@pytest.fixture
def login_page(page: Page) -> LoginPage:
    return LoginPage(page).open()


# 2. Chained fixture: a page where the user is logged in
@pytest.fixture
def logged_in_page(login_page: LoginPage) -> Page:
    login_page.login(**USER)
    expect(login_page.page).to_have_url(f"{SAUCE}inventory.html")
    return login_page.page

1. A page object fixture

  • LoginPage groups the login page’s locators and actions in one class. This is the Page Object Model, covered in depth in Module 10.
  • The login_page fixture builds on pytest-playwright’s page, opens the page and returns the object. A test that asks for login_page starts on the login screen.
  • wait_until="domcontentloaded": as you saw in Module 5, a public site’s load event can be slow because of third-party resources. The locators wait for the form anyway.

2. Chaining fixtures into a logged-in page

  • logged_in_page asks for login_page, which asks for page. pytest resolves the chain: page → login_page → logged_in_page.
  • The fixture ends with an expect(): if the login fails, the fixture fails with a clear message, and pytest reports the test as an error in setup rather than a failure in the test body. That tells you immediately that the problem is in the preparation.

📄 tests/test_login.py

from playwright.sync_api import Page, expect


def test_locked_out_user_sees_error(login_page):
    login_page.login("locked_out_user", "secret_sauce")
    expect(login_page.error).to_have_text("Epic sadface: Sorry, this user has been locked out.")


def test_products_are_listed(logged_in_page: Page):
    expect(logged_in_page.locator(".title")).to_have_text("Products")
    expect(logged_in_page.locator(".inventory_item")).to_have_count(6)

🔐 Logging In Once: a Session Fixture with storage_state

Logging in through the form in every test costs time. A faster pattern: log in once per session, save the browser’s cookies and storage to a file, and start every test’s context from that file.

📄 conftest.py

# 3. Log in once for the whole session and save the browser state
@pytest.fixture(scope="session")
def auth_state(browser: Browser, tmp_path_factory) -> str:
    context = browser.new_context()
    page = context.new_page()
    LoginPage(page).open().login(**USER)
    page.wait_for_url("**/inventory.html")

    path = tmp_path_factory.mktemp("auth") / "state.json"
    context.storage_state(path=path)       # cookies + localStorage as JSON
    context.close()
    print(f"\n[auth_state] logged in once, saved {path.name}")
    return str(path)


# 4. Each test gets a NEW context that starts from the saved state
@pytest.fixture
def fast_logged_in_page(new_context, auth_state: str) -> Page:
    page = new_context(storage_state=auth_state).new_page()
    page.goto(f"{SAUCE}inventory.html", wait_until="domcontentloaded")
    return page
  • auth_state is session-scoped, so it may only use session-scoped fixtures. It uses browser (session) and pytest’s built-in tmp_path_factory (session), not page (function).
  • context.storage_state(path=...) writes the context’s cookies and localStorage to a JSON file. SauceDemo keeps the login in a cookie named session-username.
  • fast_logged_in_page calls new_context(storage_state=...): a fresh, isolated context per test, which already contains the login cookie. The test lands directly on the products page.

📄 tests/test_fast_login.py

from playwright.sync_api import Page, expect


def test_first_fast_login(fast_logged_in_page: Page):
    expect(fast_logged_in_page.locator(".title")).to_have_text("Products")


def test_second_fast_login(fast_logged_in_page: Page):
    expect(fast_logged_in_page).to_have_url("https://www.saucedemo.com/inventory.html")

Run them with --setup-show to see that the login happens only once (an excerpt; ... marks lines removed for brevity):

⌨️ Terminal

pytest -q --setup-show tests/test_fast_login.py

🖥️ Output

...
SETUP    S browser (fixtures used: launch_browser)
...
SETUP    S tmp_path_factory
SETUP    S auth_state (fixtures used: browser, tmp_path_factory)
        ...
        SETUP    F new_context (fixtures used: _artifacts_recorder, browser, browser_context_args)
        SETUP    F fast_logged_in_page (fixtures used: auth_state, new_context)
        tests/test_fast_login.py::test_first_fast_login[chromium] (fixtures used: ...) .
        TEARDOWN F fast_logged_in_page
        TEARDOWN F new_context
        ...
        SETUP    F new_context (fixtures used: _artifacts_recorder, browser, browser_context_args)
        SETUP    F fast_logged_in_page (fixtures used: auth_state, new_context)
        tests/test_fast_login.py::test_second_fast_login[chromium] (fixtures used: ...) .
        TEARDOWN F fast_logged_in_page
        TEARDOWN F new_context
        ...
TEARDOWN S auth_state
TEARDOWN S tmp_path_factory
...
2 passed, 1 warning in 8.65s

SETUP S auth_state appears once, before the first test; both tests then create their own F fast_logged_in_page. Module 8 builds on this pattern for real authentication setups.

⚠️ Watch out: Never commit real credentials in conftest.py. The SauceDemo values are public demo data. For your own applications, read user names and passwords from environment variables or a secrets store (Module 7).


🏭 Factory Fixtures: Fixtures That Take Arguments

A fixture cannot receive arguments from the test directly. The solution is a factory: the fixture returns a function, and the test calls it with the arguments it needs.

📄 conftest.py

# 5. A factory fixture: the test decides which products to add
@pytest.fixture
def add_to_cart(logged_in_page: Page):
    added = []

    def _add(product: str) -> Page:
        item = logged_in_page.locator(".inventory_item").filter(has_text=product)
        item.get_by_role("button", name="Add to cart").click()
        added.append(product)
        return logged_in_page

    yield _add

    # Teardown: runs after the test, even if it failed
    print(f"\n[add_to_cart] teardown, products added in this test: {added}")

📄 tests/test_cart.py

from playwright.sync_api import expect


def test_one_product(add_to_cart):
    page = add_to_cart("Sauce Labs Backpack")
    expect(page.locator(".shopping_cart_badge")).to_have_text("1")


def test_two_products(add_to_cart):
    add_to_cart("Sauce Labs Backpack")
    page = add_to_cart("Sauce Labs Bike Light")
    expect(page.locator(".shopping_cart_badge")).to_have_text("2")
  • yield _add hands the inner function to the test. Everything after yield is teardown.
  • The added list remembers what the test did, so teardown knows what to clean up.
  • Here teardown only prints, because the browser context, and with it SauceDemo’s cart, is thrown away after each test anyway. In a real application the cart or order may live in a database: that is where teardown matters, for example to delete the order through an API call.

🚨 A Fixture That Watches the Page: Console and Page Errors

Fixtures can also attach listeners to the page. This one collects JavaScript errors so a test can assert that none happened:

📄 conftest.py

# 6. Collect console errors and uncaught exceptions of the page
@pytest.fixture
def js_errors(page: Page) -> list[str]:
    errors: list[str] = []
    page.on("console", lambda msg: errors.append(f"console: {msg.text}") if msg.type == "error" else None)
    page.on("pageerror", lambda exc: errors.append(f"pageerror: {exc}"))
    return errors

📄 tests/test_js_errors.py

from playwright.sync_api import Page, expect


def test_page_with_a_broken_script(page: Page, js_errors):
    page.set_content("""
        <button onclick="undefinedFunction()">Buy</button>
        <script>console.error('Payment widget failed to load')</script>
    """)
    page.get_by_role("button", name="Buy").click()
    expect(page.get_by_role("button")).to_be_visible()      # gives the events time to arrive

    print("\ncollected:", js_errors)
    assert len(js_errors) == 2
  • page.on("console", ...) receives every console message; the fixture keeps those of type "error".
  • page.on("pageerror", ...) receives uncaught JavaScript exceptions, such as calling a function that does not exist.
  • Both js_errors and the test receive the same page object: within one test, a function-scoped fixture is created only once and shared.

🔀 Parametrized Fixtures: Desktop and Mobile

A fixture with params runs every test that uses it once per parameter:

📄 conftest.py

# 7. One test, two screen sizes
@pytest.fixture(
    params=[{"width": 1280, "height": 720}, {"width": 390, "height": 844}],
    ids=["desktop", "mobile"],
)
def sized_page(request, new_context) -> Page:
    page = new_context(viewport=request.param).new_page()
    page.goto(SAUCE, wait_until="domcontentloaded")
    return page

📄 tests/test_sizes.py

from playwright.sync_api import Page, expect


def test_login_form_fits(sized_page: Page):
    print(f"\n{sized_page.viewport_size['width']} px wide")
    expect(sized_page.get_by_role("button", name="Login")).to_be_in_viewport()
  • request.param holds the current parameter; ids gives readable names in the test id.
  • new_context(viewport=...) creates a context with that window size, without changing the project’s defaults.

⌨️ Terminal

pytest -q -s tests

🖥️ Output

.
[add_to_cart] teardown, products added in this test: ['Sauce Labs Backpack']
.
[add_to_cart] teardown, products added in this test: ['Sauce Labs Backpack', 'Sauce Labs Bike Light']

[auth_state] logged in once, saved state.json
..
collected: ['console: Payment widget failed to load', 'pageerror: undefinedFunction is not defined']
...
1280 px wide
.
390 px wide
.
9 passed, 1 warning in 36.71s
  • The [add_to_cart] lines come from the fixture’s teardown, after each cart test.
  • The [auth_state] line is printed once, when the first test that needs it runs; the second fast-login test reuses the saved file.

List the generated test ids with --collect-only:

⌨️ Terminal

pytest -q --collect-only tests/test_sizes.py

🖥️ Output

tests/test_sizes.py::test_login_form_fits[desktop-chromium]
tests/test_sizes.py::test_login_form_fits[mobile-chromium]

2 tests collected in 0.00s

Your fixture’s ids come first and pytest-playwright’s browser name second.


⛔ The Scope Rule: ScopeMismatch

A fixture can only use fixtures with the same or a wider scope. page is function-scoped, so a session-scoped fixture cannot use it:

📄 demos/test_scope_error.py

import pytest
from playwright.sync_api import Page


@pytest.fixture(scope="session")
def shared_home(page: Page) -> Page:          # session fixture asking for a function fixture
    page.goto("https://www.saucedemo.com/", wait_until="domcontentloaded")
    return page


def test_uses_shared_home(shared_home: Page):
    assert shared_home.url.startswith("https://www.saucedemo.com")

⌨️ Terminal

pytest -q demos/test_scope_error.py

🖥️ Output

E                                                                        [100%]
=================================== ERRORS ====================================
______________ ERROR at setup of test_uses_shared_home[chromium] ______________
ScopeMismatch: You tried to access the function scoped fixture page with a session scoped request object. Requesting fixture stack:
demos\test_scope_error.py:5:  def shared_home(page: 'Page') -> 'Page'
Requested fixture:
..\_venv0\Lib\site-packages\pytest_playwright\pytest_playwright.py:623:  def page(context: 'BrowserContext') -> 'Page'
=========================== short test summary info ===========================
ERROR demos/test_scope_error.py::test_uses_shared_home[chromium] - Failed: Sc...
1 error in 0.03s
  • pytest refuses to start the test and reports a ScopeMismatch error in setup.
  • The fix depends on your goal. To share something expensive across tests, build it from session fixtures (browser, playwright, tmp_path_factory), as auth_state does. To share a page, do not: share its saved state instead.
Your fixture’s scopeMay use
functionEverything: page, context, new_context, browser, playwright
class / modulebrowser, playwright, browser_name and other session fixtures
sessionSession fixtures only: browser, playwright, browser_type, tmp_path_factory, pytestconfig

✅ Good Practices for Playwright Fixtures

  1. Name fixtures after the state they give you: logged_in_page, cart_with_two_items, admin_api.
  2. Assert inside setup fixtures (as logged_in_page does) so a broken setup shows up as a setup error.
  3. Keep tests isolated: share saved state (cookies, tokens) across tests, never a live page or context.
  4. Clean up server-side data after yield; browser data disappears with the context automatically.
  5. **Put shared fixtures in conftest.py** and keep page objects in their own module as the project grows.

🏋️ 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 fixture login_as that takes a username and password, logs in to SQA Shop with the current page and returns the page.

Show answer
@pytest.fixture
def login_as(page):
    def _login(username="testuser", password="Test@123"):
        page.goto("https://sqatools.in/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("login-button").click()
        return page
    return _login

Exercise 2: Write an autouse fixture that collects console errors during a test and fails the test in teardown if any were logged.

Show answer
@pytest.fixture(autouse=True)
def no_console_errors(page):
    errors = []
    page.on("console", lambda m: errors.append(m.text) if m.type == "error" else None)
    yield
    assert not errors, f"console errors: {errors}"

Exercise 3: Why does this fixture raise ScopeMismatch, and how do you fix it?

@pytest.fixture(scope="session")
def logged_in_page(page): ...
Show answer

page is function-scoped and a session fixture cannot depend on it. Either make logged_in_page function-scoped, or log in once with a session fixture that uses browser (session-scoped), saves storage_state, and let each test create its own context from it.


🧠 MCQ Quiz: Custom Fixtures for Playwright 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. Why write custom fixtures for Playwright tests?
  2. Which fixture can a session-scoped login fixture safely use?
  3. What does a page-object fixture return?
  4. What is the benefit of chaining fixtures (e.g. logged_in_page uses login_page)?
  5. Where does clean-up go in a custom fixture?
  6. What error appears when a session fixture requests a function fixture?
  7. How do you run tests once on desktop and once on mobile with one fixture?
  8. What is the advantage of logging in once with storage_state?
  9. How should a fixture signal that setup failed (e.g. login did not work)?
  10. What does a factory fixture allow that a plain fixture does not?

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


❓ Frequently Asked Questions

🤔 Can a custom fixture use the page fixture?

Yes, as long as your fixture is function-scoped (the default). The fixture and the test then share the same page object.

🤔 How do I reuse a login across tests without logging in every time?

Log in once in a session-scoped fixture that uses browser, save context.storage_state(path=...), and create each test’s context with new_context(storage_state=path).

🤔 Why is my test reported as an error instead of a failure?

The exception happened in a fixture (setup or teardown), not in the test body. Check the fixture named in the traceback.

🤔 Can I pass arguments to a fixture?

Not directly. Return a function from the fixture (a factory) and call it in the test with the arguments, or use params or indirect parametrization for fixed values.


🏁 Summary

  • Custom fixtures package preparation, such as an opened page object, a logged-in user or products in the cart, into one parameter.
  • Chain fixtures: page → login_page → logged_in_page → add_to_cart.
  • Log in once with a session fixture built on browser, save storage_state, and start each test from it with new_context(storage_state=...).
  • Factory fixtures accept arguments; yield gives you teardown.
  • Listener fixtures, such as js_errors, watch the page during the test.
  • Session fixtures cannot use page: pytest raises ScopeMismatch.

Next, you will control which browsers each test runs on with skip_browser, only_browser and per-test launch options.

🎬 Watch the Playwright tutorial series on YouTube!

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

pytest-playwright Built-in Fixtures Explained (page, context, browser and more)

Every Playwright test you have written so far started with a page parameter. Behind that one word, the pytest-playwright plugin builds a chain of fixtures: it starts Playwright, launches a browser, creates a fresh browser context and opens a page, then cleans everything up. In this lesson you will see the whole chain with pytest’s –setup-show, prove that each test is isolated, and use the other built-in fixtures: new_context, browser, browser_name, is_chromium, device, output_path, base_url and the playwright object itself.

📖 What You’ll Learn: the fixture chain from playwright to page, which fixtures are session-scoped and which run per test, watching setup and teardown with –setup-show, how a fresh context isolates cookies and storage, new_context for several users or settings in one test, using browser for contexts you manage yourself, browser_name and the is_chromium, is_firefox and is_webkit flags, browser_channel and device, output_path, base_url, and the playwright fixture for devices and API requests.


🔗 The Fixture Chain Behind page

When a test asks for page, pytest-playwright resolves a chain of fixtures, each built on the one before:

FixtureScopeWhat it gives you
playwrightsessionThe started Playwright object (sync_playwright().start())
browser_typesessionplaywright.chromium, .firefox or .webkit, chosen by --browser
browsersessionOne launched browser, shared by all tests of that browser
new_contextfunctionA function that creates browser contexts and closes them after the test
contextfunctionA fresh BrowserContext for this test, made with new_context()
pagefunctionA new Page in that context

The two scopes are the key idea:

  • Session scope: started once for the whole run. Launching a browser takes time, so all tests share one browser process.
  • Function scope: created for each test. Every test gets a brand-new context, which is like a new incognito window: no cookies, no localStorage, no cache from other tests.

So tests are fast (one browser) and isolated (a fresh context each).

Watching the chain with –setup-show

pytest’s --setup-show option prints every fixture as it is set up (SETUP) and torn down (TEARDOWN), with its scope: S for session, F for function.

📄 tests/conftest.py

import pytest
from playwright.sync_api import Page

URL = "https://sqatools.in/automation-practice-page/"


@pytest.fixture
def practice(page: Page) -> Page:
    page.goto(URL)
    return page

⌨️ Terminal

pytest -q --setup-show tests/test_isolation.py::test_first_visit

🖥️ Output

SETUP    S pytestconfig
SETUP    S delete_output_dir (fixtures used: pytestconfig)
SETUP    S browser_type_launch_args (fixtures used: pytestconfig)
SETUP    S _pw_api_request_contexts (fixtures used: pytestconfig)
SETUP    S playwright (fixtures used: _pw_api_request_contexts)
SETUP    S browser_name (fixtures used: pytestconfig)['chromium']
SETUP    S browser_type (fixtures used: browser_name, playwright)
SETUP    S connect_options
SETUP    S launch_browser (fixtures used: browser_type, browser_type_launch_args, connect_options)
SETUP    S browser (fixtures used: launch_browser)
SETUP    S device (fixtures used: pytestconfig)
SETUP    S base_url (fixtures used: pytestconfig)
SETUP    S _pw_artifacts_folder (fixtures used: pytestconfig)
SETUP    S browser_context_args (fixtures used: _pw_artifacts_folder, base_url, device, playwright, pytestconfig)
        SETUP    F _pw_trace_api_requests
        SETUP    F output_path (fixtures used: pytestconfig)
        SETUP    F _artifacts_recorder (fixtures used: _pw_api_request_contexts, _pw_artifacts_folder, output_path, playwright, pytestconfig)
        SETUP    F new_context (fixtures used: _artifacts_recorder, browser, browser_context_args)
        SETUP    F context (fixtures used: new_context)
        SETUP    F page (fixtures used: context)
        SETUP    F practice (fixtures used: page)
        tests/test_isolation.py::test_first_visit[chromium] (fixtures used: _artifacts_recorder, _pw_api_request_contexts, _pw_artifacts_folder, _pw_trace_api_requests, base_url, browser, browser_context_args, browser_name, browser_type, browser_type_launch_args, connect_options, context, delete_output_dir, device, launch_browser, new_context, output_path, page, playwright, practice, pytestconfig, request) .
        TEARDOWN F practice
        TEARDOWN F page
        TEARDOWN F context
        TEARDOWN F new_context
        TEARDOWN F _artifacts_recorder
        TEARDOWN F output_path
        TEARDOWN F _pw_trace_api_requests
TEARDOWN S browser_context_args
TEARDOWN S _pw_artifacts_folder
TEARDOWN S base_url
TEARDOWN S device
TEARDOWN S browser
TEARDOWN S launch_browser
TEARDOWN S connect_options
TEARDOWN S browser_type
TEARDOWN S browser_name['chromium']
TEARDOWN S playwright
TEARDOWN S _pw_api_request_contexts
TEARDOWN S browser_type_launch_args
TEARDOWN S delete_output_dir
TEARDOWN S pytestconfig
1 passed, 1 warning in 1.90s

Reading the output from top to bottom:

  • The session fixtures (playwright, browser_type, browser, browser_context_args and others) are set up first. Fixtures whose names start with _pw are the plugin’s internal helpers; you never use them directly.
  • browser_name is shown with ['chromium']: pytest-playwright parametrizes every browser test by browser name, which is why test ids end in [chromium].
  • The function fixtures new_context, context and page are created just for this test, then your practice fixture runs on top of page.
  • After the test (the .), teardown runs in reverse order: first the function fixtures, and at the end of the session the browser and Playwright.

🧼 Proving Test Isolation

These two tests run one after the other in the same browser. The first one stores data in the browser; the second checks that none of it is left:

📄 tests/test_isolation.py

from playwright.sync_api import Browser, BrowserContext, Page

SEEN = {}


def test_first_visit(practice: Page, context: BrowserContext, browser: Browser):
    practice.evaluate("localStorage.setItem('cart', '3 items')")
    context.add_cookies([{"name": "session", "value": "abc123", "url": practice.url}])

    SEEN["browser"], SEEN["context"] = browser, context
    print("\nstored:", practice.evaluate("localStorage.getItem('cart')"), "| cookies:", len(context.cookies()))


def test_second_visit(practice: Page, context: BrowserContext, browser: Browser):
    print("\nleft over:", practice.evaluate("localStorage.getItem('cart')"),
          "| cookies named session:", [c for c in context.cookies() if c["name"] == "session"])
    print("same browser:", browser is SEEN["browser"], "| same context:", context is SEEN["context"])
  • SEEN is a plain module-level dictionary used only to compare objects between the two tests.
  • context.add_cookies() adds a cookie; context.cookies() lists the cookies of the context. The count of 7 includes cookies that the live site set itself while loading.
  • localStorage is read and written with page.evaluate(), which runs JavaScript in the page.

Part of the output of pytest -q -s tests (the full run is at the end of this section):

🖥️ Output

stored: 3 items | cookies: 7
.
left over: None | cookies named session: []
same browser: True | same context: False

The second test sees no localStorage value and no session cookie, because it runs in a new context. The browser object, however, is the very same one.

💡 Tip: Isolation is why Playwright tests can run in any order and in parallel. If one of your tests only passes after another test has run, it secretly depends on that test’s state: fix it with a fixture that sets up what it needs.


👥 new_context: Several Users in One Test

Some scenarios need two independent sessions at once: a buyer and a seller, an admin and a user, a chat between two people. The new_context fixture is a function: each call creates another context, using the same settings as context (browser_context_args), plus any options you pass.

📄 tests/test_new_context.py

from playwright.sync_api import Page


def test_two_users(new_context):
    alice = new_context().new_page()
    bob = new_context(locale="de-DE", viewport={"width": 800, "height": 600}).new_page()

    alice.goto("https://sqatools.in/automation-practice-page/")
    bob.goto("https://sqatools.in/automation-practice-page/")
    alice.evaluate("localStorage.setItem('user', 'alice')")

    print("\nalice sees:", alice.evaluate("localStorage.getItem('user')"))
    print("bob sees  :", bob.evaluate("localStorage.getItem('user')"))
    print("bob locale:", bob.evaluate("navigator.language"), "| bob viewport:", bob.viewport_size)


def test_page_and_extra_context(page: Page, new_context):
    # page uses one context; new_context() makes a second, independent one
    other = new_context().new_page()
    print("\ncontexts in the browser:", len(page.context.browser.contexts))
    assert page.context is not other.context
  • Each new_context() call returns a new, isolated BrowserContext.
  • Options passed to the call, such as locale or viewport, are added to the configured browser_context_args for that context only.
  • You do not close these contexts yourself: the fixture closes all of them after the test. They also get the plugin’s tracing, video and screenshot handling.

🌐 browser: Contexts You Manage Yourself

You can also call browser.new_context() directly. The difference: such a context does not use browser_context_args, does not get the plugin’s artifacts, and you must close it.

📄 tests/test_browser_fixture.py

from playwright.sync_api import Browser


def test_manual_context(browser: Browser):
    context = browser.new_context(java_script_enabled=False)
    try:
        page = context.new_page()
        page.goto("https://sqatools.in/automation-practice-page/")
        print("\nbrowser:", browser.browser_type.name, browser.version.split(".")[0], "| JS enabled:", False)
    finally:
        context.close()
  • try / finally makes sure the context is closed even if the test fails.
  • Prefer new_context in tests. Use browser.new_context() when you deliberately want a context without the project’s default settings.

⌨️ Terminal

pytest -q -s tests

🖥️ Output

browser: chromium 156 | JS enabled: False
.
stored: 3 items | cookies: 7
.
left over: None | cookies named session: []
same browser: True | same context: False
.
alice sees: alice
bob sees  : None
bob locale: de-DE | bob viewport: {'width': 800, 'height': 600}
.
contexts in the browser: 2
.
5 passed, 1 warning in 8.88s

🧭 Information Fixtures: browser_name, is_*, channel and device

These session fixtures tell a test where it runs:

FixtureValue
browser_name"chromium", "firefox" or "webkit"
is_chromium, is_firefox, is_webkitTrue or False
browser_channelThe --browser-channel value, such as "chrome", or None
deviceThe --device value, such as "iPhone 15", or None
output_pathThis test’s artifact folder inside --output (function scope)

📄 info/test_where_am_i.py

from playwright.sync_api import Page


def test_where_am_i(page: Page, browser_name, is_webkit, browser_channel, device, output_path):
    print(f"\nbrowser_name={browser_name} is_webkit={is_webkit} channel={browser_channel} device={device}")
    print("viewport:", page.viewport_size, "| iPhone user agent:", "iPhone" in page.evaluate("navigator.userAgent"))
    print("output_path ends with:", output_path.replace("\\", "/").split("/")[-1])

⌨️ Terminal

pytest -q -s info --browser firefox --device "iPhone 15"

🖥️ Output

browser_name=firefox is_webkit=False channel=None device=iPhone 15
viewport: {'width': 393, 'height': 659} | iPhone user agent: True
output_path ends with: info-test-where-am-i-py-test-where-am-i-firefox
.
1 passed, 1 warning in 2.00s
  • --device "iPhone 15" applies the device’s viewport (393 x 659), user agent and touch support to every context, through browser_context_args.
  • The iPhone descriptor names WebKit as its default browser, but --browser decides which browser actually runs. Here Firefox ran with the iPhone viewport and user agent. For the most realistic iPhone emulation, run such tests on WebKit.
  • output_path is a folder name built from the test id. Nothing is written there unless an artifact is kept.

Now run on two browsers:

⌨️ Terminal

pytest -q -s info --browser chromium --browser webkit

🖥️ Output

browser_name=chromium is_webkit=False channel=None device=None
viewport: {'width': 1280, 'height': 720} | iPhone user agent: False
output_path ends with: info-test-where-am-i-py-test-where-am-i-chromium
.
browser_name=webkit is_webkit=True channel=None device=None
viewport: {'width': 1280, 'height': 720} | iPhone user agent: False
output_path ends with: info-test-where-am-i-py-test-where-am-i-webkit
.
2 passed, 1 warning in 0.72s

Each --browser adds one parametrized copy of every test, so the test ran twice with a different browser_name.


🏠 base_url: Short URLs in Tests

The base_url fixture holds the value of --base-url (or base_url in pytest.ini, or the PYTEST_BASE_URL environment variable). pytest-playwright passes it to every context, so page.goto() accepts paths:

📄 base/test_base_url.py

from playwright.sync_api import Page, expect


def test_relative_goto(page: Page, base_url):
    print("\nbase_url:", base_url)
    page.goto("/automation-practice-page/")                 # resolved against base_url
    expect(page).to_have_url("https://sqatools.in/automation-practice-page/")

⌨️ Terminal

pytest -q -s base --base-url https://sqatools.in

🖥️ Output

base_url: https://sqatools.in
.
1 passed, 1 warning in 2.46s

📝 Note: The PytestRemovedIn10Warning you have seen in every run’s summary comes from this fixture: pytest-playwright 0.10 defines base_url as a method of a helper class, which pytest 9.2 reports as deprecated. It does not affect your tests. Silence it with a filterwarnings line in pytest.ini if it bothers you, as shown in Module 3.


🎭 The playwright Fixture

The session-scoped playwright fixture is the same object you get from sync_playwright().start(). Two things you will use it for:

📄 pw/test_playwright_fixture.py

def test_device_list(playwright):
    iphone = playwright.devices["iPhone 15"]               # a device descriptor (a dict)
    print(iphone["viewport"], iphone["default_browser_type"])

def test_api(playwright):
    api = playwright.request.new_context(base_url="https://sqatools.in")
    response = api.get("/automation-practice-page/")
    assert response.ok
    api.dispose()
  • playwright.devices contains the device descriptors used by --device. You can pass one to new_context(**playwright.devices["Pixel 7"]).
  • playwright.request creates API clients without a browser. Module 9 covers API testing in detail.

📋 All Built-in Fixtures at a Glance

FixtureScopeTypical use
pagefunctionAlmost every UI test
contextfunctionCookies, permissions, routes, a second page in the same session
new_contextfunctionSeveral independent users or per-test context options
browsersessionContexts without the default settings
browser_type, launch_browsersessionLaunching another browser yourself
playwrightsessionDevices, API request contexts
browser_context_argssessionOverride to change context settings (Lesson 6)
browser_type_launch_argssessionOverride to change launch options (headless, args, channel)
connect_optionssessionOverride to connect to a remote browser server
browser_name, browser_channel, devicesessionWhere the test runs
is_chromium, is_firefox, is_webkitsessionBrowser-specific branches
output_pathfunctionThis test’s artifact folder
base_urlsessionThe --base-url value

🏋️ 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 uses new_context to open the SQA Shop as two users at once: a guest and a logged-in shopper, and checks both headers.

Show answer
def test_two_users(new_context):
    guest = new_context().new_page()
    member = new_context().new_page()
    guest.goto("https://sqatools.in/dummy-ecommerce-website/")
    member.goto("https://sqatools.in/dummy-ecommerce-website/#/login")
    member.get_by_test_id("login-username").fill("testuser")
    member.get_by_test_id("login-password").fill("Test@123")
    member.get_by_test_id("login-button").click()
    expect(guest.get_by_test_id("account-button")).to_contain_text("Login")
    expect(member.get_by_test_id("account-button")).to_contain_text("Hi, Test")

Contexts created by new_context are closed automatically after the test.

Exercise 2: Print the current browser and the folder where this test’s artifacts go.

Show answer
def test_info(browser_name, output_path):
    print(browser_name, output_path)

Exercise 3: Which command shows the fixture chain (playwright → browser_type → browser → context → page) being set up and torn down?

Show answer
pytest tests/test_home.py --setup-show

🧠 MCQ Quiz: pytest-playwright Built-in Fixtures

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 fixture is session-scoped?
  2. Which fixture gives a fresh context per test?
  3. What does new_context return?
  4. What is browser_name?
  5. Which fixture holds options passed to browser.new_context()?
  6. What does output_path provide?
  7. Why does each test get a new context instead of sharing one?
  8. Which fixture gives access to playwright.devices and playwright.request?
  9. How do you see which fixtures pytest-playwright provides?
  10. Where does the base_url fixture come from?

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


❓ Frequently Asked Questions

🤔 Is the browser restarted for every test?

No. The browser fixture is session-scoped, so one browser is launched per browser type for the whole run (per worker when you use pytest-xdist). Each test gets a fresh context instead, which is fast and fully isolated.

🤔 Can I make the page fixture shared between tests to save time?

You could write your own session-scoped page fixture, but tests would then share cookies and state and depend on each other’s order. Keep the per-test context; to save login time, reuse a saved login state instead (Module 8).

🤔 What is the difference between context and new_context?

context is one ready-made context for the test. new_context is a function that creates as many extra contexts as you need, with optional per-context settings. All of them are closed automatically after the test.

🤔 Why do all my test names end with [chromium]?

pytest-playwright parametrizes browser tests by browser_name. The suffix shows which browser ran that copy of the test, which matters when you pass several --browser options.


🏁 Summary

  • page sits on a chain: playwright → browser_type → browser (session) → new_context → context → page (per test).
  • One shared browser makes runs fast; a fresh context per test keeps them isolated.
  • --setup-show reveals which fixtures run and in which scope.
  • new_context creates extra isolated contexts with optional settings and closes them for you.
  • browser.new_context() skips the project settings and must be closed by you.
  • browser_name, is_*, browser_channel, device, output_path and base_url tell a test where and how it runs.

Next, you will write your own fixtures on top of these: page objects, logged-in pages, test data with cleanup and fixture factories.

🎬 Watch the Playwright tutorial series on YouTube!

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