Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
GimmeJob
Sign in
Test automation · Python & pytest · Chapter 01 / 02

Test automation learning path

pytest core: fixtures, scope & markers

Fixtures, scope, parametrize, markers, skip versus xfail, and the flags worth knowing.

Fixtures and scope: the full execution model

A @pytest.fixture is a function managed by pytest, not a function you call directly. A test asks for it by naming it as a parameter; pytest resolves that name, creates dependencies first, injects the result, caches it for the active scope and finalizes it when the scope ends.

The five scopes

ScopeLifetimeGood useRisk
function (default)One test invocation, including every parametrized caseMutable cart, test user, fresh UI stateRepeating expensive setup
classTests in one test classRead-only class configurationMutations leak to another method
moduleOne test fileRead-only lookup table or module setupState spills between tests in the file
packageTests in a Python test packageExpensive, immutable package-wide resourceBoundaries depend on package layout
sessionOne pytest session per processImmutable settings, reusable browser/connection factoryCross-test contamination; separate xdist workers each create their own

Scope is a lifetime, not an access modifier. Visibility is controlled by where the fixture is declared: the test file, its test class, an ancestor conftest.py directory, or an installed plugin. Wider scopes do not automatically make a fixture available everywhere. A wider-scoped fixture also cannot depend on a narrower-scoped fixture: a session fixture requesting function data raises ScopeMismatch.

Why are there no explicit fixture calls?

import pytest

@pytest.fixture
def cart():
    return []

def test_checkout(cart):
    cart.append("keyboard")
    assert cart == ["keyboard"]

Before running test_checkout, pytest looks up a fixture named cart, calls it itself, then passes the resulting list to the test parameter. The name cart is the lookup key. Writing test_checkout(cart()) or calling a decorated fixture yourself bypasses the fixture mechanism and is incorrect.

Two requests, one instance; next test, a fresh one

Python
editable · browser sandbox
Result
Run the code to see the result.

A fixture is cached within its current scope. getfixturevalue("cart") does not rerun it in the same test. test_two gets another list because the first test's function scope has ended. Parametrized cases are separate invocations and also get their own function-scoped fixtures. A parametrized fixture can be executed multiple times even at a broader scope as parameter values change.

Dependency graph and teardown

@pytest.fixture
def cart():
    items = []
    yield items
    items.clear()  # teardown

@pytest.fixture
def cart_with_mouse(cart):
    cart.append("mouse")
    return cart

def test_buy(cart_with_mouse, cart):
    assert cart_with_mouse is cart
    assert cart == ["mouse"]

Sequence: cart setup → cart_with_mouse setup → test_buy → cart teardown. Returning a value ends a fixture's setup; yield hands a value to the test and resumes for teardown afterward. Teardown still runs if the test assertion fails, but not if setup raises before the fixture reaches yield. For partially completed setup, register cleanup as resources are acquired (e.g. request.addfinalizer) or use a safe try/finally around acquisitions.

Execution order is derived from scope, dependencies, and autouse, not the order of arguments in a test function. @pytest.fixture(autouse=True) activates a fixture automatically for tests that can see it; use sparingly because invisible setup makes tests harder to understand.

A complete, executable project

The repository contains the real files, not pseudocode:

After cloning GimmeJob, from examples/pytest-fixtures:

python -m pip install pytest
python -m pytest tests/test_scopes.py -q
python -m pytest tests/test_scopes.py --setup-show -v

--setup-show displays which fixtures get created and finalized for each test. The Python-only part runs without a browser or server.

How this maps to Playwright for Python

This is pytest + `pytest-playwright`, not the separate TypeScript `@playwright/test` runner.

pytest-playwright fixtureScopeWhat gets reused
playwright / browsersessionPlaywright instance / browser process
contextfunctionFresh isolated browser context per test
pagefunctionFresh page inside that test's context
new_contextfunctionFactory for additional isolated contexts inside that test
from playwright.sync_api import Page, expect

def test_first(page: Page):
    page.set_content("<h1>First test</h1>")
    expect(page.get_by_role("heading", name="First test")).to_be_visible()

def test_second(page: Page):
    assert page.url == "about:blank"  # New context/page, not the first page.

Tests share the browser process, not the same cookies, local storage or DOM: a separate BrowserContext is like a new browser profile. To avoid polluting other tests, do not convert page into a session-scoped global. When you call browser.new_context() yourself, close that context yourself; plugin CLI context options are not automatically applied to manually created contexts.

