Skip to main content

Testing and QA · Intermediate · 22 min

Organise a growing pytest suite with fixtures, markers and conftest

By Padding · Updated 18 Nov 2026
Debian (python:3.15-slim) · Python 3.15 · pytest 9.2.0 · uv 0.13

You will turn a flat pytest folder into a layered suite with shared fixtures in conftest.py, registered markers that separate slow integration tests from fast unit tests, and parametrised fixtures with readable ids.

On this page

A test suite that starts as three files in one folder rarely stays that way. After a few months it has forty files, the same five lines of setup copied into half of them, a few tests that take ten seconds each, and nobody is sure which tests touch the disk. Running "just the fast ones" before a commit becomes guesswork.

pytest has the tools to keep this under control, and they work together: fixtures with a scope and a teardown, fixtures that return factories, conftest.py files that share fixtures with one folder and the folders below it, and markers that label tests so you can choose them on the command line.

You will build a small stock-keeping module backed by SQLite, then organise its tests into a fast unit suite and a slower integration suite. Each step adds one tool and ends with a run whose output you can check. The product names include Yoruba diacritics, the sort of text a shop in Lagos or Ibadan really stores, so the suite also proves that names survive a CSV round trip intact.

Step 1 · Create the project and the code under test

Make a throwaway project and add pytest as a development dependency. The range allows 9.2 patch releases and nothing newer:

Bash
mkdir -p ~/pytest-suite-demo
cd ~/pytest-suite-demo
uv init --no-package
uv add --dev "pytest>=9.2,<9.3"
rm main.py

Create inventory.py. A Store wraps one SQLite database file. It can add stock, take stock out (with a warning in the log when an item runs low), print a summary, and export to or import from CSV. The low-stock threshold comes from an environment variable, so a shop can change it without editing code:

Bash
cat > inventory.py <<'PY'
import csv
import logging
import os
import sqlite3

log = logging.getLogger("inventory")

SCHEMA = """
CREATE TABLE items (
    sku TEXT PRIMARY KEY,
    name TEXT NOT NULL,
    qty INTEGER NOT NULL CHECK (qty >= 0)
);
"""


def low_stock_threshold():
    return int(os.environ.get("LOW_STOCK_THRESHOLD", "5"))


def create_database(path):
    conn = sqlite3.connect(path)
    conn.executescript(SCHEMA)
    conn.close()


class Store:
    def __init__(self, path):
        self.conn = sqlite3.connect(path)

    def close(self):
        self.conn.close()

    def add(self, sku, name, qty):
        with self.conn:
            self.conn.execute("INSERT INTO items VALUES (?, ?, ?)", (sku, name, qty))

    def take(self, sku, qty):
        with self.conn:
            row = self.conn.execute("SELECT qty FROM items WHERE sku = ?", (sku,)).fetchone()
            if row is None:
                raise KeyError(sku)
            if qty > row[0]:
                raise ValueError(f"only {row[0]} of {sku} left")
            left = row[0] - qty
            self.conn.execute("UPDATE items SET qty = ? WHERE sku = ?", (left, sku))
        if left < low_stock_threshold():
            log.warning("low stock: %s has %d left", sku, left)
        return left

    def count(self):
        return self.conn.execute("SELECT COUNT(*) FROM items").fetchone()[0]

    def rows(self):
        return self.conn.execute("SELECT sku, name, qty FROM items ORDER BY sku").fetchall()

    def print_summary(self):
        for sku, name, qty in self.rows():
            print(f"{sku}  {name}  {qty}")

    def export_csv(self, path, delimiter=","):
        rows = self.rows()
        with open(path, "w", newline="", encoding="utf-8") as f:
            writer = csv.writer(f, delimiter=delimiter)
            writer.writerow(["sku", "name", "qty"])
            writer.writerows(rows)
        return len(rows)

    def import_csv(self, path, delimiter=","):
        with open(path, newline="", encoding="utf-8") as f, self.conn:
            reader = csv.DictReader(f, delimiter=delimiter)
            self.conn.executemany(
                "INSERT INTO items VALUES (?, ?, ?)",
                ((r["sku"], r["name"], int(r["qty"])) for r in reader),
            )
        return self.count()
