Skip to content
Français
Account: not signed in, sync available My learning
Select theme
Français

By updated

Improve this page

Logo Python

pytest is a very widespread testing framework for Python. A test is written with a plain function and the assert keyword, with no class and no ceremony. This guide starts from zero: you install pytest, write a first test, run it, then step up with parametrization, fixtures, testing exceptions and code coverage. The examples target pytest 9, whose latest stable version is 9.2.0 (published on 2026-10-27, Python 3.10 or later required).

It is aimed at developers who want reliable scripts and at anyone adding tests to a CI/CD pipeline. Unlike unittest (in French), which is built into Python but more verbose, pytest favors conciseness: less code for the same result.

What you will learn

  • Install pytest and write a first test with assert.
  • Run your tests and read a failure report.
  • Parametrize a test to cover several cases without duplicating it.
  • Factor out setup with fixtures.
  • Check that a function raises an exception as expected.
  • Measure the coverage of your tested code.

Why pytest rather than another tool

Python already ships unittest in its standard library. So why install something else? Because pytest reduces the code you have to write. Where unittest requires a class that inherits from TestCase and methods such as assertEqual, pytest settles for a function and the assert keyword. The same test takes fewer lines and reads at a glance.

pytest also brings test parametrization, fixtures to prepare data, detailed failure messages (it shows the compared values) and many plugins (coverage, asynchronous tests, Django). Many Python projects have adopted it: examples and plugins are easy to find.

Install pytest

pytest is installed in a virtual environment, so as not to pollute your system Python. If you have never created a virtual environment, the linked page explains how.

Terminal window
pip install pytest

Check the installation. The output must show the installed version:

Terminal window
pytest --version
# pytest 9.2.0 (the output looks like this, depending on the installed version)

Write and run a first test

Take a module to test, calculations.py:

calculations.py
def addition(a, b):
return a + b
def divide(a, b):
if b == 0:
raise ValueError("division by zero")
return a / b

The divide function is not used yet: it is tested further down, with pytest.raises and pytest.approx.

The test lives in a file whose name starts with test_ (or ends with _test.py), with a function whose name also starts with test_. It uses the assert keyword:

test_calculations.py
from calculations import addition
def test_addition():
assert addition(2, 3) == 5

Run the pytest command at the root of the project. pytest automatically discovers the test_* files and functions:

Terminal window
pytest
============================= test session starts ==============================
platform linux -- Python 3.13.5, pytest-9.2.0, pluggy-1.7.0
rootdir: /path/to/my_project
collected 1 item
test_calculations.py . [100%]
============================== 1 passed in 0.01s ===============================

The platform and rootdir lines depend on your machine. A dot marks each passing test. This automatic discovery is one of pytest's great comforts: there is no list of tests to maintain.

Read a failure

The point of a test is to flag a regression. If addition returned a wrong result, pytest would show the exact gap:

def test_addition():
> assert addition(2, 3) == 5
E assert 6 == 5
E + where 6 = addition(2, 3)
test_calculations.py:5: AssertionError
=========================== short test summary info ============================
FAILED test_calculations.py::test_addition - assert 6 == 5
============================== 1 failed in 0.02s ===============================

pytest shows the faulty line, the compared values (6 == 5) and where the value comes from. There is no need to add print() calls: the report already contains what you need to understand.

A few options that are useful every day:

Terminal window
pytest -v # details each test (verbose)
pytest -q # compact output
pytest test_calculations.py # a single file
pytest -k addition # only tests whose name contains "addition"
pytest -x # stops at the first failure

Cover several cases with parametrize

Testing addition on a single pair of values is not enough. Rather than writing one test per case, the @pytest.mark.parametrize decorator replays the same function with several data sets:

import pytest
from calculations import addition
@pytest.mark.parametrize("a, b, expected", [
(2, 3, 5),
(-1, 1, 0),
(0, 0, 0),
])
def test_addition(a, b, expected):
assert addition(a, b) == expected

pytest then counts three distinct tests, one per line, and names each one by its values:

