Design Patterns for Playwright Python Test Frameworks
Page objects solve one problem: where locators live. As a suite grows, other problems appear: test data that is copied and collides, long payloads built by hand, the same five-step journey in fifty tests, and if statements choosing how to log in. Classic design patterns, applied lightly, solve these. In this lesson you will add five patterns to a Playwright Python framework, each with a working example on the SQA Shop and the practice API: a test-data factory, a builder, the factory-as-fixture pattern with automatic clean-up, a facade for user journeys, and a strategy for interchangeable login methods.
📖 What You’ll Learn: why patterns matter in test code, the factory pattern for unique valid test data, the builder pattern for complex payloads, the factory-as-fixture pattern with clean-up, a facade or steps layer for user journeys, the strategy pattern for login methods chosen by configuration, why configuration should be a session fixture and not a global singleton, and when a pattern is overkill.
🧠 Why Patterns in Test Code?
Test code is real code: it is read far more often than it is written, and it changes every time the product changes. Patterns give names to solutions that keep it easy to change. Use them when you feel a specific pain:
| Pain | Pattern |
|---|---|
| Copied test data, collisions between runs | Factory |
| Payloads with many optional fields | Builder |
| Fixtures that create one object, tests that need several | Factory as fixture |
| The same multi-page journey repeated in many tests | Facade / steps |
if statements choosing how to do something |
Strategy |
📄 pytest.ini
[pytest]
addopts = --base-url https://sqatools.in
pythonpath = .
🏭 Factory: Valid, Unique Test Data
Tests often need “a valid object, I do not care about most fields”. A factory returns one with sensible defaults and a unique part, and lets the test override only what matters:
📄 framework/factories.py
import itertools
import uuid
_counter = itertools.count(1)
def unique(prefix: str) -> str:
return f"{prefix}-{next(_counter)}-{uuid.uuid4().hex[:6]}"
def make_user(**overrides) -> dict:
user = {"name": "Test User", "email": f"{unique('user')}@example.com", "age": 30}
user.update(overrides)
return user
def make_object(**overrides) -> dict:
obj = {"name": unique("pw-object"), "data": {"price": 999, "color": "black"}}
obj.update(overrides)
return obj
📄 tests/test_factory.py
from framework.factories import make_user
def test_factory_defaults_are_valid_and_unique(playwright):
api = playwright.request.new_context(base_url="https://sqatools.in/wp-json/sqa-api/v1/")
a, b = make_user(), make_user()
assert a["email"] != b["email"]
assert api.post("validate/user", data=a).status == 200 # defaults pass validation
def test_override_only_what_matters(playwright):
api = playwright.request.new_context(base_url="https://sqatools.in/wp-json/sqa-api/v1/")
response = api.post("validate/user", data=make_user(age=17)) # the one field this test is about
assert response.status == 422
assert [d["field"] for d in response.json()["error"]["details"]] == ["age"]
⌨️ Terminal
pytest tests/test_factory.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_factory.py::test_factory_defaults_are_valid_and_unique PASSED [ 50%]
tests/test_factory.py::test_override_only_what_matters PASSED [100%]
============================= 2 passed in 13.64s ==============================
The second test states its intent in one argument, age=17. Every other field is valid, so a failure can only come from the age rule.
💡 Tip: Libraries such as Faker (realistic names, addresses) and factory_boy (factories with sequences and relations) build on the same idea. Plain functions are enough until you need them.
🧱 Builder: Complex Payloads Step by Step
When an object has many optional parts, keyword arguments get unwieldy. A builder assembles it in readable steps and returns the result with build():
📄 framework/builders.py
import json
from dataclasses import dataclass, field
@dataclass
class CartBuilder:
"""Builds the SQA Shop cart (localStorage 'spCart') for fast test setup."""
lines: list[dict] = field(default_factory=list)
def with_item(self, product_id: str, qty: int = 1, size: str = "", color: str = ""):
self.lines.append({"id": product_id, "size": size, "color": color, "qty": qty})
return self # returning self enables chaining
def with_earbuds(self, qty: int = 1):
return self.with_item("EL-013", qty)
def with_handbook(self, qty: int = 1):
return self.with_item("DG-010", qty)
def build(self) -> list[dict]:
return list(self.lines)
def as_init_script(self) -> str:
data = json.dumps(json.dumps(self.build()))
return (f"if (!sessionStorage.getItem('seeded')) {{ localStorage.setItem('spCart', {data});"
f" sessionStorage.setItem('seeded', '1'); }}")
📄 tests/test_builder.py
from playwright.sync_api import BrowserContext, Page, expect
from framework.builders import CartBuilder
def test_cart_total_items(context: BrowserContext, page: Page):
cart = CartBuilder().with_earbuds().with_handbook(qty=3)
context.add_init_script(cart.as_init_script())
page.goto("/dummy-ecommerce-website/#/cart")
expect(page.get_by_test_id("cart-count")).to_have_text("4")
expect(page.get_by_test_id("cart-item-name")).to_have_text(["Wireless Earbuds", "Agile Testing Handbook"])
⌨️ Terminal
pytest tests/test_builder.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 1 item
tests/test_builder.py::test_cart_total_items[chromium] PASSED [100%]
============================== 1 passed in 2.06s ==============================
CartBuilder().with_earbuds().with_handbook(qty=3) reads like the test’s precondition, and the details of the storage format live in one class.
🧪 Factory as Fixture: Create Many, Clean Up All
A normal fixture creates one object. Often a test needs two or five. The factory-as-fixture pattern returns a function that creates objects on demand, remembers them, and deletes them all in teardown:
📄 tests/conftest.py
import pytest
from playwright.sync_api import Playwright
from framework.factories import make_object
@pytest.fixture(scope="session")
def api(playwright: Playwright):
context = playwright.request.new_context(base_url="https://sqatools.in/wp-json/sqa-api/v1/")
yield context
context.dispose()
@pytest.fixture
def create_object(api):
created: list[str] = []
def _create(**overrides) -> dict:
response = api.post("objects", data=make_object(**overrides))
assert response.status == 201, response.text()
obj = response.json()
created.append(obj["id"])
return obj
yield _create
for object_id in created: # clean up everything this test created
api.delete(f"objects/{object_id}")
print(f"\n[teardown] deleted {len(created)} object(s)")
📄 tests/test_factory_fixture.py
def test_two_objects_are_independent(api, create_object):
first = create_object(data={"price": 100})
second = create_object(data={"price": 200})
api.patch(f"objects/{first['id']}", data={"data": {"price": 150}})
assert api.get(f"objects/{second['id']}").json()["data"]["price"] == 200
⌨️ Terminal
pytest tests/test_factory_fixture.py -v -s
🖥️ 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_factory_fixture.py::test_two_objects_are_independent PASSED
[teardown] deleted 2 object(s)
============================== 1 passed in 5.57s ==============================
The test creates exactly what it needs, and the teardown line proves both objects were removed, even if an assertion had failed.
🎭 Facade: One Call for a User Journey
Page objects model screens. Many tests, though, need the same journey across several screens: log in, find a product, add it, open the cart. A facade (often called a steps or actions layer) wraps the journey in one method built on the page objects:
📄 framework/shop.py
from playwright.sync_api import Page
SHOP = "/dummy-ecommerce-website/"
class Shop:
"""Facade over the SQA Shop page interactions, named after user goals."""
def __init__(self, page: Page):
self.page = page
def login(self, username: str = "testuser", password: str = "Test@123"):
self.page.goto(SHOP + "#/login")
self.page.get_by_test_id("login-username").fill(username)
self.page.get_by_test_id("login-password").fill(password)
self.page.get_by_test_id("login-button").click()
self.page.get_by_test_id("account-button").filter(has_text="Hi,").wait_for()
return self
def add_to_cart(self, search_term: str, product_name: str):
self.page.goto(SHOP + "#/search/" + search_term)
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
def open_cart_with_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()
return self
📄 tests/test_facade.py
from playwright.sync_api import Page, expect
from framework.shop import Shop
def test_member_gets_flat200(page: Page):
Shop(page).login().add_to_cart("earbuds", "Wireless Earbuds").open_cart_with_coupon("FLAT200")
expect(page.get_by_test_id("coupon-discount")).to_have_text("−₹200")
⌨️ Terminal
pytest tests/test_facade.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 1 item
tests/test_facade.py::test_member_gets_flat200[chromium] PASSED [100%]
============================== 1 passed in 2.31s ==============================
In a full framework the facade methods call page objects (LoginPage(...).login(...)) instead of raw locators; it is shown flat here to keep the example short. The facade sits above page objects: page objects know screens, the facade knows journeys, tests know expectations.
🔀 Strategy: Interchangeable Ways to Log In
Sometimes there are several ways to reach the same state: log in through the UI, load a saved storage state, or log in through an API. Writing if method == "ui": ... elif ... in fixtures spreads that choice everywhere. The strategy pattern gives each way its own class with the same method, and the configuration picks one:
📄 framework/login_strategies.py
import json
from typing import Protocol
from playwright.sync_api import BrowserContext, Page
SHOP = "/dummy-ecommerce-website/"
class LoginStrategy(Protocol):
def login(self, context: BrowserContext, page: Page) -> None: ...
class UiLogin:
"""Slow but realistic: types into the login form."""
def login(self, context, 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("remember-me").check()
page.get_by_test_id("login-button").click()
page.get_by_test_id("account-button").filter(has_text="Hi,").wait_for()
class StoredLogin:
"""Fast: writes the 'remembered user' the app reads, before any page script runs."""
def login(self, context, page):
context.add_init_script(f"localStorage.setItem('spUser', {json.dumps(json.dumps('testuser'))});")
STRATEGIES: dict[str, LoginStrategy] = {"ui": UiLogin(), "stored": StoredLogin()}
The option is registered in the root conftest.py. pytest calls pytest_addoption only for plugins and for the conftest files it loads before parsing the command line; a conftest in a sub-folder is loaded that early only when that folder is passed as an argument, so its option would vanish when someone runs plain pytest.
📄 conftest.py
from framework.login_strategies import STRATEGIES
def pytest_addoption(parser):
parser.addoption("--login", default="stored", choices=sorted(STRATEGIES), help="how tests log in")
📄 tests/strategy/test_member_area.py
import pytest
from playwright.sync_api import Page, expect
from framework.login_strategies import STRATEGIES
@pytest.fixture
def member_page(request, context, page: Page) -> Page:
STRATEGIES[request.config.getoption("--login")].login(context, page)
return page
def test_greeting(member_page: Page):
member_page.goto("/dummy-ecommerce-website/")
expect(member_page.get_by_test_id("account-button")).to_contain_text("Hi, Test")
⌨️ Terminal
pytest tests/strategy -v --login stored --durations=1
pytest tests/strategy -v --login ui --durations=1
🖥️ 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/strategy/test_member_area.py::test_greeting[chromium] PASSED [100%]
============================= slowest 1 durations =============================
1.45s call tests/strategy/test_member_area.py::test_greeting[chromium]
============================== 1 passed in 1.91s ==============================
============================= 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/strategy/test_member_area.py::test_greeting[chromium] PASSED [100%]
============================= slowest 1 durations =============================
1.76s setup tests/strategy/test_member_area.py::test_greeting[chromium]
============================== 1 passed in 2.38s ==============================
Same test, two strategies, chosen from the command line. Run the fast one on every commit and the realistic one nightly. Adding an API login later means adding one class, not editing every fixture.
🚫 Configuration: Session Fixture, Not a Global Singleton
The singleton pattern (“exactly one instance”) is often used for configuration. In pytest, a module-level global that reads environment variables at import time is hard to override in tests and leaks between them. A session-scoped fixture gives you the same “one instance per run” with none of the downsides:
@pytest.fixture(scope="session")
def settings() -> Settings: # created once per run, easy to override in a conftest
return load_settings()
Tests that need special settings can override the fixture locally, which a global variable cannot offer.
⚖️ When a Pattern Is Overkill
- Three tests do not need a facade. Add one when the same journey appears in many tests.
- A builder for an object with two fields is noise; a factory function is enough.
- Patterns that hide what the test does are harmful. A reader should still see the important inputs and the expected result in the test itself.
🏋️ 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 factory make_product(**overrides) for the practice API that returns a product dictionary with a unique name, price 499 and category “books”, and use it to create a product with price=0 for a negative test.
Show answer
def make_product(**overrides) -> dict:
product = {"name": unique("book"), "price": 499, "category": "books"}
product.update(overrides)
return product
bad = make_product(price=0)Only the field under test differs from a valid default.
Exercise 2: Extend CartBuilder with with_size(product_id, size) for clothing items and use it to build a cart with one T-shirt CL-001 in size M.
Show answer
def with_size(self, product_id: str, size: str, qty: int = 1):
return self.with_item(product_id, qty=qty, size=size)
cart = CartBuilder().with_size("CL-001", "M").build()Exercise 3: Convert this fixture into the factory-as-fixture pattern so tests can create several users and all are deleted afterwards:
@pytest.fixture
def user(api):
u = api.post("users", data=make_user()).json()
yield u
api.delete(f"users/{u['id']}")Show answer
@pytest.fixture
def create_user(api):
created = []
def _create(**overrides):
u = api.post("users", data=make_user(**overrides)).json()
created.append(u["id"])
return u
yield _create
for user_id in created:
api.delete(f"users/{user_id}")Exercise 4: Add an ApiLogin strategy to the lesson’s STRATEGIES for an application whose login API sets a session cookie. Which object should it use to call the API, and why?
Show answer
class ApiLogin:
def login(self, context, page):
response = context.request.post("https://app.example.com/api/login", data={"username": "testuser", "password": "..."})
assert response.okUse context.request, because it shares the browser context’s cookie jar: the session cookie from the API response is then available to every page (Lesson 55).
🧠 MCQ Quiz: Design Patterns for Playwright 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.
- What does a test-data factory return?Answer: A valid object with sensible defaults and unique values, with optional overrides. Factories make the “valid default” explicit so tests override only what they test.
- Why include a unique part (counter or UUID) in factory data?Answer: To avoid collisions between tests and between runs. Unique values prevent “already exists” errors and cross-test interference, especially in parallel runs.
- What does a builder’s method usually return to allow chaining?Answer:
self. ReturningselfenablesBuilder().with_a().with_b().build(). - What does the factory-as-fixture pattern yield?Answer: A function that creates objects and records them for clean-up. Tests call the function as often as needed; teardown deletes everything recorded.
- Where does a facade sit in a framework?Answer: Above page objects, combining them into user journeys. Page objects model screens; the facade models journeys across them.
- What problem does the strategy pattern solve in the lesson?Answer: Choosing between interchangeable ways to log in without
ifchains in fixtures. Each method is a class with the same interface; configuration chooses one. - Why should
pytest_addoptionlive in the rootconftest.py?Answer: pytest registers options only from plugins and conftests loaded before the command line is parsed; a sub-folder conftest is not always loaded that early. Running plainpytestfrom the root would not loadtests/strategy/conftest.pyearly, so its option would be unknown. - Why prefer a session-scoped settings fixture over a global singleton?Answer: It is created once per run but can be overridden locally and does not leak through imports. Fixtures give controlled lifetime and easy overrides; import-time globals do not.
- In
make_user(age=17), why is the test easy to understand?Answer: The only non-default value is the one under test. Highlighting the single relevant input makes intent and failure causes obvious. - When is a pattern overkill?Answer: When it adds abstraction without removing real duplication or hides what the test does. Patterns should solve a felt problem; otherwise they only add indirection.
Want a longer, timed test? Take the Module 10 mock interview (20 MCQs in 20 minutes).
❓ Frequently Asked Questions
🤔 What is the Screenplay pattern?
An alternative to page objects where actors perform tasks made of interactions and ask questions. It scales well for very large suites but adds more classes. Most Python teams get far with page objects plus a facade.
🤔 Should factories call the API or only return dictionaries?
Keep both layers: a pure function that returns data (make_object) and a fixture that sends it (create_object). Pure factories are reusable for negative tests and for UI form input.
🤔 Where should these modules live?
In a framework package such as framework/ or split by role (data/factories.py, flows/shop.py). See Lesson 57 for the layout.
🤔 Can a facade method contain assertions?
Prefer synchronisation (wait until the next page is ready) over verdicts. Leave the expected outcome to the test, so the same journey serves positive and negative tests.
🤔 Is dependency injection a pattern in pytest?
Yes, and you use it constantly: fixtures are pytest’s dependency injection. Asking for page, api or settings in a test’s arguments is exactly that.
🏁 Summary
- Factory: valid, unique defaults with overrides; tests state only what matters.
- Builder: readable, chainable construction of complex data such as carts and payloads.
- Factory as fixture: create many objects on demand and clean up all of them in teardown.
- Facade: user journeys built on page objects, so tests stay short and intent-focused.
- Strategy: interchangeable implementations (UI, stored, API login) chosen by configuration; prefer session fixtures over global singletons.
🎬 Watch the Playwright tutorial series on YouTube!
Subscribe to SqaToolsByDY • Practice on the SQA Tools Automation Practice Page