PY

Check it worked

Bash
uv run pytest --version
uv run python -c "import inventory; print(inventory.low_stock_threshold())"

The first line reads pytest 9.2.0, or a later 9.2 release. The second prints 5, the default threshold.

Step 2 · Lay out the folders and the configuration

Split the tests by what they need, not by which module they test. Unit tests run in memory or against a throwaway file and finish in milliseconds. Integration tests read and write real files, and some of them are slow. Two folders make the split visible to anyone who opens the project:

Bash
mkdir -p tests/unit tests/integration
cat >> pyproject.toml <<'TOML'

[tool.pytest.ini_options]
testpaths = ["tests"]
pythonpath = ["."]
addopts = "--strict-markers -ra"
markers = [
    "slow: takes a second or more; leave out with -m 'not slow'",
    "integration: reads or writes real files outside a single test",
]
TOML

What each setting does:

  • testpaths is where a bare pytest looks, so it never wanders into .venv.
  • pythonpath puts the project folder on the import path, so tests can import inventory.
  • addopts adds options to every run. --strict-markers turns a mistyped marker into an error instead of a silent no-op. -ra prints a short summary of every test that did not pass, including skips, at the end.
  • markers registers the labels you will use, with a description each.

There are no __init__.py files in the test folders. With pytest's default import mode that works as long as every test file has a unique name across the whole suite. Two files both called test_store.py, one per folder, would fail at collection. Keep the names distinct, as this tutorial does.

Check it worked

Bash
uv run pytest --markers | grep -E "^@pytest.mark.(slow|integration)"

You see your two markers, each with its description, among pytest's built-in ones such as skip and parametrize.

Step 3 · Share a database fixture with scope and teardown

Creating the schema once is cheap here, but in a real project it might be twenty migrations. Do expensive setup once per run and give each test a cheap, private copy of the result. That is what fixture scopes are for.

Create tests/conftest.py. Fixtures in a conftest.py are available to every test in that folder and the folders below it, without an import:

Bash
cat > tests/conftest.py <<'PY'
import shutil

import pytest

from inventory import Store, create_database


@pytest.fixture(scope="session")
def template_db(tmp_path_factory):
    """An empty database with the schema applied, built once per run."""
    path = tmp_path_factory.mktemp("template") / "inventory.db"
    create_database(path)
    return path


@pytest.fixture
def open_store(template_db, tmp_path):
    """A factory: each call copies the template and opens a new Store."""
    opened = []

    def _open(name="inventory.db"):
        path = tmp_path / name
        shutil.copy(template_db, path)
        store = Store(path)
        opened.append(store)
        return store

    yield _open
    for store in opened:
        store.close()


@pytest.fixture
def store(open_store):
    return open_store()
PY

Three ideas sit in this file:

  • scope="session" on template_db means pytest builds it once and reuses it for the whole run. tmp_path_factory is the session-scoped sibling of tmp_path, so the template has a folder that outlives a single test.
  • open_store uses yield instead of return. Code before the yield is setup, and code after it is teardown. pytest runs the teardown after the test finishes, whether it passed or failed, so every connection gets closed.
  • open_store returns a function rather than a store. A test that needs two databases, say to export from one and import into the other, calls it twice. The plain store fixture covers the common case of needing one.

A function-scoped fixture can use a session-scoped one, as open_store uses template_db. The reverse is an error, because a long-lived fixture cannot depend on something that is thrown away after each test.

Add the first unit tests:

Bash
cat > tests/unit/test_store.py <<'PY'
import pytest


def test_new_store_is_empty(store):
    assert store.count() == 0


