Browse all tutorials →
Tutorial November 20, 2026 11 min read

Playwright Pytest Tutorial: Fixtures, conftest & Parallel Runs

The pytest-playwright plugin turns Playwright into a set of Pytest fixtures. You write plain test functions, ask for page and Pytest handles the browser. Here is the full setup, from install to logged-in fixtures and parallel runs.

🐍

Quick answer: pip install pytest-playwright, then ask for the page fixture

Install the plugin, run playwright install, and write def test_x(page: Page). Use CLI flags for browsers and tracing, conftest.py for shared fixtures, and pytest-xdist for parallel runs.

What pytest-playwright is

pytest-playwright is the official plugin that connects Playwright for Python to Pytest. Instead of launching and closing browsers yourself, you request fixtures:

  • page: a fresh page in a fresh browser context for every test.
  • context, browser, browser_name: the layers underneath, when you need them.
  • Command-line flags for browser choice, headed mode, base URL, tracing, screenshots and video.

If you are new to Playwright in Python, start with the Playwright Python tutorial; this guide focuses on the Pytest side.

Install pytest-playwright

Terminal
python -m venv .venv
source .venv/bin/activate        # Windows: .venv\Scripts\activate

pip install pytest-playwright
playwright install               # downloads Chromium, Firefox and WebKit

Tip: on a fresh Linux CI image use playwright install --with-deps chromium to install only the browser you need plus its system libraries.

Your first Playwright Pytest test

Pytest finds files named test_*.py. Ask for the page fixture by naming it as an argument:

tests/test_home.py
import re
from playwright.sync_api import Page, expect


def test_has_title(page: Page):
    page.goto("https://playwright.dev/")
    expect(page).to_have_title(re.compile("Playwright"))


def test_get_started_link(page: Page):
    page.goto("https://playwright.dev/")
    page.get_by_role("link", name="Get started").click()
    expect(page.get_by_role("heading", name="Installation")).to_be_visible()

Run pytest. Both tests run headless in Chromium, each in its own isolated context. Use expect(...) rather than a bare assert: expect retries until the condition is met, while assert page.is_visible(...) checks once and causes flaky failures.

pytest-playwright command-line flags

FlagWhat it does
--headedShow the browser window
--browser firefoxPick an engine; repeat the flag to run on several
--browser-channel chromeUse branded Chrome or msedge
--base-url URLLets page.goto("/login") resolve against an environment
--slowmo 500Pause 500 ms between actions
--device "iPhone 13"Emulate a device
--tracing retain-on-failureKeep a trace zip for failed tests
--screenshot only-on-failureScreenshot on failure
--video retain-on-failureVideo of failed tests
--output DIRWhere artifacts go (default test-results)

Put the flags you always want in pytest.ini so nobody has to remember them:

pytest.ini
[pytest]
addopts = --browser chromium --tracing retain-on-failure --screenshot only-on-failure
base_url = https://staging.example.com

Open a saved trace with playwright show-trace test-results/<test>/trace.zip. The Trace Viewer tutorial shows what to look for.

Want the fundamentals behind these tests?

Locators, assertions and page objects step by step, then Claude Code and the MCP Server.

See the course plan →

Built-in fixtures and their scope

FixtureScopeUse it for
pagefunctionAlmost every test
contextfunctionMultiple tabs, cookies, permissions
browsersessionCreating your own contexts
browser_namesessionBranching on the current engine
browser_context_argssessionDefault options for every context
browser_type_launch_argssessionLaunch options such as proxies

Custom fixtures in conftest.py

conftest.py is where shared setup lives. Two fixtures cover most projects: default context options, and a logged-in page.

tests/conftest.py
import os
import pytest
from playwright.sync_api import Browser


@pytest.fixture(scope="session")
def browser_context_args(browser_context_args):
    # Extend the plugin's defaults instead of replacing them
    return {**browser_context_args, "viewport": {"width": 1280, "height": 720}, "locale": "en-US"}


@pytest.fixture(scope="session")
def auth_state(browser: Browser, base_url, tmp_path_factory) -> str:
    # Log in once per worker and save cookies + local storage
    path = tmp_path_factory.mktemp("auth") / "state.json"
    context = browser.new_context(base_url=base_url)
    page = context.new_page()
    page.goto("/login")
    page.get_by_label("Email").fill(os.environ["QA_EMAIL"])
    page.get_by_label("Password").fill(os.environ["QA_PASSWORD"])
    page.get_by_role("button", name="Sign in").click()
    page.wait_for_url("**/dashboard")
    context.storage_state(path=path)
    context.close()
    return str(path)


@pytest.fixture
def logged_in_page(browser: Browser, base_url, auth_state):
    context = browser.new_context(base_url=base_url, storage_state=auth_state)
    page = context.new_page()
    yield page
    context.close()

Any test that takes logged_in_page starts on an authenticated session without repeating the login UI. The pattern is the same idea as storageState in the Node runner.

Parametrize and browser markers

tests/test_search.py
import pytest
from playwright.sync_api import Page, expect