test_calculations.py::test_addition[2-3-5] PASSED
test_calculations.py::test_addition[-1-1-0] PASSED
test_calculations.py::test_addition[0-0-0] PASSED

If a case fails, you know immediately which one. This is the idiomatic way to cover edge cases without duplicating code.

Factor out setup with fixtures

A fixture prepares a reusable context (data, a connection, a temporary file) and injects it into the tests that need it. You declare it with @pytest.fixture, and a test receives it simply by naming it in its parameters:

import pytest
@pytest.fixture
def user():
return {"name": "Alice", "roles": ["admin"]}
def test_admin_rights(user):
assert "admin" in user["roles"]
def test_name(user):
assert user["name"] == "Alice"

By default, each test receives a fresh instance of the fixture, which guarantees their independence: one test cannot pollute another. pytest also provides very useful built-in fixtures, such as tmp_path for a clean temporary directory for each test.

Check that an exception is raised

Testing the error path is as important as the nominal case. The pytest.raises context manager checks that a block raises the expected exception, and match checks the message:

import pytest
from calculations import divide
def test_division_by_zero():
with pytest.raises(ValueError, match="division by zero"):
divide(10, 0)

To compare floating-point numbers, whose strict equality is a trap, use pytest.approx:

def test_float_result():
assert divide(10, 3) == pytest.approx(3.3333, rel=1e-3)

Measure code coverage

Coverage tells you what share of your code is actually executed by the tests. The pytest-cov plugin adds it to pytest:

Terminal window
pip install pytest-cov
pytest --cov=calculations --cov-report=term-missing
Name Stmts Miss Cover Missing
-----------------------------------------------
calculations.py 6 0 100%
-----------------------------------------------
TOTAL 6 0 100%

The Missing column lists the lines never executed by a test, and therefore not verified.

Organize your tests

On a real project, code and tests live apart: the tests in a tests/ directory, and the shared fixtures in a conftest.py file that pytest loads automatically for the whole directory.

  • Répertoiremy_project/
    • calculations.py
    • Répertoiretests/
      • conftest.py
      • test_calculations.py

With this layout, test_calculations.py can no longer find the module calculations. This module is importable only if the project directory is in Python's search path, and pytest does not add it by itself when the tests are in tests/. Without any setting, the pytest command stops at collection with ModuleNotFoundError: No module named 'calculations'. Two solutions: run python -m pytest, which adds the current directory to that path, or declare pytest's pythonpath option in pyproject.toml:

[tool.pytest.ini_options]
pythonpath = ["."]

This split keeps the project readable and lets you run the whole suite with a single pytest command. Built into a CI/CD pipeline, this command becomes a safety net: every change is validated automatically before being merged or deployed.

Put it into practice

The last lab of the Python training's running thread has you write the pytest suite for security_check.py, with Click's CliRunner for exit codes. It is not graded on its number of green tests, but on what it catches: this is mutation testing. Your suite must pass on the reference tool, then fail on four mutants that each carry a realistic bug: exclusive threshold, forgotten letter case, duplicates counted, missing report that returns 1. A suite that kills no mutant protects against nothing.

This lab closes the running thread of the Python training and uses Click. In the training on AI-generated applications, where this lesson is shared, it is optional.

Key takeaways

  • pytest tests with a simple test_* function and the assert keyword, with no class.
  • The pytest command discovers test files and functions by itself.
  • On failure, the report shows the compared values and the faulty line.
  • @pytest.mark.parametrize replays a test on several cases without duplicating it.
  • A fixture prepares a reusable context that is independent between tests.
  • pytest.raises checks exceptions, pytest.approx compares floats.
  • pytest-cov measures coverage, but 100% does not guarantee the absence of bugs.
  • pytest also runs unittest tests: the migration can be gradual.

Knowledge check

Check that you have grasped the essentials of this guide. The questions cover only what has just been explained here.

Knowledge check

Check what you have learned with this interactive quiz

6 questions
6 min
70% to pass

How it works

  • The timer starts when you click Start
  • Multiple choice, true/false and short answer questions
  • You can move between questions
  • Detailed results are shown at the end

Starts the quiz and the timer

FAQ: pytest in Python