def test_add_then_count(store):
    store.add("SKU-001", "Rice 5kg", 20)
    store.add("SKU-002", "Palm oil 1L", 8)
    assert store.count() == 2


def test_take_reduces_quantity(store):
    store.add("SKU-001", "Rice 5kg", 10)
    assert store.take("SKU-001", 3) == 7


def test_cannot_take_more_than_stock(store):
    store.add("SKU-001", "Rice 5kg", 2)
    with pytest.raises(ValueError, match="only 2"):
        store.take("SKU-001", 5)
PY
uv run pytest -q

Check it worked

The run ends with 4 passed. Now ask pytest to show when each fixture is set up and torn down:

Bash
uv run pytest --setup-show tests/unit/test_store.py > setup.txt
grep -E "^(SETUP|TEARDOWN) +S template_db" setup.txt
grep -cE "SETUP +F store" setup.txt

The S and F letters are the scope: session and function. template_db has exactly one SETUP line and one TEARDOWN line for the whole run, while the count of SETUP F store lines is 4, one per test. Each test also shows TEARDOWN F open_store, which is where the connections close.

Step 4 · Replace copied setup with a factory fixture

The tests above each invent a SKU, a name and a quantity, though most of them care about only one of those. As the suite grows, that copied setup is where tests drift apart and break together. A factory fixture gives every test sensible defaults and lets it override only what matters to it.

Add make_item to the shared conftest.py:

Bash
cat >> tests/conftest.py <<'PY'


@pytest.fixture
def make_item(store):
    """Add an item with default values. Returns the new SKU."""
    counter = 0

    def _make(name="Rice 5kg", qty=20):
        nonlocal counter
        counter += 1
        sku = f"SKU-{counter:03d}"
        store.add(sku, name, qty)
        return sku

    return _make
PY

The counter lives inside the fixture, so it starts at 1 in every test and SKUs never collide. Because make_item asks for store, and pytest gives a test the same fixture instance however many times it is requested, a test that names both gets the item in its own store.

Use it in a new file of unit tests that also brings in four of pytest's built-in fixtures:

Bash
cat > tests/unit/test_reports.py <<'PY'
import logging


def test_low_stock_logs_a_warning(store, make_item, monkeypatch, caplog):
    monkeypatch.setenv("LOW_STOCK_THRESHOLD", "10")
    sku = make_item(qty=12)
    with caplog.at_level(logging.WARNING, logger="inventory"):
        store.take(sku, 4)
    assert f"low stock: {sku} has 8 left" in caplog.text


def test_no_warning_above_threshold(store, make_item, monkeypatch, caplog):
    monkeypatch.setenv("LOW_STOCK_THRESHOLD", "3")
    sku = make_item(qty=12)
    with caplog.at_level(logging.WARNING, logger="inventory"):
        store.take(sku, 4)
    assert caplog.records == []


def test_summary_lists_each_item(store, make_item, capsys):
    make_item(name="Garri", qty=4)
    store.print_summary()
    assert capsys.readouterr().out == "SKU-001  Garri  4\n"


def test_export_writes_header_and_rows(store, make_item, tmp_path):
    make_item(name="Rice 5kg", qty=3)
    out = tmp_path / "stock.csv"
    assert store.export_csv(out) == 1
    assert out.read_text(encoding="utf-8").splitlines() == [
        "sku,name,qty",
        "SKU-001,Rice 5kg,3",
    ]
PY
uv run pytest -q

What the built-ins give you:

  • monkeypatch.setenv sets an environment variable for one test and restores the old value afterwards, so no test leaks configuration into the next. It can also patch attributes and dictionary entries.
  • caplog captures log records. caplog.at_level raises the capture level for one logger inside a with block, and caplog.text and caplog.records let you assert on what was logged.
  • capsys captures what the code prints. readouterr() returns the output so far and resets the capture.
  • tmp_path is a fresh folder per test, as in the first pytest tutorial.