@pytest.mark.parametrize("term", ["locators", "assertions", "fixtures"])
def test_search_returns_results(logged_in_page: Page, term: str):
    logged_in_page.goto("/search")
    logged_in_page.get_by_role("searchbox").fill(term)
    logged_in_page.keyboard.press("Enter")
    expect(logged_in_page.get_by_role("article").first).to_be_visible()


@pytest.mark.skip_browser("webkit")
def test_file_download(page: Page): ...


@pytest.mark.only_browser("chromium")
def test_chrome_devtools_feature(page: Page): ...

Combine parametrize with several --browser flags and Pytest multiplies them: 3 terms × 3 engines = 9 test runs.

Run Playwright Pytest tests in parallel

Terminal
pip install pytest-xdist pytest-rerunfailures

pytest -n auto                       # one worker per CPU core
pytest -n 4 --browser chromium --browser firefox
pytest -n auto --reruns 1            # retry a failure once

Watch out: with xdist, a scope="session" fixture runs once per worker. Four workers mean four logins. Tests must not depend on each other or on shared mutable data, because they now run at the same time.

Retries hide problems as easily as they absorb them. If a test only passes on rerun, open its trace and fix the cause; the flaky tests guide lists the usual suspects.

Page objects with Pytest

pages/login_page.py
from playwright.sync_api import Page


class LoginPage:
    def __init__(self, page: Page):
        self.page = page
        self.email = page.get_by_label("Email")
        self.password = page.get_by_label("Password")
        self.sign_in = page.get_by_role("button", name="Sign in")

    def goto(self):
        self.page.goto("/login")

    def login(self, email: str, password: str):
        self.email.fill(email)
        self.password.fill(password)
        self.sign_in.click()

Expose page objects as fixtures (def login_page(page): return LoginPage(page)) so tests read like specifications. Keep expect calls in the tests.

pytest-playwright vs Playwright Test (Node)

Needpytest-playwrightPlaywright Test
FixturesPytest fixturesBuilt-in fixtures
Parallel runspytest-xdistBuilt in, with sharding
Retriespytest-rerunfailuresBuilt in
HTML reportpytest-htmlBuilt in
UI modeNoYes
Playwright Test AgentsNoYes
Trace Viewer, codegenYesYes

Pytest is the right call when your team already writes Python and has Pytest plugins it relies on. The Node runner ships more out of the box and gets new features, including the AI tooling, first.

How to learn Playwright with Pytest

Get the Playwright concepts solid first (locators, auto-waiting, web-first assertions, context isolation), then layer Pytest on top. Pytest itself is the easy part if you know Python.

Playwright + Claude AI & MCP Server: AI QA Automation 2026 teaches Playwright in JavaScript, not Python. It is still a useful next step: the locators, assertions, auto-waiting and Page Object Model you learn there are the same Playwright API with different casing, so everything carries over to Python. It then adds Claude Code, the Playwright MCP Server and Playwright Test Agents. See the course plan for what each section covers.


Frequently Asked Questions

What is pytest-playwright?

It is the official Pytest plugin for Playwright. It provides fixtures such as page, context and browser, plus command-line flags for browser choice, headed mode, tracing, screenshots and video.

How do I run Playwright Pytest tests in headed mode?

Run pytest --headed. Add --slowmo 500 to slow each action down so you can follow along.

How do I run Playwright Pytest tests in parallel?

Install pytest-xdist and run pytest -n auto. Each worker gets its own browser; session-scoped fixtures run once per worker, not once overall.

How do I share a logged-in state across Pytest tests?

Log in once in a session-scoped fixture, save context.storage_state(path=...), then create new contexts with storage_state= that path. Read credentials from environment variables, not from the code.

Should I use the sync or async Playwright API with Pytest?

Use the sync API for tests. It is simpler and pytest-playwright is built around it. Async tests need the separate pytest-playwright-asyncio plugin.

Does pytest-playwright have UI mode or Test Agents?

No. UI mode, the built-in HTML reporter and Playwright Test Agents are part of the Node test runner. With Pytest you use plugins such as pytest-html for reports and the Trace Viewer for debugging.

Asim Noaman, Playwright and Claude AI course instructor

Asim Noaman

Sr. SQA Manager & AI Automation Engineer

18+ years in QA. Asim currently runs an 80+ engineer QA function at Tkxel and built a Testing Center of Excellence for a major Saudi bank. He builds AI testing agents with Playwright, Claude AI and the MCP Server at work, and teaches the same workflow in his courses.

18+ Years in QA 80+ engineer QA function
Udemy Instructor 4.5★ · 140+ ratings · 570+ students
Anthropic Certificates Claude API · MCP
Connect on LinkedIn

Full profile →

Playwright + Claude AI Course on Udemy

Learn Playwright Once. Use It in Python Too.

The course teaches Playwright in JavaScript from zero: locators, assertions, hooks and the Page Object Model. The same API powers pytest-playwright with snake_case names. Then it adds Claude Code, the Playwright MCP Server and Playwright Test Agents. 107 lectures, 11.5 hours, rated 4.5★ from 140+ ratings, 570+ students.

  • Playwright from scratch in JavaScript, no prior coding needed
  • Page Object Model, hooks and timeouts
  • Claude Code, custom QA subagents and the Playwright MCP Server
  • Multi-agent workflows and Playwright Test Agents
Enroll on Udemy →