Skip to main content

Testing and QA · Intermediate · 24 min

Speed up a slow pytest suite

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

You will take a sample pytest suite from about 18 seconds to about 2 by measuring it, widening a fixture scope, removing fixed sleeps, stubbing a slow external call, running it in parallel with pytest-xdist and splitting it across CI shards.

On this page

A slow suite costs more than the minutes it takes. People stop running it before they push, they batch up changes so failures are harder to read, and CI queues grow. The fix is rarely one big switch. It is a handful of small changes, each one aimed at a cost you have measured.

You will build a small shop library with a test suite that is slow on purpose, in the ways real suites tend to be slow: an expensive setup repeated for every test, fixed time.sleep calls waiting for background work, a call to an outside service on every run, and a few tests that are slow for good reasons. Then you fix one cost at a time and re-time the suite after each change, so you can see what each fix bought.

The slow parts are time.sleep calls that stand in for real work (parsing a large file, a network round trip, rendering a report). That keeps the timings the same on any machine, so the numbers you see should be close to the ones here.

Step 1 · Build the sample project and time it

Create a throwaway project with a virtual environment and pinned test dependencies:

Bash
mkdir -p ~/test-speed-demo/shop ~/test-speed-demo/tests
cd ~/test-speed-demo
python3 -m venv .venv
cat > requirements-dev.txt <<'TXT'
pytest==9.2.0
TXT
.venv/bin/python -m pip install --quiet -r requirements-dev.txt
touch shop/__init__.py
cat > pyproject.toml <<'TOML'
[tool.pytest.ini_options]
testpaths = ["tests"]
pythonpath = ["."]
addopts = "--strict-markers"
markers = ["slow: takes a second or more; leave out with -m 'not slow'"]
TOML

Add the code under test. Prices are in kobo (one hundredth of a naira), and the exchange rates are made up for the demo:

Bash
cat > shop/pricing.py <<'PY'
import time


def load_price_list():
    """Return the supplier price list in kobo.

    The sleep stands in for parsing a large supplier file.
    """
    time.sleep(0.5)
    return {
        "rice-5kg": 950000,
        "beans-1kg": 220000,
        "garri-2kg": 310000,
        "palm-oil-1l": 280000,
        "tomato-paste": 45000,
        "sugar-1kg": 160000,
        "salt-500g": 30000,
        "yam-tuber": 250000,
    }


def fetch_exchange_rate(currency):
    """Return how many naira one unit of `currency` costs.

    The sleep stands in for a call to a currency API over a slow link.
    """
    time.sleep(1.0)
    return {"NGN": 1, "KES": 12, "GHS": 100}[currency]


def quote(cart, currency, prices, get_rate=fetch_exchange_rate):
    """Total a cart of {sku: quantity} in `currency`, in minor units."""
    total_kobo = sum(prices[sku] * qty for sku, qty in cart.items())
    return round(total_kobo / get_rate(currency))
PY

cat > shop/money.py <<'PY'
SYMBOLS = {"NGN": "₦", "KES": "KSh ", "GHS": "GH₵"}
_settings = {"currency": None}


def set_currency(code):
    if code not in SYMBOLS:
        raise ValueError(f"unknown currency {code}")
    _settings["currency"] = code


def current_currency():
    return _settings["currency"]


def format_price(minor_units):
    code = _settings["currency"]
    if code is None:
        raise RuntimeError("call set_currency() first")
    return f"{SYMBOLS[code]}{minor_units / 100:,.2f}"
PY

cat > shop/export.py <<'PY'
import csv
import os
import threading
import time


def start_export(rows, path):
    """Write rows to a CSV file in the background and return the thread."""

    def work():
        time.sleep(0.2)  # stands in for gathering the rows
        tmp = f"{path}.tmp"
        with open(tmp, "w", newline="", encoding="utf-8") as f:
            csv.writer(f).writerows(rows)
        os.replace(tmp, path)  # the file appears complete or not at all

    thread = threading.Thread(target=work)
    thread.start()
    return thread
PY

cat > shop/reports.py <<'PY'
import time


def build_monthly_report(daily_sales):
    time.sleep(1.0)  # stands in for rendering the full report
    return {"lines": len(daily_sales), "total": sum(daily_sales)}
PY

Now the tests. They pass, and each one is reasonable on its own, which is how slow suites usually look:

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

from shop.pricing import load_price_list


@pytest.fixture
def price_list():
    return load_price_list()
PY

