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:yieldreturns the finished report, which the hook can enrich.report.when == "call"limits it to the test body (not setup or teardown).item.funcargsholds the fixtures the test used, so the hook can reach the still-openpage.pytest_html.extrasofferspng,jpg,image,url,text,jsonandhtmlattachments.
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_titlesets 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/rowreceive 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-htmlExercise 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 reportRemember: 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.
- Which option creates a single-file HTML report?Answer:
--html=report.html --self-contained-html.--self-contained-htmlembeds CSS, JavaScript and images in the one HTML file. - Which hook is used to attach a screenshot to a failed test’s report row?Answer:
pytest_runtest_makereport. It produces the report object for each phase, where you can add extras. - What does
report.when == "call"check?Answer: That the report is for the test body, not setup or teardown. makereport runs for setup, call and teardown; “call” is the test function itself. - How does the hook reach the Playwright page of the test?Answer:
item.funcargs["page"].item.funcargscontains the fixture values the test received. - Which helper adds a PNG screenshot from base64 data?Answer:
pytest_html.extras.png(b64_string, name=...).pytest_html.extrasprovides png, jpg, image, url, text, json and html. - Where does pytest-html get the environment table from?Answer: pytest-metadata, editable via
config.stash[metadata_key]. pytest-metadata collects platform, packages and plugins; you can add and remove keys. - Which hook changes the report heading?Answer:
pytest_html_report_title.pytest_html_report_title(report)setsreport.title. - Why should a screenshot be taken in the hook rather than in a fixture teardown?Answer: The hook knows the test failed and runs while the page is still open, before fixture teardown closes it. The call-phase report exists before teardown, so the failed state can be captured.
- What happens if you define
pytest_runtest_makereporttwice in the same conftest.py?Answer: The second definition replaces the first. It is plain Python: the later function with the same name overwrites the earlier one in the module. - What is a main advantage of Allure over pytest-html?Answer: Steps, history and trends across runs. Allure builds a report site with history; pytest-html makes one standalone file per run.
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-htmlcreates a shareable single-file report.- A
pytest_runtest_makereportwrapper hook can attach screenshots, URLs, text and console errors to failed tests viapytest_html.extras, usingitem.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