Track: test automation in depth · Lesson 30 of 41 · 20 min
pytest in depth: fixtures, scope, parametrize, conftest and hooks
How to build a pytest suite that scales: fixtures with different scopes, yield teardown, parametrization, markers, conftest.py and pytest hooks.
Why pytest
pytest is the most popular framework for automated tests in Python: plain assert, powerful fixtures and hundreds of plugins. If you saw beforeEach and fixtures in the Playwright with hooks lesson, here are the same ideas in the Python world — in more depth.
A fixture = setup + cleanup
import pytest
@pytest.fixture
def cart(api, user):
c = api.post("/carts", json={"items": [{"sku": "TSHIRT-M", "qty": 1}]}, token=user.token).json()
yield c # the test gets the cart
api.delete(f"/carts/{c['id']}", token=user.token) # teardown after the test
def test_promo_sale10(api, user, cart):
r = api.post(f"/carts/{cart['id']}/promo", json={"code": "SALE10"}, token=user.token)
assert r.status_code == 200
assert r.json()["total"] == 112.5
The test simply lists fixtures as arguments — pytest builds the dependency graph itself: cart needs api and user, user needs api.
Scope: how long a fixture lives
| scope | Created | Example |
|---|---|---|
| function (default) | For every test | A cart, an order |
| class | For a test class | Rarely needed |
| module | For a file | The module's test user |
| package | For a package | Reference data |
| session | Once per run | The HTTP client, an admin token, the browser |
The rule: data a test modifies lives only in function scope. Wider scopes are for expensive, unchanging things only.
conftest.py
Fixtures in conftest.py are available to every test in that folder and its subfolders — no imports needed. A typical layout:
tests/
conftest.py # api, admin_token (session)
api/
conftest.py # user, cart (function)
test_promo.py
ui/
conftest.py # page, logged_in_page
test_checkout.py
Parametrize instead of copy-paste
@pytest.mark.parametrize("code, status, message", [
("SALE10", 200, None),
("sale10", 200, None), # case-insensitive
("EXPIRED5", 422, "This promo code has expired"),
("NOPE", 404, "Promo code not found"),
("", 400, "Enter a promo code"),
("A" * 13, 400, "Must be 4 to 12 characters"), # length boundary
], ids=["valid", "lowercase", "expired", "unknown", "empty", "too-long"])
def test_promo_codes(api, user, cart, code, status, message):
r = api.post(f"/carts/{cart['id']}/promo", json={"code": code}, token=user.token)
assert r.status_code == status
if message:
assert r.json()["error"] == message
Take the values from equivalence classes and boundary values — the technique from the test design lesson turns straight into a parameter table.
Markers
@pytest.mark.smoke
@pytest.mark.critical
def test_checkout_happy_path(...): ...
Run smoke only: pytest -m smoke. Register markers in pytest.ini, or you'll get a warning — and with --strict-markers, an error.
pytest hooks
Hooks are functions in conftest.py that pytest calls at certain stages. The most useful one for QA saves artifacts on failure:
@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport(item, call):
outcome = yield
report = outcome.get_result()
if report.when == "call" and report.failed and "page" in item.funcargs:
item.funcargs["page"].screenshot(path=f"artifacts/{item.name}.png")
Other useful ones: pytest_collection_modifyitems (ordering, conditional skips), pytest_sessionfinish (send a summary to QA Tools via the API).
Common mistakes
- A session-scoped fixture returns an object that tests modify — tests start depending on each other.
- Test logic inside a fixture: a fixture should set up, not assert.
- A 200-row parametrization without ids — nobody can tell from the report what failed.
Next on this track: API test automation with schemas.
Key takeaways
- A yield fixture combines setup and cleanup; a test just asks for it as an argument.
- Data a test modifies lives only in function scope; wide scopes are for expensive, unchanging things.
- The pytest_runtest_makereport hook saves screenshots and logs exactly when a test fails.
Check yourself
1. Which scope should a fixture have if it creates a cart the test modifies?
2. What runs after yield in a fixture?
3. How do you run only tests marked @pytest.mark.smoke?