Check it worked

The run ends with 8 passed. Change "10" to "5" in the first test, run it again, and it fails because 8 left is no longer below the threshold. Put "10" back before you continue.

Step 5 · Layer a conftest.py for integration tests

Some fixtures only make sense for one group of tests. A store pre-filled with realistic stock is useful to the integration tests and noise everywhere else. Put it in a conftest.py inside tests/integration, and only tests in that folder can see it:

Bash
cat > tests/integration/conftest.py <<'PY'
import pytest

STOCK = [
    ("SKU-001", "Gààrí Ìjẹ̀bú 2kg", 12),
    ("SKU-002", "Rice 5kg", 3),
    ("SKU-003", "Epo pupa 1L", 8),
]


@pytest.fixture
def seeded_store(store):
    for row in STOCK:
        store.add(*row)
    return store
PY

pytest looks for fixtures from the test outwards: the test file, then the conftest.py in the same folder, then each parent folder's conftest.py, then plugins and built-ins. A deeper conftest.py can also define a fixture with the same name as a shallower one, and tests below it get the deeper version. Use that sparingly: it is a powerful way to change behaviour for one folder, and a confusing one when nobody expects it.

Now write the integration tests. pytestmark at the top of a module applies a marker to every test in it, so nobody has to remember to label each new test:

Bash
cat > tests/integration/test_csv_files.py <<'PY'
import pytest

pytestmark = pytest.mark.integration


def test_roundtrip_keeps_names(seeded_store, open_store, tmp_path):
    out = tmp_path / "stock.csv"
    seeded_store.export_csv(out)
    copy = open_store("copy.db")
    assert copy.import_csv(out) == 3
    assert copy.rows() == seeded_store.rows()


@pytest.mark.slow
def test_import_a_large_file(open_store, tmp_path):
    path = tmp_path / "big.csv"
    with open(path, "w", newline="", encoding="utf-8") as f:
        f.write("sku,name,qty\n")
        for n in range(200_000):
            f.write(f"SKU-{n:06d},Item {n},{n % 50}\n")
    store = open_store()
    assert store.import_csv(path) == 200_000
PY
uv run pytest -q

The round trip compares every row, including the names with tone marks, so a wrong encoding anywhere in the export or import would fail it. The large import stands in for the kind of test that is worth having but not worth waiting for on every save.

Check it worked

The full run ends with 10 passed. The integration fixture is invisible to unit tests:

Bash
uv run pytest --fixtures tests/integration | grep -c seeded_store
if uv run pytest --fixtures tests/unit | grep -q seeded_store; then echo "seeded_store leaked into unit tests"; false; else echo "unit tests cannot see seeded_store"; fi

The first command prints 1. The second prints unit tests cannot see seeded_store.

Step 6 · Choose tests with -m and -k

Markers and names give you two independent ways to pick tests. -m takes an expression over markers, and -k takes an expression over names:

Bash
uv run pytest -q -m "not slow"
uv run pytest -q -m integration
uv run pytest -q -m "integration and not slow"
uv run pytest -q -k "export or roundtrip"

-m "not slow" is the one to run before every commit. -m integration is a good CI job of its own. -k matches substrings of test names and of their parent names, so -k roundtrip would also select every test in a file called test_roundtrip.py. That is why the integration file has a neutral name. -k also matches marker names, so keep words such as slow out of test names if you want the two to stay separate.

Check it worked

The four runs report, in order:

  • 9 passed, 1 deselected
  • 2 passed, 8 deselected
  • 1 passed, 9 deselected
  • 2 passed, 8 deselected

Catch a mistyped marker

Without --strict-markers, a typo such as @pytest.mark.slwo creates a new, unregistered marker with only a warning, and the test quietly runs on every "fast" run. Try it:

Bash
cat > tests/unit/test_typo.py <<'PY'
import pytest


@pytest.mark.slwo
def test_with_a_typo():
    assert True