cat > tests/test_config.py <<'PY'
import pytest

from shop import money


def test_set_currency_stores_the_code():
    money.set_currency("NGN")
    assert money.current_currency() == "NGN"


def test_unknown_currency_is_rejected():
    with pytest.raises(ValueError):
        money.set_currency("XYZ")
PY

cat > tests/test_currency_format.py <<'PY'
from shop.money import format_price


def test_naira_has_symbol_and_grouping():
    assert format_price(950000) == "₦9,500.00"


def test_small_amount():
    assert format_price(5000) == "₦50.00"


def test_zero():
    assert format_price(0) == "₦0.00"
PY

cat > tests/test_export.py <<'PY'
import time

from shop.export import start_export


def test_writes_header_and_rows(tmp_path):
    out = tmp_path / "stock.csv"
    start_export([["sku", "qty"], ["rice-5kg", "4"]], out)
    time.sleep(1.5)
    assert out.read_text(encoding="utf-8").splitlines() == ["sku,qty", "rice-5kg,4"]


def test_keeps_yoruba_names(tmp_path):
    out = tmp_path / "names.csv"
    start_export([["ẹ̀wà", "3"]], out)
    time.sleep(1.5)
    assert "ẹ̀wà" in out.read_text(encoding="utf-8")


def test_empty_export_writes_an_empty_file(tmp_path):
    out = tmp_path / "empty.csv"
    start_export([], out)
    time.sleep(1.5)
    assert out.read_text(encoding="utf-8") == ""
PY

cat > tests/test_pricing.py <<'PY'
import pytest

SKUS = ["rice-5kg", "beans-1kg", "garri-2kg", "palm-oil-1l",
        "tomato-paste", "sugar-1kg", "salt-500g", "yam-tuber"]


@pytest.mark.parametrize("sku", SKUS)
def test_every_item_has_a_positive_price(price_list, sku):
    assert price_list[sku] > 0
PY

cat > tests/test_quote.py <<'PY'
from shop.pricing import quote


def test_naira_total(price_list):
    assert quote({"rice-5kg": 2}, "NGN", price_list) == 1900000


def test_cedi_total(price_list):
    assert quote({"rice-5kg": 1, "salt-500g": 2}, "GHS", price_list) == 10100


def test_shilling_total(price_list):
    assert quote({"beans-1kg": 3}, "KES", price_list) == 55000


def test_empty_cart_is_zero(price_list):
    assert quote({}, "KES", price_list) == 0
PY

cat > tests/test_reports.py <<'PY'
import pytest

from shop.reports import build_monthly_report

pytestmark = pytest.mark.slow


@pytest.mark.parametrize("days", [1, 7, 28, 31])
def test_report_has_a_line_per_day(days):
    assert build_monthly_report([1000] * days)["lines"] == days
PY

Run the whole suite and note the time on the last line:

Bash
.venv/bin/python -m pytest -q

Check it worked

The last line reads something like 24 passed in 18.62s. Write that number down: it is your baseline. Every later step ends with a new time to compare against it.

Step 2 · Find where the time goes

Guessing which tests are slow is unreliable. pytest records how long each test's setup, call and teardown take, and --durations=N prints the N slowest, and --durations=0 prints all of them. --durations-min hides anything quicker than the number of seconds you give it, so together they list every phase over 0.3 s:

Bash
.venv/bin/python -m pytest -q --durations=0 --durations-min=0.3

Read the table by phase, not only by test. Group what you see into causes:

  • setup, about 0.5 s, twelve times: the price_list fixture loads the same price list for every test in test_pricing.py and test_quote.py. That is 6 seconds spent producing identical data.
  • call, about 1.5 s, in test_export.py: the background export takes 0.2 s, and the test sleeps 1.5 s to be safe. Most of that wait is wasted.
  • call, about 1.0 s, in test_quote.py: every quote calls fetch_exchange_rate, the slow outside service.
  • call, about 1.0 s, in test_reports.py: report rendering is slow for real. These tests are already marked slow. You will keep them and run them in a smarter way rather than cut them.

Check it worked

You can name the four causes above from your own output: lines with setup against the pricing and quote tests, and lines with call against the export, quote and report tests. Add up the rows for each cause. Those four totals cover almost all of the baseline, so you know where to start.

Step 3 · Share expensive setup with a wider fixture scope

A fixture's scope decides how often it runs. The default, function, runs it once per test. scope="session" runs it once per test run and hands the same object to every test that asks for it.

