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.

Advertisement

📖 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

Advertisement

🧩 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

Advertisement

▶️ 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 --------------------------------
14:48:36 INFO  shop | POST objects -> 201
14:48:36 INFO  shop | GET objects/obj_5rwlt8ehgq -> 200
14:48:36 INFO  shop | DELETE objects/obj_5rwlt8ehgq -> 204
14:48:37 INFO  shop | GET objects/obj_5rwlt8ehgq -> 404
PASSED                                                                   [ 25%]
tests/ui/test_shopping.py::test_member_is_greeted[chromium] 
------------------------------- live log setup --------------------------------
14:48:37 INFO  shop | logging in once as testuser on qa
14:48:37 INFO  shop | open /dummy-ecommerce-website/#/login
14:48:39 INFO  shop | open /dummy-ecommerce-website/#/
PASSED                                                                   [ 50%]
tests/ui/test_shopping.py::test_member_coupon[chromium] 
------------------------------- live log setup --------------------------------
14:48:41 INFO  shop | open /dummy-ecommerce-website/#/
-------------------------------- live log call --------------------------------
14:48:43 INFO  shop | search 'earbuds'
14:48:43 INFO  shop | add to cart 'Wireless Earbuds'
14:48:43 INFO  shop | open /dummy-ecommerce-website/#/cart
PASSED                                                                   [ 75%]
tests/ui/test_shopping.py::test_guest_sees_login[chromium] 
------------------------------- live log setup --------------------------------
14:48:44 INFO  shop | open /dummy-ecommerce-website/#/
PASSED                                                                   [100%]

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

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 4.71s

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 11.57s
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 6.81s

📄 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 (79 KB)
test-results/tests-ui-test-broken-py-test-wrong-discount-chromium/trace.zip (1487 KB)
test-results/tests-ui-test-broken-py-test-wrong-discount-chromium/video.webm (391 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

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


Advertisement

❓ 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