PY
uv run pytest -q > typo.txt 2>&1 || echo "pytest exited with status $?"
grep "not found in" typo.txt
rm tests/unit/test_typo.py typo.txt

The status line reads pytest exited with status 2, and the error says something like 'slwo' not found in markers configuration option. Collection stops before any test runs, which is what you want in CI. The last line removes the broken file.

Step 7 · Parametrise a fixture and name the cases

Many shops and accounting tools in countries that write decimals with a comma export CSV with semicolons, because the comma is taken. The store already accepts a delimiter. A parametrised fixture runs every test that uses it once per value, which suits a setting like this that cuts across many tests.

Append the fixture to the integration conftest.py, and add a test that uses it:

Bash
cat >> tests/integration/conftest.py <<'PY'


@pytest.fixture(params=[",", ";", "\t"], ids=["comma", "semicolon", "tab"])
def delimiter(request):
    return request.param
PY
cat > tests/integration/test_delimiters.py <<'PY'
import pytest

pytestmark = pytest.mark.integration


def test_roundtrip_with_delimiter(seeded_store, open_store, tmp_path, delimiter):
    out = tmp_path / "stock.csv"
    seeded_store.export_csv(out, delimiter=delimiter)
    header = out.read_text(encoding="utf-8").splitlines()[0]
    assert header == delimiter.join(["sku", "name", "qty"])
    copy = open_store("copy.db")
    copy.import_csv(out, delimiter=delimiter)
    assert copy.rows() == seeded_store.rows()
PY
uv run pytest --collect-only -q -m integration

request.param holds the current value. ids gives each case a readable name. Without it pytest would generate ids from the values, and a tab character makes a poor test name. In @pytest.mark.parametrize, the same job is done with ids= or with pytest.param(value, id="name") per row.

Check it worked

The collection lists five integration tests, including these three:

Text
tests/integration/test_delimiters.py::test_roundtrip_with_delimiter[comma]
tests/integration/test_delimiters.py::test_roundtrip_with_delimiter[semicolon]
tests/integration/test_delimiters.py::test_roundtrip_with_delimiter[tab]

Run one case by its id, then the whole suite:

Bash
uv run pytest -q "tests/integration/test_delimiters.py::test_roundtrip_with_delimiter[semicolon]"
uv run pytest -q

The first run reports 1 passed, and the full run 13 passed.

Step 8 · Add a plugin that tests your organisation

A suite whose tests share state passes in file order and fails in any other. pytest-randomly shuffles the order on every run and prints the seed, so you can repeat a failing order. Adding it is a quick check that your fixtures really isolate each test:

Bash
uv add --dev "pytest-randomly>=5.1,<5.2"
uv run pytest | grep "randomly-seed"
uv run pytest -q
uv run pytest -q -p no:randomly

pytest finds installed plugins on its own, so there is nothing to configure. The first command prints the header line the plugin adds, something like Using --randomly-seed=1234567890. To repeat an order, pass that number back with --randomly-seed=<the number>. -p no:randomly, as in the last command, switches the plugin off for one run, which helps when you want to compare a shuffled run with file order.

A short list of other plugins worth knowing, each a uv add --dev away:

  • pytest-xdist runs tests in parallel across CPU cores with -n auto. Shuffled order should pass before you try parallel runs.
  • pytest-cov measures coverage while the tests run.
  • pytest-timeout fails a test that hangs instead of letting CI sit for an hour.

On a prepaid data plan, each plugin is a small download, but uv sync on a fresh machine fetches them all again. Add a plugin when a real problem asks for it, not in advance.

Check it worked

The first command prints one Using --randomly-seed= line, and both later runs end with 13 passed: the suite passes shuffled and in file order. If one fails only under some seeds, a test depends on another's leftovers. Run it again with that seed to reproduce it.

Remove the demo project when you are done:

Bash
cd ~
rm -rf ~/pytest-suite-demo

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.