QA and Test Automation · Lab 14 of 35
Playwright Python With pytest: ShopRung UI Tests Step by Step
Write ShopRung UI tests in Python with Playwright and the pytest plugin: the page fixture, role and label locators, expect, page objects, a reset fixture, one login reused through storage state, and parametrized checks. 7 tests, run headed, filtered and with traces.
⏱ 60 minIntermediate💸 Free7 steps
Python 3.12playwright 1.63pytest-playwright 0.10pytest 8.3ShopRung
Overview video
What you will build
A pytest project that drives ShopRung in Chromium, with 7 tests and the structure teams use:
pages/products.pyandpages/cart.py: page objects with the locators and user actions.tests/conftest.py: a data reset through Playwright's API client, page object fixtures, and Alice logged in once for the whole run, reused by every test through storage state.test_search.py,test_cart.pyandtest_checkout.py: the mug search, case-insensitive search, the out of stock mug, SAVE10 at exactly $50.00, the shipping rule on both sides of $75.00 withparametrize, and a placed order.
It is the Python twin of Playwright end to end: same journeys, idiomatic pytest.
Before you start
- Python basics, and pytest fixtures from API tests with pytest or the pytest API lab.
- The episodes behind it: Playwright basics, Page Object Model, Fixtures and login state.
- ShopRung installed, as in lab 1 setup.
Setup
S1Start ShopRung
Start ShopRung as in lab 1 with npm start, and leave it running.
curl http://localhost:8080/api/healthcurl http://localhost:8080/api/healthcurl.exe http://localhost:8080/api/health {"status":"UP","app":"ShopRung","version":"1.0.0"} S2Project folder and virtual environment
Python 3.12 or newer (py on Windows). Make the folders, create a virtual environment and activate it; your prompt then starts with (.venv).
mkdir -p shoprung-ui-python/tests shoprung-ui-python/pages
cd shoprung-ui-python
python3 -m venv .venv
source .venv/bin/activatemkdir -p shoprung-ui-python/tests shoprung-ui-python/pages
cd shoprung-ui-python
python3 -m venv .venv
source .venv/bin/activatemkdir shoprung-ui-python\tests, shoprung-ui-python\pages
cd shoprung-ui-python
py -m venv .venv
.venv\Scripts\Activate.ps1 Install Playwright for Python and a browser
pytest, the Playwright library and its pytest plugin, pinned, plus Chromium.
Create requirements.txt. playwright is the library; pytest-playwright is the plugin that gives your tests ready-made fixtures like page and command-line options like --headed. Then playwright install chromium downloads the browser build this version is tested with.
Create pytest.ini too. Its addopts line sets options for every run: the base URL, the browser, a trace kept for every failed test, and a screenshot on failure. pythonpath = . lets tests import your pages package.
pytest==8.3.4
pytest-playwright==0.10.0
playwright==1.63.0 - The plugin: fixtures (
page,browser,context) and options (--headed,--browser).line 2
[pytest]
testpaths = tests
pythonpath = .
addopts = --base-url http://localhost:8080 --browser chromium --tracing retain-on-failure --screenshot only-on-failure - Without it,
from pages.cart import ...fails when you run plainpytest.line 3 - The default target. Pass
--base-urlagain on the command line to test another server.line 4 - A trace for every failed test, in
test-results/.line 4
pip install -r requirements.txt
playwright install chromium Successfully installed ... playwright-1.63.0 ... pytest-8.3.4 pytest-playwright-0.10.0 ... Downloading Chromium ... 100%
Stuck on this step?
- Linux: Chromium fails to start with missing libraries.
- Run
playwright install --with-deps chromium, which also installs system libraries.
Page objects in Python
ProductsPage and CartPage: each holds its locators once and offers user actions.
Create pages/__init__.py (empty: it makes pages a package), then pages/products.py and pages/cart.py. The Python API mirrors the TypeScript one with snake_case names: get_by_role, get_by_test_id, get_by_label, and filter(has_text=...).
Methods are named after what a user does, search_for, add_to_cart, apply_coupon, never after clicks. The tests will read like the behaviour, and a UI change means editing one class.
"""Page objects for ShopRung.""" """The product list: search, the result count and one card per product."""
from playwright.sync_api import Page
class ProductsPage:
def __init__(self, page: Page):
self.page = page
self.search = page.get_by_role("searchbox", name="Search products")
self.count = page.get_by_test_id("result-count")
self.cart_count = page.get_by_test_id("cart-count")
def open(self):
self.page.goto("/")
def search_for(self, term: str):
self.search.fill(term)
self.search.press("Enter")
def card(self, name: str):
return self.page.get_by_test_id("product-card").filter(has_text=name)
def add_to_cart(self, name: str):
self.card(name).get_by_role("button", name=f"Add {name} to cart").click() - Role + accessible name, the most stable locator.line 8
- Enter submits the search form, as a user would.line 17
- One product card, chosen by its content.line 20
- The buttons' accessible names include the product.line 23
"""The cart: lines, the coupon form, the totals and the Place order button."""
from playwright.sync_api import Page
class CartPage:
def __init__(self, page: Page):
self.page = page
self.coupon_message = page.get_by_test_id("coupon-message")
self.subtotal = page.get_by_test_id("subtotal")
self.discount = page.get_by_test_id("discount")
self.shipping = page.get_by_test_id("shipping")
self.total = page.get_by_test_id("total")
def open(self):
self.page.goto("/#/cart")
def set_quantity(self, name: str, quantity: int):
field = self.page.get_by_label(f"Quantity of {name}")
field.fill(str(quantity))
field.press("Tab") # the cart saves the new quantity when the field loses focus
def apply_coupon(self, code: str):
self.page.get_by_label("Coupon code").fill(code)
self.page.get_by_role("button", name="Apply").click()
def place_order(self):
self.page.get_by_test_id("checkout").click() - Each quantity field has a hidden label with its product name.line 18
- The cart saves a quantity when the field loses focus.line 20
A reset fixture and the first tests
conftest.py resets ShopRung before every test; three search tests pass.
Create tests/conftest.py. reset_shop has autouse=True, so it runs before every test. It uses the playwright fixture from the plugin to make an API client (playwright.request.new_context) with the same base URL, and posts to ShopRung's reset endpoint. products opens the product list and returns a ProductsPage; cart returns a CartPage.
Then create tests/test_search.py. Each test asks for products and uses expect, Playwright's retrying assertions: to_have_text waits up to 5 seconds for the text, so you never need time.sleep.
"""Shared setup: data reset and page objects."""
import pytest
from pages.cart import CartPage
from pages.products import ProductsPage
@pytest.fixture(autouse=True)
def reset_shop(playwright, base_url):
"""ShopRung back to its seed data before every test, through the API."""
api = playwright.request.new_context(base_url=base_url)
assert api.post("/api/test/reset").ok
yield
api.dispose()
@pytest.fixture
def products(page):
p = ProductsPage(page)
p.open()
return p
@pytest.fixture
def cart(page):
return CartPage(page) - Every test starts from the seed data.line 8
- An HTTP client from Playwright itself: no extra library.line 11
pagecomes from the plugin: a new tab in a fresh, isolated browser context.line 18
from playwright.sync_api import expect
def test_search_finds_the_two_mugs(products):
products.search_for("mug")
expect(products.count).to_have_text("2 products")
expect(products.card("Green Build Mug")).to_be_visible()
def test_search_is_not_case_sensitive(products):
products.search_for("MUG")
expect(products.count).to_have_text("2 products")
def test_the_out_of_stock_mug_cannot_be_added(products):
products.search_for("mug")
red = products.card("Red Build Mug")
expect(red).to_contain_text("Out of stock")
expect(red.get_by_role("button", name="Add Red Build Mug to cart")).to_be_disabled() - Retries until the count is right, or fails after 5 seconds.line 6
- CART rule: out of stock cannot be added.line 19
pytest -q ... [100%] 3 passed in 2.06s
Stuck on this step?
ModuleNotFoundError: No module named 'pages'- Check
pytest.inihaspythonpath = .and that you runpytestfrom the project folder. - Every test fails with
net::ERR_CONNECTION_REFUSED. - ShopRung is not running on the base URL. Start it, or pass
--base-url http://localhost:PORT.
Log in once with storage state
Alice logs in through the real form once per run; every test's browser starts logged in.
Replace tests/conftest.py. Two fixtures are new:
alice_statehas session scope: it runs once. It opens a browser context, logs Alice in through the login form, waits for Hi, Alice Shah, and saves cookies and localStorage (where ShopRung keeps its token) to a file in pytest's temporary folder.browser_context_argsis a plugin fixture you override: pytest-playwright builds every test's browser context from it. Addingstorage_statemakes every test start logged in.
A data reset does not log Alice out: it restores carts, orders and stock, not her account.
"""Shared setup: data reset, page objects, and Alice logged in once for the whole run."""
import pytest
from playwright.sync_api import Browser, expect
from pages.cart import CartPage
from pages.products import ProductsPage
ALICE = ("alice@shoprung.test", "Alice123!")
@pytest.fixture(autouse=True)
def reset_shop(playwright, base_url):
"""ShopRung back to its seed data before every test, through the API."""
api = playwright.request.new_context(base_url=base_url)
assert api.post("/api/test/reset").ok
yield
api.dispose()
@pytest.fixture(scope="session")
def alice_state(browser: Browser, base_url, tmp_path_factory):
"""Log Alice in once through the real form and save the browser state to a file."""
path = tmp_path_factory.mktemp("auth") / "alice.json"
context = browser.new_context(base_url=base_url)
page = context.new_page()
page.goto("/#/login")
page.get_by_label("Email").fill(ALICE[0])
page.get_by_label("Password").fill(ALICE[1])
page.get_by_role("button", name="Log in").click()
expect(page.get_by_test_id("user-name")).to_have_text("Hi, Alice Shah")
context.storage_state(path=path)
context.close()
return str(path)
@pytest.fixture
def browser_context_args(browser_context_args, alice_state):
"""pytest-playwright builds every test's context from these: start logged in as Alice."""
return {**browser_context_args, "storage_state": alice_state}
@pytest.fixture
def products(page):
p = ProductsPage(page)
p.open()
return p
@pytest.fixture
def cart(page):
return CartPage(page) - One real login for the whole run.line 20
- Wait until login really finished, or you save a logged-out state.line 30
- Cookies and localStorage, saved as JSON.line 31
- Overriding a plugin fixture changes every test's browser at once.line 37
pytest -q ... [100%] 3 passed in 2.4s
Cart rules, with parametrize
SAVE10 at exactly $50.00, and the shipping rule on both sides of $75.00.
Create tests/test_cart.py. The first test adds one Clean Code Notebook, waits for the cart badge to show 1, opens the cart, sets the quantity to 4 ($50.00, the SAVE10 minimum), applies save10 in lower case and checks every number the shopper sees: Coupon applied, -$5.00, $4.99 and $49.99.
The second test is parametrized: one function, two cases. The Testing Field Guide ($24.99) pays $4.99 shipping, total $29.98; the keyboard at exactly $75.00 ships Free. pytest-playwright adds the browser name to each test id, so the report says test_shipping_rule[chromium-Quiet Mechanical Keyboard-Free-$75.00].
import pytest
from playwright.sync_api import expect
def test_save10_at_exactly_50_dollars(products, cart):
products.add_to_cart("Clean Code Notebook")
expect(products.cart_count).to_have_text("1")
cart.open()
cart.set_quantity("Clean Code Notebook", 4)
expect(cart.subtotal).to_have_text("$50.00")
cart.apply_coupon("save10")
expect(cart.coupon_message).to_have_text("Coupon applied")
expect(cart.discount).to_have_text("-$5.00")
expect(cart.shipping).to_have_text("$4.99")
expect(cart.total).to_have_text("$49.99")
@pytest.mark.parametrize("product, shipping, total", [
("Testing Field Guide", "$4.99", "$29.98"), # $24.99: shipping charged
("Quiet Mechanical Keyboard", "Free", "$75.00"), # exactly $75.00: free
])
def test_shipping_rule(products, cart, product, shipping, total):
products.add_to_cart(product)
expect(products.cart_count).to_have_text("1")
cart.open()
expect(cart.shipping).to_have_text(shipping)
expect(cart.total).to_have_text(total) - Wait for the add to finish before leaving the page.line 7
- 4 × $12.50 = exactly $50.00.line 9
- Both sides of the free shipping edge in one test function.line 18
pytest -q tests/test_cart.py ... [100%] 3 passed in 2.9s
Checkout, and the whole suite
One journey to a placed order, then all 7 tests together.
Create tests/test_checkout.py: add the Testing Field Guide, open the cart, place the order, and check what the shopper sees: Thank you! Your order is placed., status PLACED, total $29.98, and a cart badge back at 0. Then run everything.
from playwright.sync_api import expect
def test_placing_an_order(page, products, cart):
products.add_to_cart("Testing Field Guide")
expect(products.cart_count).to_have_text("1")
cart.open()
cart.place_order()
expect(page.get_by_test_id("order-placed")).to_have_text("Thank you! Your order is placed.")
expect(page.get_by_test_id("order-status")).to_have_text("PLACED")
expect(page.get_by_test_id("order-total")).to_have_text("$29.98")
expect(products.cart_count).to_have_text("0") - The Place order button, through the page object.line 8
- A side effect the user sees: the cart is empty again.line 12
pytest -q ....... [100%] 7 passed in 4.74s
Headed runs, one test, and traces
The options you use every day while writing and debugging tests.
--headed shows the browser, --slowmo 300 slows every action by 300 ms so you can follow it, and -k picks tests by name. PWDEBUG=1 opens the Playwright Inspector to step through a test.
When a test fails, --tracing retain-on-failure from pytest.ini leaves a trace.zip in test-results/<test name>/. Open it with playwright show-trace to see every action, a snapshot of the page at each step, and the network calls.
pytest --headed --slowmo 300 -k save10
playwright show-trace test-results/<folder>/trace.zip 1 passed, 6 deselected
Check it works
Switch on ShopRung's coupon-boundary bug and run the suite: only test_save10_at_exactly_50_dollars fails. Its message says the coupon message was never found, because the shop refused SAVE10 at $50.00. Look at the screenshot in test-results/.
Then try free-shipping-boundary (only the keyboard case of test_shipping_rule fails) and search-case (the three search tests fail). With slow-search on, all 7 still pass: expect waits for the slow page. Turn the bugs off at the end.
curl -X POST http://localhost:8080/api/test/bugs -H "Content-Type: application/json" -d '{"enabled":["coupon-boundary"]}'
pytest -q E AssertionError: Locator expected to have text 'Coupon applied' E Actual value: None E Error: element(s) not found ... FAILED tests/test_cart.py::test_save10_at_exactly_50_dollars[chromium] - AssertionError: ... 1 failed, 6 passed in 10.34s
Troubleshooting
Executable doesn't exist at .../chromium-...
The browser for this Playwright version is missing. Run playwright install chromium with the virtual environment active.
Tests run against port 8080 though you passed another URL.
Put --base-url on the command line: it overrides the one in pytest.ini.
Cart tests behave as if logged out.
Check browser_context_args returns storage_state, and that alice_state waits for the user name before saving.
fixture 'page' not found
pytest-playwright is not installed in the active environment. Activate .venv and run pip install -r requirements.txt.
Asyncio errors when mixing with other plugins.
This lab uses the sync API (playwright.sync_api), which is what pytest-playwright gives you. Do not mix it with async tests in the same run.
What changes in production
- Python UI suites usually look exactly like this: page objects in a package, fixtures in conftest.py, the plugin's options in pytest.ini, and storage state per role.
- CI runs headless with
--tracing retain-on-failureand uploadstest-results/so anyone can open the trace of a failure. - Teams that already test their API with pytest often keep UI tests in the same repository, sharing fixtures for users and data.
- Parallel runs (
pytest-xdist) need isolated data per test instead of a shared reset, as the parallel episode shows.
Interview angle
“How do you structure Playwright tests in Python?”
pytest with the pytest-playwright plugin, which provides the page, context and browser fixtures and options like --headed and --tracing. Page objects live in their own package, conftest.py holds a data fixture (through Playwright's API client), page object fixtures and a session-scoped login that saves storage state, injected into every test through browser_context_args. Tests use role and label locators and expect, which retries, so there are no sleeps; parametrize covers boundaries. Failures keep traces and screenshots for CI.
Clean up
The full project
Every file from this lab, as it is after the last step.