Sharing has a risk: one test that changes the shared object changes it for every test after it, and the failures depend on order. Return a read-only view so that kind of mistake fails loudly at the line that made it. Replace tests/conftest.py:

Bash
cd ~/test-speed-demo
cat > tests/conftest.py <<'PY'
from types import MappingProxyType

import pytest

from shop.pricing import load_price_list


@pytest.fixture(scope="session")
def price_list():
    # Loaded once per run and shared, so it is read-only: a test that
    # tries to change a price raises TypeError instead of leaking the change.
    return MappingProxyType(load_price_list())
PY
.venv/bin/python -m pytest -q

Use module scope instead when the data must be fresh per file, and class scope for a group of tests in one class. Database connections, temporary servers and parsed fixtures files are the usual candidates for a wider scope. Anything a test changes on purpose, such as rows it inserts, stays function-scoped.

Check it worked

The suite still reports 24 passed, now in about 13 seconds, five and a half seconds faster. Run .venv/bin/python -m pytest -q --setup-show tests/test_pricing.py and you see SETUP S price_list once at the top, not once per test.

Step 4 · Replace fixed sleeps with a wait on the condition

A fixed sleep is a guess. If it is too short the test fails on a busy machine; if it is long enough to be safe, it wastes time on every fast run. Wait for the thing you need instead, checking often and giving up after a generous timeout.

Add a small wait_until fixture to tests/conftest.py. It polls a condition every 10 milliseconds and fails with a clear message if the condition never comes true:

Bash
cd ~/test-speed-demo
cat >> tests/conftest.py <<'PY'


@pytest.fixture
def wait_until():
    import time

    def wait(condition, timeout=5.0, interval=0.01):
        deadline = time.monotonic() + timeout
        while time.monotonic() < deadline:
            if condition():
                return
            time.sleep(interval)
        pytest.fail(f"condition not met within {timeout}s")

    return wait
PY

Rewrite the export tests to wait for the file. This is safe because start_export writes to a temporary file and renames it into place, so the final path only ever appears complete:

Bash
cat > tests/test_export.py <<'PY'
from shop.export import start_export


def test_writes_header_and_rows(tmp_path, wait_until):
    out = tmp_path / "stock.csv"
    start_export([["sku", "qty"], ["rice-5kg", "4"]], out)
    wait_until(out.exists)
    assert out.read_text(encoding="utf-8").splitlines() == ["sku,qty", "rice-5kg,4"]


def test_keeps_yoruba_names(tmp_path, wait_until):
    out = tmp_path / "names.csv"
    start_export([["ẹ̀wà", "3"]], out)
    wait_until(out.exists)
    assert "ẹ̀wà" in out.read_text(encoding="utf-8")


def test_empty_export_writes_an_empty_file(tmp_path, wait_until):
    out = tmp_path / "empty.csv"
    start_export([], out)
    wait_until(out.exists)
    assert out.read_text(encoding="utf-8") == ""
PY
.venv/bin/python -m pytest -q

Here the function also returns its thread, so start_export(...).join(timeout=5) would work too, and it is the simpler choice when you hold a handle on the work. Polling is the general tool for work you cannot join: a file written by another process, a row a worker inserts, a page element that appears.

Check it worked

grep -n "time.sleep" tests/test_export.py prints nothing, the suite still reports 24 passed, and the time drops to about 9 seconds. Each export test now takes about 0.2 s, the time the work really needs.

Step 5 · Stub the slow external call

The quote tests check arithmetic, but every one of them waits a second for an exchange rate. Worse, against a real API they would fail when the network is down or the rate changes. quote already accepts the rate lookup as a parameter, so the tests can pass a fake with fixed rates.

Add a fake_rate fixture to the conftest:

Bash
cd ~/test-speed-demo
cat >> tests/conftest.py <<'PY'


@pytest.fixture
def fake_rate():
    # Fixed rates, so the expected totals never change.
    return {"NGN": 1, "KES": 12, "GHS": 100}.__getitem__
PY

Pass it to every quote test, and keep one test that calls the real lookup, marked slow. That test checks the contract with the outside service (it answers, and with a number) without making every quote test depend on it:

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

from shop.pricing import fetch_exchange_rate, quote


def test_naira_total(price_list, fake_rate):
    assert quote({"rice-5kg": 2}, "NGN", price_list, get_rate=fake_rate) == 1900000


