Run Playwright Python Tests in Docker (Official Image, Dockerfile, Compose)

“It works on my machine” usually means different browser builds, system libraries, fonts or Python versions. Docker removes those differences: the tests run inside an image that is identical on every laptop and CI agent. Microsoft publishes an official Playwright Python image with Python, all browsers and their dependencies. In this lesson you will pick the right image tag, run your suite in a throwaway container, build your own test image with a Dockerfile, pass secrets and collect reports through volumes, orchestrate tests next to an application with docker compose, and run browsers in a container that your tests connect to remotely.

📖 What You’ll Learn: why Docker for browser tests, the official mcr.microsoft.com/playwright/python image and its tags (noble, jammy, resolute), matching the image to your Playwright version, docker run with a bind mount, –ipc=host and –init, a Dockerfile for a test image, .dockerignore, running as the non-root pwuser, passing secrets with -e and –env-file, getting reports out with volumes, docker compose with a service under test, playwright run-server and connecting with connect_options, and a comparison of the approaches.


🐳 Why Run Tests in Docker?

Without Docker With Docker
Each machine has its own OS, fonts and libraries Everyone uses the same image
playwright install --with-deps needs admin rights on Linux Browsers and dependencies are already in the image
Screenshot baselines differ between laptops and CI Rendering is identical, so visual tests are stable
CI agents need Python and browsers pre-installed Any agent that can run Docker can run the tests

🏷️ The Official Image and Its Tags

Microsoft publishes mcr.microsoft.com/playwright/python. Tags combine the Playwright version and the Ubuntu release:

Tag Base
v1.65.2-noble Ubuntu 24.04 LTS (recommended default)
v1.65.2-jammy Ubuntu 22.04 LTS
v1.65.2-resolute Ubuntu 26.04

Each also exists with -amd64 / -arm64 suffixes. Always use the tag that matches the playwright version in your requirements.txt. A Playwright package looks for the browser builds of its own release; a mismatch fails with “Executable doesn’t exist”.

📄 requirements.txt

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

📄 check_versions.py

"""Fail fast when the Docker image tag and the pinned playwright version differ."""
import re
import sys

IMAGE = "mcr.microsoft.com/playwright/python:v1.65.2-noble"

pinned = re.search(r"^playwright==([\d.]+)$", open("requirements.txt").read(), re.M).group(1)
tagged = re.search(r":v([\d.]+)-", IMAGE).group(1)
print(f"requirements.txt: {pinned} | image tag: {tagged}")
sys.exit(0 if pinned == tagged else "versions differ: update the image tag")

⌨️ Terminal

python check_versions.py

🖥️ Output

requirements.txt: 1.65.2 | image tag: 1.65.2

A check like this in CI catches the most common Docker problem before any test runs.


▶️ Run the Suite in a Throwaway Container

📄 pytest.ini

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

📄 tests/test_shop.py

from playwright.sync_api import Page, expect


def test_home(page: Page):
    page.goto("/dummy-ecommerce-website/")
    expect(page.get_by_test_id("product-card").first).to_be_visible()


def test_search(page: Page):
    page.goto("/dummy-ecommerce-website/#/search/course")
    expect(page.get_by_test_id("product-card").first).to_be_visible()

Run the tests inside the image, with your project folder mounted:

⌨️ Terminal

docker run --rm --ipc=host --init -v "${PWD}:/work" -w /work mcr.microsoft.com/playwright/python:v1.65.2-noble bash -c "pip install -r requirements.txt && pytest"
Part Meaning
--rm Delete the container afterwards
--ipc=host Recommended for Chromium: the default shared memory in Docker is too small and can crash it
--init A tiny init process that reaps zombie browser processes
-v "${PWD}:/work" -w /work Mount the project into the container and work there; results appear on your disk

${PWD} works in PowerShell and bash; in the old Windows cmd use %cd%.


📦 Build Your Own Test Image

For CI it is faster and more repeatable to bake the dependencies into an image:

📄 Dockerfile

FROM mcr.microsoft.com/playwright/python:v1.65.2-noble

WORKDIR /tests

# Dependencies first: this layer is cached until requirements.txt changes
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

# Then the test code
COPY . .

# Run as the image's non-root user
RUN chown -R pwuser:pwuser /tests
USER pwuser

ENTRYPOINT ["pytest"]
CMD ["-q"]

📄 .dockerignore

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

Build and run:

⌨️ Terminal

docker build -t shop-tests:1.0 .
docker run --rm --ipc=host --init shop-tests:1.0
docker run --rm --ipc=host --init shop-tests:1.0 -m smoke --browser firefox
  • Copying requirements.txt before the rest of the code means changing a test does not reinstall packages: Docker reuses the cached layer.
  • ENTRYPOINT ["pytest"] plus CMD ["-q"] makes the container behave like the pytest command: arguments after the image name replace CMD.
  • .dockerignore keeps secrets (.env, .auth/), old results and the local virtual environment out of the image.
  • pwuser is a non-root user that exists in the official image. Running browsers as root disables Chromium’s sandbox, so avoid it.

A quick self-check of these rules:

📄 check_dockerfile.py

from pathlib import Path

dockerfile = Path("Dockerfile").read_text()
ignored = Path(".dockerignore").read_text().split()
checks = {
    "image tag pinned (no :latest)": ":latest" not in dockerfile and ":v" in dockerfile,
    "requirements copied before code": dockerfile.index("COPY requirements.txt") < dockerfile.index("COPY . ."),
    "runs as non-root user": "USER pwuser" in dockerfile,
    "secrets ignored": ".env*" in ignored and ".auth/" in ignored,
}
for name, ok in checks.items():
    print(("PASS " if ok else "FAIL ") + name)

⌨️ Terminal

python check_dockerfile.py

🖥️ Output

PASS image tag pinned (no :latest)
PASS requirements copied before code
PASS runs as non-root user
PASS secrets ignored

🔐 Secrets and Results

Secrets go in at run time, never into the image:

⌨️ Terminal

docker run --rm --ipc=host -e SHOP_USER -e SHOP_PASSWORD shop-tests:1.0
docker run --rm --ipc=host --env-file .env.qa shop-tests:1.0

-e NAME without a value copies the variable from your shell. --env-file reads a file (keep it out of Git).

Results come out through a volume:

⌨️ Terminal

docker run --rm --ipc=host -v "${PWD}/results:/tests/test-results" shop-tests:1.0 --tracing retain-on-failure --screenshot only-on-failure

Traces and screenshots of failed tests now appear in ./results on your machine, ready for playwright show-trace (Lesson 62).


🧩 docker compose: Tests Next to the Application

When the application under test also runs in a container (common for pull-request environments), compose starts both and connects them on one network:

📄 compose.yaml

services:
  shop:
    image: nginx:1.27-alpine                       # stands in for your application image
    volumes:
      - ./site:/usr/share/nginx/html:ro
    healthcheck:
      test: ["CMD", "wget", "-q", "-O", "-", "http://localhost/"]
      interval: 2s
      retries: 15

  tests:
    build: .
    ipc: host
    init: true
    depends_on:
      shop:
        condition: service_healthy                 # wait until the app answers
    environment:
      PYTEST_BASE_URL: http://shop                 # the service name is the host name
    command: ["-q", "-m", "smoke"]
    volumes:
      - ./results:/tests/test-results

⌨️ Terminal

docker compose up --build --exit-code-from tests
  • Service names are DNS names on the compose network, so the tests reach the app at http://shop.
  • PYTEST_BASE_URL sets --base-url (Lesson 47), so no test changes.
  • --exit-code-from tests stops everything when the tests finish and returns their exit code, which makes CI pass or fail correctly.

📄 check_compose.py

import yaml

compose = yaml.safe_load(open("compose.yaml", encoding="utf-8"))
tests = compose["services"]["tests"]
print("services:", list(compose["services"]))
print("tests wait for:", tests["depends_on"])
print("base url:", tests["environment"]["PYTEST_BASE_URL"])

⌨️ Terminal

python check_compose.py

🖥️ Output

services: ['shop', 'tests']
tests wait for: {'shop': {'condition': 'service_healthy'}}
base url: http://shop

🌐 Browsers in a Container, Tests Anywhere

Sometimes the tests should run on your machine (fast edit-run loop, debugger) while the browsers run in Linux, for example to get the same screenshots as CI. Playwright includes a browser server for this:

⌨️ Terminal

docker run --rm --init --ipc=host -p 3000:3000 --user pwuser mcr.microsoft.com/playwright/python:v1.65.2-noble playwright run-server --port 3000 --host 0.0.0.0

pytest-playwright connects to it when the connect_options fixture returns an endpoint. Note the key name: Playwright 1.65 calls it endpoint (older versions used ws_endpoint, which now raises TypeError: ... unexpected keyword argument 'ws_endpoint'):

📄 tests/conftest.py

import os

import pytest


@pytest.fixture(scope="session")
def connect_options():
    endpoint = os.getenv("PW_WS_ENDPOINT")                  # e.g. ws://127.0.0.1:3000/
    return {"endpoint": endpoint} if endpoint else None      # None = launch a local browser as usual

To try it without Docker, this script starts the same server locally (exactly what the container runs), points the tests at it, then stops it:

📄 remote_demo.py

import os
import subprocess
import sys
import time

server = subprocess.Popen(["playwright", "run-server", "--port", "3123", "--host", "127.0.0.1"],
                          stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
try:
    print("server:", server.stdout.readline().strip())          # "Listening on ws://127.0.0.1:3123/"
    env = {**os.environ, "PW_WS_ENDPOINT": "ws://127.0.0.1:3123/"}
    result = subprocess.run([sys.executable, "-m", "pytest", "-q", "tests"], env=env, capture_output=True, text=True)
    print(result.stdout.strip().splitlines()[-1])
finally:
    if os.name == "nt":      # on Windows, also stop the Node.js process the playwright launcher started
        subprocess.run(["taskkill", "/T", "/F", "/PID", str(server.pid)], capture_output=True)
    else:
        server.terminate()
    server.wait(timeout=10)

⌨️ Terminal

python remote_demo.py

🖥️ Output

server: Listening on ws://127.0.0.1:3123/
2 passed in 3.97s

The tests passed using browsers launched by the server process, not by pytest. With the container, the only difference is the endpoint (ws://127.0.0.1:3000/ mapped from Docker). Keep the client and server Playwright versions equal; the protocol is not compatible across versions.


⚖️ Which Approach When?

Approach Best for
docker run with a bind mount Trying the suite in Linux quickly; no image to maintain
Your own test image (Dockerfile) CI agents, reproducible runs, sharing the suite
docker compose Testing an application that also runs in containers
Remote browser server Local test code with CI-identical browsers; central browser hosts
CI container option (Lesson 66) GitHub Actions jobs that run directly in the image

🏋️ Practice Exercises

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

Exercise 1: Write the docker run command that runs only the smoke tests in Firefox from your built shop-tests:1.0 image and saves failure traces to ./results.

Show answer
docker run --rm --ipc=host --init -v "${PWD}/results:/tests/test-results" shop-tests:1.0 -m smoke --browser firefox --tracing retain-on-failure

Everything after the image name replaces the Dockerfile’s CMD, and the ENTRYPOINT adds pytest in front.

Exercise 2: Your teammate’s Dockerfile starts with FROM mcr.microsoft.com/playwright/python:latest. Why is that risky, and what should it be?

Show answer

latest changes whenever Microsoft publishes a new release, so the browsers in the image can stop matching the pinned playwright package (and tests can change behaviour without any code change). Pin the exact tag that matches requirements.txt, such as v1.65.2-noble, and update both together.

Exercise 3: Reorder this Dockerfile so that changing a test file does not reinstall all packages:

COPY . .
RUN pip install -r requirements.txt
Show answer
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .

Docker caches each layer; the install layer is reused until requirements.txt changes.

Exercise 4: In compose, the tests start before the app is ready and fail with connection errors. What do you add?

Show answer

A healthcheck on the app service and depends_on: { shop: { condition: service_healthy } } on the tests service, so compose starts the tests only after the app answers.


🧠 MCQ Quiz: Playwright Python in Docker

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 image does Microsoft publish for Playwright Python?
  2. Why must the image tag match the playwright version you install?
  3. What does --ipc=host help with?
  4. Why copy requirements.txt before the rest of the code in a Dockerfile?
  5. What belongs in .dockerignore for a test project?
  6. How should secrets reach the container?
  7. How do test results get out of a container?
  8. In compose, how do the tests reach the app service named shop?
  9. Which fixture makes pytest-playwright connect to a remote browser server?
  10. Which command starts Playwright’s browser server?

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


❓ Frequently Asked Questions

🤔 Can I run headed browsers in Docker?

Not usefully without a display. Use traces, videos and screenshots instead, or run tests locally against a remote browser only when you need to watch.

🤔 Is the image large?

Yes, around 1.5 to 2 GB because it contains three browsers. CI runners cache it after the first pull, and you can build a smaller custom image with only Chromium (playwright install --with-deps chromium on a slim Python base) if size matters.

🤔 Does Docker work on Windows and macOS?

Yes, through Docker Desktop (Linux containers). The tests then run in Linux, which is exactly what makes results match Linux CI agents.

🤔 Should the test image contain the tests or mount them?

Mount them for local runs (instant edits); bake them into the image for CI and for sharing a fixed version of the suite.

🤔 Can I use the remote browser server with xdist?

Yes. Each worker opens its own connection; raise the server’s --max-clients if needed, and give the container enough CPU and memory for several browsers.


🏁 Summary

  • Use mcr.microsoft.com/playwright/python:v<version>-noble with the same version as your playwright package.
  • Run throwaway containers with --rm --ipc=host --init and a bind mount, or build a test image with a cache-friendly Dockerfile, .dockerignore and the non-root pwuser.
  • Pass secrets with -e/--env-file and collect results through volumes.
  • Use docker compose with healthchecks and --exit-code-from tests to test containerised apps.
  • Run browsers in a container with playwright run-server and connect from pytest through the connect_options fixture.

🎬 Watch the Playwright tutorial series on YouTube!

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

Run Playwright Python Tests in Jenkins (Jenkinsfile Pipeline)

Many companies run their pipelines on Jenkins, often on their own servers next to internal test environments. A Jenkins pipeline for Playwright Python does the same job as a GitHub Actions workflow: get the code, prepare Python and browsers, run pytest, and keep results and evidence. In this lesson you will write a declarative Jenkinsfile that runs inside the official Playwright Docker image, passes credentials safely, takes build parameters, records JUnit results for trend charts, publishes HTML and Allure reports, archives failure artifacts, runs browsers in parallel stages and works on Windows agents too.

📖 What You’ll Learn: Jenkins pipeline basics, a declarative Jenkinsfile, a Docker agent with the Playwright Python image, a virtual environment on plain agents, withCredentials and credentials() for secrets, parameters for environment, browser and markers, the junit step and test trends, archiveArtifacts for traces and screenshots, publishHTML for pytest-html, the Allure plugin, parallel stages per browser, cron triggers, timeouts and post conditions, and Windows agents with bat.


🏗️ Jenkins Pipeline Basics

A pipeline is defined in a file called Jenkinsfile at the root of your repository. Jenkins reads it when you create a Pipeline (or Multibranch Pipeline) job pointing at the repository.

pipeline {
    agent { ... }          // where it runs
    parameters { ... }     // inputs shown on "Build with Parameters"
    stages {
        stage('Test') {
            steps { ... }  // shell commands and plugin steps
        }
    }
    post { ... }           // always / failure / success actions
}

Plugins used in this lesson (all common on Jenkins servers): Pipeline, Docker Pipeline, Credentials Binding, JUnit, HTML Publisher and (optionally) Allure.


📦 The Project

The same project shape as in Lesson 66:

📄 requirements.txt

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

📄 pytest.ini

[pytest]
addopts = --base-url https://sqatools.in
markers =
    smoke: quick checks

📄 tests/test_shop.py

import os

import pytest
from playwright.sync_api import Page, expect


@pytest.mark.smoke
def test_home(page: Page):
    page.goto("/dummy-ecommerce-website/")
    expect(page.get_by_test_id("product-card").first).to_be_visible()


@pytest.mark.smoke
def test_login(page: Page):
    page.goto("/dummy-ecommerce-website/#/login")
    page.get_by_test_id("login-username").fill(os.getenv("SHOP_USER", "testuser"))
    page.get_by_test_id("login-password").fill(os.getenv("SHOP_PASSWORD", "Test@123"))
    page.get_by_test_id("login-button").click()
    expect(page.get_by_test_id("account-button")).to_contain_text("Hi,")

📝 The Jenkinsfile

📄 Jenkinsfile

pipeline {
    agent {
        docker {
            image 'mcr.microsoft.com/playwright/python:v1.65.2-noble'
            args '--ipc=host'
        }
    }

    parameters {
        choice(name: 'BROWSER', choices: ['chromium', 'firefox', 'webkit'], description: 'Browser to test')
        string(name: 'MARKERS', defaultValue: 'smoke', description: 'pytest -m expression (empty = all tests)')
        string(name: 'BASE_URL', defaultValue: 'https://sqatools.in', description: 'Environment under test')
    }

    triggers {
        cron('H 2 * * *')                  // nightly, at a spread-out minute in the 02:00 hour
    }

    options {
        timeout(time: 45, unit: 'MINUTES')
        buildDiscarder(logRotator(numToKeepStr: '30'))
        timestamps()
    }

    environment {
        PIP_DISABLE_PIP_VERSION_CHECK = '1'
        SHOP = credentials('sqa-shop-user')    // creates SHOP_USR and SHOP_PSW
    }

    stages {
        stage('Install') {
            steps {
                sh 'python -m venv .venv'
                sh '. .venv/bin/activate && pip install -r requirements.txt'
            }
        }

        stage('Test') {
            steps {
                sh '''
                    . .venv/bin/activate
                    export SHOP_USER="$SHOP_USR" SHOP_PASSWORD="$SHOP_PSW"
                    pytest ${MARKERS:+-m "$MARKERS"} \
                        --browser "$BROWSER" --base-url "$BASE_URL" -n 2 \
                        --tracing retain-on-failure --screenshot only-on-failure \
                        --junitxml=reports/junit.xml \
                        --html=reports/report.html --self-contained-html
                '''
            }
        }
    }

    post {
        always {
            junit allowEmptyResults: true, testResults: 'reports/junit.xml'
            publishHTML(target: [reportDir: 'reports', reportFiles: 'report.html',
                                 reportName: 'Playwright report', keepAll: true, alwaysLinkToLastBuild: true,
                                 allowMissing: true])
        }
        failure {
            archiveArtifacts artifacts: 'test-results/**', allowEmptyArchive: true
        }
    }
}

What each part does:

Part Purpose
agent { docker { image ... } } Runs every step inside Microsoft’s Playwright Python image: Python, all browsers and their system libraries are already there. Match the tag to your playwright version
args '--ipc=host' Recommended by Playwright for Chromium in Docker; avoids crashes from the small default shared memory
parameters “Build with Parameters” form: browser, markers and environment without editing code
cron('H 2 * * *') Nightly run; H lets Jenkins pick a minute to spread load across jobs
timeout, buildDiscarder, timestamps Stops hung builds, keeps 30 builds, adds times to the log
credentials('sqa-shop-user') Reads a Username with password credential and exposes SHOP_USR / SHOP_PSW, masked in the log
${MARKERS:+-m "$MARKERS"} Shell trick: adds -m ... only when the parameter is not empty
junit Records results; Jenkins draws pass/fail trends across builds and shows each failure
publishHTML Adds a “Playwright report” link to the build page (HTML Publisher plugin)
archiveArtifacts on failure Keeps traces, screenshots and videos only for failed builds

📌 Note: The image already contains the browsers, so the pipeline never runs playwright install. The virtual environment is still useful: it installs your pinned test dependencies without touching the image’s own Python packages.

What the Test stage runs

The pipeline only orchestrates; the command is the same one you run locally, which is the key to debuggable CI:

⌨️ Terminal

pytest -m smoke --browser chromium --base-url https://sqatools.in -n 2 --tracing retain-on-failure --screenshot only-on-failure --junitxml=reports/junit.xml --html=reports/report.html --self-contained-html

🖥️ Output

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

..                                                                       [100%]
- Generated html report: file:///C:/Users/you/playwright-python/reports/report.html -
2 passed in 3.92s
['junit.xml', 'report.html']

Both files the post section expects exist: junit.xml for the junit step and report.html for publishHTML.


🔐 Credentials

Create the credential once: Manage Jenkins → Credentials → (global) → Add Credentials → Username with password, ID sqa-shop-user. Two ways to use it:

// 1. In environment {}: for the whole pipeline (as above)
SHOP = credentials('sqa-shop-user')          // SHOP_USR, SHOP_PSW

// 2. Only around the step that needs it
withCredentials([usernamePassword(credentialsId: 'sqa-shop-user',
                                  usernameVariable: 'SHOP_USER',
                                  passwordVariable: 'SHOP_PASSWORD')]) {
    sh '. .venv/bin/activate && pytest -m smoke'
}

Use single-quoted Groovy strings (sh '...') so the shell, not Groovy, expands $SHOP_PASSWORD. Double-quoted Groovy strings interpolate secrets into the command text, and Jenkins warns about it.


🧭 Parallel Browsers

Run each browser in its own stage, in parallel, with separate result files:

stage('Cross-browser') {
    parallel {
        stage('Chromium') { steps { sh '. .venv/bin/activate && pytest --browser chromium --junitxml=reports/junit-chromium.xml' } }
        stage('Firefox')  { steps { sh '. .venv/bin/activate && pytest --browser firefox  --junitxml=reports/junit-firefox.xml' } }
        stage('WebKit')   { steps { sh '. .venv/bin/activate && pytest --browser webkit   --junitxml=reports/junit-webkit.xml' } }
    }
}

and record all of them with junit 'reports/junit-*.xml'. Add failFast false (the default) so one browser’s failure does not abort the others.


📈 Allure in Jenkins

With the Allure Jenkins plugin (and the Allure command-line tool configured under Manage Jenkins → Tools), add allure-pytest to the requirements, run pytest with --alluredir=allure-results and publish:

post {
    always {
        allure includeProperties: false, results: [[path: 'allure-results']]
    }
}

The plugin generates the report on the server and keeps history and trends between builds automatically (Lesson 64 covers Allure itself).


🪟 Plain and Windows Agents

Without Docker, the agent needs Python and the browsers installed. On Linux add a browser install stage (playwright install --with-deps chromium, which needs root, so many teams pre-install browsers on the agent image). On a Windows agent use bat and the Windows venv layout:

stage('Install') {
    steps {
        bat 'python -m venv .venv'
        bat '.venv\\Scripts\\pip install -r requirements.txt'
        bat '.venv\\Scripts\\playwright install chromium msedge'
    }
}
stage('Test') {
    steps {
        bat '.venv\\Scripts\\pytest -m smoke --browser-channel msedge --junitxml=reports\\junit.xml'
    }
}

Backslashes are escaped (\\) inside Groovy strings. A Windows agent is the natural place for real Edge (--browser-channel msedge) runs.


🧯 Troubleshooting

Symptom Likely cause Fix
Executable doesn't exist at .../ms-playwright/... Image or installed browsers don’t match the Playwright version Align the image tag (or rerun playwright install) with requirements.txt
Chromium crashes in Docker Small /dev/shm args '--ipc=host' (or --shm-size=1gb)
junit step finds no files Tests did not run or wrong path Check the pytest step’s output; use allowEmptyResults only intentionally
HTML report shows no styles Jenkins’ Content Security Policy blocks inline CSS/JS --self-contained-html still needs a relaxed CSP for scripts; ask your Jenkins admin, or rely on JUnit and artifacts
Build hangs A test waits forever, no timeout options { timeout(...) } and sensible Playwright timeouts

🏋️ Practice Exercises

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

Exercise 1: Add a boolean parameter HEADED_DEBUG (default false) that, when true, adds --tracing on instead of retain-on-failure.

Show answer
parameters {
    booleanParam(name: 'HEADED_DEBUG', defaultValue: false, description: 'Keep traces for every test')
}
...
sh '''
    . .venv/bin/activate
    if [ "$HEADED_DEBUG" = "true" ]; then TRACING=on; else TRACING=retain-on-failure; fi
    pytest --tracing "$TRACING" --junitxml=reports/junit.xml
'''

(A real headed browser makes no sense on a CI agent without a display; traces for every test are the CI equivalent.)

Exercise 2: Why should the junit step be in post { always { ... } } and not after pytest in the same stage?

Show answer

When tests fail, pytest exits with a non-zero code, the sh step fails and the stage stops, so a junit step placed after it would never run. In post { always } it runs regardless, recording failures (and Jenkins marks the build UNSTABLE or FAILED accordingly).

Exercise 3: Write a withCredentials block that exposes an API token stored as a Secret text credential with ID practice-api-token as API_TOKEN to one pytest call.

Show answer
withCredentials([string(credentialsId: 'practice-api-token', variable: 'API_TOKEN')]) {
    sh '. .venv/bin/activate && pytest tests/api'
}

The tests read it with os.environ["API_TOKEN"].

Exercise 4: Your Docker-based pipeline fails with “Executable doesn’t exist” after someone upgraded playwright to 1.66 in requirements.txt. What exactly do you change?

Show answer

The image tag: mcr.microsoft.com/playwright/python:v1.66.x-noble (the same version as the playwright package). Each Playwright release expects its own browser builds, and the old image contains the builds for 1.65.2.


🧠 MCQ Quiz: Playwright Python in Jenkins

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. Where is a Jenkins pipeline usually defined?
  2. Why use the mcr.microsoft.com/playwright/python image as the agent?
  3. What does credentials('sqa-shop-user') create for a Username with password credential named SHOP?
  4. Why use single-quoted strings for sh steps that use secrets?
  5. What does the junit step give you?
  6. Where should junit be placed so failures are still recorded?
  7. What does cron('H 2 * * *') mean?
  8. Which Docker argument helps Chromium run reliably in a container?
  9. How do you run browsers in parallel in a declarative pipeline?
  10. What is a symptom of an image tag that does not match the installed playwright version?

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


❓ Frequently Asked Questions

🤔 Jenkins or GitHub Actions?

Both run the same pytest command. GitHub Actions is simplest when code lives on GitHub; Jenkins suits companies with self-hosted infrastructure, private networks and existing Jenkins expertise. Keep your test command in one script or Makefile so switching is easy.

🤔 Can Jenkins show the Playwright trace?

Not directly. Archive test-results/** and open the downloaded trace with playwright show-trace or trace.playwright.dev (Lesson 62).

🤔 How do I run tests on every pull request?

Use a Multibranch Pipeline job (or GitHub/GitLab branch source plugins). Jenkins discovers branches and pull requests and runs the Jenkinsfile for each, reporting status back to the pull request.

🤔 Do I need pytest-xdist on Jenkins?

Not required, but -n with the agent’s CPU count (Lesson 65) shortens builds. Combine with parallel stages for browsers when agents have enough CPU and memory.

🤔 Why is the HTML report blank in Jenkins?

Jenkins’ default Content Security Policy blocks the JavaScript that pytest-html needs. Administrators can relax it for the HTML Publisher, or the team can rely on the JUnit results and the archived report file.


🏁 Summary

  • A declarative Jenkinsfile with a Docker agent on mcr.microsoft.com/playwright/python:<version> needs no browser installation; match the tag to your Playwright version.
  • Pass secrets with credentials() or withCredentials, in single-quoted sh strings; drive runs with parameters and nightly cron.
  • Record results with junit and reports with publishHTML or the Allure plugin in post { always }; archive test-results/** on failure.
  • Run browsers in parallel stages, add timeouts, and use bat with the Windows venv layout on Windows agents.
  • Keep the pytest command identical to local runs so CI failures are easy to reproduce.

🎬 Watch the Playwright tutorial series on YouTube!

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

Run Playwright Python Tests in GitHub Actions (CI Workflow)

Tests that only run on a laptop protect nobody. In continuous integration (CI), every push and pull request runs the suite on a clean machine, and a red result blocks the change before it reaches users. GitHub Actions is free for public repositories and built into GitHub. In this lesson you will write a complete workflow for a Playwright Python project: install Python, dependencies and browsers, run pytest with failure artifacts, use secrets, cache downloads, run a browser matrix, publish a results table in the job summary, run nightly and on demand, and cancel outdated runs.

📖 What You’ll Learn: where workflows live and how they are triggered, a minimal Playwright Python workflow step by step, actions/checkout, setup-python with pip caching, playwright install –with-deps, running pytest with screenshots, traces and JUnit, uploading artifacts on failure, secrets and environment variables, a browser matrix with fail-fast off, caching browsers, a job summary from JUnit XML, schedule and workflow_dispatch triggers with inputs, concurrency, and running in the Playwright container.


🔁 How GitHub Actions Works

A workflow is a YAML file in .github/workflows/ in your repository. It says when to run (on: push, pull request, schedule …) and what to run (jobs:, each a list of steps: on a fresh virtual machine called a runner).

your-repo/
├── .github/workflows/playwright.yml    the workflow
├── requirements.txt
├── pytest.ini
└── tests/

When you push the file, GitHub runs it and shows the result next to each commit and pull request (Actions tab).


🧪 The Project

A tiny but realistic project: pinned requirements and a few tests against the SQA Shop.

📄 requirements.txt

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

📄 pytest.ini

[pytest]
addopts = --base-url https://sqatools.in
markers =
    smoke: quick checks for every push

📄 tests/test_shop.py

import os

import pytest
from playwright.sync_api import Page, expect

SHOP = "/dummy-ecommerce-website/"


@pytest.mark.smoke
def test_home(page: Page):
    page.goto(SHOP)
    expect(page.get_by_test_id("product-card").first).to_be_visible()


@pytest.mark.smoke
def test_login(page: Page):
    page.goto(SHOP + "#/login")
    page.get_by_test_id("login-username").fill(os.getenv("SHOP_USER", "testuser"))
    page.get_by_test_id("login-password").fill(os.getenv("SHOP_PASSWORD", "Test@123"))
    page.get_by_test_id("login-button").click()
    expect(page.get_by_test_id("account-button")).to_contain_text("Hi,")


def test_coupon(page: Page):
    page.goto(SHOP + "#/search/earbuds")
    page.get_by_role("button", name="Add to cart").first.click()
    page.goto(SHOP + "#/cart")
    page.get_by_test_id("coupon-input").fill("FLAT200")
    page.get_by_test_id("apply-coupon").click()
    expect(page.get_by_test_id("coupon-discount")).to_have_text("−₹200")

📝 Step 1: A Minimal Workflow

📄 .github/workflows/playwright.yml

name: Playwright tests

on:
  push:
    branches: [main]
  pull_request:

jobs:
  test:
    runs-on: ubuntu-latest
    timeout-minutes: 30
    steps:
      - uses: actions/checkout@v7

      - uses: actions/setup-python@v7
        with:
          python-version: "3.13"
          cache: pip                     # caches pip downloads, keyed on requirements.txt

      - name: Install dependencies
        run: pip install -r requirements.txt

      - name: Install Playwright browsers
        run: playwright install --with-deps chromium

      - name: Run tests
        env:
          SHOP_USER: ${{ secrets.SHOP_USER }}
          SHOP_PASSWORD: ${{ secrets.SHOP_PASSWORD }}
        run: >
          pytest
          --tracing retain-on-failure
          --screenshot only-on-failure
          --video retain-on-failure
          --junitxml=reports/junit.xml

      - name: Upload failure artifacts
        if: failure()
        uses: actions/upload-artifact@v7
        with:
          name: playwright-results
          path: test-results/
          retention-days: 7

Line by line:

Step Why
actions/checkout@v7 Copies your repository onto the runner
actions/setup-python@v7 with cache: pip Installs Python and reuses downloaded packages between runs
pip install -r requirements.txt Pinned versions: CI uses exactly what you tested locally
playwright install --with-deps chromium Downloads the browser and the Linux system libraries it needs
env: with secrets.* Credentials come from encrypted repository secrets, never from the code (Lesson 47)
--tracing/--screenshot/--video ... Failure evidence in test-results/ (Lessons 39, 62)
if: failure() + upload-artifact Keeps the evidence only when something failed; download it from the run page
timeout-minutes: 30 A hung run cannot block the queue for six hours (the default limit)

Add the secrets under Settings → Secrets and variables → Actions → New repository secret (SHOP_USER, SHOP_PASSWORD). Secrets are masked in logs and not available to pull requests from forks.

Check the workflow file before pushing

A YAML indentation mistake is the most common reason a workflow never starts. A two-line check catches it:

📄 check_workflow.py

import yaml

wf = yaml.safe_load(open(".github/workflows/playwright.yml", encoding="utf-8"))
steps = wf["jobs"]["test"]["steps"]
print("jobs:", list(wf["jobs"]), "| steps:", len(steps))
print([s.get("uses") or s.get("name") for s in steps])

⌨️ Terminal

python check_workflow.py

🖥️ Output

jobs: ['test'] | steps: 6
['actions/checkout@v7', 'actions/setup-python@v7', 'Install dependencies', 'Install Playwright browsers', 'Run tests', 'actions/upload-artifact@v7']

Run the same command locally

CI should run what you run. GitHub sets the environment variable CI=true; the test command is the same:

⌨️ Terminal

$env:CI = "true"; pytest --tracing retain-on-failure --screenshot only-on-failure --video retain-on-failure --junitxml=reports/junit.xml

🖥️ Output

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

🎛️ Step 2: A Browser Matrix

A matrix runs the same job several times with different values, in parallel, on separate runners:

📄 .github/workflows/cross-browser.yml

name: Cross-browser

on:
  pull_request:

jobs:
  test:
    runs-on: ubuntu-latest
    timeout-minutes: 30
    strategy:
      fail-fast: false                    # let every browser finish, even if one fails
      matrix:
        browser: [chromium, firefox, webkit]
    steps:
      - uses: actions/checkout@v7
      - uses: actions/setup-python@v7
        with:
          python-version: "3.13"
          cache: pip
      - run: pip install -r requirements.txt
      - run: playwright install --with-deps ${{ matrix.browser }}
      - run: pytest --browser ${{ matrix.browser }} --junitxml=reports/junit-${{ matrix.browser }}.xml
      - uses: actions/upload-artifact@v7
        if: always()
        with:
          name: junit-${{ matrix.browser }}
          path: reports/
  • fail-fast: false matters: by default GitHub cancels the other browsers as soon as one fails, so you would not know whether the bug is browser-specific.
  • Each matrix job installs only its own browser, which keeps it fast.
  • Artifact names must be unique per job, hence junit-${{ matrix.browser }}.

⚡ Step 3: Cache the Browsers

playwright install downloads around 150 to 300 MB per browser. Cache the download folder, keyed on the Playwright version from requirements.txt:

      - name: Get Playwright version
        id: pw
        run: echo "version=$(pip show playwright | grep Version | cut -d' ' -f2)" >> "$GITHUB_OUTPUT"

      - name: Cache browsers
        id: browsers
        uses: actions/cache@v6
        with:
          path: ~/.cache/ms-playwright
          key: playwright-${{ runner.os }}-${{ steps.pw.outputs.version }}

      - name: Install browsers
        if: steps.browsers.outputs.cache-hit != 'true'
        run: playwright install --with-deps chromium

      - name: Install system dependencies only
        if: steps.browsers.outputs.cache-hit == 'true'
        run: playwright install-deps chromium

The cache restores the browsers, but the system libraries are not part of it, so playwright install-deps still runs on a cache hit. When you bump Playwright, the key changes and new browsers are downloaded automatically.


📋 Step 4: Results in the Job Summary

GitHub shows Markdown written to the file named in $GITHUB_STEP_SUMMARY on the run’s summary page. A short script turns the JUnit XML into a table:

📄 ci/junit_summary.py

"""Write a Markdown summary of a JUnit XML file to $GITHUB_STEP_SUMMARY (or print it)."""
import os
import sys
import xml.etree.ElementTree as ET

path = sys.argv[1] if len(sys.argv) > 1 else "reports/junit.xml"
cases = list(ET.parse(path).getroot().iter("testcase"))


def outcome(case):
    if case.find("failure") is not None or case.find("error") is not None:
        return "❌ failed"
    if case.find("skipped") is not None:
        return "⏭️ skipped"
    return "✅ passed"


lines = ["## Playwright results", "", "| Test | Result | Time (s) |", "|---|---|---|"]
lines += [f"| {c.get('name')} | {outcome(c)} | {float(c.get('time', 0)):.1f} |" for c in cases]
passed = sum(outcome(c) == "✅ passed" for c in cases)
lines += ["", f"**{passed} of {len(cases)} passed**"]

summary = os.getenv("GITHUB_STEP_SUMMARY")
if summary:
    with open(summary, "a", encoding="utf-8") as f:
        f.write("\n".join(lines) + "\n")
else:
    print("\n".join(lines))

⌨️ Terminal

python ci/junit_summary.py reports/junit.xml

🖥️ Output

## Playwright results

| Test | Result | Time (s) |
|---|---|---|
| test_home[chromium] | ✅ passed | 4.3 |
| test_login[chromium] | ✅ passed | 2.5 |
| test_coupon[chromium] | ✅ passed | 2.1 |

**3 of 3 passed**

In the workflow, run it even when tests fail:

      - name: Job summary
        if: always()
        run: python ci/junit_summary.py reports/junit.xml

⏰ Step 5: Nightly Runs and Manual Runs

Two more triggers cover most needs: a schedule for the full regression and workflow_dispatch for a “Run workflow” button with inputs:

📄 .github/workflows/nightly.yml

name: Nightly regression

on:
  schedule:
    - cron: "30 20 * * *"            # 20:30 UTC = 02:00 IST, every day
  workflow_dispatch:
    inputs:
      marker:
        description: "pytest -m expression"
        default: "not slow"
      browser:
        type: choice
        options: [chromium, firefox, webkit]
        default: chromium

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

jobs:
  regression:
    runs-on: ubuntu-latest
    timeout-minutes: 60
    steps:
      - uses: actions/checkout@v7
      - uses: actions/setup-python@v7
        with:
          python-version: "3.13"
          cache: pip
      - run: pip install -r requirements.txt pytest-xdist
      - run: playwright install --with-deps ${{ inputs.browser || 'chromium' }}
      - name: Run
        run: >
          pytest -n auto
          -m "${{ inputs.marker || 'not slow' }}"
          --browser ${{ inputs.browser || 'chromium' }}
          --tracing retain-on-failure --junitxml=reports/junit.xml
      - if: always()
        run: python ci/junit_summary.py reports/junit.xml
      - if: failure()
        uses: actions/upload-artifact@v7
        with:
          name: nightly-results
          path: test-results/
  • Cron times are in UTC. 30 20 * * * is 02:00 in India (UTC+5:30).
  • On scheduled runs the inputs are empty, so ${{ inputs.marker || 'not slow' }} falls back to a default.
  • concurrency with cancel-in-progress stops an older run when a newer one starts for the same branch, saving runner minutes.
  • pytest -n auto (Lesson 65) uses the runner’s CPU cores (GitHub’s standard Linux runners have 4).

📄 check_all.py

import pathlib

import yaml

for path in sorted(pathlib.Path(".github/workflows").glob("*.yml")):
    wf = yaml.safe_load(path.read_text(encoding="utf-8"))
    triggers = wf[True] if True in wf else wf["on"]      # YAML 1.1 reads the key `on` as boolean True
    print(f"{path.name:20} triggers={list(triggers)} jobs={list(wf['jobs'])}")

⌨️ Terminal

python check_all.py

🖥️ Output

cross-browser.yml    triggers=['pull_request'] jobs=['test']
nightly.yml          triggers=['schedule', 'workflow_dispatch'] jobs=['regression']
playwright.yml       triggers=['push', 'pull_request'] jobs=['test']

The wf[True] line is a classic YAML surprise: PyYAML follows YAML 1.1, where the bare word on means boolean true. GitHub reads it correctly; only your own scripts need to know.


🐳 Alternative: Run Inside the Playwright Container

Instead of installing browsers and system libraries, run the job inside Microsoft’s official image, which already contains them (Lesson 68):

jobs:
  test:
    runs-on: ubuntu-latest
    container:
      image: mcr.microsoft.com/playwright/python:v1.65.2-noble
      options: --user 1001
    steps:
      - uses: actions/checkout@v7
      - run: pip install -r requirements.txt
      - run: pytest

Keep the image tag equal to your playwright version in requirements.txt; a mismatch makes Playwright look for browsers that are not in the image.


🏋️ 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: Change the minimal workflow so it runs only the smoke tests on pull requests but the full suite on pushes to main.

Show answer
      - name: Run tests
        run: |
          if [ "${{ github.event_name }}" = "pull_request" ]; then
            pytest -m smoke
          else
            pytest
          fi

Alternatively use two jobs with if: github.event_name == 'pull_request' and if: github.event_name == 'push'.

Exercise 2: Your matrix run fails only on WebKit, but you only see “cancelled” for Firefox. What setting is missing and what does it do?

Show answer

strategy.fail-fast: false. Without it, GitHub cancels the remaining matrix jobs as soon as one fails, so you cannot tell whether the failure is WebKit-specific.

Exercise 3: Write a step that uploads both reports/ and test-results/ as one artifact named results-<run number>, always, kept for 14 days.

Show answer
      - uses: actions/upload-artifact@v7
        if: always()
        with:
          name: results-${{ github.run_number }}
          path: |
            reports/
            test-results/
          retention-days: 14

Exercise 4: A teammate printed ${{ secrets.SHOP_PASSWORD }} in a step to debug and the log shows ***. Is the secret safe, and what should the team do?

Show answer

GitHub masks the exact secret value in logs, so it appears as ***, but masking is a safety net, not a guarantee (transformed values, such as base64 or partial strings, are not masked). Remove the debug print, never echo secrets, and rotate the password if there is any doubt that it leaked.


🧠 MCQ Quiz: Playwright Python in GitHub Actions

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. Where must GitHub Actions workflow files be stored?
  2. What does playwright install --with-deps chromium do on a Linux runner?
  3. How should CI tests receive passwords?
  4. What does if: failure() on the upload step do?
  5. Why set fail-fast: false in a browser matrix?
  6. When the browser cache hits, what must still run?
  7. In which time zone are GitHub Actions cron schedules?
  8. What does concurrency with cancel-in-progress: true do?
  9. What does $GITHUB_STEP_SUMMARY point to?
  10. Why must the Playwright container image tag match the playwright version in requirements.txt?

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


❓ Frequently Asked Questions

🤔 How much does GitHub Actions cost?

It is free for public repositories. Private repositories get a monthly quota of free minutes depending on the plan; Linux runners are the cheapest. Caching and concurrency keep usage down.

🤔 Can I run the tests on Windows or macOS runners?

Yes: runs-on: windows-latest or macos-latest. Use them when you need the real Edge (--browser-channel msedge) or Safari-specific checks; Linux is faster and cheaper for everything else.

🤔 How do I block merging when tests fail?

Make the workflow a required status check in the branch protection rules (Settings → Branches). Pull requests then cannot be merged until the check is green.

🤔 Where do I see screenshots and traces from a failed run?

On the workflow run page, under Artifacts. Download the zip, extract it and open the trace with playwright show-trace (Lesson 62).

🤔 Can I publish the Allure or pytest-html report?

Yes: upload it as an artifact, or deploy it to GitHub Pages with the official Pages actions. Lesson 64 shows how to generate the Allure report.


🏁 Summary

  • A workflow in .github/workflows/ checks out the code, sets up Python with pip caching, installs pinned dependencies and browsers (--with-deps), and runs pytest.
  • Pass credentials through repository secrets, keep failure artifacts with if: failure(), and add timeout-minutes.
  • Use a browser matrix with fail-fast: false, cache ~/.cache/ms-playwright keyed on the Playwright version, and still run install-deps.
  • Publish a results table to $GITHUB_STEP_SUMMARY, schedule nightly runs in UTC, add workflow_dispatch inputs and concurrency.
  • Or run inside mcr.microsoft.com/playwright/python with a tag that matches your Playwright version.

🎬 Watch the Playwright tutorial series on YouTube!

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

Parallel Execution of Playwright Python Tests with pytest-xdist

A suite that takes 40 minutes on one CPU core can take 10 on four. pytest-xdist runs your Playwright Python tests in several worker processes at once, each with its own browser. Speed is the easy part; the real skill is keeping tests correct when they run at the same time. In this lesson you will measure the speed-up on a real suite, choose how tests are distributed, keep related tests on one worker, understand what happens to session fixtures, run one-time setup safely with a file lock, generate parallel-safe test data, and avoid the most common parallel pitfalls.

📖 What You’ll Learn: how pytest-xdist works (controller and workers), installing it, -n 4, -n auto and -n logical, measuring the speed-up, –dist load, loadscope, loadfile, loadgroup and worksteal, xdist_group and a current version caveat, session fixtures running once per worker, worker_id and testrun_uid, one-time setup shared by all workers with filelock, unique test data per worker, parallel pitfalls (shared accounts, files, order), combining -n with browsers and reruns, and turning it off with -p no:xdist.


⚙️ How pytest-xdist Works

With pytest -n 4, pytest starts a controller and 4 worker processes. Every worker collects the same tests, and the controller hands out tests to whichever worker is free. Each worker is a separate Python process with:

  • its own Playwright instance and browser,
  • its own copy of every session-scoped fixture,
  • its own output, which the controller merges into one report.

Tests are therefore isolated by process. The risks come from things outside the process: the application’s data, files on disk and user accounts.

⌨️ Terminal

pip install pytest-xdist

📏 Measure the Speed-Up

A suite of twelve independent UI tests on the SQA Shop:

📄 pytest.ini

[pytest]
addopts = --base-url https://sqatools.in
markers =
    xdist_group: keep tests on the same worker

📄 tests/test_catalog.py

import pytest
from playwright.sync_api import Page, expect

SHOP = "/dummy-ecommerce-website/"
TERMS = ["earbuds", "jeans", "course", "shirt", "watch", "laptop", "camera", "ebook", "hoodie", "speaker", "charger", "dress"]


@pytest.mark.parametrize("term", TERMS)
def test_search_returns_results(page: Page, term):
    page.goto(SHOP + "#/search/" + term)
    expect(page.get_by_test_id("product-card").first).to_be_visible()

⌨️ Terminal

pytest -q

🖥️ Output

............                                                             [100%]
12 passed in 20.82s

⌨️ Terminal

pytest -q -n 4

🖥️ Output

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

............                                                             [100%]
12 passed in 8.99s

⌨️ Terminal

pytest -q -n auto

🖥️ Output

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

............                                                             [100%]
12 passed in 11.70s

Four workers cut the time noticeably, and -n auto (one worker per CPU core, 12 on this machine) cut it further, because these tests are independent and wait mostly on the network. That is not guaranteed: each worker pays a fixed start-up cost (a process and a browser), and on a 2-core CI agent or with CPU-heavy pages, too many workers make things slower. Measure on your own machines, and use --maxprocesses to cap auto.

Option Workers
-n 4 Exactly 4
-n auto One per CPU core (physical cores if psutil is installed)
-n logical One per logical CPU (hyper-threads included; needs psutil)
-n auto --maxprocesses 6 auto, but at most 6

💡 Tip: Browser tests are limited more by CPU and memory than by Python. On CI agents with 2 to 4 cores, -n 2 to -n 4 is usually the sweet spot.


🔀 How Tests Are Distributed

--dist chooses how the controller hands out tests:

Mode Behaviour Use when
load (default with -n) Any free worker takes the next test Independent tests (the normal case)
loadscope All tests of a module (or class) go to one worker Module/class fixtures are expensive
loadfile All tests of a file go to one worker Files share setup
loadgroup Tests with the same xdist_group mark go to one worker Specific tests across files must not run in parallel (see the warning below)
worksteal Like load, but idle workers steal queued tests Test durations vary a lot

Two tests that use the same shared account must not run at the same time. The most robust way to keep them together is to put them in one file and use --dist loadfile:

📄 tests/test_shared_cart.py

from playwright.sync_api import Page


def test_add_item(page: Page, worker_id):
    print(f"[{worker_id}] add item with the shared account")


def test_remove_item(page: Page, worker_id):
    print(f"[{worker_id}] remove item with the shared account")

📄 tests/test_other.py

from playwright.sync_api import Page


def test_independent_a(page: Page, worker_id):
    print(f"[{worker_id}] independent a")


def test_independent_b(page: Page, worker_id):
    print(f"[{worker_id}] independent b")

⌨️ Terminal

pytest tests/test_shared_cart.py tests/test_other.py -n 2 --dist loadfile -v

🖥️ Output

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

scheduling tests via LoadFileScheduling

tests/test_other.py::test_independent_a[chromium] 
tests/test_shared_cart.py::test_add_item[chromium] 
[gw0] [ 25%] PASSED tests/test_shared_cart.py::test_add_item[chromium] 
tests/test_shared_cart.py::test_remove_item[chromium] 
[gw1] [ 50%] PASSED tests/test_other.py::test_independent_a[chromium] 
tests/test_other.py::test_independent_b[chromium] 
[gw0] [ 75%] PASSED tests/test_shared_cart.py::test_remove_item[chromium] 
[gw1] [100%] PASSED tests/test_other.py::test_independent_b[chromium] 

============================== 4 passed in 2.66s ==============================

Each file went to a single worker, so the two shared-account tests ran one after the other on the same worker, while the other file ran in parallel on another worker.

pytest-xdist also offers @pytest.mark.xdist_group("name") with --dist loadgroup, which groups tests across files. Check it on your versions before relying on it:

⚠️ Watch out: With pytest 9.2 and pytest-xdist 3.8.0 (the latest releases when this lesson was written) xdist_group has no effect: xdist tags grouped tests by rewriting their node id, and pytest 9 no longer reads the attribute it rewrites, so grouped tests are spread over workers like any others. While this lasts, use --dist loadfile (or loadscope for classes) to keep tests together, and watch the pytest-xdist changelog for a fix.

You can verify grouping yourself: with a working loadgroup, the test ids in -v output end in @<group name>.


🔁 Session Fixtures Run Once per Worker

A session-scoped fixture runs once per worker, not once per run:

📄 tests/conftest.py

import os
from pathlib import Path

import pytest


@pytest.fixture(scope="session")
def expensive_setup(worker_id):
    # xdist hides workers' print() output, so leave a file as evidence of each setup
    Path("setup_log").mkdir(exist_ok=True)
    Path("setup_log", f"{worker_id}-pid{os.getpid()}.txt").write_text("expensive setup ran")
    return worker_id

📄 tests/test_session.py

import pytest


@pytest.mark.parametrize("n", range(6))
def test_uses_setup(expensive_setup, n):
    assert expensive_setup

⌨️ Terminal

pytest tests/test_session.py -n 3 -q
python -c "import os; print(sorted(os.listdir('setup_log')))"

🖥️ Output

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

......                                                                   [100%]
6 passed in 2.30s
['gw0-pid35800.txt', 'gw1-pid14908.txt', 'gw2-pid32440.txt']

Six tests, three workers, three setups: one per worker process. (Note that pytest-xdist does not show print() output from workers, even with -s; that is why the fixture writes files.) That is fine for things like logging in (Lesson 51: one login per worker) but wrong for setup that must happen exactly once, such as creating a shared test account or seeding a database.


🔒 Exactly-Once Setup with a File Lock

The standard recipe from the pytest-xdist documentation: the first worker creates the data and writes it to a file; the others wait on a lock and read the file. tmp_path_factory.getbasetemp().parent is a folder shared by all workers of one run:

📄 tests/test_once.py

import json
import os
from pathlib import Path

import pytest
from filelock import FileLock


def create_shared_data() -> dict:
    Path("once_log").mkdir(exist_ok=True)
    Path("once_log", f"created-by-pid{os.getpid()}.txt").write_text("created")
    return {"coupon": "SAVE10", "created_by": os.getpid()}


@pytest.fixture(scope="session")
def shared_data(tmp_path_factory, worker_id):
    if worker_id == "master":                         # not running under xdist
        return create_shared_data()
    root = tmp_path_factory.getbasetemp().parent
    data_file = root / "shared_data.json"
    with FileLock(str(data_file) + ".lock"):
        if data_file.is_file():
            return json.loads(data_file.read_text())
        data = create_shared_data()
        data_file.write_text(json.dumps(data))
        return data


@pytest.mark.parametrize("n", range(6))
def test_shared(shared_data, n):
    assert shared_data["coupon"] == "SAVE10"

⌨️ Terminal

pip install filelock

⌨️ Terminal

pytest tests/test_once.py -n 3 -q
python -c "import os; print(sorted(os.listdir('once_log')))"

🖥️ Output

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

......                                                                   [100%]
6 passed in 2.32s
['created-by-pid5320.txt']

Three workers, but the data was created once; the other workers waited for the lock and read the file. worker_id == "master" covers normal, non-parallel runs.


🧪 Parallel-Safe Test Data

When tests create data on a shared server, two workers must never create or change the same record. Make every value unique per worker and per run:

📄 tests/test_unique.py

import uuid

import pytest


@pytest.fixture
def unique_name(worker_id, testrun_uid):
    return f"pw-{testrun_uid[:6]}-{worker_id}-{uuid.uuid4().hex[:6]}"


@pytest.mark.parametrize("n", range(4))
def test_create_object(playwright, unique_name, n):
    api = playwright.request.new_context(base_url="https://sqatools.in/wp-json/sqa-api/v1/")
    created = api.post("objects", data={"name": unique_name, "data": {"n": n}}).json()
    assert created["name"] == unique_name
    api.delete(f"objects/{created['id']}")
    api.dispose()

⌨️ Terminal

pytest tests/test_unique.py -n 2 -q

🖥️ Output

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

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

testrun_uid (same for every worker of one run) and worker_id (gw0, gw1 …) are provided by pytest-xdist; together with a random suffix they make collisions impossible, even when two CI pipelines run at the same moment.


⚠️ Common Parallel Pitfalls

Pitfall Symptom Fix
One shared user account Random logouts, wrong cart contents One account per worker (testuser-{worker_id}) or per test
Tests that depend on order Pass serially, fail with -n Make every test set up its own state
Writing the same file Corrupt or missing files Per-worker paths (tmp_path, worker_id in names)
Exactly-once setup in a session fixture Setup runs N times File lock recipe above
base_url only in pytest.ini Invalid url on relative goto() Use --base-url in addopts (Lesson 49)
Global rate limits or small test servers 429 and timeouts under load Fewer workers, or mock third parties (Lesson 52)

🧩 Combining with Other Options

  • Several browsers: pytest -n 4 --browser chromium --browser firefox spreads all browser×test combinations across the workers.
  • Retries: pytest -n 4 --reruns 2 works; reruns happen on the same worker.
  • Reports: pytest-html and Allure merge results from all workers automatically.
  • Turning it off: -n 0 runs serially with the plugin loaded; -p no:xdist disables the plugin entirely (useful when debugging with --pdb, which does not work in workers).

🏋️ 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 CI agent has 4 cores. Write the command that runs the suite in parallel with as many workers as cores but never more than 4, distributing tests so idle workers can steal queued work.

Show answer
pytest -n auto --maxprocesses 4 --dist worksteal

Exercise 2: Two tests both change the shipping address of the shared account testuser. How do you stop them from running at the same time without making the whole suite serial?

Show answer

Put both tests in the same file (for example tests/test_testuser_address.py) and run with pytest -n 4 --dist loadfile: each file runs on one worker, so the two tests run one after the other while other files run in parallel. (@pytest.mark.xdist_group with --dist loadgroup is meant for this too, but check that it works with your pytest and xdist versions, see the warning in the lesson.) Better still, give each test its own account so no grouping is needed.

Exercise 3: Write a fixture worker_account that returns testuser1 on worker gw0, testuser2 on gw1 and so on, and plain testuser without xdist.

Show answer
@pytest.fixture(scope="session")
def worker_account(worker_id):
    if worker_id == "master":
        return "testuser"
    return f"testuser{int(worker_id.removeprefix('gw')) + 1}"

Create those accounts in the test environment beforehand.

Exercise 4: Why does pytest -n 4 --pdb not stop at your failing test, and what do you run instead?

Show answer

The debugger needs an interactive terminal, but tests run inside worker processes without one. Rerun the failing test serially: pytest --lf -p no:xdist --pdb (or -n 0).


🧠 MCQ Quiz: Parallel Execution with pytest-xdist

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 -n 4 start?
  2. What does -n auto choose?
  3. How often does a session-scoped fixture run with -n 3?
  4. Which --dist mode sends all tests of one file to the same worker?
  5. What is worker_id when tests run without xdist?
  6. What is the purpose of the FileLock recipe?
  7. Which folder is shared by all workers of one run?
  8. Why might -n auto be slower than -n 4 for a small suite?
  9. A test passes alone but fails with -n 4. What is the most likely cause?
  10. How do you disable xdist completely for one run?

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


❓ Frequently Asked Questions

🤔 Is Playwright’s own parallelism different in Python?

Yes. Playwright Test (TypeScript) has built-in workers. In Python, parallelism comes from pytest-xdist; the idea (one browser per worker, isolated contexts per test) is the same.

🤔 Can I run tests in parallel inside one process with threads?

Not with the sync API: Playwright’s sync objects must be used from the thread that created them. Use processes (xdist) or the async API with asyncio (Lesson 69) for concurrency inside one process.

🤔 How do I see which worker ran a test?

Use -v: each line shows [gw0], [gw1] … Inside a test, the worker_id fixture gives the same value.

🤔 Do I need more memory for parallel browser tests?

Yes. Each worker runs a browser, roughly 150 to 400 MB each depending on the pages. Watch memory on CI agents when increasing -n.

🤔 How do I split a suite across several CI machines?

xdist parallelises on one machine. For several machines, run a subset per job (for example by folder or marker, or with a sharding plugin such as pytest-split) and merge the reports afterwards.


🏁 Summary

  • pytest-xdist runs tests in separate worker processes: -n 4, -n auto, --maxprocesses; measure before choosing.
  • --dist modes control distribution; --dist loadfile keeps a file’s tests on one worker (check xdist_group + loadgroup on your versions first).
  • Session fixtures run once per worker; use the FileLock recipe for exactly-once setup.
  • Make data unique with worker_id, testrun_uid and random suffixes; avoid shared accounts, order dependencies and shared files.
  • xdist works with browsers, reruns and reports; disable it with -p no:xdist for debugging.

🎬 Watch the Playwright tutorial series on YouTube!

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

Allure Reports for Playwright Python Tests with allure-pytest

Allure turns pytest results into an interactive report site: tests grouped by feature and story, each test broken into readable steps, screenshots and traces attached where they happened, severity, links to tickets and, across runs, history and trends. In this lesson you will add allure-pytest to a Playwright Python suite, generate a report with the Allure 3 command-line tool, describe tests with titles, features, stories, severity and links, write steps in tests and page objects, attach screenshots and traces to failed tests automatically, add environment information, and fail a CI build with an Allure quality gate.

📖 What You’ll Learn: how Allure works (results then report), installing allure-pytest and the Allure CLI, –alluredir, allure generate, open and log, @allure.title, feature, story, severity, tag, link, issue and testcase, allure.dynamic, steps with allure.step as a context manager and decorator, attachments with allure.attach and attach.file, a failure hook for screenshots and traces, environment properties, single-file reports, history and a quality gate.


🧩 How Allure Works

Allure has two parts:

  1. allure-pytest, a pytest plugin, writes result files (JSON plus attachments) into a folder while tests run.
  2. The Allure command-line tool reads that folder and generates the report (a static website you can open or publish).
pytest --alluredir=allure-results  →  allure-results/*.json  →  allure generate  →  allure-report/index.html

Keeping them separate means you can merge results from several machines or browsers into one report.


📦 Install

⌨️ Terminal

pip install allure-pytest
npm install -g allure          # Allure 3 command-line tool (needs Node.js 20 or newer)

This lesson uses allure-pytest 2.16 and Allure 3.33. Allure 3 is the current, Node.js-based report generator. The older Allure 2 (“classic”) CLI needs Java and is started with allure serve allure-results; allure-pytest produces the same results for both.

💡 Tip: Without a global install you can run Allure 3 with npx allure ... from a project that has it in package.json.


▶️ First Results and Report

📄 pytest.ini

[pytest]
addopts = --base-url https://sqatools.in --alluredir=allure-results --clean-alluredir
pythonpath = .

--clean-alluredir empties the folder at the start of each run, so old results do not mix with new ones.

📄 tests/test_basic.py

from playwright.sync_api import Page, expect


def test_home_lists_products(page: Page):
    page.goto("/dummy-ecommerce-website/")
    expect(page.get_by_test_id("product-card").first).to_be_visible()

⌨️ Terminal

pytest -q

🖥️ Output

.                                                                        [100%]
1 passed in 2.27s

📄 list_results.py

from pathlib import Path

files = sorted(p.name.split("-")[-1] for p in Path("allure-results").iterdir())
print(len(files), "files:", sorted(set(files)))

⌨️ Terminal

python list_results.py

🖥️ Output

22 files: ['container.json', 'result.json']

Each test produces a *-result.json; fixtures and setup produce *-container.json. Now generate and inspect the report:

⌨️ Terminal

npx allure generate allure-results -o allure-report

🖥️ Output

(no output)

⌨️ Terminal

npx allure open allure-report      # serves the report and opens your browser

allure log prints the same results in the terminal, which is handy in CI logs:

⌨️ Terminal

npx allure log allure-results

🖥️ Output

test_basic
  ✓ test_home_lists_products[chromium] 1544ms

Total tests: 1
Tests: 1 passed
Duration: 1.544s
the report successfully generated (86ms)

🏷️ Describe Tests: Titles, Features, Severity, Links

Allure decorators add metadata that the report uses for grouping, filtering and linking:

📄 tests/test_login.py

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

SHOP = "/dummy-ecommerce-website/"


@allure.feature("Login")
@allure.story("Valid credentials")
@allure.title("Shopper logs in with username and password")
@allure.severity(allure.severity_level.CRITICAL)
@allure.tag("smoke", "ui")
@allure.link("https://sqatools.in/dummy-ecommerce-website/", name="SQA Shop")
@allure.testcase("SHOP-101")
def test_valid_login(page: Page):
    page.goto(SHOP + "#/login")
    page.get_by_test_id("login-username").fill("testuser")
    page.get_by_test_id("login-password").fill("Test@123")
    page.get_by_test_id("login-button").click()
    expect(page.get_by_test_id("account-button")).to_contain_text("Hi, Test")


@allure.feature("Login")
@allure.story("Refused logins")
@pytest.mark.parametrize("username, message", [
    ("lockeduser", "This account is locked. Please contact support."),
    ("ghost", "Invalid username or password."),
])
def test_refused_login(page: Page, username, message):
    allure.dynamic.title(f"Login is refused for '{username}'")
    allure.dynamic.description(f"Expect the message: {message}")
    page.goto(SHOP + "#/login")
    page.get_by_test_id("login-username").fill(username)
    page.get_by_test_id("login-password").fill("Test@123")
    page.get_by_test_id("login-button").click()
    expect(page.get_by_test_id("login-error")).to_have_text(message)
Decorator Shows as
@allure.title The test name in the report
@allure.feature / @allure.story / @allure.epic The Behaviors tree
@allure.severity blocker, critical, normal, minor, trivial (filterable)
@allure.tag Tags for filtering
@allure.link, @allure.issue, @allure.testcase Links to docs, bug tracker and test-management tool
allure.dynamic.title(...) etc. Metadata computed at run time, ideal for parametrized tests

🪜 Steps: Make Tests Read Like a Plan

Steps split a test into named stages. When a test fails, the report shows which step broke. Use allure.step as a context manager in tests, or as a decorator on page-object methods so every test that uses them gets steps for free:

📄 pages/shop.py

import allure
from playwright.sync_api import Page

SHOP = "/dummy-ecommerce-website/"


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

    @allure.step("Search for {term}")
    def search(self, term: str):
        self.page.goto(SHOP)
        self.page.get_by_test_id("search-input").fill(term)
        self.page.get_by_test_id("search-button").click()

    @allure.step("Add {product} to the cart")
    def add_to_cart(self, product: str):
        card = self.page.get_by_test_id("product-card").filter(has_text=product).first
        card.get_by_role("button", name="Add to cart").click()

    @allure.step("Apply coupon {code}")
    def apply_coupon(self, code: str):
        self.page.goto(SHOP + "#/cart")
        self.page.get_by_test_id("coupon-input").fill(code)
        self.page.get_by_test_id("apply-coupon").click()

📄 tests/test_cart.py

import allure
from playwright.sync_api import Page, expect

from pages.shop import ShopPage


@allure.feature("Cart")
@allure.story("Coupons")
@allure.title("SAVE10 is capped at ₹500")
def test_save10(page: Page):
    shop = ShopPage(page)
    shop.search("earbuds")
    shop.add_to_cart("Wireless Earbuds")
    shop.apply_coupon("SAVE10")
    with allure.step("Check the discount line"):
        expect(page.get_by_test_id("coupon-discount")).to_have_text("−₹500")


@allure.feature("Cart")
@allure.story("Coupons")
@allure.title("FLAT200 discount (wrong expectation, fails on purpose)")
def test_flat200_wrong(page: Page):
    shop = ShopPage(page)
    shop.search("earbuds")
    shop.add_to_cart("Wireless Earbuds")
    shop.apply_coupon("FLAT200")
    with allure.step("Check the discount line"):
        expect(page.get_by_test_id("coupon-discount")).to_have_text("−₹250", timeout=3_000)

The {term} placeholders in step names are filled with the method’s arguments. Allure inserts string arguments with quotes (Search for 'earbuds'), so do not add your own quotes around placeholders.


📎 Attachments: Screenshots and Traces on Failure

Attach evidence exactly where it helps. The hook stores each test’s outcome on the test item; an autouse fixture then attaches a screenshot and the page URL for failed tests, while the page is still open:

📄 tests/conftest.py

import allure
import pytest
from playwright.sync_api import Page


@pytest.hookimpl(wrapper=True)
def pytest_runtest_makereport(item, call):
    report = yield
    setattr(item, f"report_{report.when}", report)          # report_setup, report_call, report_teardown
    return report


@pytest.fixture(autouse=True)
def attach_on_failure(request, page: Page):
    yield
    report = getattr(request.node, "report_call", None)
    if report is not None and report.failed:
        allure.attach(page.screenshot(full_page=True), name="screenshot", attachment_type=allure.attachment_type.PNG)
        allure.attach(page.url, name="page url", attachment_type=allure.attachment_type.URI_LIST)

Traces and videos are written by pytest-playwright when the browser context closes, which happens after this fixture has finished, so they cannot be attached from here. Keep --tracing retain-on-failure and publish the test-results/ folder as a CI artifact next to the Allure report (Lesson 66); the screenshot in Allure tells you what broke, the trace tells you why.

Run the suite and look at the failed test’s details:

⌨️ Terminal

pytest -q --tb=no

🖥️ Output

..F...                                                                   [100%]
=========================== short test summary info ===========================
FAILED tests/test_cart.py::test_flat200_wrong[chromium] - AssertionError: Loc...
1 failed, 5 passed in 16.25s

⌨️ Terminal

npx allure log allure-results --all-steps

🖥️ Output

test_cart
  ✓ SAVE10 is capped at ₹500 1838ms
    ✓ Search for 'earbuds' 1647ms
    ✓ Add 'Wireless Earbuds' to the cart 65ms
    ✓ Apply coupon 'SAVE10' 104ms
    ✓ Check the discount line 20ms
  ⨯ FLAT200 discount (wrong expectation, fails on purpose) 4634ms
    AssertionError: Locator expected to have text '−₹250'
Actual value: −₹200 
Call log:
  - Expect "to_have_text" get_by_test_id("coupon-discount") with timeout 3000ms
  - waiting for get_by_test_id("coupon-discount")
    10 × locator resolved to <dd class="save" data-testid="coupon-discount">−₹200</dd>
       - unexpected value "−₹200"

Aria snapshot:
- definition: −₹200
    ✓ Search for 'earbuds' 1421ms
    ✓ Add 'Wireless Earbuds' to the cart 35ms
    ✓ Apply coupon 'FLAT200' 108ms
    ⨯ Check the discount line 3010ms

test_basic
  ✓ test_home_lists_products[chromium] 1439ms

test_login
  ✓ Login is refused for 'lockeduser' 1847ms
  ✓ Login is refused for 'ghost' 2931ms
  ✓ Shopper logs in with username and password 1745ms

Total tests: 6
Tests: 5 passed | 1 failed
Duration: 14.434s
the report successfully generated (96ms)

The log shows every step with its duration and marks the failed one with the assertion message. Open the HTML report to see the screenshot and URL attached to that test.


🌍 Environment and Executor Information

Allure shows an Environment widget from a simple properties file in the results folder. Write it from conftest.py at the start of the run:

def pytest_sessionstart(session):
    results = session.config.getoption("--alluredir")
    if results:
        from pathlib import Path
        Path(results).mkdir(exist_ok=True)
        Path(results, "environment.properties").write_text(
            "Environment=qa\nBase.URL=https://sqatools.in\nBrowser=chromium\n", encoding="utf-8")

📄 Single-File Report and History

Allure 3 can produce one self-contained HTML file, handy for email and ticket attachments:

⌨️ Terminal

npx allure awesome allure-results --single-file -o allure-single

🖥️ Output

the report successfully generated (527ms)
index.html
summary.json
test-results.json

For history and trends (pass rate over time, flaky tests, duration changes), keep the history file from the previous run between CI builds (for example with a cache or by publishing the report to the same location) and pass it with --history-path. The Allure documentation for your CI system shows the exact recipe.


🚦 Quality Gate in CI

Allure 3 can fail a pipeline when results fall below a threshold, independent of pytest’s exit code:

⌨️ Terminal

npx allure quality-gate allure-results --success-rate 0.9

🖥️ Output

Quality Gate failed with following issues:

 ⨯ Success rate 0.833 is less, than expected 0.9    successRate

1 quality gate rules have been failed.

With one of six tests failing (a success rate of 0.833) the gate fails with exit code 1. Note that --success-rate is a ratio between 0 and 1: 0.9 means 90%. Another useful rule is --min-tests-count, which catches a suite that silently ran far fewer tests than expected.


🏋️ 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 Allure metadata to a test so it appears under epic “Shop”, feature “Search”, story “Search by keyword”, with normal severity and a link to ticket SHOP-77 at https://jira.example.com/browse/SHOP-77.

Show answer
@allure.epic("Shop")
@allure.feature("Search")
@allure.story("Search by keyword")
@allure.severity(allure.severity_level.NORMAL)
@allure.issue("https://jira.example.com/browse/SHOP-77", name="SHOP-77")
def test_search_keyword(page): ...

Exercise 2: Wrap the login steps of a test in a single Allure step named “Log in as testuser” without changing the page object.

Show answer
with allure.step("Log in as testuser"):
    page.goto("/dummy-ecommerce-website/#/login")
    page.get_by_test_id("login-username").fill("testuser")
    page.get_by_test_id("login-password").fill("Test@123")
    page.get_by_test_id("login-button").click()

Steps can be nested: a decorated page-object method called inside this block becomes a child step.

Exercise 3: Attach the JSON body of an API response to the Allure report in a test.

Show answer
response = api.get("products", params={"per_page": 3})
allure.attach(response.text(), name="products response", attachment_type=allure.attachment_type.JSON)

Exercise 4: Write the CI commands that run the tests, generate the report even when tests fail, and then apply a quality gate of 95%.

Show answer
pytest --alluredir=allure-results || true
npx allure generate allure-results -o allure-report
npx allure quality-gate allure-results --success-rate 0.95

|| true (bash) lets the pipeline continue to the report step; the quality gate decides the final status. In GitHub Actions use if: always() on the report step instead.


🧠 MCQ Quiz: Allure Reports with allure-pytest

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 allure-pytest produce during a test run?
  2. What does --clean-alluredir do?
  3. Which command builds the report with Allure 3?
  4. Which decorators build the Behaviors tree?
  5. How do you set a title computed at run time, for example from parameters?
  6. What does @allure.step("Search for {term}") on a method do?
  7. Which call attaches a PNG screenshot?
  8. Why does the lesson take the screenshot in fixture teardown after checking report_call?
  9. What does allure quality-gate --success-rate 0.9 do?
  10. What do Allure 2 (classic) and Allure 3 have in common?

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


❓ Frequently Asked Questions

🤔 Allure 2 or Allure 3?

Allure 3 is the current generator (Node.js, faster, single-file output, quality gates, new “awesome” layout). Allure 2 (Java) is still widely used and supported by many CI plugins, for example the Jenkins Allure plugin. Your tests and allure-pytest do not change either way.

🤔 Can I use Allure with pytest-xdist?

Yes. Every worker writes into the same allure-results folder, and the report combines them.

🤔 Does Allure work with pytest-bdd scenarios?

Yes, allure-pytest-bdd (a separate plugin) reports Gherkin features, scenarios and steps natively. With plain allure-pytest, pytest-bdd scenarios appear as normal tests.

🤔 How do I publish the report from CI?

Generate it in the pipeline and upload allure-report/ as an artifact, or publish it to GitHub Pages or an internal web server. Lesson 66 shows artifact uploads in GitHub Actions.

🤔 My steps are missing in the report. Why?

Steps are only recorded when they run inside a test with allure-pytest active (--alluredir given). Also check that decorated methods are actually called and that the decorator is @allure.step(...) with parentheses.


🏁 Summary

  • allure-pytest writes results with --alluredir; the Allure CLI (allure generate, open, log) builds the report.
  • Titles, epics, features, stories, severity, tags and links organise and connect tests; allure.dynamic sets them at run time.
  • allure.step (context manager or decorator on page objects) turns tests into readable plans.
  • allure.attach adds screenshots, URLs and API bodies; a makereport hook plus an autouse fixture attaches evidence on failure.
  • Add environment info, produce single-file reports, keep history between runs, and enforce a quality gate in CI.

🎬 Watch the Playwright tutorial series on YouTube!

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

HTML Reports for Playwright Python Tests with pytest-html

The terminal output of pytest is perfect for the person who ran the tests and useless for everyone else. A manager, a developer fixing a bug or a teammate looking at last night’s run wants one file they can open in a browser. pytest-html creates exactly that. In this lesson you will generate a self-contained HTML report for a Playwright suite, attach a screenshot, the page URL and the browser’s console errors to every failed test, change the title, add environment details and custom columns, and name reports per run for CI.

📖 What You’ll Learn: installing pytest-html, –html and –self-contained-html, what the report shows, adding it to addopts, the pytest_runtest_makereport hook, attaching screenshots, URLs, text and HTML with pytest_html.extras, reading the page from item.funcargs, a custom report title, environment metadata, custom columns, timestamped report names, and reports as CI artifacts.


📊 Your First HTML Report

⌨️ Terminal

pip install pytest-html

This lesson uses pytest-html 4.2. Write a few tests, one of which fails on purpose:

📄 pytest.ini

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

📄 tests/test_shop.py

import pytest
from playwright.sync_api import Page, expect

SHOP = "/dummy-ecommerce-website/"


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


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


def test_coupon_message(page: Page):
    page.goto(SHOP + "#/search/earbuds")
    page.get_by_role("button", name="Add to cart").first.click()
    page.goto(SHOP + "#/cart")
    page.get_by_test_id("coupon-input").fill("SAVE20")
    page.get_by_test_id("apply-coupon").click()
    expect(page.get_by_test_id("coupon-message")).to_have_text("Coupon SAVE20 applied.", timeout=3_000)


@pytest.mark.skip(reason="wishlist not built yet")
def test_wishlist(page: Page):
    pass

⌨️ Terminal

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

🖥️ Output

..Fs                                                                     [100%]
- Generated html report: file:///C:/Users/you/playwright-python/reports/report.html -
=========================== short test summary info ===========================
FAILED tests/test_shop.py::test_coupon_message[chromium] - AssertionError: Lo...
1 failed, 2 passed, 1 skipped in 8.47s

Open reports/report.html in any browser. It shows:

  • A summary with counts per outcome and filters (click “Failed” to see only failures).
  • The environment: Python, platform, packages and plugins (from pytest-metadata).
  • One row per test with its result and duration; click a row to expand the traceback and captured output.

--self-contained-html puts the CSS and JavaScript inside the one file, so you can email it or attach it to a ticket. Without it, pytest-html writes an assets/ folder next to the report that must travel with it.

💡 Tip: Add the options to addopts (addopts = --html=reports/report.html --self-contained-html) so every run produces a report without anyone remembering the flags.


📸 Screenshots and Details on Failure

A failed UI test without a picture is hard to judge. pytest-html lets a hook attach extras to a test’s row. The hook below runs after each test phase; when the test body failed and it used the page fixture, it attaches:

  • a screenshot of the page at the moment of failure,
  • the page URL as a link,
  • the browser console errors collected during the test.

📄 tests/conftest.py

import base64

import pytest
import pytest_html
from playwright.sync_api import Page


@pytest.fixture(autouse=True)
def console_errors(page: Page):
    errors = []
    page.on("console", lambda m: errors.append(m.text) if m.type == "error" else None)
    return errors


@pytest.hookimpl(wrapper=True)
def pytest_runtest_makereport(item, call):
    report = yield
    if report.when == "call" and report.failed:
        page = item.funcargs.get("page")
        if page is not None and not page.is_closed():
            extras = getattr(report, "extras", [])
            png = page.screenshot(full_page=True)
            extras.append(pytest_html.extras.png(base64.b64encode(png).decode(), name="Screenshot at failure"))
            extras.append(pytest_html.extras.url(page.url, name="Page URL"))
            errors = item.funcargs.get("console_errors") or []
            if errors:
                extras.append(pytest_html.extras.text("\n".join(errors), name="Console errors"))
            report.extras = extras
    return report

⌨️ Terminal

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

🖥️ Output

..Fs                                                                     [100%]
- Generated html report: file:///C:/Users/you/playwright-python/reports/report.html -
=========================== short test summary info ===========================
FAILED tests/test_shop.py::test_coupon_message[chromium] - AssertionError: Lo...
1 failed, 2 passed, 1 skipped in 7.52s

How it works:

  • @pytest.hookimpl(wrapper=True) lets the hook run around pytest’s own report creation: yield returns the finished report, which the hook can enrich.
  • report.when == "call" limits it to the test body (not setup or teardown).
  • item.funcargs holds the fixtures the test used, so the hook can reach the still-open page.
  • pytest_html.extras offers png, jpg, image, url, text, json and html attachments.

Let’s confirm what ended up in the report. pytest-html 4 stores its data as JSON inside the HTML file:

📄 read_report.py

import html
import json
import re

page = open("reports/report.html", encoding="utf-8").read()
blob = re.search(r'data-jsonblob="([^"]*)"', page).group(1)
data = json.loads(html.unescape(blob))
for test_id, runs in data["tests"].items():
    for run in runs:
        extras = [e["name"] for e in run.get("extras", [])]
        print(f"{run['result']:8} {test_id.split('::')[-1]:30} extras={extras}")

⌨️ Terminal

python read_report.py

🖥️ Output

Passed   test_home_lists_products[chromium] extras=[]
Passed   test_login[chromium]           extras=[]
Failed   test_coupon_message[chromium]  extras=['Screenshot at failure', 'Page URL']
Skipped  test_wishlist[chromium]        extras=[]

Only the failed test carries the screenshot, the URL and its console errors (if any). The screenshot is embedded as base64, so the self-contained file still opens anywhere.

📌 Note: pytest-playwright can also save screenshots, videos and traces on failure into test-results/ (--screenshot only-on-failure, Lessons 39 and 62). Use both: the HTML report for a quick look, the trace for deep debugging.


🏷️ Title, Environment and Columns

Three small hooks make the report your own. Add them to the same conftest.py:

📄 tests/conftest_report.py

import os

import pytest
from pytest_metadata.plugin import metadata_key


def pytest_html_report_title(report):
    report.title = "SQA Shop – Playwright regression"


def pytest_configure(config):
    config.stash[metadata_key]["Environment"] = os.getenv("TEST_ENV", "qa")
    config.stash[metadata_key]["Base URL"] = "https://sqatools.in"
    config.stash[metadata_key].pop("Packages", None)          # hide noise


def pytest_html_results_table_header(cells):
    cells.insert(2, "<th>Description</th>")


def pytest_html_results_table_row(report, cells):
    cells.insert(2, f"<td>{getattr(report, 'description', '')}</td>")


@pytest.hookimpl(wrapper=True)
def pytest_runtest_makereport(item, call):
    report = yield
    report.description = (item.function.__doc__ or "").strip()
    return report

📄 tests/conftest.py

import base64

import pytest
import pytest_html
from playwright.sync_api import Page

from tests.conftest_report import *  # noqa: F401,F403  (title, metadata and column hooks)


@pytest.fixture(autouse=True)
def console_errors(page: Page):
    errors = []
    page.on("console", lambda m: errors.append(m.text) if m.type == "error" else None)
    return errors


@pytest.hookimpl(wrapper=True)
def pytest_runtest_makereport(item, call):
    report = yield
    report.description = (item.function.__doc__ or "").strip()
    if report.when == "call" and report.failed:
        page = item.funcargs.get("page")
        if page is not None and not page.is_closed():
            extras = getattr(report, "extras", [])
            extras.append(pytest_html.extras.png(base64.b64encode(page.screenshot(full_page=True)).decode(), name="Screenshot at failure"))
            extras.append(pytest_html.extras.url(page.url, name="Page URL"))
            report.extras = extras
    return report

Now give tests docstrings, which become the Description column:

📄 tests/test_described.py

from playwright.sync_api import Page, expect


def test_guest_sees_login_link(page: Page):
    """A guest sees 'Login' in the header."""
    page.goto("/dummy-ecommerce-website/")
    expect(page.get_by_test_id("account-button")).to_contain_text("Login")

⌨️ Terminal

pytest --html=reports/report.html --self-contained-html -q --tb=no
python -c "t=open('reports/report.html',encoding='utf-8').read(); print('title ok:', 'SQA Shop' in t, '| description column:', 'Description' in t, '| guest docstring:', 'A guest sees' in t)"

🖥️ Output

...Fs                                                                    [100%]
- Generated html report: file:///C:/Users/you/playwright-python/reports/report.html -
=========================== short test summary info ===========================
FAILED tests/test_shop.py::test_coupon_message[chromium] - AssertionError: Lo...
1 failed, 3 passed, 1 skipped in 8.97s
title ok: True | description column: True | guest docstring: True
  • pytest_html_report_title sets the heading and browser tab title.
  • metadata_key (from pytest-metadata) is the environment table; add what matters (environment, base URL, build number) and remove noise.
  • pytest_html_results_table_header/row receive the list of cells as HTML strings; insert yours at the same position in both.

⚠️ Watch out: Only one pytest_runtest_makereport implementation per conftest file is possible (a second definition replaces the first). That is why the description line was merged into the screenshot hook instead of living in conftest_report.py too. When you split hooks across files, put each hook name in exactly one place.


🗂️ One Report per Run in CI

Overwriting report.html loses history. Put a timestamp or build number in the name from a conftest.py:

from datetime import datetime


def pytest_configure(config):
    if config.option.htmlpath:                       # only when --html was given
        stamp = datetime.now().strftime("%Y%m%d-%H%M%S")
        config.option.htmlpath = f"reports/report-{stamp}.html"

In CI, upload the report as an artifact (GitHub Actions actions/upload-artifact, Jenkins publishHTML or archiveArtifacts), as Lessons 66 and 67 show.


🆚 pytest-html or Allure?

pytest-html Allure (next lesson)
Output One HTML file A results folder, rendered by the Allure tool into a website
Setup One plugin Plugin + Allure command-line tool
Steps, history, trends No Yes
Best for Quick, shareable reports Dashboards, history, test-case management

Many teams use pytest-html for every run and Allure for nightly and release runs.


🏋️ Practice Exercises

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

Exercise 1: Write the command that runs only smoke tests and writes a self-contained report to reports/smoke.html.

Show answer
pytest -m smoke --html=reports/smoke.html --self-contained-html

Exercise 2: Extend the failure hook so it also attaches the current page’s HTML as a text extra named “Page HTML” (first 5,000 characters).

Show answer
extras.append(pytest_html.extras.text(page.content()[:5000], name="Page HTML"))

Add it inside the if report.when == "call" and report.failed: block, next to the screenshot.

Exercise 3: Add a column “Browser” to the results table that shows the browser name for each test.

Show answer
def pytest_html_results_table_header(cells):
    cells.insert(2, "<th>Browser</th>")


def pytest_html_results_table_row(report, cells):
    cells.insert(2, f"<td>{getattr(report, 'browser', '')}</td>")


@pytest.hookimpl(wrapper=True)
def pytest_runtest_makereport(item, call):
    report = yield
    callspec = getattr(item, "callspec", None)          # pytest-playwright parametrizes tests by browser_name
    report.browser = callspec.params.get("browser_name", "") if callspec else ""
    return report

Remember: one pytest_runtest_makereport per conftest file, so merge this line into your existing hook.

Exercise 4: A colleague’s report opens without styles when emailed. What is wrong?

Show answer

The report was generated without --self-contained-html, so its CSS and JavaScript live in a separate assets/ folder that was not sent. Regenerate with --self-contained-html (or zip the report together with its assets/ folder).


🧠 MCQ Quiz: HTML Reports with pytest-html

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 option creates a single-file HTML report?
  2. Which hook is used to attach a screenshot to a failed test’s report row?
  3. What does report.when == "call" check?
  4. How does the hook reach the Playwright page of the test?
  5. Which helper adds a PNG screenshot from base64 data?
  6. Where does pytest-html get the environment table from?
  7. Which hook changes the report heading?
  8. Why should a screenshot be taken in the hook rather than in a fixture teardown?
  9. What happens if you define pytest_runtest_makereport twice in the same conftest.py?
  10. What is a main advantage of Allure over pytest-html?

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


❓ Frequently Asked Questions

🤔 Does pytest-html work with pytest-xdist?

Yes. The report collects results from all workers into one file. Keep extras small (screenshots are fine) so the report stays quick to open.

🤔 Can I attach the Playwright trace to the HTML report?

You can attach a link to it with pytest_html.extras.url("../test-results/.../trace.zip", name="Trace"), but the report cannot display traces. Upload test-results/ alongside the report and open traces with playwright show-trace.

🤔 Why are my extras missing?

Check three things: the attribute name is report.extras (plural, pytest-html 4), the hook returns the report, and you are not defining the same hook twice in one file.

🤔 How do I make the report smaller?

Use JPEG screenshots (page.screenshot(type="jpeg", quality=60) with extras.jpg), skip full_page=True for very long pages, and attach screenshots only on failure.

🤔 Can I show passed tests’ logs?

Yes: by default the captured output of passed tests is hidden; set render_collapsed = all in the ini file to control which rows start collapsed, and use -rP to include passed output in the terminal.


🏁 Summary

  • pytest --html=reports/report.html --self-contained-html creates a shareable single-file report.
  • A pytest_runtest_makereport wrapper hook can attach screenshots, URLs, text and console errors to failed tests via pytest_html.extras, using item.funcargs["page"].
  • Customise the title with pytest_html_report_title, the environment with pytest-metadata, and columns with the table header/row hooks.
  • Keep one implementation of each hook per conftest file, and name reports per run in CI.
  • Use pytest-html for quick reports and Allure (next lesson) for steps, history and trends.

🎬 Watch the Playwright tutorial series on YouTube!

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

Playwright Trace Viewer for Python Tests (Record, Open, Read)

A screenshot shows the moment of failure. A trace shows the whole story: every action, the page before and after each step, the console, every network request and the line of code that ran. Playwright’s Trace Viewer turns a failed CI run into something you can replay on your laptop, step by step. In this lesson you will record traces with pytest-playwright’s --tracing option and with the context.tracing API, group steps so traces read like a test plan, split long flows into chunks, look inside a trace file, open it with playwright show-trace or trace.playwright.dev, and collect traces as CI artifacts.

📖 What You’ll Learn: what a Playwright trace contains, –tracing on and retain-on-failure, where traces are saved (–output), context.tracing.start and stop with screenshots, snapshots and sources, naming traces with title, tracing.group to label steps, start_chunk and stop_chunk for one trace per phase, the contents of trace.zip, playwright show-trace, trace.playwright.dev, the Trace Viewer tabs, traces in CI, and trace size and privacy.


🎞️ What Is a Trace?

A trace is a trace.zip file recorded while a test runs. Opened in the Trace Viewer, it shows:

Part What you see
Actions Every Playwright call (goto, click, fill, expect …) with its duration
Snapshots The DOM before, during and after each action, which you can inspect like a live page
Timeline A filmstrip of screenshots across the whole test
Console Messages and errors the page logged
Network Every request and response, with headers and bodies
Source The line of your test that triggered each action
Errors The failure message and call log, attached to the failing step

It is the single most useful artifact for a test that fails in CI but not on your machine.


⚡ Record Traces with –tracing

pytest-playwright records traces for you:

Option Traces kept
--tracing on For every test
--tracing retain-on-failure Only for failed tests (recommended for CI)
--tracing off None (default)

📄 pytest.ini

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

📄 tests/test_cart.py

from playwright.sync_api import Page, expect

SHOP = "/dummy-ecommerce-website/"


def test_add_earbuds(page: Page):
    page.goto(SHOP + "#/search/earbuds")
    page.get_by_role("button", name="Add to cart").first.click()
    expect(page.get_by_test_id("cart-count")).to_have_text("1")


def test_coupon_wrong_expectation(page: Page):
    page.goto(SHOP + "#/search/earbuds")
    page.get_by_role("button", name="Add to cart").first.click()
    page.goto(SHOP + "#/cart")
    page.get_by_test_id("coupon-input").fill("SAVE10")
    page.get_by_test_id("apply-coupon").click()
    expect(page.get_by_test_id("coupon-discount")).to_have_text("−₹400", timeout=3_000)   # real value: −₹500

⌨️ Terminal

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

🖥️ Output

.F                                                                       [100%]
================================== FAILURES ===================================
E   AssertionError: Locator expected to have text '−₹400'
    Actual value: −₹500 
    Call log:
      - Expect "to_have_text" get_by_test_id("coupon-discount") with timeout 3000ms
      - waiting for get_by_test_id("coupon-discount")
        10 × locator resolved to <dd class="save" data-testid="coupon-discount">−₹500</dd>
           - unexpected value "−₹500"
    
    Aria snapshot:
    - definition: −₹500
C:\Users\you\playwright-python\tests\test_cart.py:18: AssertionError: Locator expected to have text '−₹400'
=========================== short test summary info ===========================
FAILED tests/test_cart.py::test_coupon_wrong_expectation[chromium] - Assertio...
1 failed, 1 passed in 7.94s

📄 list_results.py

from pathlib import Path

for path in sorted(Path("test-results").rglob("*.zip")):
    print(path.as_posix(), f"{path.stat().st_size // 1024} KB")

⌨️ Terminal

python list_results.py

🖥️ Output

test-results/tests-test-cart-py-test-coupon-wrong-expectation-chromium/trace.zip 1233 KB

Only the failed test kept a trace, in a folder named after the test inside test-results/ (change the folder with --output). Combine it with --screenshot only-on-failure and --video retain-on-failure for the full set of failure artifacts.


🔍 Open the Trace

⌨️ Terminal

playwright show-trace test-results/tests-test-cart-py-test-coupon-wrong-expectation-chromium/trace.zip

The Trace Viewer opens in a window. Alternatively, drag the zip onto https://trace.playwright.dev: the page loads the viewer, but the trace is processed locally in your browser and is not uploaded.

How to read it for this failure:

  1. In the actions list on the left, the last item, expect.to_have_text, is red.
  2. Click it: the Call tab shows the expected −₹400 and the received −₹500.
  3. The After snapshot shows the cart with the discount line; hover elements to see their locators.
  4. The Network tab shows that no request failed, so the app behaved; the expectation was wrong.

Thirty seconds, and you know whether to fix the test or file a bug.


🧾 What Is Inside trace.zip?

A trace is an ordinary zip file. Looking inside once makes it far less mysterious:

📄 inspect_trace.py

import json
import zipfile
from collections import Counter
from pathlib import Path

trace = next(Path("test-results").rglob("trace.zip"))
with zipfile.ZipFile(trace) as z:
    names = z.namelist()
    print("contents:", dict(Counter(n.split("/")[0] + ("/" if "/" in n else "") for n in names)))
    events = [json.loads(line) for line in z.read("trace.trace").decode("utf-8").splitlines() if line.strip()]

for e in events:
    if e.get("type") == "before" and e.get("class") in ("Frame", "Page", "Locator") or e.get("method") == "expect":
        params = e.get("params", {})
        print(f"{e.get('method'):12} {params.get('selector', params.get('url', ''))[:70]}")

⌨️ Terminal

python inspect_trace.py

🖥️ Output

contents: {'trace.trace': 1, 'trace.network': 1, 'screencast/': 29, 'resources/': 22, 'trace.stacks': 1, 'src/': 1}
goto         /dummy-ecommerce-website/#/search/earbuds
click        internal:role=button[name="Add to cart"i] >> nth=0
goto         /dummy-ecommerce-website/#/cart
fill         internal:testid=[data-testid="coupon-input"s]
click        internal:testid=[data-testid="apply-coupon"s]
expect       internal:testid=[data-testid="coupon-discount"s]

trace.trace holds the actions as JSON lines, trace.network the HTTP traffic, resources/ the snapshots and response bodies, screencast/ the filmstrip frames and src/ your test’s source code. The action list also shows how Playwright stores locators internally: get_by_role("button", name="Add to cart") becomes internal:role=button[name="Add to cart"i], where the trailing i means case-insensitive matching. You never need to read these by hand, but it explains why traces can contain sensitive data: everything the page sent and received is in there.


🎛️ Record Traces Yourself: context.tracing

Outside pytest-playwright (scripts, custom fixtures) or when you need more control, use the tracing API on a browser context:

📄 manual_trace.py

from playwright.sync_api import expect, sync_playwright

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

with sync_playwright() as p:
    browser = p.chromium.launch()
    context = browser.new_context()
    context.tracing.start(screenshots=True, snapshots=True, sources=True, title="Checkout as guest")
    page = context.new_page()

    with context.tracing.group("Find and add the earbuds"):
        page.goto(SHOP + "#/search/earbuds")
        page.get_by_role("button", name="Add to cart").first.click()
        expect(page.get_by_test_id("cart-count")).to_have_text("1")

    with context.tracing.group("Apply a coupon"):
        page.goto(SHOP + "#/cart")
        page.get_by_test_id("coupon-input").fill("FLAT200")
        page.get_by_test_id("apply-coupon").click()
        expect(page.get_by_test_id("coupon-discount")).to_have_text("−₹200")

    context.tracing.stop(path="traces/guest-checkout.zip")
    browser.close()
print("saved traces/guest-checkout.zip")

⌨️ Terminal

python manual_trace.py

🖥️ Output

saved traces/guest-checkout.zip
  • screenshots=True builds the filmstrip, snapshots=True records DOM snapshots and network, sources=True embeds your source code so the viewer can show it.
  • title names the trace in the viewer.
  • tracing.group(...) (usable as a with block) collapses the actions under a readable heading, so a long trace reads like a test plan.

✂️ One Trace per Phase: Chunks

For a long flow you may want separate traces for each phase, without restarting tracing. start_chunk() / stop_chunk(path=...) cut the recording into pieces:

📄 chunks.py

from playwright.sync_api import sync_playwright

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

with sync_playwright() as p:
    browser = p.chromium.launch()
    context = browser.new_context()
    context.tracing.start(screenshots=True, snapshots=True)
    page = context.new_page()

    context.tracing.start_chunk(title="login")
    page.goto(SHOP + "#/login")
    page.get_by_test_id("login-username").fill("testuser")
    page.get_by_test_id("login-password").fill("Test@123")
    page.get_by_test_id("login-button").click()
    page.get_by_test_id("account-button").filter(has_text="Hi,").wait_for()
    context.tracing.stop_chunk(path="traces/1-login.zip")

    context.tracing.start_chunk(title="search")
    page.get_by_test_id("search-input").fill("course")
    page.get_by_test_id("search-button").click()
    page.get_by_test_id("product-card").first.wait_for()
    context.tracing.stop_chunk(path="traces/2-search.zip")

    context.tracing.stop()
    browser.close()

from pathlib import Path
for f in sorted(Path("traces").glob("*.zip")):
    print(f.name, f"{f.stat().st_size // 1024} KB")

⌨️ Terminal

python chunks.py

🖥️ Output

1-login.zip 826 KB
2-search.zip 472 KB
guest-checkout.zip 829 KB

Chunks are handy for monitoring scripts and for very long tests where one giant trace would be slow to open.


🏭 Traces in CI

In a pipeline, record traces only for failures and upload the results folder as a build artifact:

- name: Run tests
  run: pytest --tracing retain-on-failure --screenshot only-on-failure --video retain-on-failure

- name: Upload failure artifacts
  if: failure()
  uses: actions/upload-artifact@v7
  with:
    name: playwright-test-results
    path: test-results/
    retention-days: 7

Download the artifact from the failed run, unzip it, and open the trace with playwright show-trace (Lesson 66 builds the full workflow). Combine with retries (Lesson 44): with pytest-rerunfailures, each failed attempt keeps its own trace, so you can compare a failing and a passing attempt of a flaky test.


🔐 Size and Privacy

  • A trace for a short test is typically 0.5 to 3 MB; long tests with many screenshots can reach tens of MB. retain-on-failure keeps storage small.
  • Traces contain everything: page content, form values, cookies and API bodies. Use test accounts and test data, restrict who can download CI artifacts, and set a short retention period.

🏋️ Practice Exercises

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

Exercise 1: Write the pytest command that keeps a trace, a screenshot and a video only for failed tests, and stores them in a folder called artifacts.

Show answer
pytest --tracing retain-on-failure --screenshot only-on-failure --video retain-on-failure --output artifacts

Exercise 2: Write a fixture that records a trace for every test manually (instead of --tracing) and saves it as traces/<test name>.zip only when the test failed.

Show answer
import pytest


@pytest.hookimpl(wrapper=True)
def pytest_runtest_makereport(item, call):
    report = yield
    if report.when == "call":
        item.failed_call = report.failed
    return report


@pytest.fixture
def traced_page(context, request):
    context.tracing.start(screenshots=True, snapshots=True, sources=True)
    page = context.new_page()
    yield page
    if getattr(request.node, "failed_call", False):
        context.tracing.stop(path=f"traces/{request.node.name}.zip")
    else:
        context.tracing.stop()

The hook (in conftest.py) records whether the test body failed; the fixture saves the trace only then. pytest-playwright’s --tracing retain-on-failure does exactly this for you, so prefer it unless you need custom names.

Exercise 3: In the Trace Viewer, how do you find out whether a failure was caused by a slow API or by a wrong locator?

Show answer

Select the failing action. If its call log shows the element was never found, check the After snapshot for the element (wrong locator or changed UI). Then open the Network tab around that time: a request still pending or a 500 response points to the backend, while all requests finishing normally points to the locator or expectation.

Exercise 4: Group the steps of the SQA Shop login in a manual trace under the heading “Log in as testuser”.

Show answer
with context.tracing.group("Log in as testuser"):
    page.goto(SHOP + "#/login")
    page.get_by_test_id("login-username").fill("testuser")
    page.get_by_test_id("login-password").fill("Test@123")
    page.get_by_test_id("login-button").click()

Without with, call context.tracing.group("...") and later context.tracing.group_end().


🧠 MCQ Quiz: Trace Viewer for Python 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 option keeps traces only for failing tests?
  2. Where does pytest-playwright save traces by default?
  3. How do you open a trace on your machine?
  4. Is a trace uploaded to a server when you open it at trace.playwright.dev?
  5. What does snapshots=True add in tracing.start()?
  6. What does context.tracing.group("Apply a coupon") do?
  7. What are start_chunk() and stop_chunk(path=...) for?
  8. Which Trace Viewer tab tells you if the backend returned an error?
  9. Why must CI trace artifacts be protected?
  10. What does sources=True add to a trace?

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


❓ Frequently Asked Questions

🤔 Do traces slow tests down?

A little: recording snapshots and screenshots costs some time and disk. retain-on-failure still records every test but deletes passing traces, so most teams accept the small overhead in CI for the debugging value. Locally, turn tracing on only when you need it.

🤔 Do traces include API calls made with page.request?

Yes. Requests made through page.request or context.request appear in the trace alongside UI actions. A separate playwright.request.new_context() is not part of the browser context’s trace.

🤔 Can I share a trace with a developer?

Yes, send the zip (or the CI artifact link). They can open it with playwright show-trace or at trace.playwright.dev without installing anything else. Check it for sensitive data first.

🤔 What is the difference between a trace and a HAR file?

A HAR (Lesson 53) records only network traffic and can be replayed. A trace records actions, DOM snapshots, console and network for debugging. Use traces to investigate failures, HARs to mock APIs.

🤔 Why does my trace not show my assertions?

Assertions made with Playwright’s expect appear as actions in the trace. Plain Python assert statements do not, because they never talk to the browser; their failure shows up as the test’s error instead.


🏁 Summary

  • A trace records actions, DOM snapshots, screenshots, console, network and source for a test.
  • Use --tracing retain-on-failure (with screenshots and videos) to keep artifacts only for failures in test-results/.
  • Open traces with playwright show-trace or trace.playwright.dev; start from the failing action, then check snapshots and network.
  • context.tracing.start/stop records traces manually; group() labels steps and start_chunk()/stop_chunk() splits phases.
  • Upload test-results/ as a CI artifact on failure, and treat traces as sensitive data.

🎬 Watch the Playwright tutorial series on YouTube!

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

Debugging Playwright Python Tests: Inspector, PWDEBUG, page.pause and breakpoint

A failing test is a question: what did the page really look like when the step failed? Playwright Python gives you several ways to answer it, from reading the error message properly to stepping through a test in a live browser. In this lesson you will learn a debugging routine that works: read Playwright’s call log, reproduce one test headed and slowed down, open the Playwright Inspector with PWDEBUG, stop at a line with page.pause or breakpoint, log every API call with DEBUG=pw:api, capture the page’s console errors, and debug in VS Code.

📖 What You’ll Learn: a step-by-step debugging routine, reading the call log and aria snapshot in errors, strict mode violations, -x, –lf, -k and –tb to narrow a failure, –headed and –slowmo, PWDEBUG=1 and the Playwright Inspector, page.pause(), breakpoint() and pytest –pdb, DEBUG=pw:api logging, capturing console messages and page errors, locator.highlight(), screenshots mid-test, and debugging in VS Code with launch.json.


🧭 A Debugging Routine

When a test fails, work through these steps in order. Most failures are solved by step 2.

  1. Run only the failing test (-k, --lf, node id).
  2. Read the whole error: the call log and the aria snapshot usually say exactly what happened.
  3. Watch it: --headed --slowmo 500.
  4. Step through it: PWDEBUG=1 or page.pause().
  5. Look after the fact: the trace (next lesson), screenshots and videos.

🎯 Step 1: Narrow the Failure

📄 pytest.ini

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

📄 tests/test_shop.py

from playwright.sync_api import Page, expect

SHOP = "/dummy-ecommerce-website/"


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


def test_add_first_product(page: Page):
    page.goto(SHOP)
    page.get_by_role("button", name="Add to cart").click(timeout=3_000)   # bug: which product?


def test_login_greeting(page: Page):
    page.goto(SHOP + "#/login")
    page.get_by_test_id("login-username").fill("testuser")
    page.get_by_test_id("login-password").fill("Test@123")
    page.get_by_test_id("login-button").click()
    expect(page.get_by_test_id("account-button")).to_have_text("Hello, Test", timeout=3_000)   # bug: wrong text

⌨️ Terminal

pytest -q --tb=no

🖥️ Output

.FF                                                                      [100%]
=========================== short test summary info ===========================
FAILED tests/test_shop.py::test_add_first_product[chromium] - playwright._imp...
FAILED tests/test_shop.py::test_login_greeting[chromium] - AssertionError: Lo...
2 failed, 1 passed in 8.37s

Useful selection options while debugging:

Option Effect
-x Stop at the first failure
--lf Run only the tests that failed last time
-k login Run tests whose name matches
tests/test_shop.py::test_login_greeting Run exactly one test
--tb=short / --tb=line / --tb=no Shorter or no tracebacks

⌨️ Terminal

pytest --lf -q --tb=no

🖥️ Output

FF                                                                       [100%]
=========================== short test summary info ===========================
FAILED tests/test_shop.py::test_add_first_product[chromium] - playwright._imp...
FAILED tests/test_shop.py::test_login_greeting[chromium] - AssertionError: Lo...
2 failed in 6.61s

📜 Step 2: Read the Call Log

Playwright errors contain much more than “timeout”. Run one failing test with its full output:

⌨️ Terminal

pytest tests/test_shop.py::test_add_first_product -q

🖥️ Output

>           return await func()
                   ^^^^^^^^^^^^
E           playwright._impl._errors.Error: Locator.click: Error: strict mode violation: get_by_role("button", name="Add to cart") resolved to 12 elements:
E               1) <button type="button" class="sp-btn sm" data-add="EL-039" data-testid="add-to-cart-EL-039">Add to cart</button> aka get_by_test_id("add-to-cart-EL-039")
E               2) <button type="button" class="sp-btn sm" data-add="EL-021" data-testid="add-to-cart-EL-021">Add to cart</button> aka get_by_test_id("add-to-cart-EL-021")
E               3) <button type="button" class="sp-btn sm" data-add="EL-007" data-testid="add-to-cart-EL-007">Add to cart</button> aka get_by_test_id("add-to-cart-EL-007")
E               4) <button type="button" class="sp-btn sm" data-add="EL-020" data-testid="add-to-cart-EL-020">Add to cart</button> aka get_by_test_id("add-to-cart-EL-020")
E               5) <button type="button" class="sp-btn sm" data-add="DG-010" data-testid="add-to-cart-DG-010">Add to cart</button> aka get_by_test_id("add-to-cart-DG-010")
E               6) <button type="button" class="sp-btn sm" data-add="CL-023" data-testid="add-to-cart-CL-023">Add to cart</button> aka get_by_test_id("add-to-cart-CL-023")
E               7) <button type="button" class="sp-btn sm" data-add="CL-024" data-testid="add-to-cart-CL-024">Add to cart</button> aka get_by_test_id("add-to-cart-CL-024")
E               8) <button type="button" class="sp-btn sm" data-add="EL-012" data-testid="add-to-cart-EL-012">Add to cart</button> aka get_by_test_id("add-to-cart-EL-012")
E               9) <button type="button" class="sp-btn sm" data-add="CL-035" data-testid="add-to-cart-CL-035">Add to cart</button> aka get_by_test_id("add-to-cart-CL-035")
E               10) <button type="button" class="sp-btn sm" data-add="CL-001" data-testid="add-to-cart-CL-001">Add to cart</button> aka get_by_test_id("add-to-cart-CL-001")
E               ...
E           
E           Call log:
E             - waiting for get_by_role("button", name="Add to cart")

..\..\.venv\Lib\site-packages\playwright\_impl\utils\zones.py:58: Error
=========================== short test summary info ===========================
FAILED tests/test_shop.py::test_add_first_product[chromium] - playwright._imp...
1 failed in 2.05s

The message says it all: strict mode violation. The locator matched every “Add to cart” button on the page, and Playwright refuses to guess which one you meant. It lists the first matches with a suggested unique locator for each. Fix the test by saying which product you mean, for example page.get_by_test_id("product-card").filter(has_text="Wireless Earbuds").get_by_role("button", name="Add to cart"), or .first if any product will do.

⌨️ Terminal

pytest tests/test_shop.py::test_login_greeting -q

🖥️ Output

        page.get_by_test_id("login-button").click()
>       expect(page.get_by_test_id("account-button")).to_have_text("Hello, Test", timeout=3_000)   # bug: wrong text
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
E       AssertionError: Locator expected to have text 'Hello, Test'
E       Actual value: Hi, Test 
E       Call log:
E         - Expect "to_have_text" get_by_test_id("account-button") with timeout 3000ms
E         - waiting for get_by_test_id("account-button")
E           10 × locator resolved to <button type="button" class="sp-tool" id="account-btn" aria-haspopup="true" aria-expanded="false" data-testid="account-button">…</button>
E              - unexpected value "Hi, Test"
E       
E       Aria snapshot:
E       - button "Hi, Test"

tests\test_shop.py:21: AssertionError
=========================== short test summary info ===========================
FAILED tests/test_shop.py::test_login_greeting[chromium] - AssertionError: Lo...
1 failed in 4.85s

For a failed assertion the call log shows how often Playwright re-checked (9 × locator resolved to ...), the actual value (“Hi, Test”) and an aria snapshot of the element. Here the test, not the app, is wrong.

💡 Tip: Read errors from the bottom up: the last lines of the call log describe the final state of the page. Most “flaky” failures are explained there: the element existed but was hidden, disabled, covered or had different text.


👀 Step 3: Watch the Test Run

⌨️ Terminal

pytest tests/test_shop.py::test_login_greeting --headed --slowmo 500

--headed opens a real browser window and --slowmo 500 waits half a second before every Playwright action, so you can follow along. Add --browser firefox to watch another engine.


🕵️ Step 4a: PWDEBUG and the Playwright Inspector

Setting the environment variable PWDEBUG=1 runs tests headed, sets timeouts to zero (no waiting out a 30 s timeout while you think) and opens the Playwright Inspector, which pauses before the first action:

⌨️ Terminal

$env:PWDEBUG = "1"; pytest tests/test_shop.py::test_add_first_product    # PowerShell
PWDEBUG=1 pytest tests/test_shop.py::test_add_first_product              # macOS / Linux

In the Inspector you can:

  • Step over each Playwright call, or resume to the next pause.
  • See which element each locator matches, highlighted in the browser.
  • Use Pick locator to click an element and get the recommended locator for it.
  • Edit a locator in the Inspector’s field and see the matches live.

Remove the variable afterwards (Remove-Item Env:PWDEBUG in PowerShell, unset PWDEBUG in bash), or it will slow every run.


⏸️ Step 4b: page.pause() at One Line

To stop at one specific point, add page.pause() where you want to look around. Run the test headed (--headed); the Inspector opens at that line with the browser in exactly that state:

def test_add_first_product(page: Page):
    page.goto(SHOP)
    page.pause()                       # Inspector opens here; try locators, then press Resume
    page.get_by_role("button", name="Add to cart").first.click()

page.pause() needs a headed browser, so run the test with --headed (or PWDEBUG=1), and delete the line before committing.


🐞 Step 4c: Python Breakpoints and –pdb

Playwright pauses the browser; Python’s debugger pauses your code, so you can inspect variables and call Playwright interactively:

def test_login_greeting(page: Page):
    ...
    breakpoint()                       # drops into pdb: try page.url, page.get_by_test_id("account-button").inner_text()

Or let pytest open the debugger automatically when a test fails:

⌨️ Terminal

pytest tests/test_shop.py::test_login_greeting --pdb --headed

At the (Pdb) prompt the browser is still open in the failed state. Useful commands: p page.url, p page.get_by_test_id("account-button").inner_text(), l (list code), c (continue), q (quit). Use --pdb together with -s if your test prints output.


📡 Step 5: Log Every Playwright Call

The DEBUG=pw:api environment variable makes Playwright log each API call with timings to stderr. It is invaluable in CI, where you cannot watch the browser:

⌨️ Terminal

$env:DEBUG = "pw:api"; pytest tests/test_shop.py::test_home_has_products -q -s

🖥️ Output

pw:api => BrowserType.launch started
pw:api <= BrowserType.launch succeeded
pw:api => Browser.new_context started
pw:api <= Browser.new_context succeeded
pw:api => BrowserContext.new_page started
pw:api <= BrowserContext.new_page succeeded
pw:api => Page.goto started
pw:api <= Page.goto succeeded
pw:api => LocatorAssertions.to_be_visible started
pw:api <= LocatorAssertions.to_be_visible succeeded
.pw:api => Tracing.stop started
pw:api <= Tracing.stop succeeded
pw:api => BrowserContext.close started
pw:api <= BrowserContext.close succeeded

Each => line is a call starting and each <= line the call finishing, so you can see exactly which call was running when a test hung or failed. (The command filters the output to start/finish lines; unfiltered, pw:api also logs every frame navigation, including the page’s ad iframes.)


🖥️ Capture the Page’s Own Errors

Many UI failures start with a JavaScript error in the application. Collect console messages and uncaught page errors in a fixture, and print them when a test fails:

📄 tests/conftest.py

import pytest
from playwright.sync_api import Page


@pytest.fixture(autouse=True)
def browser_log(page: Page):
    messages = []
    page.on("console", lambda msg: messages.append(f"console.{msg.type}: {msg.text}") if msg.type in ("error", "warning") else None)
    page.on("pageerror", lambda err: messages.append(f"pageerror: {err}"))
    yield messages
    if messages:
        print("\n--- browser log ---\n" + "\n".join(messages[:10]))

📄 tests/test_page_errors.py

from playwright.sync_api import Page


def test_page_with_js_error(page: Page, browser_log):
    page.set_content("<button onclick=\"undefinedFunction()\">Buy</button><script>console.error('price service unavailable')</script>")
    page.get_by_role("button", name="Buy").click()
    page.wait_for_timeout(200)          # give the click handler a moment; only for this demonstration
    assert any("undefinedFunction" in m for m in browser_log)

⌨️ Terminal

pytest tests/test_page_errors.py -q -s

🖥️ Output

.
--- browser log ---
console.error: price service unavailable
pageerror: undefinedFunction is not defined

1 passed in 0.73s

pageerror catches uncaught exceptions (here, calling an undefined function) and console catches console.error() messages the app logs. Printing them on failure often explains the failure before you open a trace.


🔦 Quick Tricks Inside a Test

Trick Use
locator.highlight() Outline the matched element in headed runs
print(locator.count()) How many elements match right now
print(locator.all_inner_texts()) What the matched elements contain
page.screenshot(path="debug.png", full_page=True) A picture of this exact moment
print(page.get_by_test_id("filters").aria_snapshot()) The accessible structure of a region as text

📄 tests/test_tricks.py

from playwright.sync_api import Page


def test_inspect_buttons(page: Page):
    page.goto("/dummy-ecommerce-website/")
    buttons = page.get_by_role("button", name="filters")
    print("\nmatches:", buttons.count(), buttons.all_inner_texts())
    page.screenshot(path="debug-home.png")

⌨️ Terminal

pytest tests/test_tricks.py -q -s

🖥️ Output

matches: 1 ['Clear all filters']
.
1 passed in 1.89s

The output shows a trap that no error message would reveal. The test meant the “Filters” button, but at desktop width that button is hidden, and role names match substrings, case-insensitively by default, so name="filters" matched exactly one visible button: “Clear all filters”. A click() would have succeeded on the wrong button. count() and all_inner_texts() expose this in seconds; exact=True (name="Filters", exact=True) prevents it.


🧑‍💻 Debugging in VS Code

With the Python extension, VS Code’s Testing panel runs and debugs pytest tests directly: right-click a test and choose Debug Test, and red-dot breakpoints in your test or page objects work. To debug headed, add the options to a launch configuration:

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Debug current Playwright test (headed)",
      "type": "debugpy",
      "request": "launch",
      "module": "pytest",
      "args": ["${file}", "--headed", "--slowmo", "300", "-s"],
      "console": "integratedTerminal",
      "justMyCode": false
    }
  ]
}

Save it as .vscode/launch.json, open a test file and press F5.


🏋️ Practice Exercises

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

Exercise 1: Write a test that opens the “Filters” panel on a phone-sized viewport, using a locator that cannot match “Clear all filters”, and checks that the panel becomes visible.

Show answer
def test_open_filters(page: Page):
    page.set_viewport_size({"width": 400, "height": 800})
    page.goto(SHOP)
    page.get_by_role("button", name="Filters", exact=True).click()
    expect(page.get_by_test_id("filters")).to_be_visible()

exact=True makes the role name match the whole name, so “Clear all filters” no longer matches. The button only exists on narrow screens (Lesson 50), and a fresh load at 400 px starts with the panel closed, so the click really opens it.

Exercise 2: A test passes locally and fails in CI with a timeout on click(). Which two debugging tools from this lesson help most when you cannot watch the CI browser?

Show answer

DEBUG=pw:api (logs every Playwright call with timings, showing where it waited) and the call log in the error message (shows the element’s state on every retry: hidden, disabled, covered). Add traces and screenshots on failure (Lesson 60, next lesson) for a full picture.

Exercise 3: Write the command that runs only the tests that failed in the previous run, stops at the first failure, and opens pdb there with the browser visible.

Show answer
pytest --lf -x --pdb --headed

Exercise 4: Your app logs console.error("Payment SDK failed to load") but the test only fails later with a timeout. Write an autouse fixture that fails the test early (in teardown) if any console error was logged.

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

Use an allow-list for known, harmless third-party errors so the check stays useful.


🧠 MCQ Quiz: Debugging: Inspector, PWDEBUG and page.pause

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 should you do first when a Playwright test fails?
  2. What does a “strict mode violation” mean?
  3. What does --slowmo 500 do?
  4. What does PWDEBUG=1 enable?
  5. Where does page.pause() stop?
  6. What does pytest --pdb do?
  7. What does DEBUG=pw:api log?
  8. Which page event reports uncaught JavaScript exceptions?
  9. How do you see how many elements a locator matches at the moment?
  10. Which option re-runs only the tests that failed in the previous run?

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


❓ Frequently Asked Questions

🤔 Why does my test pass in headed mode but fail headless?

Headless browsers use a different default viewport (1280×720) and no visible window focus, and timing is slightly different. Set the viewport explicitly, avoid relying on hover or focus side effects, and use expect instead of fixed waits. Compare traces from both runs.

🤔 Can I attach the Playwright Inspector to a CI run?

No, CI has no screen. Use traces (--tracing retain-on-failure), screenshots and videos, plus DEBUG=pw:api logs, and debug locally with the trace viewer.

🤔 How do I find a good locator quickly?

Use Pick locator in the Inspector (PWDEBUG=1 or page.pause()), or playwright codegen <url> (Lesson 7). Both recommend role and test-id based locators.

🤔 Does page.pause() work with pytest-xdist?

Not usefully: parallel workers have no interactive console. Run the test alone, without -n, when you need to pause it.

🤔 Why are my print() calls not shown?

pytest captures output by default and shows it only for failing tests. Run with -s (or --capture=no) to see prints live, or use logging with log_cli (Lesson 60).


🏁 Summary

  • Narrow the failure (-k, --lf, node ids) and read the full error: call log, actual value, aria snapshot.
  • Watch with --headed --slowmo, step through with PWDEBUG=1 or page.pause(), inspect code with breakpoint() or --pdb.
  • Log Playwright calls with DEBUG=pw:api, and collect console and pageerror events from the app.
  • Use count(), all_inner_texts(), highlight(), screenshots and aria snapshots for quick checks.
  • Debug in VS Code’s Testing panel or with a launch.json that runs pytest headed.

🎬 Watch the Playwright tutorial series on YouTube!

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

Build a Real-World Enterprise Test Framework with Playwright Python

Earlier lessons each solved one problem: configuration, page objects, API clients, data, login reuse, patterns. A company framework needs all of them working together, plus the things only teams care about: logs a support engineer can read, links from each test to a test-management ID, artifacts on failure, a JUnit file for CI dashboards and a single command that runs everything. In this lesson you will assemble a complete, runnable framework for the SQA Shop and the practice API, file by file, and see what each piece contributes when a test fails at 3 a.m.

📖 What You’ll Learn: the architecture of an enterprise framework and its layers, environment configuration with a validated settings object, page objects with components, a typed API client, data factories, a session login with storage state, layered fixtures, structured logging with log_cli and log_file, a testcase marker linked to test-management IDs via record_property, screenshots, traces and videos only on failure, JUnit XML for CI, and the commands a team runs every day.


🏗️ Architecture

enterprise-shop-tests/
├── pyproject.toml              pytest settings, markers, logging
├── conftest.py                 options (--env), settings, report header, testcase IDs
├── config/
│   ├── environments.json       URLs and flags per environment
│   └── settings.py             validated, frozen Settings
├── framework/
│   ├── api_client.py           typed client for the practice API
│   ├── factories.py            unique, valid test data
│   └── log.py                  one logger for the framework
├── pages/
│   ├── base.py                 BasePage + Header component
│   ├── login.py, catalog.py, cart.py
└── tests/
    ├── conftest.py             browser fixtures: login once, page objects
    ├── ui/test_shopping.py
    └── api/test_objects.py

Layers depend only downwards: tests use pages, framework and fixtures; pages use Playwright; nothing imports tests. That rule keeps each layer replaceable.


⚙️ Settings and Environments

📄 config/environments.json

{
  "qa":   {"base_url": "https://sqatools.in", "shop_path": "/dummy-ecommerce-website/", "api_url": "https://sqatools.in/wp-json/sqa-api/v1/", "read_only": false},
  "prod": {"base_url": "https://sqatools.in", "shop_path": "/dummy-ecommerce-website/", "api_url": "https://sqatools.in/wp-json/sqa-api/v1/", "read_only": true}
}

📄 config/settings.py

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

from dotenv import load_dotenv

ROOT = Path(__file__).resolve().parent.parent


@dataclass(frozen=True)
class Settings:
    env: str
    base_url: str
    shop_path: str
    api_url: str
    read_only: bool
    shop_user: str
    shop_password: str = field(repr=False)


def load_settings(env: str) -> Settings:
    load_dotenv(ROOT / f".env.{env}")
    data = json.loads((ROOT / "config" / "environments.json").read_text(encoding="utf-8"))[env]
    user, password = os.getenv("SHOP_USER", "testuser"), os.getenv("SHOP_PASSWORD", "Test@123")
    if not user or not password:
        raise RuntimeError(f"SHOP_USER / SHOP_PASSWORD missing for environment '{env}'")
    return Settings(env=env, shop_user=user, shop_password=password, **data)

🧰 Framework Utilities

📄 framework/log.py

import logging

log = logging.getLogger("shop")          # one named logger; pytest's log settings control output

📄 framework/factories.py

import uuid


def make_object(**overrides) -> dict:
    data = {"name": f"enterprise-{uuid.uuid4().hex[:8]}", "data": {"price": 999}}
    data.update(overrides)
    return data

📄 framework/api_client.py

from playwright.sync_api import APIRequestContext

from framework.log import log


class ShopApi:
    """Typed wrapper around the practice API: one method per business action."""

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

    def create_object(self, payload: dict) -> dict:
        response = self._request.post("objects", data=payload)
        log.info("POST objects -> %s", response.status)
        assert response.status == 201, response.text()
        return response.json()

    def get_object(self, object_id: str) -> dict | None:
        response = self._request.get(f"objects/{object_id}")
        log.info("GET objects/%s -> %s", object_id, response.status)
        return response.json() if response.ok else None

    def delete_object(self, object_id: str) -> None:
        response = self._request.delete(f"objects/{object_id}")
        log.info("DELETE objects/%s -> %s", object_id, response.status)

📄 Page Objects

📄 pages/base.py

from playwright.sync_api import Page

from framework.log import log


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


class BasePage:
    route = ""

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

    def open(self):
        log.info("open %s%s", self.shop_path, self.route)
        self.page.goto(self.shop_path + self.route)
        return self

📄 pages/login.py

from pages.base import BasePage


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

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

    def login(self, user: str, password: str):
        self.username.fill(user)
        self.password.fill(password)
        self.remember.check()
        self.button.click()
        self.header.account.filter(has_text="Hi,").wait_for()
        return self

📄 pages/catalog.py

from framework.log import log
from pages.base import BasePage


class CatalogPage(BasePage):
    route = "#/"

    def search(self, term: str):
        log.info("search %r", term)
        self.header.search_input.fill(term)
        self.header.search_button.click()
        return self

    def add_to_cart(self, product_name: str):
        log.info("add to cart %r", product_name)
        card = self.page.get_by_test_id("product-card").filter(has_text=product_name).first
        card.get_by_role("button", name="Add to cart").click()
        return self

📄 pages/cart.py

from pages.base import BasePage


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

    def __init__(self, page, shop_path):
        super().__init__(page, shop_path)
        self.items = page.get_by_test_id("cart-item-name")
        self.coupon = page.get_by_test_id("coupon-input")
        self.apply = page.get_by_test_id("apply-coupon")
        self.discount = page.get_by_test_id("coupon-discount")
        self.checkout_note = page.get_by_test_id("logged-in-note")

    def apply_coupon(self, code: str):
        self.coupon.fill(code)
        self.apply.click()
        return self

🧩 Root conftest: Options, Settings, Traceability

📄 conftest.py

import pytest

from config.settings import Settings, load_settings


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


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


@pytest.fixture(scope="session")
def base_url(settings) -> str:              # pytest-playwright uses this for relative goto()
    return settings.base_url


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


@pytest.fixture(autouse=True)
def _testcase_id(request, record_property):
    """Copy @pytest.mark.testcase("SHOP-123") into the JUnit XML, so CI tools can link results to test cases."""
    marker = request.node.get_closest_marker("testcase")
    if marker:
        record_property("testcase_id", marker.args[0])


def pytest_collection_modifyitems(config, items):
    if load_settings(config.getoption("--env")).read_only:
        for item in items:
            if item.get_closest_marker("destructive"):
                item.add_marker(pytest.mark.skip(reason="destructive test on a read-only environment"))

🧪 Browser Fixtures: Log In Once

📄 tests/conftest.py

from pathlib import Path

import pytest
from playwright.sync_api import Browser, Playwright

from framework.api_client import ShopApi
from framework.log import log
from pages.cart import CartPage
from pages.catalog import CatalogPage
from pages.login import LoginPage

AUTH = Path(__file__).resolve().parent.parent / ".auth"


@pytest.fixture(scope="session")
def member_state(browser: Browser, settings) -> Path:
    log.info("logging in once as %s on %s", settings.shop_user, settings.env)
    context = browser.new_context(base_url=settings.base_url)
    LoginPage(context.new_page(), settings.shop_path).open().login(settings.shop_user, settings.shop_password)
    path = AUTH / f"member-{settings.env}.json"
    context.storage_state(path=path)
    context.close()
    return path


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


@pytest.fixture
def catalog(page, settings) -> CatalogPage:
    return CatalogPage(page, settings.shop_path).open()


@pytest.fixture
def cart_page(page, settings) -> CartPage:
    return CartPage(page, settings.shop_path)


@pytest.fixture(scope="session")
def shop_api(playwright: Playwright, settings):
    request = playwright.request.new_context(base_url=settings.api_url)
    yield ShopApi(request)
    request.dispose()

✅ The Tests

📄 tests/ui/test_shopping.py

import pytest
from playwright.sync_api import expect


@pytest.mark.smoke
@pytest.mark.testcase("SHOP-101")
def test_member_is_greeted(catalog):
    expect(catalog.header.account).to_contain_text("Hi, Test")


@pytest.mark.testcase("SHOP-102")
def test_member_coupon(catalog, cart_page):
    catalog.search("earbuds").add_to_cart("Wireless Earbuds")
    expect(catalog.header.cart_count).to_have_text("1")
    cart_page.open().apply_coupon("SAVE10")
    expect(cart_page.discount).to_have_text("−₹500")


@pytest.mark.guest
@pytest.mark.testcase("SHOP-103")
def test_guest_sees_login(catalog):
    expect(catalog.header.account).to_contain_text("Login")

📄 tests/api/test_objects.py

import pytest

from framework.factories import make_object


@pytest.mark.smoke
@pytest.mark.destructive
@pytest.mark.testcase("API-201")
def test_object_round_trip(shop_api):
    created = shop_api.create_object(make_object(data={"price": 1234}))
    try:
        assert shop_api.get_object(created["id"])["data"]["price"] == 1234
    finally:
        shop_api.delete_object(created["id"])
    assert shop_api.get_object(created["id"]) is None

🛠️ pyproject.toml: Logging, Artifacts, Reports

📄 pyproject.toml

[tool.pytest.ini_options]
testpaths = ["tests"]
pythonpath = ["."]
addopts = [
    "--strict-markers", "-ra",
    "--screenshot=only-on-failure",
    "--tracing=retain-on-failure",
    "--video=retain-on-failure",
    "--output=test-results",
    "--junitxml=reports/junit.xml",
]
markers = [
    "smoke: fast checks for every commit",
    "guest: run without the saved login",
    "destructive: creates or deletes data",
    "testcase(id): link to a test-management case",
]
junit_family = "xunit1"      # xunit1 keeps per-test <properties> (testcase IDs)
log_cli = true
log_cli_level = "INFO"
log_cli_format = "%(asctime)s %(levelname)-5s %(name)s | %(message)s"
log_cli_date_format = "%H:%M:%S"
log_file = "reports/run.log"
log_file_level = "DEBUG"

What the team gets from these lines:

Setting Benefit
--screenshot/--tracing/--video ...-on-failure Every failed test leaves a screenshot, a trace (Lesson 62) and a video in test-results/; passing tests leave nothing
--junitxml with junit_family = "xunit1" # xunit1 keeps per-test <properties> (testcase IDs) A standard XML file that Jenkins, GitHub Actions, Azure DevOps and test-management tools read
log_cli Live, timestamped framework logs in the terminal
log_file A complete DEBUG log per run, attached to CI artifacts
testcase(id) marker + record_property Each result in the JUnit XML carries its test-management ID

▶️ Run It

⌨️ Terminal

pytest

🖥️ Output

============================= test session starts =============================
platform win32 -- Python 3.15.1, pytest-9.2.0, pluggy-1.7.0
environment: qa
rootdir: C:\Users\you\playwright-python
configfile: pyproject.toml
testpaths: tests
plugins: allure-pytest-2.16.2, base-url-2.1.0, bdd-9.0.1, html-4.2.0, metadata-3.1.1, playwright-0.10.0, rerunfailures-16.7, xdist-3.8.0
collected 4 items

tests/api/test_objects.py::test_object_round_trip 
-------------------------------- live log call --------------------------------
19:04:35 INFO  shop | POST objects -> 201
19:04:35 INFO  shop | GET objects/obj_q6cghllmgh -> 200
19:04:36 INFO  shop | DELETE objects/obj_q6cghllmgh -> 204
19:04:36 INFO  shop | GET objects/obj_q6cghllmgh -> 404
PASSED                                                                   [ 25%]
tests/ui/test_shopping.py::test_member_is_greeted[chromium] 
------------------------------- live log setup --------------------------------
19:04:37 INFO  shop | logging in once as testuser on qa
19:04:37 INFO  shop | open /dummy-ecommerce-website/#/login
19:04:40 INFO  shop | open /dummy-ecommerce-website/#/
PASSED                                                                   [ 50%]
tests/ui/test_shopping.py::test_member_coupon[chromium] 
------------------------------- live log setup --------------------------------
19:04:43 INFO  shop | open /dummy-ecommerce-website/#/
-------------------------------- live log call --------------------------------
19:04:45 INFO  shop | search 'earbuds'
19:04:45 INFO  shop | add to cart 'Wireless Earbuds'
19:04:45 INFO  shop | open /dummy-ecommerce-website/#/cart
PASSED                                                                   [ 75%]
tests/ui/test_shopping.py::test_guest_sees_login[chromium] 
------------------------------- live log setup --------------------------------
19:04:46 INFO  shop | open /dummy-ecommerce-website/#/
PASSED                                                                   [100%]

- generated xml file: C:\Users\you\playwright-python\reports\junit.xml -
============================= 4 passed in 14.12s ==============================

The live log shows exactly what the framework did: one login for the whole session, the page actions, and every API call with its status. Now the smoke tests only, on the read-only production configuration:

⌨️ Terminal

pytest -m smoke --env prod -q -o log_cli=false

🖥️ Output

s.                                                                       [100%]
=========================== short test summary info ===========================
SKIPPED [1] tests\api\test_objects.py:6: destructive test on a read-only environment
1 passed, 1 skipped, 2 deselected in 5.31s

The API round trip is skipped on prod because it is marked destructive. Finally, the traceability data in the JUnit report:

📄 show_junit.py

import xml.etree.ElementTree as ET

root = ET.parse("reports/junit.xml").getroot()
for case in root.iter("testcase"):
    ids = [p.get("value") for p in case.iter("property") if p.get("name") == "testcase_id"]
    status = "skipped" if case.find("skipped") is not None else "failed" if case.find("failure") is not None else "passed"
    print(f"{ids[0] if ids else '-':9} {status:8} {case.get('name')}")

⌨️ Terminal

pytest -q -o log_cli=false
python show_junit.py

🖥️ Output

....                                                                     [100%]
4 passed in 12.83s
API-201   passed   test_object_round_trip
SHOP-101  passed   test_member_is_greeted[chromium]
SHOP-102  passed   test_member_coupon[chromium]
SHOP-103  passed   test_guest_sees_login[chromium]

💥 What a Failure Looks Like

Break one expectation to see what the framework leaves behind:

📄 tests/ui/test_broken.py

import pytest
from playwright.sync_api import expect


@pytest.mark.testcase("SHOP-999")
def test_wrong_discount(catalog, cart_page):
    catalog.search("earbuds").add_to_cart("Wireless Earbuds")
    cart_page.open().apply_coupon("SAVE10")
    expect(cart_page.discount).to_have_text("−₹999", timeout=2_000)

⌨️ Terminal

pytest tests/ui/test_broken.py -q -o log_cli=false

🖥️ Output

INFO     shop:base.py:22 open /dummy-ecommerce-website/#/
------------------------------ Captured log call ------------------------------
INFO     shop:catalog.py:9 search 'earbuds'
INFO     shop:catalog.py:15 add to cart 'Wireless Earbuds'
INFO     shop:base.py:22 open /dummy-ecommerce-website/#/cart
=========================== short test summary info ===========================
FAILED tests/ui/test_broken.py::test_wrong_discount[chromium] - AssertionErro...
1 failed in 7.83s

📄 list_artifacts.py

from pathlib import Path

for path in sorted(Path("test-results").rglob("*")):
    if path.is_file():
        print(path.as_posix(), f"({path.stat().st_size // 1024} KB)")

⌨️ Terminal

python list_artifacts.py

🖥️ Output

test-results/tests-ui-test-broken-py-test-wrong-discount-chromium/test-failed-1.png (74 KB)
test-results/tests-ui-test-broken-py-test-wrong-discount-chromium/trace.zip (1480 KB)
test-results/tests-ui-test-broken-py-test-wrong-discount-chromium/video.webm (351 KB)

For the failed test there is a screenshot, a trace and a video, in a folder named after the test. Open the trace with playwright show-trace test-results/<folder>/trace.zip to replay every step (Lesson 62).


📋 Daily Commands

Goal Command
Everything on QA pytest
Smoke on every commit pytest -m smoke
Read-only checks on prod pytest -m smoke --env prod
One test, headed, slowed down pytest -k coupon --headed --slowmo 300
Parallel (Lesson 65) pytest -n auto
Rerun failures only pytest --lf

🏋️ 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 @pytest.mark.owner("checkout-team") marker and record it in the JUnit XML like testcase, so CI dashboards can route failures to the right team.

Show answer
# pyproject.toml markers: "owner(team): team responsible for the test"

@pytest.fixture(autouse=True)
def _owner(request, record_property):
    marker = request.node.get_closest_marker("owner")
    if marker:
        record_property("owner", marker.args[0])

Every <testcase> then carries <property name="owner" value="checkout-team"/>.

Exercise 2: The live log is too noisy in CI. How do you keep the DEBUG log file but show only warnings in the terminal for one run?

Show answer

Override the ini option on the command line: pytest -o log_cli_level=WARNING. The log_file with log_file_level = "DEBUG" keeps everything for later analysis.

Exercise 3: Write a ShopApi.list_objects() method that returns the list of objects and logs how many were returned.

Show answer
def list_objects(self, per_page: int = 50) -> list[dict]:
    response = self._request.get("objects", params={"per_page": per_page})
    assert response.ok, response.text()
    objects = response.json()["data"]
    log.info("GET objects -> %s, %d object(s)", response.status, len(objects))
    return objects

Exercise 4: Why does the framework record failures as screenshot, trace and video, but only on-failure?

Show answer

Each artifact answers a different question (what the page looked like, what every step and network call did, how the page moved in time). Keeping them only for failures gives full diagnostics where they are needed without slowing down or filling storage on the thousands of passing tests.


🧠 MCQ Quiz: Real-World Enterprise Framework in Python

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

  1. What is the dependency rule between framework layers?
  2. What does record_property("testcase_id", "SHOP-101") do?
  3. Which option keeps a Playwright trace only for failed tests?
  4. What does log_cli = true do?
  5. Why does the framework log in through a session fixture with storage state?
  6. What happens to test_object_round_trip with --env prod?
  7. Why does the API test delete its object in a finally block?
  8. What is JUnit XML mainly used for?
  9. What is the benefit of a single named logger (logging.getLogger("shop"))?
  10. Which command reruns only the tests that failed last time?

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


❓ Frequently Asked Questions

🤔 Is this framework too big for a small team?

Start with settings, page objects and one conftest, and add the rest when you feel the need: logging when debugging CI failures takes too long, test-case IDs when results must be reported, storage state when logins slow the suite.

🤔 Should I build a custom framework or use an existing one?

pytest plus pytest-playwright already is the framework engine. What you build on top (pages, clients, fixtures, conventions) is specific to your product, so a thin layer of your own code is normal and healthy.

🤔 How do I connect test-case IDs to Jira, Xray or TestRail?

Most tools import JUnit XML and match a property or the test name to a case ID. Some provide pytest plugins that read markers directly. The testcase marker pattern in this lesson works with both approaches.

🤔 Where do CI files go?

In the repository: .github/workflows/ for GitHub Actions (Lesson 66) or a Jenkinsfile at the root (Lesson 67). Both simply run the daily commands from the table above.

🤔 How do I keep the framework fast as it grows?

Log in once, seed state instead of clicking (Lesson 55), mock slow third parties (Lesson 52), run in parallel (Lesson 65) and keep end-to-end journeys few and focused.


🏁 Summary

  • An enterprise framework layers config, framework utilities, page objects, fixtures and tests, with dependencies pointing downwards only.
  • Settings come from an environment file plus validated variables; one --env option selects the target.
  • Log in once with storage state, use typed API clients and factories, and clean up data even when tests fail.
  • log_cli/log_file give readable logs; a testcase marker plus record_property link results to test-management IDs in JUnit XML.
  • Screenshots, traces and videos are kept only for failures, so every red test comes with everything needed to fix it.

🎬 Watch the Playwright tutorial series on YouTube!

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

BDD with pytest-bdd and Playwright Python (Gherkin Step by Step)

Behaviour-Driven Development (BDD) describes features in plain-language scenarios that product owners, testers and developers can all read: Given a shopper is on the login page, When they log in, Then they see a greeting. pytest-bdd turns those Gherkin scenarios into ordinary pytest tests, so they run with your Playwright fixtures, markers and reports. In this lesson you will write feature files for the SQA Shop, implement step definitions with Playwright, pass values with parsers, use Scenario Outlines and data tables, share state between steps with target_fixture, run scenarios by tag, and let pytest-bdd generate missing step code.

📖 What You’ll Learn: what BDD and Gherkin are, installing pytest-bdd, a feature file with Feature, Background and Scenario, step definitions with given, when and then, binding scenarios with scenarios(), parsers.parse for values in steps, target_fixture to pass objects between steps, Scenario Outline with Examples, data tables, tags as pytest markers, –generate-missing, the gherkin terminal reporter, and good practices for readable scenarios.


🗣️ What Are BDD and Gherkin?

BDD is a way of working: before building a feature, the team agrees on examples of how it should behave. The examples are written in Gherkin, a structured plain-English format:

Feature: Coupons in the cart
  Scenario: A member applies SAVE10
    Given my cart contains Wireless Earbuds
    When I apply the coupon "SAVE10"
    Then the coupon discount is "−₹500"
Keyword Meaning
Feature The capability being described
Background Steps run before every scenario in the file
Scenario One concrete example
Given / When / Then Context / action / expected outcome
And, But Continue the previous step type
Scenario Outline + Examples One scenario run for every row of a table

The scenarios become living documentation: they are executed on every run, so they cannot silently go out of date.


📦 Set Up pytest-bdd

⌨️ Terminal

pip install pytest-bdd

This lesson uses pytest-bdd 9.0. Configure where feature files live and register the tags you will use as markers:

📄 pytest.ini

[pytest]
addopts = --base-url https://sqatools.in --strict-markers
bdd_features_base_dir = features/
markers =
    smoke: quick checks
    coupons: coupon scenarios

📝 Step 1: A Feature File

📄 features/login.feature

@smoke
Feature: Log in to SQA Shop
  As a shopper
  I want to log in
  So that my saved details are used at checkout

  Background:
    Given I am on the login page

  Scenario: Successful login
    When I log in as "testuser" with password "Test@123"
    Then I see the greeting "Hi, Test"

  Scenario Outline: Login is refused
    When I log in as "<username>" with password "<password>"
    Then I see the login error "<message>"

    Examples:
      | username   | password | message                                          |
      | testuser   | wrong    | Invalid username or password.                    |
      | lockeduser | Test@123 | This account is locked. Please contact support.  |
      | ghost      | Test@123 | Invalid username or password.                    |

The scenarios use the business language of the shop, not locators or clicks.


🔗 Step 2: Step Definitions

Step definitions are Python functions decorated with @given, @when and @then. parsers.parse extracts the quoted values from the step text and passes them as arguments. Shared steps go in conftest.py so every feature can use them:

📄 tests/conftest.py

from playwright.sync_api import Page, expect
from pytest_bdd import given, parsers, then, when

SHOP = "/dummy-ecommerce-website/"


@given("I am on the login page")
def on_login_page(page: Page):
    page.goto(SHOP + "#/login")


@when(parsers.parse('I log in as "{username}" with password "{password}"'))
def log_in(page: Page, username: str, password: str):
    page.get_by_test_id("login-username").fill(username)
    page.get_by_test_id("login-password").fill(password)
    page.get_by_test_id("login-button").click()


@then(parsers.parse('I see the greeting "{greeting}"'))
def see_greeting(page: Page, greeting: str):
    expect(page.get_by_test_id("account-button")).to_contain_text(greeting)


@then(parsers.parse('I see the login error "{message}"'))
def see_login_error(page: Page, message: str):
    expect(page.get_by_test_id("login-error")).to_have_text(message)

Then bind the feature file to a test module with scenarios(), which creates one pytest test per scenario:

📄 tests/test_login.py

from pytest_bdd import scenarios

scenarios("login.feature")          # path is relative to bdd_features_base_dir

⌨️ Terminal

pytest tests/test_login.py -v

🖥️ Output

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

tests/test_login.py::test_successful_login PASSED                        [ 25%]
tests/test_login.py::test_login_is_refused[testuser-wrong-Invalid username or password.] PASSED [ 50%]
tests/test_login.py::test_login_is_refused[lockeduser-Test@123-This account is locked. Please contact support.] PASSED [ 75%]
tests/test_login.py::test_login_is_refused[ghost-Test@123-Invalid username or password.] PASSED [100%]

============================== 4 passed in 6.44s ==============================

Every scenario (and every Examples row) is a normal pytest test with a readable name. Steps receive Playwright’s page fixture like any test, so everything from earlier modules (storage state, tracing, browsers) works unchanged.


🧺 Step 3: Data Tables and target_fixture

A data table passes a small table to one step. A step can also create an object for later steps with target_fixture: its return value becomes a fixture with that name.

📄 features/coupons.feature

@coupons
Feature: Coupons in the cart

  Scenario: SAVE10 is capped at ₹500
    Given my cart contains:
      | product | qty |
      | EL-013  | 1   |
    When I apply the coupon "SAVE10"
    Then the coupon discount is "−₹500"

  Scenario: FLAT200 needs a bigger cart
    Given my cart contains:
      | product | qty |
      | DG-010  | 1   |
    When I apply the coupon "FLAT200"
    Then the coupon message is "Add ₹1,000 more to use FLAT200."

📄 tests/test_coupons.py

import json

from playwright.sync_api import BrowserContext, Page, expect
from pytest_bdd import given, parsers, scenarios, then, when

scenarios("coupons.feature")

SHOP = "/dummy-ecommerce-website/"


@given("my cart contains:", target_fixture="cart_page")
def cart_contains(context: BrowserContext, page: Page, datatable):
    header, *rows = datatable                                   # first row is the header
    lines = [{"id": r[header.index("product")], "size": "", "color": "", "qty": int(r[header.index("qty")])} for r in rows]
    context.add_init_script(f"if (!sessionStorage.getItem('seeded')) {{ localStorage.setItem('spCart', {json.dumps(json.dumps(lines))}); sessionStorage.setItem('seeded', '1'); }}")
    page.goto(SHOP + "#/cart")
    return page


@when(parsers.parse('I apply the coupon "{code}"'))
def apply_coupon(cart_page: Page, code: str):
    cart_page.get_by_test_id("coupon-input").fill(code)
    cart_page.get_by_test_id("apply-coupon").click()


@then(parsers.parse('the coupon discount is "{amount}"'))
def coupon_discount(cart_page: Page, amount: str):
    expect(cart_page.get_by_test_id("coupon-discount")).to_have_text(amount)


@then(parsers.parse('the coupon message is "{message}"'))
def coupon_message(cart_page: Page, message: str):
    expect(cart_page.get_by_test_id("coupon-message")).to_have_text(message)

⌨️ Terminal

pytest tests/test_coupons.py -v

🖥️ Output

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

tests/test_coupons.py::test_save10_is_capped_at_500 PASSED               [ 50%]
tests/test_coupons.py::test_flat200_needs_a_bigger_cart PASSED           [100%]

============================== 2 passed in 3.56s ==============================
  • datatable is a built-in pytest-bdd fixture: a list of rows, each a list of cell strings.
  • target_fixture="cart_page" makes the step’s return value available to later steps as cart_page. That is how steps share state without global variables.
  • Steps defined in a test module are only visible to scenarios bound in that module; steps in conftest.py are visible everywhere.

🏷️ Tags Become Markers

Gherkin tags (@smoke, @coupons) become pytest markers, so the usual -m selection works:

⌨️ Terminal

pytest -m coupons -q

🖥️ Output

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

⌨️ Terminal

pytest -m "smoke and not coupons" -q

🖥️ Output

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

Because --strict-markers is on, a tag that is not registered in pytest.ini is reported as an error, which catches typos in feature files.


🤖 Generate Missing Step Code

When a product owner adds a new scenario, pytest-bdd can write the skeleton code for you, in two passes:

📄 features/search.feature

Feature: Search

  Scenario: Search finds earbuds
    Given I am on the home page
    When I search for "earbuds"
    Then I see at least 1 product

Pass 1: the scenario is not bound to any test yet, so pytest-bdd prints a test module that binds it:

⌨️ Terminal

pytest --generate-missing --feature features/search.feature

🖥️ Output

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

Scenario "Search finds earbuds" is not bound to any test in the feature "Search" in the file C:\Users\you\playwright-python\features\search.feature:3
-------------------------------------------------------------------------------
Please place the code above to the test file(s):

"""Search feature tests."""

from pytest_bdd import (
    given,
    scenario,
    then,
    when,
)


@scenario('features\search.feature', 'Search finds earbuds')
def test_search_finds_earbuds():
    """Search finds earbuds."""



============================ no tests ran in 0.02s ============================

Pass 2: bind the feature (the shorter scenarios() form does the same as the printed @scenario), then ask again. Now it prints a stub for every step that has no definition:

📄 tests/test_search.py

from pytest_bdd import scenarios

scenarios("search.feature")

⌨️ Terminal

pytest --generate-missing --feature features/search.feature

🖥️ Output

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

Step Given "I am on the home page" is not defined in the scenario "Search finds earbuds" in the feature "Search" in the file C:\Users\you\playwright-python\features\search.feature:4

Step When "I search for "earbuds"" is not defined in the scenario "Search finds earbuds" in the feature "Search" in the file C:\Users\you\playwright-python\features\search.feature:5

Step Then "I see at least 1 product" is not defined in the scenario "Search finds earbuds" in the feature "Search" in the file C:\Users\you\playwright-python\features\search.feature:6
-------------------------------------------------------------------------------
Please place the code above to the test file(s):

@given('I am on the home page')
def _():
    """I am on the home page."""
    raise NotImplementedError


@when('I search for "earbuds"')
def _():
    """I search for "earbuds"."""
    raise NotImplementedError


@then('I see at least 1 product')
def _():
    """I see at least 1 product."""
    raise NotImplementedError

============================ no tests ran in 0.02s ============================

Copy the stubs into the module, give each function a real name, and replace literal values with parsers ('I search for "{term}"'), so one step serves many scenarios. Steps that already exist, for example in conftest.py, are not generated again.


📣 Gherkin-Style Output

For demos and CI logs that business readers look at, print scenarios step by step. Here is the finished step module:

📄 tests/test_search.py

from playwright.sync_api import Page, expect
from pytest_bdd import given, parsers, scenarios, then, when

scenarios("search.feature")


@given("I am on the home page")
def home(page: Page):
    page.goto("/dummy-ecommerce-website/")


@when(parsers.parse('I search for "{term}"'))
def search(page: Page, term: str):
    page.get_by_test_id("search-input").fill(term)
    page.get_by_test_id("search-button").click()


@then(parsers.parse("I see at least {count:d} product"))
def at_least(page: Page, count: int):
    expect(page.get_by_test_id("product-card").first).to_be_visible()
    assert page.get_by_test_id("product-card").count() >= count

⌨️ Terminal

pytest tests/test_search.py --gherkin-terminal-reporter -v

🖥️ Output

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

tests/test_search.py::test_search_finds_earbuds 
Feature: Search
    Scenario: Search finds earbuds PASSED

============================== 1 passed in 1.96s ==============================

{count:d} in the parser converts the value to an int. Other format types include {price:f} for floats and {name:w} for a single word.


✅ Good Practices for Readable Scenarios

  1. Describe behaviour, not clicks. “When I apply the coupon SAVE10”, not “When I click the apply button”.
  2. One behaviour per scenario, with one When (a scenario with five When steps tests five things).
  3. Declarative Given steps that set up state quickly (seeded cart, saved login), not long click-paths.
  4. Reuse steps through conftest.py, and keep step texts consistent so they can be shared.
  5. Keep locators out of feature files and out of step texts; use page objects inside step definitions as the suite grows.
  6. Use BDD for collaboration. If nobody outside the test team reads the feature files, plain pytest tests are simpler.

💡 Tip: The Playwright TypeScript course builds the same idea with the playwright-bdd package for TypeScript, if your team works in both languages.


🏋️ 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 Scenario Outline for the SQA Shop search with three terms (earbuds, jeans, course) and a minimum result count for each, plus the step definition for the count step.

Show answer
Scenario Outline: Search returns results
  Given I am on the home page
  When I search for "<term>"
  Then I see at least <count> product

  Examples:
    | term    | count |
    | earbuds | 1     |
    | jeans   | 3     |
    | course  | 3     |

The existing @then(parsers.parse("I see at least {count:d} product")) step already handles it; <count> is substituted before parsing, and :d turns it into an int.

Exercise 2: Two feature files both need “Given I am logged in”. Where do you put the step definition, and how should it log in quickly?

Show answer

Put it in tests/conftest.py so every scenario can use it. Make it fast by loading saved login state or seeding storage instead of typing into the form, for example with a storage-state file (Lesson 51) or context.add_init_script that sets spUser in localStorage.

Exercise 3: A step “When I add the product to the cart” needs to know which product the earlier Given step opened. How do you share it without a global variable?

Show answer

Return the product from the Given step with target_fixture, then request that fixture in the When step:

@given(parsers.parse('I open the product "{product_id}"'), target_fixture="product_id")
def open_product(page, product_id):
    page.goto(f"/dummy-ecommerce-website/#/p/{product_id}")
    return product_id


@when("I add the product to the cart")
def add(page, product_id):
    page.get_by_test_id("pdp-add-to-cart").click()

Exercise 4: Your feature file has the tag @regresion (typo) and the run fails with “not found in markers”. Why is that good, and what is the fix?

Show answer

--strict-markers turned the typo into an error instead of silently ignoring the tag (which would make -m regression skip those scenarios). Fix the tag to @regression and make sure regression is registered under markers in pytest.ini.


🧠 MCQ Quiz: BDD with pytest-bdd and 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 pytest-bdd do?
  2. Which keyword describes context that every scenario in a feature needs?
  3. What does scenarios("login.feature") do?
  4. How do you extract "SAVE10" from the step text I apply the coupon "SAVE10"?
  5. What does target_fixture="cart_page" on a Given step do?
  6. How does a Scenario Outline run?
  7. What does the datatable fixture contain?
  8. How are Gherkin tags such as @smoke used in pytest?
  9. Where should step definitions shared by several features live?
  10. Which step text is better BDD style?

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


❓ Frequently Asked Questions

🤔 pytest-bdd or behave?

behave is a standalone BDD runner with its own fixtures and hooks. pytest-bdd runs inside pytest, so you keep pytest-playwright fixtures, xdist, reruns and every pytest plugin. For Playwright Python projects pytest-bdd is usually the better fit.

🤔 Can I generate a Cucumber JSON report?

Yes: pytest --cucumberjson=reports/cucumber.json. Many CI and reporting tools read that format. Allure also shows pytest-bdd scenarios with their steps (Lesson 64).

🤔 Can steps use page objects?

Yes, and they should in larger suites: create page objects in fixtures (Lesson 56) and call them from step definitions, so locators stay out of steps.

🤔 How do I run one scenario?

Use -k with part of the scenario name (pytest -k "Successful login"), or select the generated test by node id from --collect-only output.

🤔 What changed in recent pytest-bdd versions?

pytest-bdd 8 and 9 use the official Gherkin parser, pass data tables through the datatable fixture and doc strings through docstring, and substitute Scenario Outline values directly into step text (parsed like any other value). Old tutorials using example_converters or <param> fixtures no longer apply.


🏁 Summary

  • BDD describes behaviour as Gherkin scenarios; pytest-bdd runs them as pytest tests with Playwright fixtures.
  • Write steps with @given/@when/@then and parsers.parse, bind features with scenarios(), and share common steps in conftest.py.
  • Scenario Outlines run once per Examples row; data tables arrive in the datatable fixture; target_fixture passes state between steps.
  • Tags become markers (-m smoke), --strict-markers catches tag typos, and --generate-missing writes step skeletons.
  • Keep scenarios declarative and behaviour-focused; use BDD where non-testers read the scenarios.

🎬 Watch the Playwright tutorial series on YouTube!

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