To run the real Playwright tests from examples/pytest-fixtures:

python -m pip install pytest pytest-playwright
python -m playwright install chromium
python -m pytest tests/test_playwright_isolation.py -q --browser chromium

No external URL is needed: page.set_content() creates each page's DOM locally. The Playwright test package and browser bundle are required.

What changes with parallelism?

pytest -n 4 requires the optional pytest-xdist plugin. Each worker is a separate Python process with its own fixture cache: session scope is not a single shared resource across all four workers. Worker-scoped isolation does not isolate a remote database, globally shared account, or external service. Allocate unique per-worker resources or orchestrate globally shared setup once with locking.

Practice: predict before running

Run --setup-show on the included project. Predict whether run_identity, pricing, tax_rate and cart are recreated for every test. Then change cart to scope="module" and observe how mutation between tests becomes a hidden dependency. Restore function scope afterward. Finally run the browser example and explain why two pages can share a browser process without sharing the DOM.

Official references: pytest fixture lifetime, fixture availability and ordering, Playwright Python pytest fixtures.

Fixtures: setup, teardown and dependency injection

A fixture is named setup that pytest injects by parameter name, and fixtures compose into a dependency graph.

A pytest fixture is a function whose return value is injected into any test that names it as a parameter. Using yield instead of return splits the function into setup and teardown around a single suspension point, which puts both halves next to each other where a reviewer can see them together. The property that makes fixtures more than a helper function is composition: a fixture may request other fixtures, so asking for one causes pytest to build the entire chain in order and tear it down in reverse. That turns preconditions into a declarative graph rather than a pile of setup calls copied between tests. One rule catches everybody eventually — code after yield does not run if the code before yield raised. If setup can fail halfway, clean up defensively at the start of the fixture as well as at the end, because the previous run may have crashed and left state behind.

Key points

  • Fixtures are injected by parameter name, so a test declares its preconditions in its signature
  • yield puts setup and teardown in one readable function; teardown runs in reverse dependency order
  • Teardown after yield is skipped if setup raised — clean defensively at the start as well

Code

@pytest.fixture
def shop_as_user(shop, worker_account):
    """A logged-in API facade with a guaranteed-empty cart."""
    username, password = worker_account
    shop.login_as(username, password)

    shop.cart.clear()   # BEFORE, because the previous run may have crashed
    yield shop
    shop.cart.clear()   # and after


@pytest.fixture
def cart_with_item(shop_as_user):
    """Composition: five tests need this precondition, so write it once."""
    product = shop_as_user.products.first_in_stock()
    shop_as_user.cart.add_item(product.id, 1)
    return shop_as_user, product


def test_remove_item_updates_total(cart_with_item):
    shop, product = cart_with_item          # Arrange came from the graph
    cart = shop.cart.remove_item(product.id)
    assert cart.line_for(product.id) is None

Requesting cart_with_item builds shop_as_user, which builds shop and worker_account, in that order.

See it in the framework

  • Implementation · Root fixtures: conftest.py — live · reviewed
  • Used by · Service-layer fixtures: tests/services/conftest.py — live · reviewed

Reviewed against commit f9ada16 (2026-08-14).

Common pitfalls

  • Assuming teardown always runs; a failure before yield skips it entirely and leaves state behind
  • Building deep fixture chains nobody can follow — if you cannot explain the graph, neither can the next reader

Practice exercise

Add print statements to three dependent fixtures and run pytest with --setup-show. Predict the construction and teardown order for two tests, then verify that default function-scoped fixtures are rebuilt for each test while a session-scoped dependency is reused. Run the standalone examples/pytest-fixtures/tests/test_scopes.py example.

Fixture scope, and what it means under parallel runs

Scope decides how often setup runs; with xdist, session scope means once per worker, which changes everything.

A fixture's scope controls how often it is created: function scope rebuilds it for every test, while class, module and session scopes reuse one instance across a wider group. The temptation is to widen scope for speed, and the correct question is not how expensive setup is but whether any test can modify the result. Anything mutable should stay function-scoped even when creation is cheap, because a shared mutable object turns test order into a hidden dependency that only appears when somebody reorders a file. The detail that catches experienced engineers is what session scope means under pytest-xdist: workers are separate processes, so a session-scoped fixture runs once per worker, not once per run. Four workers means four copies. If that fixture owns something shared — a server, a database reset, a single user account — the copies fight, and the failures move between tests from run to run. Pytest also supports package scope (between module and session); package boundaries follow Python package structure. Scope sets fixture lifetime, not which tests can see it: visibility comes from the test module, class, conftest.py hierarchy and plugins. A broad session-scoped fixture cannot depend on a function-scoped fixture; pytest reports ScopeMismatch. To see all five scopes execute without any running service, use the examples/pytest-fixtures project.