def test_cedi_total(price_list, fake_rate):
    assert quote({"rice-5kg": 1, "salt-500g": 2}, "GHS", price_list, get_rate=fake_rate) == 10100


def test_shilling_total(price_list, fake_rate):
    assert quote({"beans-1kg": 3}, "KES", price_list, get_rate=fake_rate) == 55000


def test_empty_cart_is_zero(price_list, fake_rate):
    assert quote({}, "KES", price_list, get_rate=fake_rate) == 0


@pytest.mark.slow
def test_real_rate_lookup_returns_a_number():
    assert fetch_exchange_rate("KES") > 0
PY
.venv/bin/python -m pytest -q

If the code does not take the dependency as a parameter, monkeypatch.setattr can replace the function on its module for one test. Passing it in is clearer, though: the test shows exactly what it depends on. For code that talks HTTP directly, a local fake server is often better still; see the tutorial on testing code that calls other services.

Check it worked

The run reports 25 passed (the new contract test is the 25th) in about 6 seconds. Run .venv/bin/python -m pytest -q --durations=5 and the only call lines over a second are the four report tests and test_real_rate_lookup_returns_a_number, all marked slow.

Step 6 · Run in parallel and fix what it exposes

What is left is mostly tests that are slow for a reason. Running them side by side is the next gain. pytest-xdist starts several worker processes and hands tests out between them. Add it to the pinned dependencies:

Bash
cd ~/test-speed-demo
cat > requirements-dev.txt <<'TXT'
pytest==9.2.0
pytest-xdist==3.8.0
TXT
.venv/bin/python -m pip install --quiet -r requirements-dev.txt
.venv/bin/python -m pytest --version

-n auto starts one worker per CPU available to the process. Without psutil installed (this tutorial does not install it), that is the logical CPU count, so hyperthreads count; install pytest-xdist[psutil] and it counts physical cores instead. Start with a fixed four workers so your run splits the tests the way this one does:

Bash
.venv/bin/python -m pytest -q -n 4

The currency format tests fail with RuntimeError: call set_currency() first, yet they have passed in every run so far. They never set a currency. They worked because test_config.py sorts first, runs first and leaves NGN behind in a module-level setting. Each xdist worker is a separate Python process, and the scheduler sends the first couple of tests to one worker and the next couple to another, so the format tests now start in a process where nothing set the currency.

Parallel runs expose this class of bug: tests that lean on state another test left behind, in memory, in a file or in a database. The fix is in the tests, not in the runner. Make every test start from a known state and set up what it needs. Reset the setting before every test with an autouse fixture, which undoes itself when the test ends:

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


@pytest.fixture(autouse=True)
def no_currency(monkeypatch):
    # Every test starts with no currency chosen, whatever ran before it.
    from shop import money

    monkeypatch.setitem(money._settings, "currency", None)
PY

Then have the format tests choose the currency themselves:

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

from shop.money import format_price, set_currency


@pytest.fixture(autouse=True)
def naira():
    set_currency("NGN")


def test_naira_has_symbol_and_grouping():
    assert format_price(950000) == "₦9,500.00"


def test_small_amount():
    assert format_price(5000) == "₦50.00"


def test_zero():
    assert format_price(0) == "₦0.00"
PY

Rerun only the tests that failed last time with --lf, then the whole suite in parallel:

Bash
.venv/bin/python -m pytest -q -n 4 --lf
.venv/bin/python -m pytest -q -n 4

Now try the other common distribution mode. --dist loadscope keeps all the tests from one module in the same worker:

Bash
.venv/bin/python -m pytest -q -n 4 --dist loadscope

It is slower here, at about 4.5 seconds: the four slow report tests share one module, so one worker runs them back to back while the others sit idle. loadscope pays off when a module- or class-scoped fixture is expensive, because the default mode can set it up once on every worker that receives a test from that module. Time both modes on your own suite and keep the faster one.

One more thing parallel runs change: each worker runs session fixtures for itself, so price_list now loads once per worker. That is fine for read-only data. For a shared database or a fixed port, give each worker its own, as the tutorial on fixing flaky tests shows with the worker_id fixture.

Check it worked

The --lf run reports 3 passed and deselects the rest. The full -n 4 run reports 25 passed in about 2 to 3 seconds, which includes starting the workers. The --dist loadscope run also passes, but takes a couple of seconds longer.

On a low-cost laptop with two cores and 4 GB of memory, -n auto starts two workers, or four if the cores are hyperthreaded and psutil is not installed, and each one imports your code and dependencies separately. If memory runs short, set the count yourself with -n 2, or turn parallelism off with -n 0.

