Testing in CI

suggest change

Continuous integration (CI) runs your test suite automatically on every push and pull request, on a clean machine, often on several Python versions and operating systems. A CI run only helps if it is strict (it fails on real problems), readable (you can see why it failed without re-running it) and reproducible (you can run the same thing on your own machine).

This article shows how to set up a Python project for that with pytest and a few plugins:

Tool Role in CI
pytest runs tests, sets the exit code, writes JUnit XML
pytest-cov measures coverage and fails below a threshold
pytest-xdist runs tests in parallel (-n auto)
pytest-timeout kills hanging tests
pytest-randomly shuffles test order to expose hidden dependencies
nox runs the same test sessions locally and in CI
GitHub Actions runs the workflow on every push

For writing tests themselves see Unit tests with pytest, Intro to Test Fixtures and Parameterized tests.

All examples were run with Python 3.13, pytest 9.1, pytest-cov 7.1, pytest-xdist 3.8, pytest-timeout 2.4 and nox 2026.8. Long paths in the output were shortened.

The example project

We'll use a small project with a src layout:

pricing/
├── pyproject.toml
├── noxfile.py
├── src/
│   └── pricing/
│       └── __init__.py
└── tests/
    ├── conftest.py
    ├── test_pricing.py
    └── test_slow.py

src/pricing/__init__.py:

from decimal import Decimal, ROUND_HALF_UP


def apply_discount(price: Decimal, percent: int) -> Decimal:
    if not 0 <= percent <= 100:
        raise ValueError(f"percent must be 0-100, got {percent}")
    result = price * (100 - percent) / 100
    return result.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)


def total(prices: list[Decimal]) -> Decimal:
    return sum(prices, Decimal("0"))

tests/test_pricing.py:

from decimal import Decimal

import pytest

from pricing import apply_discount, total


@pytest.mark.parametrize(
    "price, percent, expected",
    [("100.00", 0, "100.00"), ("100.00", 15, "85.00"), ("19.99", 33, "13.39")],
)
def test_apply_discount(price, percent, expected):
    assert apply_discount(Decimal(price), percent) == Decimal(expected)


def test_discount_out_of_range():
    with pytest.raises(ValueError, match="0-100"):
        apply_discount(Decimal("10"), 120)


def test_total():
    assert total([Decimal("1.10"), Decimal("2.20")]) == Decimal("3.30")

Configuration in pyproject.toml

Put the test dependencies and the pytest settings in pyproject.toml. Then CI and every developer use the same options, and the CI command line stays short:

[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"

[project]
name = "pricing"
version = "0.1.0"
requires-python = ">=3.10"

[dependency-groups]
test = ["pytest>=9", "pytest-cov>=7", "pytest-xdist>=3.8", "pytest-timeout>=2.4"]

[tool.pytest]
testpaths = ["tests"]
addopts = ["-ra", "--import-mode=importlib"]
strict = true
filterwarnings = ["error"]
markers = [
    "slow: takes more than a second",
    "integration: needs external services",
]
timeout = "60"

What the settings do:

Running pytest now gives:

$ pytest
============================= test session starts =============================
platform win32 -- Python 3.13.15, pytest-9.1.1, pluggy-1.7.0
rootdir: C:\...\pricing
configfile: pyproject.toml
testpaths: tests
plugins: cov-7.1.0, timeout-2.4.0, xdist-3.8.0
timeout: 60.0s
timeout method: thread
timeout func_only: False
collected 5 items

tests\test_pricing.py .....                                              [100%]

============================== 5 passed in 0.13s ==============================

Strict mode catches mistakes in tests

A misspelled marker is silently ignored by default. A test marked @pytest.mark.slwo would then run in the fast job instead of being excluded. With strict_markers it is an error:

import pytest


@pytest.mark.slwo
def test_big_order():
    assert True
$ pytest
...
=================================== ERRORS ====================================
_____________________ ERROR collecting tests/test_typo.py _____________________
'slwo' not found in `markers` configuration option
=========================== short test summary info ===========================
ERROR tests/test_typo.py - Failed: 'slwo' not found in `markers` configuratio...
!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!!
============================== 1 error in 0.26s ===============================
$ echo $?
2

strict_config does the same for unknown configuration options. For example, if pytest-timeout is not installed in the CI environment, the timeout option becomes unknown. Without strict mode pytest only prints a warning and your tests run without a timeout. With it, the run stops right away:

$ pytest -p no:timeout
ERROR: Unknown config option: timeout

filterwarnings = ["error"] makes deprecation warnings fail the build while they are still easy to fix, instead of after the next major release of a library removes the deprecated function:

import warnings


def old_api():
    warnings.warn("old_api() is deprecated, use new_api()", DeprecationWarning, stacklevel=2)
    return 42


def test_old_api():
    assert old_api() == 42
$ pytest tests/test_warn.py
...
    def old_api():
>       warnings.warn("old_api() is deprecated, use new_api()", DeprecationWarning, stacklevel=2)
E       DeprecationWarning: old_api() is deprecated, use new_api()

tests\test_warn.py:5: DeprecationWarning
=========================== short test summary info ===========================
FAILED tests/test_warn.py::test_old_api - DeprecationWarning: old_api() is de...
============================== 1 failed in 0.09s ==============================

If a third-party library emits a warning you can't fix, add a narrow exception after "error". Later entries take precedence:

filterwarnings = [
    "error",
    "ignore:datetime.datetime.utcnow:DeprecationWarning:botocore.*",
]

Exit codes

CI decides whether a step passed only by the exit code of the command. pytest uses these:

import pytest

print(list(pytest.ExitCode))
[<ExitCode.OK: 0>, <ExitCode.TESTS_FAILED: 1>, <ExitCode.INTERRUPTED: 2>, <ExitCode.INTERNAL_ERROR: 3>, <ExitCode.USAGE_ERROR: 4>, <ExitCode.NO_TESTS_COLLECTED: 5>, <ExitCode.MAX_WARNINGS_ERROR: 6>]

Exit code 5 (no tests collected) is a non-zero exit code, so it fails the job. That is usually what you want: a wrong path or a -m expression that matches nothing should not look like success.

$ pytest -m integration
...
============================ 5 deselected in 0.15s ============================
$ echo $?
5

Be careful with shell pipes. In pytest | tee log.txt the step gets the exit code of tee, which is 0. Add set -o pipefail at the start of the script. GitHub Actions does that for you only when the step explicitly says shell: bash; the default shell on Linux runners is bash -e {0} without pipefail.

Readable failures: the CI environment variable

Most CI services set the environment variable CI (GitHub Actions, GitLab CI, CircleCI, Travis CI, Bitbucket Pipelines). pytest also checks for BUILD_NUMBER, which Jenkins sets. When either is set, pytest doesn't shorten assertion diffs or the short test summary. You can't add -v and re-run a failed CI job the way you would locally, so the full information must be in the first log.

def test_order_ids():
    assert list(range(1000, 1012)) == list(range(1000, 1011)) + [1013]

Locally:

>       assert list(range(1000, 1012)) == list(range(1000, 1011)) + [1013]
E       assert [1000, 1001, ...04, 1005, ...] == [1000, 1001, ...04, 1005, ...]
E         
E         At index 11 diff: 1011 != 1013
E         Use -v to get more diff

With CI=true:

>       assert list(range(1000, 1012)) == list(range(1000, 1011)) + [1013]
E       assert [1000, 1001, ...04, 1005, ...] == [1000, 1001, ...04, 1005, ...]
E         
E         At index 11 diff: 1011 != 1013
E         
E         Full diff:
E           [
E               1000,
E               1001,
...
E               1010,
E         -     1013,
E         ?        ^
E         +     1011,
E         ?        ^
E           ]

Selecting tests: slow and integration tests

A common setup is a fast job that runs on every push and a slower job that also runs integration tests against real services. Mark the tests with the markers registered in pyproject.toml:

import os
import time

import pytest

from pricing import total
from decimal import Decimal


@pytest.mark.slow
def test_total_many_prices():
    time.sleep(1.2)  # stands in for an expensive computation
    assert total([Decimal("0.01")] * 100_000) == Decimal("1000.00")


@pytest.mark.integration
def test_prices_from_database():
    dsn = os.environ["DATABASE_URL"]
    assert dsn.startswith("postgresql://")


@pytest.mark.skipif(os.name == "nt", reason="uses POSIX file permissions")
def test_readonly_cache(tmp_path):
    path = tmp_path / "cache"
    path.write_text("x")
    path.chmod(0o400)
    assert oct(path.stat().st_mode & 0o777) == "0o400"

Integration tests should be skipped unless they are explicitly enabled, so pytest works on a laptop without a database. A hook in tests/conftest.py does that for every test with the integration marker:

import os

import pytest


def pytest_collection_modifyitems(config, items):
    if os.environ.get("RUN_INTEGRATION") == "1":
        return
    skip = pytest.mark.skip(reason="set RUN_INTEGRATION=1 to run")
    for item in items:
        if "integration" in item.keywords:
            item.add_marker(skip)

Thanks to -ra, every skipped test and the reason shows up in the summary:

$ pytest
...
collected 8 items

tests\test_pricing.py .....                                              [ 62%]
tests\test_slow.py .ss                                                   [100%]

=========================== short test summary info ===========================
SKIPPED [1] tests\test_slow.py:16: set RUN_INTEGRATION=1 to run
SKIPPED [1] tests\test_slow.py:22: uses POSIX file permissions
======================== 6 passed, 2 skipped in 1.36s =========================

-m selects tests by marker expression:

$ pytest -m "not slow" -q
.....ss                                                                  [100%]
=========================== short test summary info ===========================
SKIPPED [1] tests\test_slow.py:16: set RUN_INTEGRATION=1 to run
SKIPPED [1] tests\test_slow.py:22: uses POSIX file permissions
5 passed, 2 skipped, 1 deselected in 0.04s

$ RUN_INTEGRATION=1 DATABASE_URL=postgresql://ci@localhost/test pytest -m integration -q
.                                                                        [100%]
1 passed, 7 deselected in 0.02s

Reports: JUnit XML and coverage

--junitxml writes results in the JUnit XML format. GitLab, Jenkins, Azure Pipelines and many GitHub Actions show these files as a test report with per-test timing and failure messages. --durations=N prints the slowest tests, which helps to keep the suite fast as it grows.

Coverage is measured with pytest-cov (see Code coverage for details). In CI the important option is --cov-fail-under, which makes the run fail when coverage drops below a threshold:

$ CI=true pytest --junitxml=reports/junit.xml --cov=pricing --cov-branch --cov-report=term-missing --cov-report=xml:reports/coverage.xml --cov-fail-under=90 --durations=3
...
collected 8 items

tests\test_pricing.py .....                                              [ 62%]
tests\test_slow.py .ss                                                   [100%]

- generated xml file: C:\...\pricing\reports\junit.xml -
=============================== tests coverage ================================
______________ coverage: platform win32, python 3.13.15-final-0 _______________

Name                      Stmts   Miss Branch BrPart  Cover   Missing
---------------------------------------------------------------------
src\pricing\__init__.py       8      0      2      0   100%
---------------------------------------------------------------------
TOTAL                         8      0      2      0   100%
Coverage XML written to file reports/coverage.xml
Required test coverage of 90% reached. Total coverage: 100.00%
============================= slowest 3 durations =============================
1.21s call     tests/test_slow.py::test_total_many_prices

(2 durations < 0.005s hidden.  Use -vv to show these durations.)
=========================== short test summary info ===========================
SKIPPED [1] tests\test_slow.py:16: set RUN_INTEGRATION=1 to run
SKIPPED [1] tests\test_slow.py:22: uses POSIX file permissions
======================== 6 passed, 2 skipped in 1.36s =========================

If someone adds a shipping_cost() function without tests, the run fails even though every test passed:

Name                      Stmts   Miss Branch BrPart  Cover   Missing
---------------------------------------------------------------------
src\pricing\__init__.py      12      3      4      0    69%   16-18
---------------------------------------------------------------------
TOTAL                        12      3      4      0    69%
FAIL Required test coverage of 90% not reached. Total coverage: 68.75%
=========================== short test summary info ===========================
SKIPPED [1] tests\test_slow.py:16: set RUN_INTEGRATION=1 to run
SKIPPED [1] tests\test_slow.py:22: uses POSIX file permissions
6 passed, 2 skipped in 1.37s
$ echo $?
1

Use --cov=pricing (the package name) rather than --cov=src. With the package name, coverage is measured for the installed package wherever it lives.

Timeouts for hanging tests

A test that deadlocks or waits on a socket that never answers doesn't fail. It hangs until the CI service kills the whole job, often after hours, and the log doesn't say which test it was. pytest-timeout fails the test instead. The global timeout = "60" in pyproject.toml applies to every test, and a marker overrides it for one test:

import threading

import pytest


@pytest.mark.timeout(2)
def test_waits_for_event_that_never_comes():
    done = threading.Event()
    done.wait()  # nobody calls done.set()


def test_after_hang():
    assert True

On Linux and macOS pytest-timeout uses SIGALRM by default. Only the hanging test fails and the run continues:

$ pytest --tb=line
...
test_hang.py F.                                                          [100%]

=================================== FAILURES ===================================
E   Failed: Timeout (>2.0s) from pytest-timeout.
/usr/lib/python3.14/threading.py:369: Failed: Timeout (>2.0s) from pytest-timeout.
=========================== short test summary info ============================
FAILED test_hang.py::test_waits_for_event_that_never_comes - Failed: Timeout ...
========================= 1 failed, 1 passed in 2.02s ==========================

Windows has no SIGALRM, so the plugin uses the thread method: it prints the stack of every thread (which shows exactly where the test was stuck) and then terminates the whole pytest process. The remaining tests don't run, but the job fails quickly with a useful log instead of hanging. With pytest-xdist only the worker process dies and xdist starts a new one.

Also set a job-level limit in the CI configuration (timeout-minutes in GitHub Actions) as a last line of defense.

Running tests in parallel

pytest-xdist distributes tests across worker processes. -n auto starts one worker per CPU core, so the same command works on a 4-core CI runner and a 24-core workstation:

$ pytest -n auto
...
created: 24/24 workers
24 workers [8 items]

ss......                                                                 [100%]
...
======================== 6 passed, 2 skipped in 8.31s =========================

Starting workers takes time, so for a tiny suite like this one it's slower than a serial run. It pays off once the suite takes more than a few seconds. pytest-cov supports xdist and combines the coverage data from all workers.

Tests that run in parallel must not share state: each test should use tmp_path instead of a fixed file name, a random free port instead of a fixed one, and its own database or schema.

Finding order-dependent tests

A test that passes only because another test ran before it is a bug waiting for the day someone reorders files or uses -n auto. pytest-randomly shuffles the test order on every run and prints the seed:

CART = []


def test_add_item():
    CART.append("book")
    assert CART == ["book"]


def test_cart_has_one_item():
    assert len(CART) == 1
$ pip install pytest-randomly
$ pytest
...
Using --randomly-seed=2365349480
collected 2 items

test_cart.py F.                                                          [100%]

================================== FAILURES ===================================
___________________________ test_cart_has_one_item ____________________________

    def test_cart_has_one_item():
>       assert len(CART) == 1
E       assert 0 == 1
E        +  where 0 = len([])

test_cart.py:10: AssertionError
=========================== short test summary info ===========================
FAILED test_cart.py::test_cart_has_one_item - assert 0 == 1
========================= 1 failed, 1 passed in 0.19s =========================

When a CI run fails this way, copy the seed from the log and reproduce the same order locally with pytest --randomly-seed=2365349480. pytest -p no:randomly turns shuffling off. pytest-randomly also resets random.seed() before each test, so tests that use random are reproducible.

The same commands locally and in CI: nox

A CI configuration that contains a long pytest command and the dependency list can only be tested by pushing. Moving that logic into a noxfile.py makes the CI step a one-liner and lets anyone run exactly the same thing locally:

import nox

nox.options.default_venv_backend = "venv"
nox.options.reuse_existing_virtualenvs = True

PYPROJECT = nox.project.load_toml("pyproject.toml")
PYTHONS = ["3.10", "3.13"]


@nox.session(python=PYTHONS)
def tests(session: nox.Session) -> None:
    session.install("-e", ".", *nox.project.dependency_groups(PYPROJECT, "test"))
    session.run(
        "pytest",
        f"--junitxml=reports/junit-{session.python}.xml",
        "--cov=pricing",
        "--cov-branch",
        "--cov-fail-under=90",
        *session.posargs,
    )

nox creates a fresh virtual environment for every Python version, installs the package and the test dependency group, and runs pytest. Arguments after -- are passed to pytest through session.posargs:

$ nox -l
Sessions defined in C:\...\pricing\noxfile.py:

* tests-3.10
* tests-3.13

sessions marked with * are selected, sessions marked with - are skipped.

$ nox -s tests -- -m "not slow"
nox > Running session tests-3.10
nox > Creating virtual environment (venv) using python.exe in .nox\tests-3-10
nox > python -m pip install -e . 'pytest>=9' 'pytest-cov>=7' 'pytest-xdist>=3.8' 'pytest-timeout>=2.4'
nox > pytest --junitxml=reports/junit-3.10.xml --cov=pricing --cov-branch --cov-fail-under=90 -m 'not slow'
============================= test session starts =============================
platform win32 -- Python 3.10.11, pytest-9.1.1, pluggy-1.7.0
...
================= 5 passed, 2 skipped, 1 deselected in 0.57s ==================
nox > Session tests-3.10 was successful in a minute.
nox > Running session tests-3.13
...
================= 5 passed, 2 skipped, 1 deselected in 0.28s ==================
nox > Session tests-3.13 was successful in 39 seconds.
nox > Ran 2 sessions in 2 minutes:
nox > * tests-3.10: success, took a minute
nox > * tests-3.13: success, took 39 seconds

Locally, a session whose Python version isn't installed is skipped. When the CI environment variable is set, nox treats a missing interpreter as an error, so CI never silently skips a version. In CI you'd run one version per job: nox -s tests-3.13. If uv is installed, nox can use it to create environments much faster (default_venv_backend = "uv|venv").

A GitHub Actions workflow

.github/workflows/tests.yml runs the suite on every push to main and on every pull request: on all supported Python versions on Linux, plus one version on Windows and macOS:

name: tests

on:
  push:
    branches: [main]
  pull_request:

concurrency:
  group: ${{ github.workflow }}-${{ github.ref }}
  cancel-in-progress: true

permissions:
  contents: read

jobs:
  test:
    name: py${{ matrix.python-version }} on ${{ matrix.os }}
    runs-on: ${{ matrix.os }}
    timeout-minutes: 15
    strategy:
      fail-fast: false
      matrix:
        os: [ubuntu-latest]
        python-version: ["3.10", "3.11", "3.12", "3.13", "3.14"]
        include:
          - os: windows-latest
            python-version: "3.13"
          - os: macos-latest
            python-version: "3.13"

    steps:
      - uses: actions/checkout@v5

      - uses: actions/setup-python@v6
        with:
          python-version: ${{ matrix.python-version }}
          cache: pip
          cache-dependency-path: pyproject.toml

      - name: Install
        run: |
          python -m pip install --upgrade pip
          python -m pip install -e . --group test

      - name: Run tests
        run: >
          pytest -n auto
          --junitxml=reports/junit.xml
          --cov=pricing --cov-branch
          --cov-report=term-missing --cov-report=xml:reports/coverage.xml
          --cov-fail-under=90
          --durations=10

      - name: Upload reports
        if: ${{ !cancelled() }}
        uses: actions/upload-artifact@v4
        with:
          name: reports-${{ matrix.os }}-py${{ matrix.python-version }}
          path: reports/

Notes on the workflow:

With nox, the install and test steps become a single step: pipx run nox -s tests-${{ matrix.python-version }}.

With uv instead of pip, use the astral-sh/setup-uv action and replace both steps with uv run --group test pytest -n auto .... uv run creates the environment, installs the project and the group from uv.lock and runs the command.

An integration test job with a service container

GitHub Actions can start a database next to the job. The job sets the variables that enable the integration tests from earlier:

  integration:
    runs-on: ubuntu-latest
    timeout-minutes: 15
    services:
      postgres:
        image: postgres:18
        env:
          POSTGRES_PASSWORD: ci
        ports: ["5432:5432"]
        options: >-
          --health-cmd pg_isready --health-interval 5s --health-retries 10
    env:
      RUN_INTEGRATION: "1"
      DATABASE_URL: postgresql://postgres:ci@localhost:5432/postgres
    steps:
      - uses: actions/checkout@v5
      - uses: actions/setup-python@v6
        with:
          python-version: "3.13"
      - run: python -m pip install --upgrade pip && python -m pip install -e . --group test
      - run: pytest -m integration

The health check makes the job wait until PostgreSQL accepts connections before the steps run. pytest -m integration exits with code 5 if a refactoring accidentally removes all integration tests, so the job doesn't pass by running nothing.

Best practices

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents