pytest Plugins and Hooks: pytest_addoption, Custom Options and Screenshot on Failure

pytest is built from plugins. Even its core features, such as assertion rewriting and the terminal report, are plugins, and pytest-playwright is one too. In this lesson you will install and control third-party plugins, then write your own hooks in conftest.py: a custom –env command-line option, automatic markers based on folder names, a header line with run information, and a screenshot-on-failure hook for Playwright tests that attaches the image to the test report.

📖 What You’ll Learn: what plugins and hooks are, installing and listing plugins, three plugins every Playwright team uses (rerunfailures, xdist, pytest-html), disabling plugins with -p no:, adding command-line options with pytest_addoption, reading them in fixtures, pytest_report_header, pytest_collection_modifyitems, and a pytest_runtest_makereport hook wrapper that saves a screenshot when a test fails.


🔌 Plugins: pytest’s Building Blocks

A plugin is a Python package (or a conftest.py file) that adds behaviour to pytest by implementing hook functions: functions with special names, starting with pytest_, that pytest calls at defined moments. pytest itself is assembled from dozens of internal plugins, and the ecosystem has well over a thousand external ones.

Installed plugins activate automatically. The run header lists them:

🖥️ Output

plugins: html-4.2.0, metadata-3.1.1, playwright-0.10.0, rerunfailures-16.7, xdist-3.8.0

(pytest-metadata is installed automatically as a dependency of pytest-html.)

Three plugins every Playwright Python team uses

PluginInstallWhat it adds
pytest-rerunfailurespip install pytest-rerunfailures--reruns N re-runs failed tests (Module 6)
pytest-xdistpip install pytest-xdist-n auto runs tests in parallel processes (Module 12)
pytest-htmlpip install pytest-html--html=report.html writes an HTML report (Module 11)

A quick taste of the first two. This test fails on its first attempt only (plugins_demo/test_flaky.py):

📄 plugins_demo/test_flaky.py

import pathlib


def test_sometimes_fails(tmp_path_factory):
    marker = tmp_path_factory.getbasetemp() / "attempted"
    if not marker.exists():
        marker.touch()
        assert False, "first attempt fails"
    assert True

⌨️ Terminal

pytest -q --reruns 2 plugins_demo/test_flaky.py

🖥️ Output

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

R marks the rerun: the first attempt failed, the second passed. And pytest-xdist spreads tests over worker processes (plugins_demo/test_parallel.py):

📄 plugins_demo/test_parallel.py

import os
import time

import pytest


@pytest.mark.parametrize("n", range(4))
def test_slow_step(n):
    time.sleep(1)
    assert os.environ.get("PYTEST_XDIST_WORKER", "").startswith("gw")

⌨️ Terminal

pytest -q -n 2 plugins_demo/test_parallel.py

🖥️ Output

bringing up nodes...
bringing up nodes...
....                                                                     [100%]
4 passed in 2.98s

Four tests of one second each finished in under 3 seconds with two workers (gw0 and gw1, including the time to start them), instead of 4+ seconds in one process. Each worker sets the PYTEST_XDIST_WORKER environment variable, which the test checks.

Disabling plugins

  • -p no:NAME disables one plugin for a run, for example -p no:playwright (you used it in earlier lessons) or -p no:cacheprovider.
  • The environment variable PYTEST_DISABLE_PLUGIN_AUTOLOAD=1 disables all automatically loaded plugins; you then enable the ones you need with -p NAME.

🪝 Hooks in conftest.py

You do not need to publish a package to write a plugin: hook functions in conftest.py are a local plugin. All the hooks below live in the project’s root conftest.py.

1. A custom command-line option: pytest_addoption

Real suites run against several environments. Add an --env option and turn it into a fixture:

📄 conftest.py

import pathlib

import pytest

ENVIRONMENTS = {
    "qa": "https://qa.example.com",
    "staging": "https://staging.example.com",
    "prod": "https://sqatools.in",
}


def pytest_addoption(parser):
    parser.addoption(
        "--env",
        action="store",
        default="staging",
        choices=sorted(ENVIRONMENTS),
        help="environment to test against: qa, staging or prod",
    )


@pytest.fixture(scope="session")
def env_name(pytestconfig) -> str:
    return pytestconfig.getoption("--env")


@pytest.fixture(scope="session")
def app_url(env_name: str) -> str:
    return ENVIRONMENTS[env_name]


# 2. Show the environment in the report header
def pytest_report_header(config):
    return f"environment: {config.getoption('--env')}"


# 3. Mark every test in tests/smoke automatically
def pytest_collection_modifyitems(config, items):
    for item in items:
        if "smoke" in item.path.parts:
            item.add_marker(pytest.mark.smoke)


# 4. Screenshot on failure, attached to the report
@pytest.hookimpl(wrapper=True)
def pytest_runtest_makereport(item, call):
    report = yield                                   # let pytest build the report first
    page = item.funcargs.get("page")
    if report.when == "call" and report.failed and page is not None:
        folder = pathlib.Path("test-results") / "failures"
        folder.mkdir(parents=True, exist_ok=True)
        path = folder / f"{item.name}.png".replace("[", "_").replace("]", "")
        page.screenshot(path=str(path), full_page=True)
        report.sections.append(("screenshot", str(path)))
    return report

Let us go through each hook.

**pytest_addoption(parser)** registers new options. parser.addoption accepts the same arguments as Python’s argparse: action, default, choices (only these values are accepted) and help (shown in pytest --help). Option hooks must be in the root conftest.py or a plugin, because pytest reads them before collecting tests.

Reading the option: the env_name fixture uses the built-in pytestconfig fixture and getoption("--env"). app_url builds on it, so tests simply ask for app_url.

📄 pytest.ini

[pytest]
testpaths = tests
markers =
    smoke: quick checks of the most important flows
filterwarnings =
    ignore:Session-scoped fixtures defined as instance methods:pytest.PytestRemovedIn10Warning

📄 tests/test_env.py

from playwright.sync_api import Page, expect


def test_env_url(env_name: str, app_url: str):
    print(f"\n  testing {env_name} at {app_url}")
    assert app_url.startswith("https://")


def test_env_home_page(page: Page, env_name: str, app_url: str):
    if env_name != "prod":
        return                                   # the example qa/staging hosts are placeholders
    page.goto(app_url + "/automation-practice-page/")
    expect(page).to_have_title("Automation Practice Page - SQA Tools")

⌨️ Terminal

pytest --env prod -k env

🖥️ Output

============================= test session starts =============================
platform win32 -- Python 3.15.1, pytest-9.2.0, pluggy-1.7.0
environment: prod
rootdir: C:\pwv\pytest-plugins-hooks
configfile: pytest.ini
testpaths: tests
plugins: 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_env.py ..                                                     [100%]

======================= 2 passed, 2 deselected in 2.81s =======================

The line environment: prod in the header comes from **pytest_report_header**, which returns text (or a list of lines) to show at the top of a run. It records which environment a CI log belongs to. The header is hidden in quiet mode (-q), so run without -q when you need it.

An invalid value is rejected before any test runs, thanks to choices:

⌨️ Terminal

python -m pytest -q --env qaa

🖥️ Output

ERROR: usage: python -m pytest [options] [file_or_dir] [file_or_dir] [...]
python -m pytest: error: argument --env: invalid choice: 'qaa', maybe you meant 'qa'? (choose from 'prod', 'qa', 'staging')

pytest exits with code 4 (usage error), and Python’s argparse even suggests the closest valid value.

(With --env qa the tests run against the placeholder URL https://qa.example.com, which is just an example host here.)

3. Changing collected tests: pytest_collection_modifyitems

This hook receives the list of collected test items after collection, and may add markers, reorder or deselect them. The version above adds the smoke marker to every test inside a tests/smoke/ folder, so nobody can forget the decorator:

📄 tests/smoke/test_login_smoke.py

from playwright.sync_api import Page, expect


def test_login_button_visible(page: Page):
    page.goto("https://sqatools.in/login-page/")
    expect(page.get_by_role("button", name="Log in")).to_be_visible()

⌨️ Terminal

pytest -q --collect-only -m smoke

🖥️ Output

tests/smoke/test_login_smoke.py::test_login_button_visible[chromium]

1/4 tests collected (3 deselected) in 0.01s

The test has no @pytest.mark.smoke decorator, yet -m smoke selected it, because the hook marked it by folder. (item.path is the test file’s path as a pathlib.Path, and .parts splits it into folder names.)

4. Screenshot on failure: pytest_runtest_makereport

pytest-playwright already has --screenshot only-on-failure. Writing the hook yourself shows how such features work, and lets you customise them, for example by attaching the path to the report or uploading to a test-management tool.

  • @pytest.hookimpl(wrapper=True) makes the hook a wrapper: code before yield runs before pytest’s own implementation, yield returns the finished report, and the wrapper must return it.
  • pytest calls this hook three times per test: for setup, call (the test body) and teardown. report.when == "call" and report.failed selects a failure in the test body.
  • item.funcargs holds the fixture values of the test; if it used page, we take a full-page screenshot.
  • report.sections.append(...) adds a section to the failure report, so the path is printed with the failure details.

A deliberately failing test (tests/test_broken.py):

📄 tests/test_broken.py

from playwright.sync_api import Page, expect


def test_broken_heading(page: Page):
    page.goto("https://sqatools.in/automation-practice-page/")
    expect(page.get_by_role("heading", name="Web Table")).to_have_text("Web Tables", timeout=1000)

⌨️ Terminal

pytest -q -k broken

🖥️ Output

E       AssertionError: Locator expected to have text 'Web Tables'
E       Actual value: Web Table
...
tests\test_broken.py:6: AssertionError
--------------------------------- screenshot ----------------------------------
test-results\failures\test_broken_heading_chromium.png
=========================== short test summary info ===========================
FAILED tests/test_broken.py::test_broken_heading[chromium] - AssertionError: ...
1 failed, 3 deselected in 3.93s

The “screenshot” section printed under the failure is the one the hook appended to report.sections.

The screenshot file exists next to the report:

🖥️ Output

test_broken_heading_chromium.png

⚠️ Watch out: pytest-playwright clears test-results at the start of every run (Lesson 5). Save custom artifacts in a sub-folder you create during the run, as here, or in a different folder.


📚 Other Useful Hooks

HookCalled whenTypical use
pytest_configure(config)After options are parsedRegister markers in code, set global state
pytest_sessionstart(session) / pytest_sessionfinish(session, exitstatus)Start / end of the whole runStart or stop services, write a summary file
pytest_runtest_setup(item)Before each test’s setupSkip tests based on markers or options
pytest_terminal_summary(terminalreporter, exitstatus, config)At the end of the terminal outputPrint custom statistics

🏋️ 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 --env option (choices qa, staging; default qa) in the root conftest.py and a session fixture env that returns it.

Show answer
import pytest


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


@pytest.fixture(scope="session")
def env(pytestconfig) -> str:
    return pytestconfig.getoption("--env")

Exercise 2: Write a pytest_collection_modifyitems hook that adds the marker ui to every test that uses the page fixture.

Show answer
def pytest_collection_modifyitems(items):
    for item in items:
        if "page" in getattr(item, "fixturenames", ()):
            item.add_marker("ui")

Register ui under markers if you use --strict-markers.

Exercise 3: Write the command that runs the suite with 4 parallel workers, 2 reruns for failures and an HTML report, and the command that runs it once with the xdist plugin disabled.

Show answer
pytest -n 4 --reruns 2 --html=report.html --self-contained-html
pytest -p no:xdist

🧠 MCQ Quiz: pytest Plugins and Hooks

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 pytest hook?
  2. Which command lists installed plugins and versions?
  3. How do you disable a plugin for one run?
  4. Which hook adds command-line options?
  5. How do you read a custom option inside a fixture?
  6. Which hook adds text to the top of the test session output?
  7. Which hook can reorder, filter or mark collected tests?
  8. Which hook is used to save a screenshot when a test fails?
  9. Which plugin runs tests in parallel?
  10. What does @pytest.hookimpl(wrapper=True) let a hook do?

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


❓ Frequently Asked Questions

🤔 Should I write hooks in conftest.py or make a plugin package?

Start in conftest.py. When several projects need the same hooks, move them into a package and install it; the code stays almost the same.

🤔 Why do I see two versions of hook wrappers online?

Older examples use @pytest.hookimpl(hookwrapper=True) with outcome = yield and outcome.get_result(). The newer form shown here, @pytest.hookimpl(wrapper=True) with report = yield and return report, is the recommended style in current pytest and pluggy.

🤔 Can I make my custom option required?

You can set required=True in parser.addoption, but a sensible default is usually friendlier, so a plain pytest still works.

🤔 How do I find all available hooks?

The pytest documentation’s “API Reference” lists every hook with its arguments. Plugins such as pytest-xdist add their own hooks too.


🏁 Summary

  • Plugins add features through hook functions; installed plugins load automatically, -p no:NAME disables one.
  • rerunfailures (--reruns), xdist (-n) and pytest-html (--html) are standard in Playwright projects.
  • pytest_addoption plus pytestconfig.getoption() gives you options like --env; pytest_report_header labels runs.
  • pytest_collection_modifyitems changes collected tests; a pytest_runtest_makereport wrapper can screenshot failures.

That completes Module 3. Test yourself with the Module 3 mock interview, then move on to Module 4: locators and interactions.

🎬 Watch the Playwright tutorial series on YouTube!

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

pytest Configuration Guide: pytest.ini, pyproject.toml, addopts and Key Settings

In Lesson 6 you used pytest.ini for a few Playwright options. This lesson is the complete reference for the settings that matter in real test projects: which file pytest reads and how it picks the project root, changing discovery rules, silencing known warnings, live logging, enforcing plugin and pytest versions, and overriding settings from the environment in CI. Every setting shown here was tested with pytest 9.2.

📖 What You’ll Learn: which configuration files pytest reads and their precedence, rootdir and the configfile header, testpaths and norecursedirs, custom discovery with python_files, python_classes and python_functions, filterwarnings, live logging with log_cli, required_plugins and minversion, the PYTEST_ADDOPTS environment variable, and a complete recommended pytest.ini for Playwright.


📄 Which File Does pytest Read?

pytest looks for configuration in the folder of your test paths and then in its parent folders, and uses the first match it finds. In each folder it checks, in this order:

FileSectionNotes
pytest.ini[pytest]Always wins, even if empty. Recommended for test projects.
pyproject.toml[tool.pytest.ini_options] (or [tool.pytest] in pytest 9)Common when the project already uses pyproject.toml.
tox.ini[pytest]Used by projects that also use tox.
setup.cfg[tool:pytest]Older projects; not recommended for new ones.

The folder containing the chosen file becomes the rootdir, the base for test IDs and relative paths. The first lines of every run tell you what pytest decided:

🖥️ Output

rootdir: C:\pwv\pytest-configuration
configfile: pytest.ini
testpaths: tests

Check these lines first whenever settings seem to be ignored. You can also force a specific file with -c path/to/pytest.ini.


🗂️ Where to Look for Tests

testpaths = tests
norecursedirs = .venv node_modules test-results
  • testpaths lists the folders that a bare pytest command searches. It makes collection faster and avoids picking up stray files.
  • norecursedirs lists folder names (glob patterns) that pytest never enters. pytest already skips common ones such as .*, venv and build by default; setting this option replaces that default list, so include anything you still need to skip.

🔍 Custom Discovery Rules

If your team names files differently, change the patterns. This project collects check_*.py files, Verify* classes and check_* functions in addition to the defaults (pytest.ini below, used for the whole lesson):

📄 pytest.ini

[pytest]
minversion = 9.0
testpaths = tests
pythonpath = .
python_files = test_*.py check_*.py
python_classes = Test* Verify*
python_functions = test_* check_*
addopts = --strict-markers -ra
markers =
    smoke: quick checks of the most important flows
filterwarnings =
    ignore:Session-scoped fixtures defined as instance methods:pytest.PytestRemovedIn10Warning
log_cli = true
log_cli_level = INFO
required_plugins = pytest-playwright>=0.10.0

📄 tests/check_login.py

import logging

import pytest
from playwright.sync_api import Page, expect

log = logging.getLogger(__name__)


@pytest.mark.smoke
def check_login_page(page: Page):
    log.info("opening the SQA Tools login page")
    page.goto("https://sqatools.in/login-page/")
    expect(page.get_by_role("button", name="Log in")).to_be_visible()
    log.info("login button is visible")


class VerifyPracticePage:
    def check_table_rows(self, page: Page):
        page.goto("https://sqatools.in/automation-practice-page/")
        expect(page.locator("table tbody tr")).to_have_count(3)
  • python_files = test_*.py check_*.py adds check_*.py files to the default test_*.py.
  • python_classes and python_functions work the same way for classes and functions. With these settings, check_login_page and VerifyPracticePage.check_table_rows are real tests.
  • Patterns are separated by spaces.

⚠️ Watch out: Changing discovery rules surprises new team members, who expect test_ names. Only do it when you have a strong reason, such as an existing naming convention.


🔇 filterwarnings: Silence Known Warnings

Since Lesson 2 you have seen the same harmless PytestRemovedIn10Warning from pytest-playwright’s base_url fixture. filterwarnings hides warnings you have reviewed and accepted, so new, important warnings stand out:

filterwarnings =
    ignore:Session-scoped fixtures defined as instance methods:pytest.PytestRemovedIn10Warning

The format is action:message:category:

  • action: ignore, error (turn the warning into a test failure), default, always and others;
  • message: the start of the warning text (a regular expression);
  • category: the warning class, here pytest.PytestRemovedIn10Warning.

error is useful too: filterwarnings = error::DeprecationWarning makes your suite fail as soon as your own code uses something deprecated.

💡 Tip: Keep filters narrow. Ignoring a whole category like DeprecationWarning hides warnings you would want to see.


📝 Live Logging with log_cli

Tests and page objects should use Python’s logging module rather than print. With log_cli = true, pytest shows log messages live as each test runs, at or above log_cli_level:

⌨️ Terminal

pytest -v

🖥️ Output

configfile: pytest.ini
testpaths: tests
plugins: playwright-0.10.0
collecting ... collected 2 items

tests/check_login.py::check_login_page[chromium]
-------------------------------- live log call --------------------------------
INFO     check_login:check_login.py:11 opening the SQA Tools login page
INFO     check_login:check_login.py:14 login button is visible
PASSED                                                                   [ 50%]
tests/check_login.py::VerifyPracticePage::check_table_rows[chromium] PASSED [100%]

============================== 2 passed in 4.76s ==============================

Notice three things in this real output:

  1. Both custom-named tests were collected (check_login_page and VerifyPracticePage::check_table_rows).
  2. The log lines appear under “live log call”, with level, logger name, file and line.
  3. There is no warnings summary: the filter silenced the known plugin warning.

Related settings: log_cli_format and log_cli_date_format change the line format, and log_file = logs/pytest.log also writes logs to a file.


🛡️ Guard Rails: minversion and required_plugins

  • minversion = 9.0 stops the run if pytest is older than 9.0.
  • required_plugins = pytest-playwright>=0.10.0 stops the run if a plugin is missing or too old.

Both turn “works on my machine” problems into a clear error message. Here is what happens when a required plugin is missing (strict/pytest.ini asks for a plugin that is not installed):

📄 strict/pytest.ini

[pytest]
required_plugins = pytest-rerunfailures>=14.0

📄 strict/test_nothing.py

def test_placeholder():
    assert True

⌨️ Terminal

pytest -q -c strict/pytest.ini strict

🖥️ Output

ERROR: Missing required plugins: pytest-rerunfailures>=14.0

pytest refuses to run any test until the environment is fixed, and exits with code 4 (a usage error), so CI fails clearly.


🌍 Override Settings from the Environment: PYTEST_ADDOPTS

CI systems often need extra options without editing files. pytest reads the PYTEST_ADDOPTS environment variable and adds its contents to the command line, after addopts from the config file. This script proves it by running the same tests twice (addopts_env.py):

📄 addopts_env.py

import os
import subprocess

PY = r"C:\pwv\_venv0\Scripts\python"
base = [PY, "-m", "pytest", "-p", "no:cacheprovider", "-q", "--collect-only"]

normal = subprocess.run(base, capture_output=True, text=True).stdout
print("normal run:", normal.strip().splitlines()[-1])

env = dict(os.environ, PYTEST_ADDOPTS="-m smoke")
smoke = subprocess.run(base, capture_output=True, text=True, env=env).stdout
print("with PYTEST_ADDOPTS='-m smoke':", smoke.strip().splitlines()[-1])

🖥️ Output

normal run: 2 tests collected in 0.02s
with PYTEST_ADDOPTS='-m smoke': 1/2 tests collected (1 deselected) in 0.02s

In a CI pipeline you would set PYTEST_ADDOPTS="-m smoke --browser firefox" for one job and something else for another, with the same pytest.ini.


✅ A Recommended pytest.ini for Playwright Projects

[pytest]
minversion = 9.0
testpaths = tests
pythonpath = .
addopts =
    --strict-markers
    -ra
    --tracing retain-on-failure
    --screenshot only-on-failure
markers =
    smoke: quick checks of the most important flows
    regression: full functional coverage
    slow: tests that take longer than a few seconds
xfail_strict = true
filterwarnings =
    ignore:Session-scoped fixtures defined as instance methods:pytest.PytestRemovedIn10Warning
log_cli = true
log_cli_level = INFO
required_plugins = pytest-playwright>=0.10.0
  • A multi-line addopts is allowed: indent the continuation lines.
  • -ra prints a short summary of every test that did not pass (failures, errors, skips, xfails), which is ideal in CI logs.
  • Browser choice stays on the command line or in PYTEST_ADDOPTS, for the reason explained in Lesson 6: --browser values add up.

🏋️ 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 recommended pytest.ini for a Playwright project: tests in tests/, ignore a scratch/ folder, strict markers, a short summary of every outcome, base URL, and live logging at INFO level.

Show answer
[pytest]
testpaths = tests
norecursedirs = scratch .venv
addopts = --strict-markers -ra --base-url https://sqatools.in
log_cli = true
log_cli_level = INFO
markers =
    smoke: quick checks

Exercise 2: Your team keeps check files called check_*.py with functions check_*. Configure pytest to collect them.

Show answer
[pytest]
python_files = test_*.py check_*.py
python_functions = test_* check_*

Exercise 3: In CI you want every run to retry failures twice without editing pytest.ini. How?

Show answer

Set the environment variable PYTEST_ADDOPTS="--reruns 2" in the CI job (pytest-rerunfailures must be installed). pytest adds it to the command line of every run.


🧠 MCQ Quiz: pytest Configuration: pytest.ini and addopts

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 the “configfile:” line in pytest’s header tell you?
  2. What does norecursedirs do?
  3. Which setting changes which files count as test files?
  4. What does log_cli = true enable?
  5. What does filterwarnings = error do?
  6. What does required_plugins do?
  7. What does minversion check?
  8. How do you add options to every run from the environment?
  9. What is the rootdir?
  10. Which file wins when both pytest.ini and setup.cfg have settings?

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


❓ Frequently Asked Questions

🤔 pytest.ini or pyproject.toml?

Either works. pytest.ini is explicit and always takes priority; pyproject.toml keeps all tool settings in one file. Pick one and use only one, since pytest.ini silently wins when both exist (apart from a note in the header).

🤔 Can command-line options override the config file?

Yes. addopts comes first, then PYTEST_ADDOPTS, then what you type, so later single-value options win. Ini settings that are not command-line options (such as testpaths) can be overridden with -o name=value, for example pytest -o log_cli=false.

🤔 Should log_cli be on in CI?

It is helpful in CI logs because you see progress live. Locally, some people prefer it off and use -s or the captured log sections shown for failed tests.

🤔 Where do I set the default expect timeout?

Not in pytest.ini: it is a Playwright setting. Call expect.set_options(timeout=10_000) in conftest.py, as shown in Lesson 6.


🏁 Summary

  • pytest uses the first of pytest.ini, pyproject.toml, tox.ini or setup.cfg it finds; check the rootdir and configfile header.
  • Use testpaths, pythonpath, addopts, markers and xfail_strict in almost every project; change discovery patterns only with good reason.
  • filterwarnings silences reviewed warnings, log_cli shows logs live, minversion and required_plugins guard the environment.
  • PYTEST_ADDOPTS and -o name=value adjust a run without editing files.

Next, you will extend pytest itself with plugins and hook functions, including a screenshot-on-failure hook for Playwright.

🎬 Watch the Playwright tutorial series on YouTube!

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

pytest Markers: skip, skipif, xfail and Custom Markers (smoke, regression)

Markers are labels you attach to tests with @pytest.mark. Some built-in markers change how a test runs: skip it, skip it on certain systems, or expect it to fail. Custom markers such as smoke or regression let you run exactly the group of tests you need, for example a quick smoke suite on every commit and the full regression suite at night. In this lesson you will use all of them, register your own markers properly and select tests with -m expressions.

📖 What You’ll Learn: skip and skipif with reasons, skipping from inside a test, xfail and the difference between xfailed and xpassed, strict xfail, custom markers like smoke and regression, registering markers in pytest.ini, –strict-markers, selecting tests with -m and boolean expressions, listing markers, and marking whole classes and modules.


🏷️ What Is a Marker?

A marker is a decorator of the form @pytest.mark.<name> placed above a test (or a class). pytest uses markers in two ways:

  1. Built-in markers change execution: skip, skipif, xfail, parametrize, usefixtures, filterwarnings.
  2. Custom markers are labels you invent, such as smoke, regression or slow, used to select tests with -m.

⏭️ skip, skipif and xfail

Create tests/test_skip_xfail.py:

📄 tests/test_skip_xfail.py

import sys

import pytest


@pytest.mark.skip(reason="payment page is being redesigned")
def test_payment_form():
    assert False                       # never runs


@pytest.mark.skipif(sys.platform == "win32", reason="uses a Linux-only path")
def test_linux_path():
    assert sys.platform != "win32"


def test_skip_from_inside():
    feature_enabled = False            # imagine reading a feature flag
    if not feature_enabled:
        pytest.skip("feature flag 'new-cart' is off")
    assert True


@pytest.mark.xfail(reason="bug #42: total ignores discounts")
def test_discount_total():
    assert 100 - 10 == 100             # fails: expected while the bug exists


@pytest.mark.xfail(reason="bug #57: badge count off by one")
def test_badge_count():
    assert 1 + 1 == 2                  # passes unexpectedly: XPASS
MarkerEffect
@pytest.mark.skip(reason=...)Never runs the test. Always give a reason.
@pytest.mark.skipif(condition, reason=...)Skips only when the condition is true, e.g. a platform or Python version.
pytest.skip("...") inside a testSkips at runtime, after checking something such as a feature flag or environment.
@pytest.mark.xfail(reason=...)Runs the test but expects it to fail. A failure is reported as xfailed; an unexpected pass as xpassed.

Run it with -rsxX to see a summary of skips (s), xfails (x) and xpasses (X):

⌨️ Terminal

pytest -q -rsxX tests/test_skip_xfail.py

🖥️ Output

sssxX                                                                    [100%]
=========================== short test summary info ===========================
SKIPPED [1] tests\test_skip_xfail.py:6: payment page is being redesigned
SKIPPED [1] tests\test_skip_xfail.py:11: uses a Linux-only path
SKIPPED [1] tests\test_skip_xfail.py:19: feature flag 'new-cart' is off
XFAIL tests/test_skip_xfail.py::test_discount_total - bug #42: total ignores discounts
XPASS tests/test_skip_xfail.py::test_badge_count - bug #57: badge count off by one
3 skipped, 1 xfailed, 1 xpassed in 0.05s

(This run was on Windows, so test_linux_path was skipped; on Linux it would pass.)

💡 Tip: Use xfail for known bugs rather than skip. The test keeps running, so the day the bug is fixed you see XPASS and know to remove the marker. A skipped test tells you nothing.


🔒 Strict xfail

By default an XPASS does not fail the run, so a fixed bug can go unnoticed. With strict=True, an unexpected pass fails the test (tests/test_strict_xfail.py):

📄 tests/test_strict_xfail.py

import pytest


@pytest.mark.xfail(reason="bug #57: badge count off by one", strict=True)
def test_badge_count_strict():
    assert 1 + 1 == 2

⌨️ Terminal

pytest -q -rX tests/test_strict_xfail.py

🖥️ Output

F                                                                        [100%]
================================== FAILURES ===================================
___________________________ test_badge_count_strict ___________________________
[XPASS(strict)] bug #57: badge count off by one
1 failed in 0.02s

To make every xfail strict, set xfail_strict = true in pytest.ini. Other useful xfail options: raises=SomeError (only that exception counts as the expected failure) and run=False (do not even run it, for example when it would hang).


🏷️ Custom Markers: smoke, regression, slow

Custom markers group tests by purpose. First register them in pytest.ini, with a short description each:

📄 pytest.ini

[pytest]
markers =
    smoke: quick checks of the most important flows (run on every commit)
    regression: full functional coverage (run nightly)
    slow: tests that take longer than a few seconds

Then label the tests (tests/test_suite.py):

📄 tests/test_suite.py

import pytest
from playwright.sync_api import Page, expect


@pytest.mark.smoke
@pytest.mark.regression
def test_login_page_loads(page: Page):
    page.goto("https://sqatools.in/login-page/")
    expect(page.get_by_role("button", name="Log in")).to_be_visible()


@pytest.mark.regression
def test_practice_page_table(page: Page):
    page.goto("https://sqatools.in/automation-practice-page/")
    expect(page.locator("table tbody tr")).to_have_count(3)


@pytest.mark.regression
@pytest.mark.slow
def test_practice_page_all_headings(page: Page):
    page.goto("https://sqatools.in/automation-practice-page/")
    expect(page.get_by_role("heading", name="Bottom of Page")).to_be_visible()

A test can carry several markers. Now select groups with -m:

⌨️ Terminal

pytest -q -m smoke tests/test_suite.py

🖥️ Output

.                                                                        [100%]
1 passed, 2 deselected, 1 warning in 3.82s

(The warning is the pytest-playwright base_url notice from Lesson 2.)

-m accepts boolean expressions with and, or, not and parentheses:

⌨️ Terminal

pytest -q -m "regression and not slow" tests/test_suite.py

🖥️ Output

..                                                                       [100%]
2 passed, 1 deselected, 1 warning in 5.02s
CommandRuns
pytest -m smokeTests marked smoke
pytest -m "smoke or regression"Tests with either marker
pytest -m "regression and not slow"Regression tests except slow ones
pytest -m "not slow"Everything except slow tests

📝 Note: -m selects by marker, -k selects by name. You can combine them: pytest -m regression -k login.


⚠️ Typos in Marker Names: Register and Use –strict-markers

pytest does not know whether @pytest.mark.smoek is a typo or a new marker. Without registration it only warns (unregistered/test_typo.py):

📄 unregistered/test_typo.py

import pytest


@pytest.mark.smoek            # typo of "smoke"
def test_typo():
    assert True

⌨️ Terminal

pytest -q unregistered/test_typo.py

🖥️ Output

  C:\pwv\pytest-markers\unregistered\test_typo.py:4: PytestUnknownMarkWarning: Unknown pytest.mark.smoek - is this a typo?  You can register custom marks to avoid this warning - for details, see https://docs.pytest.org/en/stable/how-to/mark.html
    @pytest.mark.smoek            # typo of "smoke"

1 passed, 1 warning in 0.01s

The test still ran, but pytest -m smoke would silently skip it. With --strict-markers, an unregistered marker is an error instead:

⌨️ Terminal

pytest -q --strict-markers unregistered/test_typo.py

🖥️ Output

=================================== ERRORS ====================================
'smoek' not found in `markers` configuration option
=========================== short test summary info ===========================
ERROR unregistered/test_typo.py - Failed: 'smoek' not found in `markers` conf...
!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!!
1 error in 0.07s

The run stops during collection with exit code 2, so the typo cannot go unnoticed.

Add --strict-markers to addopts in pytest.ini so typos can never slip through:

[pytest]
addopts = --strict-markers
markers =
    smoke: quick checks of the most important flows

📋 Listing Markers

pytest --markers lists every marker available: your registered ones (with their descriptions) first, then those added by plugins, then pytest’s built-in ones. With pytest-playwright installed the list starts like this:

🖥️ Output

@pytest.mark.smoke: quick checks of the most important flows (run on every commit)

@pytest.mark.regression: full functional coverage (run nightly)

@pytest.mark.slow: tests that take longer than a few seconds

@pytest.mark.skip_browser(name): mark test to be skipped a specific browser

@pytest.mark.only_browser(name): mark test to run only on a specific browser

@pytest.mark.browser_context_args(**kwargs): provide additional arguments to browser.new_context()

@pytest.mark.skip(reason=None): skip the given test function with an optional reason. ...

You will use skip_browser, only_browser and the browser_context_args marker in Module 6.


📦 Marking a Whole Class or Module

  • A class: put the marker above the class and every test method inherits it.
  • A whole file: set a module-level variable pytestmark = pytest.mark.regression (or a list of markers) at the top of the test file.
import pytest

pytestmark = [pytest.mark.regression]       # applies to every test in this file


@pytest.mark.smoke
class TestCheckout:
    def test_shipping_form(self, page):      # marked regression AND smoke
        ...

🏋️ 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: Register two markers smoke and regression in pytest.ini, enable strict markers, and write the command that runs smoke tests that are not also marked slow.

Show answer
[pytest]
addopts = --strict-markers
markers =
    smoke: quick checks for every commit
    regression: full regression suite
    slow: takes more than a minute
pytest -m "smoke and not slow"

Exercise 2: Skip a test on Windows with a clear reason, and skip another from inside the test when an environment variable RUN_PAYMENTS is not set.

Show answer
import os
import sys

import pytest


@pytest.mark.skipif(sys.platform == "win32", reason="uses a Linux-only tool")
def test_linux_only(): ...


def test_payments():
    if not os.getenv("RUN_PAYMENTS"):
        pytest.skip("set RUN_PAYMENTS=1 to run payment tests")
    ...

Exercise 3: Mark a known bug as an expected failure so that the run turns red as soon as the bug is fixed.

Show answer
@pytest.mark.xfail(reason="BUG-482: coupon rounds down", strict=True)
def test_coupon_rounding(): ...

With strict=True an unexpected pass (XPASS) fails the run, reminding the team to remove the marker.


🧠 MCQ Quiz: pytest Markers: skip, skipif, xfail, Custom

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(reason="...") do?
  2. What does skipif add?
  3. What is the result when an xfail test fails?
  4. What does xfail(strict=True) do when the test passes?
  5. Why register custom markers?
  6. Which option runs tests marked smoke?
  7. Which command lists registered markers?
  8. How do you mark every test in a module?
  9. Which expression selects regression tests that are not slow?
  10. How do you skip from inside a test at runtime?

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


❓ Frequently Asked Questions

🤔 Should I delete skipped tests?

Not immediately, but review them regularly. A test skipped for months is usually dead code. Prefer xfail for known bugs so you notice when they are fixed.

🤔 What is the difference between -m and -k?

-m selects tests by marker expression; -k selects by test name (including parametrize IDs). Both accept and, or and not.

🤔 Can I skip a test only in one browser?

Yes, with pytest-playwright’s @pytest.mark.skip_browser("webkit"), or check the browser_name fixture inside the test and call pytest.skip(). Module 6 covers both.

🤔 Why use reason= everywhere?

Reasons appear in reports and in the -rs summary, so whoever reads the results knows why a test did not run without opening the code.


🏁 Summary

  • skip, skipif and pytest.skip() stop tests from running, with a reason; xfail expects failure and reports xfailed or xpassed.
  • strict=True (or xfail_strict = true) turns an unexpected pass into a failure.
  • Register custom markers in pytest.ini, add --strict-markers, and select groups with -m expressions.
  • Mark whole classes with a decorator and whole files with pytestmark.

Next, you will put all of pytest’s settings together in pytest.ini or pyproject.toml.

🎬 Watch the Playwright tutorial series on YouTube!

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

pytest parametrize: Run One Test with Many Inputs (with Playwright Examples)

Good test suites check the same behaviour with many inputs: several users, several prices, several pages. Copying a test for each input creates duplicate code that is painful to maintain. pytest’s parametrize marker runs one test function once per set of values, each reported as its own test. In this lesson you will parametrize plain functions and Playwright login tests, give every case a readable name, mark individual cases, combine parameters, and parametrize fixtures.

📖 What You’ll Learn: @pytest.mark.parametrize with one and several arguments, how pytest builds test IDs, custom ids, pytest.param with id and marks, stacking decorators for combinations, a data-driven Playwright login test, parametrized fixtures with params and request.param, and how parametrize combines with pytest-playwright’s browser parameter.


🔁 One Test, Many Inputs

@pytest.mark.parametrize(names, values) takes:

  1. a string with the argument names, separated by commas;
  2. a list of values: single values for one argument, or tuples for several.

pytest then generates one test per item. Create tests/test_basic_params.py:

📄 tests/test_basic_params.py

import pytest


def to_price(text: str) -> float:
    return float(text.replace("$", "").replace(",", ""))


@pytest.mark.parametrize("text", ["$29.99", "$9.99", "$7.99"])
def test_price_is_positive(text):
    assert to_price(text) > 0


@pytest.mark.parametrize(
    "text, expected",
    [
        ("$29.99", 29.99),
        ("$1,299.00", 1299.0),
        ("15", 15.0),
    ],
)
def test_price_parsing(text, expected):
    assert to_price(text) == expected
  • The first test has one argument, so the list holds plain strings.
  • The second has two arguments ("text, expected"), so each item is a tuple in the same order.
  • The test function’s parameters must match the names exactly.

⌨️ Terminal

pytest -v tests/test_basic_params.py

🖥️ Output

tests/test_basic_params.py::test_price_is_positive[$29.99] PASSED        [ 16%]
tests/test_basic_params.py::test_price_is_positive[$9.99] PASSED         [ 33%]
tests/test_basic_params.py::test_price_is_positive[$7.99] PASSED         [ 50%]
tests/test_basic_params.py::test_price_parsing[$29.99-29.99] PASSED      [ 66%]
tests/test_basic_params.py::test_price_parsing[$1,299.00-1299.0] PASSED  [ 83%]
tests/test_basic_params.py::test_price_parsing[15-15.0] PASSED           [100%]

Each case is a separate test with an ID in square brackets. pytest builds the ID from the values, joined with -. If one case fails, the others still run and you see exactly which input broke.


🏷️ Readable IDs and Per-Case Marks

Auto-generated IDs work for simple values but become unreadable for dictionaries or long strings. Use ids= for a list of names, or pytest.param(..., id=...) to name one case and attach markers to it (tests/test_param_marks.py):

📄 tests/test_param_marks.py

import pytest


@pytest.mark.parametrize(
    "a, b, expected",
    [(2, 3, 5), (10, -4, 6), (0, 0, 0)],
    ids=["small", "negative", "zeros"],
)
def test_add(a, b, expected):
    assert a + b == expected


@pytest.mark.parametrize(
    "username, can_log_in",
    [
        pytest.param("standard_user", True, id="standard"),
        pytest.param("locked_out_user", False, id="locked"),
        pytest.param("glitch_user", True, id="glitch",
                     marks=pytest.mark.xfail(reason="no such user on the demo site")),
    ],
)
def test_known_users(username, can_log_in):
    known = {"standard_user": True, "locked_out_user": False}
    assert known[username] == can_log_in
  • ids=[...] gives the cases names in order: test_add[small], test_add[negative], test_add[zeros].
  • pytest.param(values..., id="...") names a single case right next to its data, which is easier to keep in sync than a separate list.
  • marks=pytest.mark.xfail(...) applies a marker to that case only. You can also use pytest.mark.skip this way.

⌨️ Terminal

pytest -q -rx tests/test_param_marks.py

🖥️ Output

.....x                                                                   [100%]
=========================== short test summary info ===========================
XFAIL tests/test_param_marks.py::test_known_users[glitch] - no such user on the demo site
5 passed, 1 xfailed in 0.02s

-rx adds the summary line for xfailed tests, showing the case’s ID and reason.


✖️ Stacking: Every Combination

Stacking two parametrize decorators runs every combination of their values (a Cartesian product). Use --collect-only to see the generated tests without running them (tests/test_stacked.py):

📄 tests/test_stacked.py

import pytest


@pytest.mark.parametrize("width", [375, 768, 1280])
@pytest.mark.parametrize("theme", ["light", "dark"])
def test_layout(width, theme):
    assert width > 0 and theme in ("light", "dark")

⌨️ Terminal

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

🖥️ Output

tests/test_stacked.py::test_layout[light-375]
tests/test_stacked.py::test_layout[light-768]
tests/test_stacked.py::test_layout[light-1280]
tests/test_stacked.py::test_layout[dark-375]
tests/test_stacked.py::test_layout[dark-768]
tests/test_stacked.py::test_layout[dark-1280]

6 tests collected in 0.01s

2 themes × 3 widths = 6 tests. Combinations grow fast, so stack only when every combination is worth testing.


🎭 Data-Driven Playwright Login Tests

Now the real use case: one login test, many users, each with its expected result (tests/test_login_data.py):

📄 tests/test_login_data.py

import pytest
from playwright.sync_api import Page, expect

LOGIN_CASES = [
    pytest.param("standard_user", "secret_sauce", None, id="valid-user"),
    pytest.param("locked_out_user", "secret_sauce", "Sorry, this user has been locked out.", id="locked-user"),
    pytest.param("standard_user", "wrong", "Username and password do not match", id="wrong-password"),
    pytest.param("", "secret_sauce", "Username is required", id="empty-username"),
]


@pytest.mark.parametrize("username, password, error", LOGIN_CASES)
def test_login(page: Page, username: str, password: str, error: str | None):
    page.goto("https://www.saucedemo.com/")
    page.get_by_placeholder("Username").fill(username)
    page.get_by_placeholder("Password").fill(password)
    page.get_by_role("button", name="Login").click()

    if error is None:
        expect(page.locator(".title")).to_have_text("Products")
    else:
        expect(page.locator("[data-test='error']")).to_contain_text(error)
  • The test data lives in one list at the top of the file, separate from the test logic. In Module 7 you will load it from JSON and CSV files instead.
  • error=None means “login should succeed”; otherwise the test checks the error message.
  • Parametrize arguments and fixtures mix freely: page comes from pytest-playwright, the other three from the parameters.

⌨️ Terminal

pytest -v tests/test_login_data.py

🖥️ Output

tests/test_login_data.py::test_login[chromium-valid-user] PASSED         [ 25%]
tests/test_login_data.py::test_login[chromium-locked-user] PASSED        [ 50%]
tests/test_login_data.py::test_login[chromium-wrong-password] PASSED     [ 75%]
tests/test_login_data.py::test_login[chromium-empty-username] PASSED     [100%]

Notice the ID: chromium-valid-user. pytest-playwright parametrizes every test that uses page by browser, and pytest combines that with your parameters. Run in two browsers and the cases double:

⌨️ Terminal

pytest -q --collect-only --browser chromium --browser firefox tests/test_login_data.py

🖥️ Output

tests/test_login_data.py::test_login[chromium-valid-user]
tests/test_login_data.py::test_login[chromium-locked-user]
tests/test_login_data.py::test_login[chromium-wrong-password]
tests/test_login_data.py::test_login[chromium-empty-username]
tests/test_login_data.py::test_login[firefox-valid-user]
tests/test_login_data.py::test_login[firefox-locked-user]
tests/test_login_data.py::test_login[firefox-wrong-password]
tests/test_login_data.py::test_login[firefox-empty-username]

8 tests collected in 0.02s

💡 Tip: Select single cases by ID with -k: pytest -k "locked-user" runs only that case, in every browser.


🧪 Parametrized Fixtures

Sometimes it is the fixture that should vary, for example a viewport size used by many tests. Give the fixture params=[...]; every test that uses it runs once per value, and the fixture reads the current value from request.param (tests/test_fixture_params.py):

📄 tests/test_fixture_params.py

import pytest
from playwright.sync_api import Page


@pytest.fixture(params=[(375, 812), (1280, 720)], ids=["mobile", "desktop"])
def sized_page(page: Page, request) -> Page:
    width, height = request.param
    page.set_viewport_size({"width": width, "height": height})
    return page


def test_practice_page_fits(sized_page: Page):
    sized_page.goto("https://sqatools.in/automation-practice-page/")
    width = sized_page.viewport_size["width"]
    assert sized_page.evaluate("document.documentElement.clientWidth") <= width
  • params lists the values; ids names them in reports.
  • request.param holds the value for the current run.
  • page.set_viewport_size() resizes the page’s viewport, and the test checks that the page is not wider than the screen.

🖥️ Output

tests/test_fixture_params.py::test_practice_page_fits[mobile-chromium] PASSED [ 50%]
tests/test_fixture_params.py::test_practice_page_fits[desktop-chromium] PASSED [100%]

Here the fixture’s ID comes first and the browser second (mobile-chromium), while in the login example the browser came first (chromium-valid-user). The order follows how pytest resolves the parameters, so do not rely on it when filtering; -k mobile matches either way.

Choose parametrize for test data that belongs to one test, and fixture params when a whole group of tests should run in several configurations.


🏋️ 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: Parametrize a test that checks is_valid_pincode(pin) for “411001” (True), “900001” (True format), “12345” (False) and “abcdef” (False), with readable ids.

Show answer
import pytest


@pytest.mark.parametrize("pin, expected", [
    pytest.param("411001", True, id="pune"),
    pytest.param("900001", True, id="starts-with-9"),
    pytest.param("12345", False, id="five-digits"),
    pytest.param("abcdef", False, id="letters"),
])
def test_pincode_format(pin, expected):
    assert is_valid_pincode(pin) is expected

Exercise 2: Write a parametrized fixture role with “admin” and “viewer” and a test that prints which role it runs with.

Show answer
@pytest.fixture(params=["admin", "viewer"])
def role(request):
    return request.param


def test_dashboard(role):
    print(role)

The test runs twice, ids [admin] and [viewer].

Exercise 3: A parametrized Playwright test with 3 data rows runs with --browser chromium --browser firefox. How many tests run, and what does one id look like?

Show answer

3 × 2 = 6 tests, because pytest-playwright also parametrizes by browser. An id looks like test_login[chromium-wrong-password].


🧠 MCQ Quiz: Parametrize Tests with @pytest.mark.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("x", [1, 2, 3]) create?
  2. How do you pass several arguments per case?
  3. How do you give one case a custom id?
  4. How do you mark one case as expected to fail?
  5. Two stacked parametrize decorators with 2 and 3 values create:
  6. How does a parametrized fixture access the current value?
  7. What can ids= be?
  8. Why give parametrized cases readable ids?
  9. What does pytest-playwright add to parametrized test ids?
  10. When is a parametrized fixture better than @pytest.mark.parametrize?

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


❓ Frequently Asked Questions

🤔 Why do my IDs show names like user0 and user1?

pytest builds IDs only from simple values (numbers, strings, booleans, None); for other objects such as dictionaries it uses the argument name plus an index (user0, user1).

🤔 Can I parametrize a test class?

Yes. Put @pytest.mark.parametrize on the class and every test method receives the parameters.

🤔 How do I load parameters from a JSON or CSV file?

Read the file into a list at module level (or in a helper function) and pass that list to parametrize. Module 7 shows this step by step.

🤔 Is it a problem if one parametrized case fails?

No. Each case is an independent test, so the others still run, and the report shows exactly which input failed.


🏁 Summary

  • @pytest.mark.parametrize("a, b", [(1, 2), ...]) runs a test once per value set, each with its own ID.
  • Use ids= or pytest.param(..., id=..., marks=...) for readable names and per-case markers.
  • Stacked decorators produce every combination; pytest-playwright adds the browser to every ID.
  • Fixture params with request.param vary a fixture for all tests that use it.

Next, you will use markers to skip, expect failures, and tag tests so you can run exactly the group you need.

🎬 Watch the Playwright tutorial series on YouTube!

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

pytest conftest.py Explained: Share and Override Fixtures Across Your Test Suite

Once fixtures are useful in more than one test file, they belong in conftest.py. pytest loads these special files automatically, makes their fixtures available to every test below them, and lets sub-folders override fixtures with their own versions. In this lesson you will build a small Playwright project with a root conftest.py and two sub-folder conftest files, see exactly where each test’s fixtures come from, and learn the rules that keep conftest files tidy.

📖 What You’ll Learn: what conftest.py is and where pytest looks for it, sharing fixtures without imports, how nested conftest files add and override fixtures, overriding a fixture while reusing the parent version, inspecting fixture sources with –fixtures-per-test, putting hooks in conftest.py, and common mistakes such as importing from conftest.


📄 What Is conftest.py?

conftest.py is a normal Python file with a special name. pytest finds it automatically and:

  • makes every fixture defined in it available to all tests in the same folder and all sub-folders, with no import;
  • runs any hook functions in it (functions with special names such as pytest_addoption) to customise pytest itself;
  • adds its folder to sys.path, which is why a root conftest.py also fixes the import problem from Lesson 19.

You can have one conftest.py per folder. They stack: a test sees the fixtures from every conftest.py between the project root and its own folder.


🗂️ The Example Project

🖥️ Output

project/
├── pytest.ini
├── conftest.py                 # shared by every test
└── tests/
    ├── test_home.py
    ├── shop/
    │   ├── conftest.py         # adds logged_in_page for shop tests
    │   └── test_cart.py
    └── admin/
        ├── conftest.py         # overrides the user fixture
        └── test_admin.py

📄 pytest.ini

[pytest]
testpaths = tests
pythonpath = .

The root conftest.py

📄 conftest.py

import pytest

BASE_URL = "https://www.saucedemo.com/"


@pytest.fixture(scope="session")
def base_url_value() -> str:
    """The application under test (shared by every test)."""
    return BASE_URL


@pytest.fixture
def user() -> dict:
    """The default user for most tests."""
    return {"username": "standard_user", "password": "secret_sauce", "role": "customer"}
  • base_url_value is session-scoped: it never changes during a run.
  • user is function-scoped and returns fresh data each time.

A test in the root tests folder

📄 tests/test_home.py

from playwright.sync_api import Page, expect


def test_login_page_title(page: Page, base_url_value: str):
    page.goto(base_url_value)
    expect(page).to_have_title("Swag Labs")


def test_default_user(user: dict):
    print(f"\n  tests/test_home.py sees role={user['role']}")
    assert user["username"] == "standard_user"

Neither fixture is imported: pytest finds them in the root conftest.py.


➕ Adding Fixtures in a Sub-folder

Fixtures that only the shop tests need go in tests/shop/conftest.py. They can use fixtures from the root conftest.py and from pytest-playwright:

📄 tests/shop/conftest.py

import re

import pytest
from playwright.sync_api import Page, expect


@pytest.fixture
def logged_in_page(page: Page, base_url_value: str, user: dict) -> Page:
    """A page that is already logged in as `user`."""
    page.goto(base_url_value)
    page.get_by_placeholder("Username").fill(user["username"])
    page.get_by_placeholder("Password").fill(user["password"])
    page.get_by_role("button", name="Login").click()
    expect(page).to_have_url(re.compile(r".*/inventory\.html"))
    return page

📄 tests/shop/test_cart.py

from playwright.sync_api import Page, expect


def test_add_backpack(logged_in_page: Page):
    logged_in_page.locator("[data-test='add-to-cart-sauce-labs-backpack']").click()
    expect(logged_in_page.locator("[data-test='shopping-cart-badge']")).to_have_text("1")

logged_in_page is visible to tests in tests/shop/ only. A test in tests/admin/ that asked for it would fail with “fixture ‘logged_in_page’ not found”.


🔄 Overriding a Fixture in a Sub-folder

The admin tests need a different user. Instead of a new fixture name, tests/admin/conftest.py overrides user. It can even receive the parent version by requesting a fixture with the same name:

📄 tests/admin/conftest.py

import pytest


@pytest.fixture
def user(user: dict) -> dict:
    """Same as the root user, but with the admin role."""
    return {**user, "role": "admin"}

📄 tests/admin/test_admin.py

def test_admin_role(user: dict):
    print(f"\n  tests/admin/test_admin.py sees role={user['role']}")
    assert user["role"] == "admin"
    assert user["username"] == "standard_user"   # inherited from the root fixture
  • Inside tests/admin/, the nearest user fixture wins.
  • Because the override asks for user as a parameter, pytest passes it the parent fixture’s value (from the root conftest.py). {**user, "role": "admin"} copies it and changes one key.
  • This is exactly the technique you used for browser_context_args in Lesson 6: your conftest.py overrides the plugin’s fixture and extends the original.

Run everything:

⌨️ Terminal

pytest -q -s

🖥️ Output

  tests/admin/test_admin.py sees role=admin
...
  tests/test_home.py sees role=customer
.
4 passed, 1 warning in 11.51s

(The warning is pytest-playwright’s harmless base_url deprecation notice from Lesson 2.)

The same fixture name gives admin in one folder and customer in another.


🔎 Where Does Each Fixture Come From?

When a project has several conftest files, --fixtures-per-test shows which file every fixture of a test comes from:

⌨️ Terminal

pytest -q --fixtures-per-test tests/admin/test_admin.py

🖥️ Output

---------------------- fixtures used by test_admin_role -----------------------
------------------------ (tests\admin\test_admin.py:1) ------------------------
delete_output_dir -- ..\_venv0\Lib\site-packages\pytest_playwright\pytest_playwright.py:95
    no docstring available
pytestconfig -- ...\_pytest\fixtures.py:1644
    Session-scoped fixture that returns the session's :class:`pytest.Config`
    object.
user -- tests\admin\conftest.py:4
    Same as the root user, but with the admin role.

user comes from tests\admin\conftest.py line 4, the override. The other two entries are automatic fixtures from pytest-playwright and pytest itself. The docstring of each fixture is shown under it, another reason to write one. Related commands: pytest --fixtures lists every available fixture, and pytest --fixtures -v adds the file each one comes from.


🪝 Hooks Also Live in conftest.py

Besides fixtures, conftest.py can contain hook functions: functions with names pytest recognises, which let you change pytest’s behaviour. For example, adding a custom command-line option:

def pytest_addoption(parser):
    parser.addoption("--env", default="staging", help="Environment to test against")

Option hooks such as pytest_addoption must live in the root conftest.py (or a plugin), because pytest reads them before it collects test folders. You will write hooks in pytest Plugins and Hooks.


🧭 A Recommended Layout for Playwright Projects

FilePut here
conftest.py (root)Settings overrides (browser_context_args), command-line options, session fixtures (config, API clients), screenshot-on-failure hooks
tests/<area>/conftest.pyFixtures for one feature area, such as logged_in_page for shop tests or an admin user
pages/, utils/ packagesPage objects and helpers (imported normally, not fixtures)

⚠️ Common Mistakes

  • Importing from conftest.py. Never write from conftest import user. pytest loads conftest files itself; importing them can load a second copy. If you need shared helper functions (not fixtures), put them in a normal module such as utils/helpers.py.
  • One giant root conftest.py. Move area-specific fixtures into the conftest.py of that folder.
  • Duplicate conftest.py at the same level as pytest.ini and in tests/ with conflicting fixtures. Keep one owner for each fixture name and override deliberately.
  • Expecting a sub-folder fixture to be visible higher up. Fixtures flow down the folder tree, never up or sideways.

🏋️ Practice Exercises

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

Exercise 1: Your project has tests/ui/ and tests/api/. Where do you put a fixture used by both, one used only by UI tests, and why?

Show answer

The shared fixture goes in tests/conftest.py; the UI-only fixture goes in tests/ui/conftest.py. A conftest applies to its directory and everything below it, so each fixture is visible exactly where it is needed.

Exercise 2: In tests/mobile/conftest.py, override browser_context_args so mobile tests use a 390×844 viewport while keeping the parent settings.

Show answer
import pytest


@pytest.fixture(scope="session")
def browser_context_args(browser_context_args):
    return {**browser_context_args, "viewport": {"width": 390, "height": 844}, "is_mobile": True, "has_touch": True}

Requesting the fixture by its own name gives you the parent version to extend.

Exercise 3: A teammate wrote from conftest import logged_in_page in a test and sees strange errors. What is wrong, and which command shows where each fixture of a test comes from?

Show answer

Fixtures from conftest.py are provided automatically and should never be imported; importing can register them twice or load the wrong conftest. Remove the import. pytest --fixtures-per-test tests/test_x.py lists each test’s fixtures with their source files.


🧠 MCQ Quiz: Sharing Fixtures with conftest.py

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 conftest.py used for?
  2. Do tests need to import fixtures from conftest.py?
  3. Can there be several conftest.py files?
  4. How do you override a fixture for one folder?
  5. How does an override reuse the parent fixture’s value?
  6. Which command shows the fixtures available to tests?
  7. Can conftest.py contain hooks such as pytest_runtest_makereport?
  8. Where must pytest_addoption live to always work?
  9. What is a good reason to split fixtures into several conftest files?
  10. What does --fixtures-per-test show?

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


❓ Frequently Asked Questions

🤔 Do I need __init__.py files for conftest.py to work?

No. pytest finds conftest.py files in the folders it collects tests from, with or without __init__.py.

🤔 Can a test file override a conftest fixture?

Yes. A fixture defined in the test module itself is the closest of all, so it wins for the tests in that file.

🤔 Why is my fixture “not found”?

The fixture is defined in a conftest.py that is not on the path from the root to the test’s folder (for example in a sibling folder), or the name is misspelled. pytest --fixtures lists what the test can see.

🤔 Can I override pytest-playwright fixtures such as page?

Yes, the same way, but prefer overriding the settings fixtures (browser_context_args, browser_type_launch_args) or writing new fixtures on top of page. Replacing page itself is rarely necessary.


🏁 Summary

  • conftest.py fixtures are available to every test in its folder and below, without imports.
  • Nested conftest files add fixtures and override names; an override can request the parent version by name.
  • --fixtures-per-test and pytest --fixtures show where fixtures come from.
  • Keep option hooks in the root conftest.py, area fixtures in sub-folders, and helpers in normal modules.

Next, you will run the same test with many inputs using @pytest.mark.parametrize.

🎬 Watch the Playwright tutorial series on YouTube!

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

pytest Fixtures Explained: Setup, Teardown, yield, Scope and autouse

Fixtures are pytest’s way of preparing everything a test needs and cleaning up afterwards. The page fixture you have used since Lesson 4 is one, provided by pytest-playwright. In this lesson you will write your own: simple data fixtures, setup and teardown with yield, fixtures that depend on other fixtures, scopes that control how often a fixture runs, autouse fixtures, factories, and a logged-in page fixture for Playwright tests.

📖 What You’ll Learn: what a fixture is and how tests request it by name, return vs yield, teardown that runs even after a failure, fixture scopes (function, class, module, package, session) and how to see them with –setup-show, fixtures that use other fixtures, autouse, the request object, factory fixtures, useful built-in fixtures, and a reusable logged-in Playwright page.


🧩 What Is a Fixture?

A fixture is a function decorated with @pytest.fixture. A test asks for it by adding a parameter with the same name; pytest runs the fixture first and passes its result in. This is called *dependency injection*: the test declares what it needs, and pytest provides it.

📄 tests/test_data_fixtures.py

import pytest


@pytest.fixture
def user():
    """Test data for a standard user."""
    return {"username": "standard_user", "password": "secret_sauce"}


@pytest.fixture
def cart_items():
    return ["Sauce Labs Backpack", "Sauce Labs Onesie"]


def test_user_has_password(user):
    assert user["password"] == "secret_sauce"


def test_cart_count(cart_items):
    assert len(cart_items) == 2


def test_both_fixtures(user, cart_items):
    assert user["username"].startswith("standard")
    assert "Sauce Labs Backpack" in cart_items
  • Each test lists the fixtures it needs as parameters, in any order.
  • The fixture runs once per test that uses it by default, so every test gets a fresh dictionary or list. One test changing its data can never affect another.
  • The docstring appears in pytest --fixtures, which lists every fixture available to your tests.

🖥️ Output

...                                                                      [100%]
3 passed in 0.01s

🔁 Setup and Teardown with yield

Many resources must be cleaned up: files, test users, database rows, browser contexts. Put the setup before yield, give the test its value with yield, and put the cleanup after it (tests/test_yield.py):

📄 tests/test_yield.py

import pytest


@pytest.fixture
def temp_user():
    print("\n  [setup] create user qa_temp")
    user = {"name": "qa_temp", "active": True}
    yield user                                  # the test runs here
    print("  [teardown] delete user qa_temp")   # runs after the test, pass or fail


def test_user_is_active(temp_user):
    print("  [test] checking user")
    assert temp_user["active"]


def test_failure_still_tears_down(temp_user):
    print("  [test] about to fail on purpose")
    with pytest.raises(AssertionError):
        assert temp_user["name"] == "someone_else"

⌨️ Terminal

pytest -q -s tests/test_yield.py

🖥️ Output

  [setup] create user qa_temp
  [test] checking user
.  [teardown] delete user qa_temp

  [setup] create user qa_temp
  [test] about to fail on purpose
.  [teardown] delete user qa_temp

2 passed in 0.01s
  • The order is always setup, test, teardown. (The dot that marks a passed test is printed between the test and its teardown.)
  • Teardown code after yield runs even when the test fails, because pytest resumes the fixture after the test finishes, whatever the result.
  • If the setup part raises an exception, the test is reported as an *error* and the teardown part does not run (there was nothing set up to clean).

This is exactly how pytest-playwright’s context and page fixtures work: create a context and page, yield the page to your test, close them afterwards.


📏 Fixture Scope: How Often Does It Run?

scope= decides how long a fixture’s value lives and how often it is created:

ScopeCreated once perTypical use
function (default)testPages, test data, anything a test may change
classtest classShared state for a group of related tests
moduletest fileExpensive setup used by one file
packagepackage (folder with __init__.py)Shared setup for a folder
sessionwhole test runBrowsers, API clients, config loaded once

pytest can show exactly when each fixture is set up and torn down with --setup-show (tests/test_scopes.py):

📄 tests/test_scopes.py

import pytest


@pytest.fixture(scope="session")
def config():
    return {"base_url": "https://www.saucedemo.com/"}


@pytest.fixture(scope="module")
def api_token(config):
    return "token-for-" + config["base_url"]


@pytest.fixture
def cart():
    return []


def test_first(config, api_token, cart):
    cart.append("Backpack")
    assert len(cart) == 1


def test_second(config, api_token, cart):
    assert cart == []                   # a fresh cart: function scope

These tests do not use a browser, so the command below adds -p no:playwright to switch the pytest-playwright plugin off for this run and keep the output short:

⌨️ Terminal

pytest -q --setup-show -p no:playwright tests/test_scopes.py

🖥️ Output

SETUP    S config
    SETUP    M api_token (fixtures used: config)
        SETUP    F cart
        tests/test_scopes.py::test_first (fixtures used: api_token, cart, config) .
        TEARDOWN F cart
        SETUP    F cart
        tests/test_scopes.py::test_second (fixtures used: api_token, cart, config) .
        TEARDOWN F cart
    TEARDOWN M api_token
TEARDOWN S config
2 passed in 0.00s

With the plugin active, the same command also lists pytest-playwright’s own automatic fixtures, such as SETUP S delete_output_dir (which clears test-results once per run) and a function-scoped _pw_trace_api_requests. Fixtures whose names start with _ are the plugin’s internals; you never request them yourself.

Reading it:

  • S, M and F mark session, module and function scope.
  • config and api_token were created once and reused by both tests; cart was created fresh for each test, which is why the second test sees an empty list.
  • Teardown happens in reverse order: function first, then module, then session.
  • api_token asks for config: fixtures can use other fixtures, and pytest resolves the whole chain for you.

⚠️ Watch out: A fixture can only use fixtures of the same or wider scope. A session fixture that asks for a function-scoped fixture (such as page) fails with ScopeMismatch: You tried to access the function scoped fixture page with a session scoped request object., because the session value would outlive the page.

Scope in pytest-playwright

pytest-playwright uses these scopes to make tests fast and isolated at the same time:

FixtureScopeWhy
playwright, browser_type, browser, browser_namesessionLaunching a browser is slow, so it happens once per run
browser_context_argssessionSettings are calculated once
context, pagefunctionEvery test gets a clean, isolated session

🤖 autouse Fixtures

A fixture with autouse=True runs for every test in its scope without being requested. Use it for things every test needs, such as resetting state or setting timeouts:

@pytest.fixture(autouse=True)
def short_action_timeout(page):
    page.set_default_timeout(10_000)

Use autouse sparingly: hidden setup makes tests harder to understand. If only some tests need something, request it explicitly.


🏭 Factory Fixtures and the request Object

Sometimes a test needs several objects of the same kind, with different settings. Return a function (a *factory*) instead of a value. And when a fixture needs information about the test that uses it, ask for the built-in request fixture (tests/test_factory.py):

📄 tests/test_factory.py

import pytest


@pytest.fixture
def make_user():
    created = []

    def _make_user(name: str, role: str = "viewer") -> dict:
        user = {"name": name, "role": role}
        created.append(user)
        return user

    yield _make_user
    print(f"\n  cleaning up {len(created)} users: {[u['name'] for u in created]}")


def test_two_users(make_user, request):
    admin = make_user("ana", role="admin")
    viewer = make_user("ben")
    print(f"\n  running {request.node.name}")
    assert admin["role"] == "admin" and viewer["role"] == "viewer"
  • make_user yields the inner function _make_user; the test calls it as many times as it wants.
  • The fixture remembers what it created and cleans everything up after the test.
  • request.node.name is the current test’s name. The request object also gives access to markers, the config and parametrized values.

🧰 Useful Built-in Fixtures

pytest itself provides fixtures you can request at any time (tests/test_builtins.py):

📄 tests/test_builtins.py

import os


def test_tmp_path(tmp_path):
    report = tmp_path / "report.txt"           # a fresh folder for this test
    report.write_text("2 passed")
    assert report.read_text() == "2 passed"


def test_monkeypatch_env(monkeypatch):
    monkeypatch.setenv("BASE_URL", "https://staging.example.com")
    assert os.environ["BASE_URL"] == "https://staging.example.com"
    # the variable is restored automatically after the test


def test_capsys(capsys):
    print("Products")
    captured = capsys.readouterr()
    assert captured.out == "Products\n"
FixtureWhat it gives you
tmp_pathA unique temporary folder (pathlib.Path) per test
tmp_path_factoryTemporary folders for session-scoped fixtures
monkeypatchTemporarily change environment variables, attributes or dict items; undone after the test
capsysCapture what the test printed
requestInformation about the requesting test (name, markers, params, config)
pytestconfigAccess to command-line options and ini values

⌨️ Terminal

pytest -q -s tests/test_factory.py tests/test_builtins.py

🖥️ Output

  running test_two_users
.
  cleaning up 2 users: ['ana', 'ben']
...
4 passed in 0.02s

🎭 A Logged-in Page Fixture for Playwright

Here is the pattern you will use constantly: a fixture that builds on page, logs in, and hands the test a page that is already on the products screen (tests/test_logged_in.py):

📄 tests/test_logged_in.py

import re

import pytest
from playwright.sync_api import Page, expect


@pytest.fixture
def logged_in_page(page: Page) -> 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()
    expect(page).to_have_url(re.compile(r".*/inventory\.html"))
    return page


def test_six_products_listed(logged_in_page: Page):
    expect(logged_in_page.locator(".inventory_item")).to_have_count(6)


def test_add_to_cart(logged_in_page: Page):
    logged_in_page.locator("[data-test='add-to-cart-sauce-labs-backpack']").click()
    expect(logged_in_page.locator("[data-test='shopping-cart-badge']")).to_have_text("1")
  • logged_in_page requests page (function scope), so it is function-scoped too, and every test gets its own fresh, logged-in session.
  • The expect inside the fixture makes the setup fail loudly (as an *error*) if login is broken, instead of producing confusing failures later.
  • The tests are now about behaviour, not login steps.

🖥️ Output

..                                                                       [100%]
2 passed in 3.73s

In Module 8 you will make this even faster by logging in once and reusing the saved session with storage_state.


🏋️ 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 shop_home that opens the SQA Shop home page and returns the page, and a test that uses it to check the cart badge shows 0.

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


@pytest.fixture
def shop_home(page: Page) -> Page:
    page.goto("https://sqatools.in/dummy-ecommerce-website/")
    return page


def test_cart_empty(shop_home: Page):
    expect(shop_home.get_by_test_id("cart-count")).to_have_text("0")

Exercise 2: Write a yield fixture that creates a temporary object through the practice API and deletes it after the test.

Show answer
@pytest.fixture
def temp_object(playwright):
    api = playwright.request.new_context(base_url="https://sqatools.in/wp-json/sqa-api/v1/")
    obj = api.post("objects", data={"name": "fixture demo", "data": {}}).json()
    yield obj
    api.delete(f"objects/{obj['id']}")
    api.dispose()

Exercise 3: Which command shows the setup and teardown order of fixtures for a test file?

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

It prints SETUP/TEARDOWN lines with each fixture’s scope (S, M, F).


🧠 MCQ Quiz: pytest Fixtures: Setup, Teardown, Scope and yield

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. How does a test request a fixture?
  2. Where does teardown code go in a yield fixture?
  3. Does teardown after yield run when the test fails?
  4. What is the default fixture scope?
  5. Which scope runs a fixture once for the whole test run?
  6. What does autouse=True do?
  7. Which built-in fixture tells a fixture about the requesting test?
  8. What is a factory fixture?
  9. Can a fixture use another fixture?
  10. Which built-in fixture provides a temporary folder per test?

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


❓ Frequently Asked Questions

🤔 Where should I put fixtures that many test files use?

In a conftest.py file. Fixtures defined there are available to all tests in that folder and below without imports. That is the next lesson.

🤔 Can a fixture return nothing?

Yes. A fixture that only does setup (such as setting a timeout) can return None; tests request it, or it is autouse=True.

🤔 What happens if two fixtures have the same name?

The one closest to the test wins: a fixture in the test file overrides one in conftest.py, which overrides one from a plugin. pytest-playwright’s browser_context_args customisation in Lesson 6 relies on exactly this.

🤔 Should I use a session-scoped page to make tests faster?

No. Sharing a page lets tests leak state into each other and makes failures depend on test order. Share the browser (pytest-playwright already does), not the page.


🏁 Summary

  • Fixtures are requested by parameter name; pytest runs them and injects the result.
  • yield separates setup from teardown, and teardown runs even after a failed test.
  • Scope controls lifetime: function (default), class, module, package, session; --setup-show reveals the order.
  • Fixtures can use other fixtures of the same or wider scope; factories create many objects; built-ins include tmp_path, monkeypatch, capsys and request.

Next, you will organise fixtures across your project with conftest.py files and learn how pytest overrides them.

🎬 Watch the Playwright tutorial series on YouTube!

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

pytest Tutorial for Beginners: Test Discovery, assert and Running Tests

pytest is the test runner behind every Playwright Python suite in this course. Before going deeper into fixtures and plugins, it pays to understand pytest itself: how it finds tests, why a plain assert statement gives such helpful failure messages, how to test for exceptions and floating-point values, what each test outcome means, and how to read the results. Most examples in this lesson use plain Python so you can focus on pytest; the last one brings Playwright back in.

📖 What You’ll Learn: test discovery rules, plain assert and pytest’s assertion introspection, pytest.raises and pytest.approx, test classes, the five test outcomes, reading the short summary with -r, controlling tracebacks with –tb, exit codes for CI, and the most useful command-line flags.


🤔 Why pytest?

Python ships with a test framework called unittest, modelled on Java’s JUnit: tests live in classes that inherit from unittest.TestCase and use methods such as self.assertEqual(). pytest, the most popular alternative, lets you write tests as plain functions with plain assert, and adds fixtures, parametrization and a large plugin ecosystem. It can also run existing unittest tests, so teams can switch gradually.

unittestpytest
A test isA method in a TestCase subclassAny test_ function (or method in a Test class)
Checking a valueself.assertEqual(a, b)assert a == b
Setup and teardownsetUp / tearDown methodsFixtures with yield
PluginsFewMore than a thousand, including pytest-playwright

🔍 How pytest Finds Tests

When you run pytest, it walks through the current folder (or the testpaths you configured) and collects:

  1. files named test_*.py or *_test.py;
  2. inside them, functions whose names start with test;
  3. classes whose names start with Test and that have no __init__ method, and inside them, methods whose names start with test.

Everything else is ignored. Helper functions without the test prefix are never run as tests, which is exactly what you want.


✅ Plain assert, Powerful Messages

Create tests/test_basics.py:

📄 tests/test_basics.py

import pytest


def to_price(text: str) -> float:
    """Convert '$29.99' to 29.99."""
    return float(text.replace("$", ""))


def test_price_is_parsed():
    assert to_price("$29.99") == 29.99


def test_total_with_tax():
    total = to_price("$29.99") + to_price("$9.99")
    assert total * 1.08 == pytest.approx(43.1784)


def test_bad_price_raises_value_error():
    with pytest.raises(ValueError, match="could not convert"):
        to_price("free")


def test_tags_contain_smoke():
    tags = ["smoke", "login", "regression"]
    assert "smoke" in tags
    assert len(tags) == 3

What each test shows:

  • **assert expression**: if the expression is false, the test fails. You need no special methods; ==, in, <, is None and every other Python expression work.
  • **pytest.approx()**: floating-point maths is not exact (0.1 + 0.2 is 0.30000000000000004), so compare floats with approx, which allows a tiny tolerance.
  • **pytest.raises()**: a context manager that passes only if the code inside raises the given exception. match= checks the error message with a regular expression.

⌨️ Terminal

pytest -q tests/test_basics.py

🖥️ Output

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

What a failure looks like

pytest rewrites assert statements while importing test files, so when one fails it can show you the values involved, not just “AssertionError”. These tests fail on purpose (tests/test_failures.py):

📄 tests/test_failures.py

def test_compare_lists():
    expected = ["Backpack", "Bike Light", "Onesie"]
    actual = ["Backpack", "Bolt T-Shirt", "Onesie"]
    assert actual == expected


def test_compare_dicts():
    expected = {"browser": "chromium", "retries": 2, "headless": True}
    actual = {"browser": "chromium", "retries": 0, "headless": True}
    assert actual == expected

⌨️ Terminal

pytest -q tests/test_failures.py

🖥️ Output

_____________________________ test_compare_lists ______________________________

    def test_compare_lists():
        expected = ["Backpack", "Bike Light", "Onesie"]
        actual = ["Backpack", "Bolt T-Shirt", "Onesie"]
>       assert actual == expected
E       AssertionError: assert ['Backpack', ...rt', 'Onesie'] == ['Backpack', ...ht', 'Onesie']
E
E         At index 1 diff: 'Bolt T-Shirt' != 'Bike Light'
E         Use -v to get more diff

tests\test_failures.py:4: AssertionError
_____________________________ test_compare_dicts ______________________________

    def test_compare_dicts():
        expected = {"browser": "chromium", "retries": 2, "headless": True}
        actual = {"browser": "chromium", "retries": 0, "headless": True}
>       assert actual == expected
E       AssertionError: assert {'browser': '...adless': True} == {'browser': '...adless': True}
E
E         Omitting 2 identical items, use -vv to show
E         Differing items:
E         {'retries': 0} != {'retries': 2}
E         Use -v to get more diff

tests\test_failures.py:10: AssertionError
=========================== short test summary info ===========================
FAILED tests/test_failures.py::test_compare_lists - AssertionError: assert ['...
FAILED tests/test_failures.py::test_compare_dicts - AssertionError: assert {'...
2 failed in 0.06s

For the list, pytest pinpoints the first difference (“At index 1 diff”). For the dictionary, it hides the two identical items and shows only the key that differs: {'retries': 0} != {'retries': 2}. The long values are shortened with ...; add -v or -vv to see a full diff.

Shorter tracebacks: –tb

When many tests fail, long tracebacks are hard to scan. --tb controls them: --tb=short (shorter), --tb=line (the error plus one location line per failure) or --tb=no (none).

⌨️ Terminal

pytest -q --tb=line tests/test_failures.py

🖥️ Output

E   AssertionError: assert ['Backpack', ...rt', 'Onesie'] == ['Backpack', ...ht', 'Onesie']

      At index 1 diff: 'Bolt T-Shirt' != 'Bike Light'
      Use -v to get more diff
C:\pwv\pytest-tutorial-for-beginners\tests\test_failures.py:4: AssertionError: assert ['Backpack', ...rt', 'Onesie'] == ['Backpack', ...ht', 'Onesie']
E   AssertionError: assert {'browser': '...adless': True} == {'browser': '...adless': True}
      ...
C:\pwv\pytest-tutorial-for-beginners\tests\test_failures.py:10: AssertionError: assert {'browser': '...adless': True} == {'browser': '...adless': True}
2 failed in 0.01s

The code listings are gone; only the assertion message and the file and line of each failure remain.


🚦 The Five Test Outcomes

Every collected test ends in one of these outcomes. This file produces all of them (tests/test_outcomes.py):

📄 tests/test_outcomes.py

import sys

import pytest


@pytest.fixture
def broken_setup():
    raise RuntimeError("database not reachable")


def test_passes():
    assert 2 + 2 == 4


def test_fails():
    assert "Products" == "Product"


def test_errors_in_setup(broken_setup):
    assert True


@pytest.mark.skipif(sys.platform == "win32", reason="Linux-only check")
def test_skipped_on_windows():
    assert True


@pytest.mark.xfail(reason="known bug #123: cart badge shows 0")
def test_known_bug():
    assert 1 == 0
OutcomeLetterMeaning
passed.All asserts held
failedFAn assert or exception inside the test body
errorESomething went wrong outside the test body, in a fixture’s setup or teardown
skippedsThe test was not run (by marker or pytest.skip())
xfailedxExpected to fail, and did; xpassed (X) means it unexpectedly passed

The -r option prints a short summary for chosen outcomes; -rA means “all”:

⌨️ Terminal

pytest -q -rA tests/test_outcomes.py

🖥️ Output

.FEsx                                                                    [100%]
...
=========================== short test summary info ===========================
PASSED tests/test_outcomes.py::test_passes
SKIPPED [1] tests\test_outcomes.py:23: Linux-only check
XFAIL tests/test_outcomes.py::test_known_bug - known bug #123: cart badge shows 0
ERROR tests/test_outcomes.py::test_errors_in_setup - RuntimeError: database n...
FAILED tests/test_outcomes.py::test_fails - AssertionError: assert 'Products'...
1 failed, 1 passed, 1 skipped, 1 xfailed, 1 error in 0.07s

The progress line .FEsx shows one letter per test. The skip appears because this run was on Windows; on Linux that test would pass. pytest shortens long summary lines with ... to fit the terminal width.

The difference between failed and error matters when you read CI results: a failure usually means the application is wrong, an error usually means your test setup is broken. Markers such as skipif and xfail are covered in detail in pytest Markers.


🗃️ Grouping Tests in a Class

Classes are a simple way to group related tests. pytest creates a new instance for every test method, so tests never share instance attributes (tests/test_cart_class.py):

📄 tests/test_cart_class.py

class TestCart:
    items = []                          # class attribute: shared, avoid mutating

    def test_starts_empty(self):
        cart = []
        assert cart == []

    def test_add_item(self):
        cart = ["Backpack"]
        cart.append("Onesie")
        assert cart == ["Backpack", "Onesie"]

    def test_instances_are_separate(self):
        self.note = "set in this test only"
        assert hasattr(self, "note")

⚠️ Watch out: Do not store state on the class (like items = [] above) and change it from tests. Class attributes are shared between all tests and make results depend on run order. Use fixtures instead (next lesson).


🎭 And with Playwright

Everything above applies unchanged to browser tests. The only addition is the page fixture (tests/test_ui.py):

📄 tests/test_ui.py

import pytest
from playwright.sync_api import Page, expect


def test_practice_page_heading(page: Page):
    page.goto("https://sqatools.in/automation-practice-page/")
    expect(page.get_by_role("heading", name="Web Table")).to_be_visible()


def test_table_has_three_rows(page: Page):
    page.goto("https://sqatools.in/automation-practice-page/")
    rows = page.locator("table tbody tr")
    assert rows.count() == 3                       # plain assert on a Python value
    with pytest.raises(AssertionError):
        expect(rows).to_have_count(4, timeout=500)  # expect raises AssertionError
  • rows.count() returns a plain int, so a plain assert is fine.
  • A failing expect() raises AssertionError, which is why pytest reports it as a normal test failure. Here pytest.raises proves it, using a short timeout to keep the demo fast.

🔢 Exit Codes for CI

pytest’s exit code tells CI servers what happened. This script runs pytest from Python and prints the code for three situations (exit_codes.py):

📄 exit_codes.py

import subprocess

PY = r"C:\pwv\_venv0\Scripts\python"
cases = {
    "all passed": ["tests/test_basics.py"],
    "some failed": ["tests/test_failures.py"],
    "no tests collected": ["tests/test_basics.py", "-k", "nothing_matches"],
}
for label, args in cases.items():
    code = subprocess.run([PY, "-m", "pytest", "-q", "-p", "no:cacheprovider", *args], capture_output=True).returncode
    print(f"{label:20} -> exit code {code}")

🖥️ Output

all passed           -> exit code 0
some failed          -> exit code 1
no tests collected   -> exit code 5
CodeMeaning
0All collected tests passed
1Some tests failed
2Run interrupted (for example Ctrl+C or a collection error)
3Internal pytest error
4Command-line usage error (for example an unknown option)
5No tests were collected

💡 Tip: Exit code 5 catches a sneaky CI problem: a typo in a -k or -m filter that selects nothing would otherwise look like a “green” build.


🧭 Everyday Command-Line Flags

FlagEffect
-v / -qMore / less output
-k "login and not slow"Select by name expression
-m smokeSelect by marker
-x / --maxfail=3Stop after the first / third failure
--lf / --ffRun only last failures / run them first
-r fESummary of failed and errored tests
--tb=shortShorter tracebacks
--durations=5Show the 5 slowest tests
--collect-only -qList tests without running them
-sShow print() output

🏋️ 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 tests for def discount(price, percent) that returns the discounted price: one normal case, one that checks pytest.approx for 33.3%, and one that expects ValueError for a negative percent.

Show answer
import pytest

from shop import discount


def test_ten_percent():
    assert discount(200, 10) == 180


def test_odd_percent():
    assert discount(100, 33.3) == pytest.approx(66.7)


def test_negative_percent():
    with pytest.raises(ValueError, match="percent"):
        discount(100, -5)

Exercise 2: Group two tests for the cart in a test class. What naming rules must the class follow?

Show answer
class TestCart:
    def test_starts_empty(self): ...
    def test_add_item(self): ...

The class name must start with Test and the class must not define __init__; methods must start with test.

Exercise 3: Write the command that runs all tests quietly, shows a short summary line for skipped and failed tests, and uses short tracebacks.

Show answer
pytest -q -rsf --tb=short

🧠 MCQ Quiz: pytest Basics: Discovery, assert and Running Tests

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

  1. Which test outcome is shown as s?
  2. What does pytest’s assertion introspection give you?
  3. How do you check that a function raises ZeroDivisionError?
  4. Why use pytest.approx for floats?
  5. What is the difference between F and E?
  6. What does -r control?
  7. Which --tb value shows one line per failure?
  8. What exit code does pytest return when some tests fail?
  9. Which flag shows each test name with its result?
  10. What does -s do?

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


❓ Frequently Asked Questions

🤔 Can pytest run my old unittest tests?

Yes. pytest collects unittest.TestCase classes automatically, so you can migrate step by step.

🤔 Why does pytest show values in assertion errors but plain Python does not?

pytest rewrites the assert statements in test modules (and conftest.py files) when it imports them, adding code that records the values. Plain Python only knows the assertion failed.

🤔 Should I use assert or expect in Playwright tests?

Use expect() for anything on the page, because it waits and retries. Use plain assert for values you already have, such as a count you read or data you computed.

🤔 What is the difference between a failure and an error?

A failure happens in the test body; an error happens in setup or teardown, usually in a fixture. Errors point at broken test infrastructure rather than a broken application.


🏁 Summary

  • pytest collects test_*.py files, test functions and Test classes without __init__.
  • Plain assert plus assertion rewriting gives detailed failure messages; use pytest.approx for floats and pytest.raises for exceptions.
  • Outcomes are passed, failed, error, skipped and xfailed/xpassed; -rA summarises them.
  • Exit codes (0, 1, 2, 3, 4, 5) tell CI what happened; 5 means nothing was collected.

Next, you will learn fixtures, the feature that makes pytest so powerful for setup, teardown and sharing resources such as browsers.

🎬 Watch the Playwright tutorial series on YouTube!

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

Python async/await and asyncio for Playwright: A Beginner’s Guide

Playwright for Python offers an async API next to the sync API you have used so far. To read and write async code confidently you need three ideas: coroutines, await and the event loop. In this lesson you will learn them with small timing experiments, avoid the classic mistakes, and then use async Playwright to load several pages at the same time.

📖 What You’ll Learn: what concurrency means, async def and coroutines, await, asyncio.run, running tasks together with asyncio.gather, the “coroutine was never awaited” mistake, async with and async for, using async_playwright to open pages concurrently, and when async is (and is not) worth it for testing.


⏳ Why Async Exists

Most of the time a browser test is waiting: for a page to load, a response to arrive, an element to appear. In normal (synchronous) code, while one operation waits, nothing else happens. Asynchronous code lets a single Python thread start an operation, and while it waits, switch to other work. This is called concurrency.

An everyday comparison: a synchronous cook boils the water, waits, then chops vegetables. An asynchronous cook starts the water, chops the vegetables while it heats, and comes back when it boils. One cook, less total time.


🧩 async def, await and asyncio.run

Three building blocks:

  • async def defines a coroutine function. Calling it does not run it yet; it returns a coroutine object.
  • await runs a coroutine (or another awaitable) and pauses the current coroutine until the result is ready, letting other work run meanwhile. You can only use await inside an async def.
  • asyncio.run(main()) creates the event loop (the scheduler that switches between waiting tasks), runs main() until it finishes, and closes the loop.

⏱️ Experiment: Sequential vs Concurrent

asyncio.sleep(1) simulates waiting one second for something, such as a page load. Save this as sequential_vs_gather.py:

📄 sequential_vs_gather.py

import asyncio
import time


async def load_page(name: str, seconds: float) -> str:
    await asyncio.sleep(seconds)          # pretend we are waiting for the network
    return f"{name} loaded"


async def one_after_another() -> None:
    start = time.perf_counter()
    a = await load_page("home", 1)
    b = await load_page("login", 1)
    c = await load_page("cart", 1)
    print("sequential:", [a, b, c], f"{time.perf_counter() - start:.1f}s")


async def all_together() -> None:
    start = time.perf_counter()
    results = await asyncio.gather(
        load_page("home", 1),
        load_page("login", 1),
        load_page("cart", 1),
    )
    print("gather:    ", results, f"{time.perf_counter() - start:.1f}s")


asyncio.run(one_after_another())
asyncio.run(all_together())

🖥️ Output

sequential: ['home loaded', 'login loaded', 'cart loaded'] 3.0s
gather:     ['home loaded', 'login loaded', 'cart loaded'] 1.0s

What happened:

  • In one_after_another, each await waits for its one-second sleep to finish before the next one starts: 3 seconds in total.
  • asyncio.gather(...) starts all three coroutines at once and waits until all are done. Because the waits overlap, the total is about 1 second.
  • gather returns the results in the order you passed the coroutines, not in the order they finished.

📝 Note: Concurrency helps when code is waiting (network, disk, browsers). It does not make CPU-heavy calculations faster, because one thread still does one calculation at a time.


🐞 The Classic Mistake: Forgetting await

Calling a coroutine function without await does not run it. Save this as forgot_await.py:

📄 forgot_await.py

import asyncio


async def get_title() -> str:
    await asyncio.sleep(0.1)
    return "Swag Labs"


async def main() -> None:
    wrong = get_title()               # missing await: nothing runs
    print("Without await:", type(wrong).__name__)

    right = await get_title()
    print("With await:   ", right)


asyncio.run(main())

🖥️ Output

Without await: coroutine
With await:    Swag Labs

Python also prints a warning on the error stream when the forgotten coroutine is cleaned up:

🖥️ Output

RuntimeWarning: coroutine 'get_title' was never awaited

In async Playwright the same mistake looks like title = page.title() printing <coroutine object Page.title at 0x...> instead of the title. Whenever you see “coroutine” where you expected a value, look for a missing await.


🎭 Async Playwright: Load Three Pages Concurrently

The async API has the same methods as the sync API; every call is awaited, and with becomes async with. This script opens three practice sites at the same time in one browser (async_titles.py):

📄 async_titles.py

import asyncio
import time

from playwright.async_api import Browser, async_playwright

URLS = [
    "https://sqatools.in/automation-practice-page/",
    "https://www.saucedemo.com/",
    "https://sqatools.in/login-page/",
]


async def get_title(browser: Browser, url: str) -> str:
    context = await browser.new_context()       # one isolated context per page
    page = await context.new_page()
    await page.goto(url)
    title = await page.title()
    await context.close()
    return title


async def main() -> None:
    async with async_playwright() as p:
        browser = await p.chromium.launch()

        start = time.perf_counter()
        titles = await asyncio.gather(*(get_title(browser, url) for url in URLS))
        elapsed = time.perf_counter() - start

        for url, title in zip(URLS, titles):
            print(f"{title:40} <- {url}")
        print(f"{len(titles)} pages loaded concurrently")
        print("Finished in under 10 seconds:", elapsed < 10)

        await browser.close()


asyncio.run(main())

🖥️ Output

Automation Practice Page - SQA Tools     <- https://sqatools.in/automation-practice-page/
Swag Labs                                <- https://www.saucedemo.com/
Login Page - SQA Tools                   <- https://sqatools.in/login-page/
3 pages loaded concurrently
Finished in under 10 seconds: True

Line by line:

  1. from playwright.async_api import ... selects the async API. Browser is imported for the type hint.
  2. get_title() is a coroutine: it creates its own context and page, loads the URL, reads the title, and closes the context. Each call is independent, just like separate tests.
  3. async with async_playwright() as p: starts and stops Playwright.
  4. get_title(browser, url) for url in URLS is a generator expression that creates one coroutine per URL; the * unpacks them into asyncio.gather(...), which runs them concurrently.
  5. zip(URLS, titles) pairs each URL with its title, in the original order. {title:40} pads the title to 40 characters so the arrows line up.

💡 Tip: Exact timings depend on your network, so this script prints a yes/no check instead of a number. Try changing it to load the URLs one by one with a for loop and compare the times yourself.


🔁 async with and async for

Two more async keywords you will meet:

  • async with uses an *asynchronous* context manager, one whose setup and cleanup are awaited (async with async_playwright() as p:).
  • async for loops over an *asynchronous* iterator, which produces items that must be awaited. Playwright’s main API rarely needs it, but you will see it in async libraries.

🚫 You Cannot Start an Event Loop Inside Another

asyncio.run() creates a new event loop, and Python allows only one running loop per thread. Calling asyncio.run() from code that is already async fails (nested_run.py):

📄 nested_run.py

import asyncio


async def inner() -> str:
    return "done"


async def outer() -> None:
    coroutine = inner()
    try:
        asyncio.run(coroutine)                 # not allowed inside a running loop
    except RuntimeError as error:
        print("RuntimeError:", error)
        coroutine.close()                      # tidy up the unused coroutine
    print("Correct way:", await inner())


asyncio.run(outer())

🖥️ Output

RuntimeError: asyncio.run() cannot be called from a running event loop
Correct way: done

Inside async code, always await coroutines instead of calling asyncio.run() again. This is also why the sync Playwright API refuses to run inside an event loop (you saw that error in Lesson 1).


🧪 Should Your Tests Be Async?

For most UI test suites, no. The sync API with pytest-playwright is simpler, gives each test its own page automatically, and pytest-xdist (Module 12) already runs tests in parallel processes. Async is worth it when:

  • your application or tooling is already built on asyncio;
  • one test or script must drive many pages or API calls at the same time (for example, simulating several users);
  • you build tools such as crawlers or monitors rather than test suites.

When you do want async tests, the official pytest-playwright-asyncio plugin provides async fixtures. Module 13 covers it in detail.


🏋️ 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 an async function fetch_title(context, url) that opens a new page, goes to the URL and returns its title. Then run it for two URLs concurrently.

Show answer
import asyncio

from playwright.async_api import async_playwright


async def fetch_title(context, url):
    page = await context.new_page()
    await page.goto(url)
    title = await page.title()
    await page.close()
    return title


async def main():
    async with async_playwright() as p:
        browser = await p.chromium.launch()
        context = await browser.new_context()
        titles = await asyncio.gather(
            fetch_title(context, "https://sqatools.in/automation-practice-page/"),
            fetch_title(context, "https://sqatools.in/dummy-ecommerce-website/"),
        )
        print(titles)
        await browser.close()

asyncio.run(main())

Exercise 2: This code prints a warning and the delay never happens. Fix it.

async def wait():
    asyncio.sleep(2)
Show answer

The coroutine is created but never awaited (“coroutine was never awaited”). Write await asyncio.sleep(2).

Exercise 3: Why does time.sleep(2) inside an async function slow down every other task, while await asyncio.sleep(2) does not?

Show answer

time.sleep blocks the whole thread, so the event loop cannot run anything else. await asyncio.sleep hands control back to the event loop, which runs other tasks while this one waits.


🧠 MCQ Quiz: async/await and asyncio for Playwright

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

  1. What does async def create when called?
  2. How do you start the top-level async function?
  3. What does await do?
  4. What does asyncio.gather(a(), b()) do?
  5. What does “coroutine was never awaited” mean?
  6. Which Playwright entry point is used with asyncio?
  7. What does async with do?
  8. When is async worth it for test automation?
  9. Which should you use inside async code to wait?
  10. Concurrency in asyncio means:

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


❓ Frequently Asked Questions

🤔 Is async the same as multithreading?

No. Async runs on one thread and switches between tasks only at await points. Threads can switch at any moment and need more care with shared data. For network-bound work like browser automation, async is usually simpler and lighter.

🤔 Can I call a sync function inside an async function?

Yes, but if it blocks (for example time.sleep(5)), it freezes the whole event loop and every other task waits too. Use await asyncio.sleep(5) instead inside async code.

🤔 Does gather stop if one coroutine fails?

By default the first exception is raised from await asyncio.gather(...), but the other coroutines are not cancelled and keep running in the background. Pass return_exceptions=True to get exceptions back as results instead.

🤔 Do I need the async API to run tests in parallel?

No. Parallel test runs come from pytest-xdist with the sync API, which is the most common setup for Playwright Python suites.


🏁 Summary

  • async def creates coroutines; await runs them; asyncio.run() starts the event loop.
  • asyncio.gather() runs waiting tasks concurrently and returns results in order.
  • A missing await gives you a coroutine object and a “never awaited” warning.
  • Async Playwright uses the same methods with await and async with; use it when you truly need concurrency.

That completes Module 2. Test yourself with the Module 2 mock interview, then continue to Module 3, where you master pytest itself.

🎬 Watch the Playwright tutorial series on YouTube!

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

Python Context Managers and the with Statement for Playwright (expect_popup, expect_download)

The with statement appears in almost every Playwright Python program: it starts Playwright, waits for new tabs, catches downloads and opens files. It is powered by context managers, objects that run setup code when a block starts and cleanup code when it ends, even if the block fails. In this lesson you will learn how they work, use Playwright’s built-in ones, and write your own for timing and logging test steps.

📖 What You’ll Learn: what the with statement does, __enter__ and __exit__, why cleanup runs even after an exception, Playwright’s context managers (sync_playwright, expect_popup, expect_download), writing context managers with a class and with contextlib.contextmanager, and how pytest yield fixtures use the same idea.


🚪 What the with Statement Does

You have already used with to work with files. This program (files_demo.py) writes a small test data file and reads it back:

📄 files_demo.py

with open("users.txt", "w", encoding="utf-8") as f:
    f.write("standard_user\n")
    f.write("problem_user\n")

print("File closed after the block?", f.closed)

with open("users.txt", encoding="utf-8") as f:
    users = f.read().splitlines()

print(users)

🖥️ Output

File closed after the block? True
['standard_user', 'problem_user']
  • open(...) returns a file object, and as f gives it a name for the block.
  • When the indented block ends, the file is closed automatically: you never forget f.close().
  • splitlines() turns the text into a list of lines without the \n characters.

Any object that knows how to “start” and “finish” a block like this is a context manager.


🔧 How It Works: __enter__ and __exit__

A context manager is an object with two special methods. Python calls __enter__ when the block starts and __exit__ when it ends. This demo (enter_exit.py) prints each step, including what happens when the block raises an error:

📄 enter_exit.py

class Step:
    def __init__(self, name: str) -> None:
        self.name = name

    def __enter__(self) -> "Step":
        print(f"START {self.name}")
        return self                      # this becomes the 'as' variable

    def __exit__(self, exc_type, exc_value, traceback) -> bool:
        status = "FAILED" if exc_type else "OK"
        print(f"END   {self.name}: {status}")
        return False                     # False = let any exception continue


with Step("open login page"):
    print("  ...doing the work")

try:
    with Step("submit form"):
        raise ValueError("button not found")
except ValueError as error:
    print("Caught after cleanup:", error)

🖥️ Output

START open login page
  ...doing the work
END   open login page: OK
START submit form
END   submit form: FAILED
Caught after cleanup: button not found

Line by line:

  1. __enter__ runs first; whatever it returns is assigned to the variable after as.
  2. __exit__ always runs when the block ends, normally or through an exception. Its three parameters describe the exception (exc_type is None when there was none).
  3. Returning False from __exit__ means “do not swallow the error”, so the ValueError still reaches the except block, after the cleanup printed FAILED.

⚠️ Watch out: If __exit__ returns True, the exception is silently swallowed. In test code that hides real failures, so return False (or None) unless you truly mean to suppress an error.


🎭 Context Managers in Playwright

Starting Playwright

with sync_playwright() as p: starts the Playwright driver in __enter__ and stops it in __exit__. That is why standalone scripts in Lesson 3 never leave a Playwright process running, even when they crash.

Waiting for a new tab: expect_popup

When a click opens a new tab, you must start waiting for it before the click, otherwise the tab might open before you are listening. Playwright solves this with a context manager: the waiting starts when the block begins, and the result is available when the block ends. The practice page’s Open Google link opens in a new tab (target="_blank"). Save this as tests/test_popup.py:

📄 tests/test_popup.py

import re

from playwright.sync_api import Page, expect


def test_link_opens_new_tab(page: Page):
    page.goto("https://sqatools.in/automation-practice-page/")

    with page.expect_popup() as popup_info:              # 1. start waiting
        page.get_by_role("link", name="Open Google").click()   # 2. trigger it

    new_tab = popup_info.value                           # 3. the new Page
    new_tab.wait_for_load_state()

    print("\nNew tab URL:", new_tab.url.split("?")[0])
    expect(new_tab).to_have_url(re.compile(r"google\."))
    expect(page).to_have_url("https://sqatools.in/automation-practice-page/")
    new_tab.close()
  1. page.expect_popup() returns a context manager. Entering it starts listening for a popup.
  2. The click inside the block opens the new tab.
  3. When the block ends, Playwright waits (up to the default timeout) for the popup and stores it in popup_info.value. It is an ordinary Page, so you can use locators and assertions on it.

The original page is untouched and still on the practice page. You will learn more popup and tab techniques in Module 4.

Waiting for a download: expect_download

Downloads work the same way. To keep the example self-contained, the test builds a tiny page with a download link using page.set_content() (tests/test_download.py):

📄 tests/test_download.py

from pathlib import Path

from playwright.sync_api import Page


def test_download_report(page: Page, tmp_path: Path):
    page.set_content(
        '<a href="data:text/plain,id,name%0A1,Deepesh" download="report.csv">Download report</a>'
    )

    with page.expect_download() as download_info:        # start waiting
        page.get_by_role("link", name="Download report").click()

    download = download_info.value
    target = tmp_path / download.suggested_filename      # report.csv
    download.save_as(target)

    print("\nSaved:", target.name, "->", target.read_text().splitlines())
    assert download.suggested_filename == "report.csv"
    assert target.read_text().splitlines() == ["id,name", "1,Deepesh"]
  • page.set_content(html) replaces the page with your own HTML; handy for small, reliable demos.
  • The download attribute on the link makes the browser download the data instead of opening it. %0A is an encoded line break.
  • download.suggested_filename is the name the site proposed; save_as() copies the file where you want it.
  • tmp_path is a built-in pytest fixture that gives each test its own temporary folder, cleaned up automatically.

Other Playwright waiters follow the same pattern: page.expect_response(...), page.expect_request(...), page.expect_file_chooser(), page.expect_console_message() and context.expect_page().

Run both tests:

⌨️ Terminal

pytest -q -s tests/test_popup.py tests/test_download.py

🖥️ Output

New tab URL: https://www.google.com/
.
Saved: report.csv -> ['id,name', '1,Deepesh']
.
2 passed in 3.42s

🛠️ Write Your Own with contextlib

Writing a class with __enter__ and __exit__ works, but for most cases the contextlib.contextmanager decorator is shorter: you write a generator function with one yield. Code before yield is the setup, code after it is the cleanup. This helper times a test step (tests/test_timed_steps.py):

📄 tests/test_timed_steps.py

import time
from contextlib import contextmanager
from typing import Iterator

from playwright.sync_api import Page, expect


@contextmanager
def timed_step(name: str) -> Iterator[None]:
    start = time.perf_counter()
    print(f"\n> {name}")
    try:
        yield                                   # the body of the with block runs here
    finally:
        seconds = time.perf_counter() - start   # always runs, even if the step fails
        print(f"< {name} took {seconds:.1f}s")


def test_login_with_timed_steps(page: Page):
    with timed_step("open login page"):
        page.goto("https://www.saucedemo.com/")

    with timed_step("log in"):
        page.get_by_placeholder("Username").fill("standard_user")
        page.get_by_placeholder("Password").fill("secret_sauce")
        page.get_by_role("button", name="Login").click()

    with timed_step("check products page"):
        expect(page.locator(".title")).to_have_text("Products")
  • @contextmanager turns the generator function into a context manager.
  • Iterator[None] is the type hint for a generator that yields nothing useful.
  • try/finally around yield guarantees the cleanup line runs even when a step inside the with block raises an error. Without it, a failure would skip the timing message.
  • time.perf_counter() is a precise clock for measuring durations.

When you run it with -s, each step reports its duration (your timings will differ):

🖥️ Output

> open login page
< open login page took 0.5s

> log in
< log in took 0.1s

> check products page
< check products page took 0.1s

🔗 The Same Idea in pytest Fixtures

pytest fixtures that use yield follow exactly this setup / yield / cleanup shape:

import pytest


@pytest.fixture
def temp_user():
    user = {"name": "qa_user"}      # setup: before the test
    yield user                      # the test runs here and receives 'user'
    user.clear()                    # cleanup: after the test, even if it failed

pytest-playwright’s own page fixture works this way: it creates a context and page, yields the page to your test, and closes them afterwards. You will write many fixtures like this in Module 3.


🏋️ 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 class-based context manager Timer that prints how long the block took, and use it around a page.goto.

Show answer
import time


class Timer:
    def __enter__(self):
        self.start = time.perf_counter()
        return self

    def __exit__(self, exc_type, exc, tb):
        print(f"took {time.perf_counter() - self.start:.2f}s")
        return False          # do not swallow exceptions


with Timer():
    page.goto("https://sqatools.in/automation-practice-page/")

Exercise 2: Write the same timer with contextlib.contextmanager.

Show answer
import time
from contextlib import contextmanager


@contextmanager
def timer():
    start = time.perf_counter()
    try:
        yield
    finally:
        print(f"took {time.perf_counter() - start:.2f}s")

finally makes sure the time is printed even if the block raises.

Exercise 3: Use Playwright’s context manager to wait for a download when clicking a button with test id download-csv, then save the file.

Show answer
with page.expect_download() as info:
    page.get_by_test_id("download-csv").click()
info.value.save_as("statement.csv")

🧠 MCQ Quiz: Context Managers and the with Statement

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 the with statement guarantee?
  2. Which methods define a class-based context manager?
  3. What does __exit__ returning True do?
  4. What decorator turns a generator function into a context manager?
  5. Which Playwright call is a context manager?
  6. What does with page.expect_popup() as info: do?
  7. Where should clean-up code go in a @contextmanager function to run even on errors?
  8. How are pytest yield fixtures related to context managers?
  9. What does with open("data.csv") as f: ensure?
  10. What does the as variable receive?

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


❓ Frequently Asked Questions

🤔 Why can’t I just click and then call page.wait_for_event(“popup”)?

Because the popup may already have opened before you start waiting, and then you would wait until the timeout. Starting the wait first with with page.expect_popup() removes that race.

🤔 Can one with statement manage several context managers?

Yes: with open("a.txt") as a, open("b.txt") as b:. Both are cleaned up in reverse order when the block ends.

🤔 What is the difference between a context manager and a fixture?

A context manager wraps a block of code inside a function. A pytest fixture wraps a whole test and is requested by name. Fixtures with yield use the same setup/cleanup pattern.

🤔 Is there an async version of with?

Yes, async with, used with the async API (async with async_playwright() as p:). You will see it in the next lesson.


🏁 Summary

  • with calls __enter__ at the start and __exit__ at the end, even after an exception.
  • Playwright uses context managers to start the driver and to wait for popups, downloads, responses and more: start waiting, trigger the action, then read .value.
  • Write your own with @contextmanager plus try/finally around a single yield.
  • pytest’s yield fixtures apply the same pattern to whole tests.

Next, you will learn Python’s async/await and asyncio, the foundation of Playwright’s async API.

🎬 Watch the Playwright tutorial series on YouTube!

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

Python Type Hints for Playwright Tests: Page, Locator and Typed Test Data

Type hints are labels that say what kind of value a variable, parameter or return value should hold. Python does not enforce them when the code runs, but your editor and tools like mypy read them to give you accurate auto-complete and to catch mistakes before a test ever opens a browser. Playwright for Python ships complete type information, so a few hints make your test code much easier to write and maintain.

📖 What You’ll Learn: basic hints for str, int, float, bool, lists and dictionaries, optional values with str | None, function signatures, Playwright’s types (Page, Locator, BrowserContext, Response), typed test data with dataclasses and Literal, why hints are not checked at runtime, and how mypy finds bugs before you run tests.


🏷️ The Basics

A type hint goes after a colon for variables and parameters, and after -> for a function’s return value:

browser_name: str = "chromium"
retries: int = 2
timeout_seconds: float = 7.5
headless: bool = True

tags: list[str] = ["smoke", "login"]
expected_counts: dict[str, int] = {"products": 6, "cart": 0}
viewport: tuple[int, int] = (1280, 720)


def full_url(base: str, path: str) -> str:
    return base.rstrip("/") + "/" + path.lstrip("/")
  • list[str] means “a list whose items are strings”; dict[str, int] means “string keys with integer values”. Since Python 3.9 you can use the built-in list, dict and tuple directly in hints.
  • -> str documents that full_url returns a string.
  • Hints are optional. You can add them gradually, starting with function parameters, where they help most.

Values that might be missing: str | None

Many values can be “something or nothing”, such as an attribute that may not exist. Since Python 3.10 you write that with |:

def read_error(text: str | None) -> str:
    if text is None:
        return "no error shown"
    return text.strip()

str | None means “a string or None”. Older code writes the same thing as Optional[str] from the typing module. Playwright uses it everywhere: locator.get_attribute("href") returns str | None, because the attribute might not be there.


🎭 Playwright’s Own Types

Every Playwright class can be imported from playwright.sync_api and used as a hint:

TypeWhat it isWhere you meet it
PageA browser tabThe page fixture
LocatorA way to find element(s)page.get_by_role(...), page.locator(...)
BrowserContextAn isolated sessionThe context fixture
BrowserA browser processThe browser fixture
ResponseAn HTTP responsepage.goto() returns `ResponseNone`
APIRequestContextAn HTTP client for API testsModule 9

With these hints, VS Code knows exactly which methods exist: type page. and it lists goto, get_by_role, screenshot and the rest, with their parameters.


🧱 A Typed Page Object and Typed Test Data

Real projects combine hints in three places: page objects, test data and tests. First, the test data. A dataclass is a class that only holds data; Python writes its __init__ for you from the typed fields. Save this as data.py:

📄 data.py

from dataclasses import dataclass
from typing import Literal

BrowserName = Literal["chromium", "firefox", "webkit"]


@dataclass(frozen=True)
class User:
    username: str
    password: str
    can_log_in: bool = True


STANDARD_USER = User("standard_user", "secret_sauce")
LOCKED_USER = User("locked_out_user", "secret_sauce", can_log_in=False)


def is_supported(name: str) -> bool:
    supported: tuple[BrowserName, ...] = ("chromium", "firefox", "webkit")
    return name in supported
  • @dataclass(frozen=True) creates User(username, password, can_log_in) and makes instances read-only, so a test cannot accidentally change shared data.
  • can_log_in: bool = True has a default value, so most users only need two arguments.
  • Literal["chromium", "firefox", "webkit"] allows only those exact strings. BrowserName is a type alias: a short name for a longer hint.
  • tuple[BrowserName, ...] means “a tuple of any length whose items are BrowserName values”.

Next, a typed page object (pages/login_page.py):

📄 pages/login_page.py

from playwright.sync_api import Locator, Page

from data import User


class LoginPage:
    URL = "https://www.saucedemo.com/"

    def __init__(self, page: Page) -> None:
        self.page = page
        self.username: Locator = page.get_by_placeholder("Username")
        self.password: Locator = page.get_by_placeholder("Password")
        self.error: Locator = page.locator("[data-test='error']")

    def open(self) -> None:
        self.page.goto(self.URL)

    def login_as(self, user: User) -> None:
        self.username.fill(user.username)
        self.password.fill(user.password)
        self.page.get_by_role("button", name="Login").click()

    def error_text(self) -> str | None:
        if self.error.count() == 0:
            return None
        return self.error.inner_text()
  • The constructor takes a Page and stores Locator objects. -> None says __init__ and the action methods return nothing.
  • login_as(self, user: User) accepts a whole User, so a test cannot pass the username and password in the wrong order.
  • error_text() returns str | None, which forces callers to think about the “no error” case.

And the tests (tests/test_typed_login.py):

📄 tests/test_typed_login.py

from playwright.sync_api import Page, expect

from data import LOCKED_USER, STANDARD_USER, is_supported
from pages.login_page import LoginPage


def test_standard_user_logs_in(page: Page, browser_name: str) -> None:
    assert is_supported(browser_name)
    login = LoginPage(page)
    login.open()
    login.login_as(STANDARD_USER)
    expect(page.locator(".title")).to_have_text("Products")
    assert login.error_text() is None


def test_locked_user_sees_error(page: Page) -> None:
    login = LoginPage(page)
    login.open()
    login.login_as(LOCKED_USER)
    message = login.error_text()
    assert message is not None and "locked out" in message

🖥️ Output

..                                                                       [100%]
2 passed, 1 warning in 6.63s

(The one warning is the harmless pytest-playwright base_url deprecation notice explained in Lesson 2.)

Notice assert message is not None and ... in the second test: because error_text() may return None, checking it first is both correct Python and what the type checker expects.


⚠️ Hints Are Not Checked When Code Runs

Python stores hints but never enforces them at runtime. This file (runtime_demo.py) passes the wrong types, yet runs without any error:

📄 runtime_demo.py

def triple_retries(retries: int) -> int:
    return retries * 3


print(triple_retries(5))           # correct use: 15
print(triple_retries("5"))         # wrong type, but Python does not stop it
print(triple_retries.__annotations__)

🖥️ Output

15
555
{'retries': <class 'int'>, 'return': <class 'int'>}

Multiplying the string "5" by 3 repeats it, so instead of a crash you get a silently wrong value (555): exactly the kind of bug a type checker catches before you run anything. The hints are still stored, in the function’s __annotations__.


🔎 Catch Bugs Early with mypy

mypy is the most widely used Python type checker. Install it in your virtual environment and point it at your code:

⌨️ Terminal

python -m pip install mypy
python -m mypy --strict pages tests data.py

🖥️ Output

Success: no issues found in 4 source files

--strict turns on all of mypy’s optional checks, such as requiring hints on every function. Now look at a file with three typical mistakes (broken.py):

📄 broken.py

from playwright.sync_api import Page

from data import STANDARD_USER


def broken_steps(page: Page) -> None:
    page.goto(42)                                   # 1. a number instead of a URL string
    page.get_by_rol("button", name="Login")         # 2. typo in the method name
    href: str = page.locator("a").get_attribute("href")   # 3. may be None
    STANDARD_USER.password = "changed"              # 4. frozen dataclass

⌨️ Terminal

python -m mypy --strict broken.py

🖥️ Output

broken.py:7: error: Argument 1 to "goto" of "Page" has incompatible type "int"; expected "str"  [arg-type]
broken.py:8: error: "Page" has no attribute "get_by_rol"; maybe "get_by_role" or "get_by_ref"?  [attr-defined]
broken.py:9: error: Incompatible types in assignment (expression has type "str | None", variable has type "str")  [assignment]
broken.py:10: error: Property "password" defined in "User" is read-only  [misc]
Found 4 errors in 1 file (checked 1 source file)

mypy found all four bugs in under a second, without starting a browser:

  1. goto() expects a string URL.
  2. The typo get_by_rol is caught, with suggestions of similar real methods.
  3. get_attribute() can return None, so assigning it to a plain str is unsafe. Fix it with str | None and an if check.
  4. The frozen dataclass protects shared test data from being changed.

💡 Tip: VS Code’s Python extension (with its Pylance language server) shows many of these problems as red underlines while you type. Running mypy in CI makes the checks automatic for the whole team.


🏋️ 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 type hints to this helper:

def login(page, username, password, remember=False):
    ...
    return page
Show answer
from playwright.sync_api import Page


def login(page: Page, username: str, password: str, remember: bool = False) -> Page:
    ...
    return page

Exercise 2: Write a frozen dataclass LoginCase with username: str, password: str, an optional error: str | None = None, and browser limited to “chromium”, “firefox” or “webkit” with Literal.

Show answer
from dataclasses import dataclass
from typing import Literal


@dataclass(frozen=True)
class LoginCase:
    username: str
    password: str
    error: str | None = None
    browser: Literal["chromium", "firefox", "webkit"] = "chromium"

Exercise 3: This code runs without errors but mypy reports a problem. What is it?

def price(text: str) -> int:
    return text.replace("₹", "")
Show answer

The function promises to return an int but returns a str. Python does not check hints at runtime, so it “works” until a caller does arithmetic. Fix: return int(text.replace("₹", "").replace(",", "")).


🧠 MCQ Quiz: Type Hints 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. Are type hints enforced when Python runs your code?
  2. How do you write “a string or None” in modern Python?
  3. Which type describes a Playwright locator?
  4. How do you hint a list of strings?
  5. How do you hint a dictionary with string keys and int values?
  6. What does Literal["chromium", "firefox"] allow?
  7. What is the return type hint of a function that returns nothing?
  8. Why are type hints useful in Playwright tests?
  9. Which tool checks type hints statically?
  10. Which type do you import to annotate the page fixture?

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


❓ Frequently Asked Questions

🤔 Do type hints make my tests run faster or slower?

Neither, in any noticeable way. Python stores them but does not check them at runtime.

🤔 Do I have to add hints everywhere?

No. Start with function parameters and return types, especially page: Page in tests and page objects. Add more as the project grows.

🤔 What is the difference between str | None and Optional[str]?

They mean the same thing. str | None is the modern syntax (Python 3.10+, which Playwright requires anyway); Optional[str] is the older form you will still see in many projects.

🤔 Should test data be a dict or a dataclass?

A dataclass gives you named, typed fields, auto-complete and protection from typos. A dict is fine for quick, loosely structured data such as JSON you load and pass straight through.


🏁 Summary

  • Hints use name: type and -> return_type; collections use list[str], dict[str, int]; missing values use str | None.
  • Import Playwright types (Page, Locator, BrowserContext, Response) from playwright.sync_api.
  • Dataclasses and Literal give typed, read-only test data.
  • Python never enforces hints at runtime; mypy and your editor do, catching bugs before tests run.

Next, you will learn the with statement and context managers, which Playwright uses for starting browsers, waiting for new tabs and downloads, and which pytest fixtures are built on.

🎬 Watch the Playwright tutorial series on YouTube!

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