Step 7 · Run only what you need while you work

The full suite belongs in CI and before you push. While you edit one area, run less. pytest has the tools built in:

Bash
cd ~/test-speed-demo
.venv/bin/python -m pytest -q -m "not slow"
.venv/bin/python -m pytest -q tests/test_export.py
.venv/bin/python -m pytest -q -k "quote and not real"
.venv/bin/python -m pytest -q --ff -x

What each one does:

  • -m "not slow" leaves out everything marked slow. This is the run to repeat every few minutes.
  • A file or folder path runs only the tests in it. Add ::test_name to run one test.
  • -k matches test names (and file names and markers) with and, or and not.
  • --ff runs the tests that failed last time first, then the rest, and -x stops at the first failure, so a broken change shows up in seconds rather than at the end of the run.

The habit matters more than any tool: keep the fast set fast. When a new test needs a second or more, mark it slow in the same change.

Check it worked

The first command reports 20 passed, 5 deselected in about a second, which is the 0.5 s price list load plus the three exports. The -k run reports 4 passed, 21 deselected: the four stubbed quote tests and not the real lookup.

Step 8 · Split the suite across CI shards

One machine has a limited number of cores. Past that point, run several CI jobs at the same time, each with a share of the tests. Every job must collect the same tests in the same order and pick a different slice.

Add a collection hook to tests/conftest.py. With SHARD_TOTAL=3 and SHARD_INDEX=0, 1 or 2, it keeps every third test, starting at that index, and reports the rest as deselected. Taking every third test, rather than one third of the list in a block, spreads neighbouring slow tests across the shards:

Bash
cd ~/test-speed-demo
cat >> tests/conftest.py <<'PY'


def pytest_collection_modifyitems(config, items):
    import os

    total = int(os.environ.get("SHARD_TOTAL", "1"))
    index = int(os.environ.get("SHARD_INDEX", "0"))
    if total == 1:
        return
    keep = [item for i, item in enumerate(items) if i % total == index]
    drop = [item for i, item in enumerate(items) if i % total != index]
    config.hook.pytest_deselected(items=drop)
    items[:] = keep
PY

Before trusting a split, check that the shards together cover every test exactly once:

Bash
for i in 0 1 2; do
  SHARD_TOTAL=3 SHARD_INDEX=$i .venv/bin/python -m pytest --collect-only -q | grep "::" > "shard-$i.txt"
  echo "shard $i: $(wc -l < "shard-$i.txt") tests"
done
.venv/bin/python -m pytest --collect-only -q | grep "::" | sort > all-tests.txt
cat shard-0.txt shard-1.txt shard-2.txt | sort | diff - all-tests.txt && echo "shards cover every test exactly once"

In GitHub Actions a matrix starts one job per shard. Each job gets its index from the matrix, and each job can still use -n auto on its own runner:

YAML
jobs:
  test:
    runs-on: ubuntu-latest
    strategy:
      fail-fast: false
      matrix:
        shard: [0, 1, 2]
    steps:
      - uses: actions/checkout@v7
      - uses: actions/setup-python@v7
        with:
          python-version: "3.15"
      - run: python -m pip install -r requirements-dev.txt
      - run: python -m pytest -n auto
        env:
          SHARD_INDEX: ${{ matrix.shard }}
          SHARD_TOTAL: 3

fail-fast: false lets every shard finish, so one failing shard does not hide failures in the others. Shards cost more runner time in total, since each job installs dependencies and starts Python. On a plan with a monthly minutes limit, or where every download comes out of a data bundle, cache the pip downloads and add shards only while the wall-clock gain is worth it. Once one shard is much slower than the others, a plugin that splits by recorded test durations balances them better than counting tests.

Check it worked

The loop prints shard 0: 9 tests, shard 1: 8 tests and shard 2: 8 tests, then shards cover every test exactly once. If diff prints any lines instead, a test is missing from every shard or appears in two; fix the hook before you put it in CI. Running SHARD_TOTAL=3 SHARD_INDEX=1 .venv/bin/python -m pytest -q reports 8 passed, 17 deselected.

When you are finished, delete the demo project:

Bash
cd ~
rm -rf ~/test-speed-demo

Next steps

You took the sample suite from about 18 seconds to about 2, and each fix came from a measurement. On your own suite, run --durations first and fix the biggest cost before the next one.

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.