Key points

  • Choose scope by mutability first and cost second: anything a test can dirty stays function-scoped
  • Under xdist, session scope runs once per worker — four workers create four instances
  • A session-scoped fixture that owns a shared resource is a parallel-execution bug waiting to happen
  • Pytest has five scopes (function, class, module, package, session); scope is different from fixture visibility.

Code

# WRONG under `pytest -n 4`: "session" means once per WORKER, so each of the
# four workers wipes the other three workers' live sessions mid-run.
@pytest.fixture(autouse=True, scope="session")
def _reset_everything(base_url):
    httpx.post(f"{base_url}/api/testing/reset")


# RIGHT: give each worker its own data instead of resetting shared state.
@pytest.fixture(scope="session")
def worker_account(base_url, worker_id):
    username = f"qa_{worker_id}_{uuid.uuid4().hex[:8]}"
    httpx.post(
        f"{base_url}/api/auth/register",
        json={"username": username, "password": "Str0ng!Passw0rd"},
    ).raise_for_status()
    return username, "Str0ng!Passw0rd"

The worker_id fixture comes from pytest-xdist and is the key to per-worker isolation. For a runnable, no-server scope comparison, see examples/pytest-fixtures/README.md.

See it in the framework

  • Implementation · Root fixtures: conftest.py — live · reviewed
  • Used by · Web-layer fixtures: tests/web/conftest.py — live · reviewed

Reviewed against commit f9ada16 (2026-08-14).

Common pitfalls

  • Widening scope to session to speed the suite up, and silently introducing order-dependent failures
  • Putting a global state reset in a session-scoped autouse fixture — each worker then wipes the other workers' state mid-run

Practice exercise

Take a suite that passes sequentially and run it with -n 4 several times. If nothing fails, deliberately move a mutable fixture to session scope and run again until you reproduce a failure that moves between tests.

Parametrize: one test, many cases

Turn copy-pasted variants into a readable table, and label the rows so failures diagnose themselves.

The parametrize marker runs one test body against many input sets, producing a separate reported test per row. Its value is not saving keystrokes but making the coverage visible: a table of boundary values shows at a glance what is checked and what is missing, where five near-identical copied functions hide the gaps. Two habits make the difference between a table that helps and one that hurts. First, carry a human-readable label in each row, or set ids explicitly, so a failure reads as the case name rather than a mangled list of values. Second, choose rows using boundary-value analysis — minimum, one below minimum, maximum, one above maximum, and the type boundary — because the middle of a valid range almost never finds a defect. Stop parametrizing the moment the bodies diverge: if a row needs an if statement, it is a different test wearing a disguise.

Key points

  • Each row becomes its own reported test, so coverage is visible instead of buried in copies
  • Label rows or set ids: a failure should read [below minimum], not [0-422]
  • Pick rows by boundary analysis; stacking two parametrize decorators gives the cartesian product

Code

@pytest.mark.parametrize(
    ("quantity", "expected_status", "case"),
    [
        (1,   201, "minimum valid"),
        (99,  201, "maximum valid"),
        (0,   422, "below minimum"),
        (-1,  422, "negative"),
        (100, 422, "above maximum"),
        (1.5, 422, "non-integer"),
        ("2", 201, "numeric string, coerced by the API"),
    ],
)
def test_quantity_boundaries(shop_as_user, quantity, expected_status, case):
    product = shop_as_user.products.first_in_stock()

    response = shop_as_user.cart.add_item_raw(product.id, quantity)

    assert response.status_code == expected_status, f"[{case}] {response.text[:300]}"

Seven cases, one body. Triage starts from the test name before anyone opens a log.

See it in the framework

  • Used by · Parametrized product tests: tests/services/test_products.py — live · reviewed
  • Used by · Parametrized auth tests: tests/services/test_auth.py — live · reviewed

Reviewed against commit f9ada16 (2026-08-14).

Common pitfalls

  • Unlabelled rows, which turn a failure report into a puzzle of raw values
  • Keeping a row in the table once its body needs a branch — that is a separate test, not a case

Practice exercise

Find three near-identical tests in a suite and merge them into one parametrized table. Then add the boundary rows that were missing, and check whether any of the new rows fail.

Markers, skip and xfail

Markers select what runs; xfail with strict mode is how a known bug stays visible instead of rotting.

Markers are labels that let you select subsets of a suite — a smoke gate, everything except the slow tests, a single layer. Declaring every marker in configuration and enabling strict marker validation converts a misspelled @pytest.mark.foo decorator on a test into an immediate collection error instead of a marker that silently matches nothing. That check happens at collection time, though, and only covers markers applied to tests — it says nothing about a typo in the -m selection expression on the command line (pytest -m smoek), which pytest just evaluates against whatever it collected: no match means zero tests selected, with an exit status that looks exactly like a clean pass. Guard that separately — for example, fail the run (or the CI step) whenever the selected count is zero. Skip and xfail look interchangeable and are not. Skip says this test does not apply here, and is right for a missing device or the wrong operating system; nothing happens when the situation changes, so a skip can rot for years. Xfail says this is a known defect, and with strict mode enabled an unexpected pass turns the build red. That inversion is the whole point: the day somebody fixes the bug, the build forces the marker to be removed, so the known-issues list cannot quietly become permanent.

Key points

  • --strict-markers turns an unregistered @pytest.mark.foo decorator into a collection error — a typo in an -m selection expression is a different, unguarded failure mode: it just selects zero tests
  • skip means "not applicable here"; xfail means "known defect, with a ticket"
  • xfail_strict makes an unexpected pass fail the build, forcing the marker to be cleaned up

Code

# pyproject.toml
# [tool.pytest.ini_options]
# addopts = ["--strict-markers"]
# xfail_strict = true
# markers = ["smoke: minimal always-green set", "slow: takes over 30s"]

@pytest.mark.xfail(
    reason="KNOWN DEFECT SHOP-114: GET /api/orders/{id} does not check ownership",
    strict=True,
)
def test_order_belongs_to_its_owner(cart_with_item, shop_as_second_user):
    shop, _ = cart_with_item
    order = shop.orders.create()

    response = shop_as_second_user.client.get(f"/api/orders/{order.id}")

    assert response.status_code in (403, 404)

# The build is green today. The day SHOP-114 is fixed this test passes
# unexpectedly, strict mode turns the build red, and somebody deletes the marker.

# --strict-markers catches THIS:
#   @pytest.mark.smoek   # unregistered decorator -> collection error
# It does NOT catch this:
#   pytest -m smoek       # typo in selection -> exits clean, 0 tests run

A known defect that stays visible, carries a ticket number, and cleans itself up when fixed.

See it in the framework

  • Implementation · Marker declarations: pyproject.toml — live · reviewed
  • Used by · xfail example: tests/services/test_auth.py — live · reviewed

Reviewed against commit f9ada16 (2026-08-14).

Common pitfalls

  • Commenting out a failing test instead of marking it xfail — the coverage and the signal are both lost
  • Using skip for a known bug, which hides it permanently because nothing ever forces a review
  • Trusting --strict-markers to catch a typo in an -m expression on the command line — it only validates markers applied to tests, so a misspelled selection just runs nothing and exits clean

Practice exercise

Register a marker in your configuration with strict-markers enabled, then deliberately apply an unregistered marker like @pytest.mark.smoek to a test and confirm collection fails immediately. Separately, run pytest -m <a-misspelled-marker> and notice it exits clean having selected zero tests — then add a guard (in the CI step or a conftest hook) that fails the run whenever the selected count is zero. Finally, convert one commented-out test into a strict xfail with a ticket reference.

Source registry

7 chapter references
pytest fixtures reference

Fixture scope, autouse, finalisation and the dependency graph

pytest-dev · Official reference
Source ↗
pytest documentation

Test discovery, assertions, configuration and the plugin model

pytest-dev · Official documentation
Source ↗
qa-automation-python reference framework

The runnable framework and demo application every lesson in this path is drawn from

sergiiiavt · Reference implementation
Source ↗
pytest-xdist documentation

Parallel execution, worker identity and test distribution modes

pytest-dev · Official documentation
Source ↗
Parametrizing tests

Data-driven tests, test ids and parametrized fixtures

pytest-dev · Official how to
Source ↗
Marking test functions

Custom markers, strict marker validation and selection expressions

pytest-dev · Official how to
Source ↗
Skip and xfail

The difference between skipping a test and recording a known failure

pytest-dev · Official how to
Source ↗