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.

Advertisement

📖 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.14s

📄 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] 1665ms

Total tests: 1
Tests: 1 passed
Duration: 1.665s
the report successfully generated (79ms)

Advertisement

🏷️ 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.


Advertisement

📎 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 13.95s

⌨️ Terminal

npx allure log allure-results --all-steps

🖥️ Output

test_login
  ✓ Login is refused for 'lockeduser' 1803ms
  ✓ Login is refused for 'ghost' 1853ms
  ✓ Shopper logs in with username and password 1357ms

test_cart
  ⨯ FLAT200 discount (wrong expectation, fails on purpose) 4610ms
    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' 1482ms
    ✓ Add 'Wireless Earbuds' to the cart 36ms
    ✓ Apply coupon 'FLAT200' 76ms
    ⨯ Check the discount line 3006ms
  ✓ SAVE10 is capped at ₹500 1622ms
    ✓ Search for 'earbuds' 1519ms
    ✓ Add 'Wireless Earbuds' to the cart 47ms
    ✓ Apply coupon 'SAVE10' 53ms
    ✓ Check the discount line 2ms

test_basic
  ✓ test_home_lists_products[chromium] 1549ms

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

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 (443ms)
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.


Advertisement

🏋️ 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).


Advertisement

❓ 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