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.
pip install pytestuv add --dev pytestCheck the installation. The output must show the installed version:
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:
def addition(a, b): return a + b
def divide(a, b): if b == 0: raise ValueError("division by zero") return a / bThe 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:
from calculations import addition
def test_addition(): assert addition(2, 3) == 5Run the pytest command at the root of the project. pytest automatically discovers the test_* files and functions:
pytest============================= test session starts ==============================platform linux -- Python 3.13.5, pytest-9.2.0, pluggy-1.7.0rootdir: /path/to/my_projectcollected 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) == 5E assert 6 == 5E + 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:
pytest -v # details each test (verbose)pytest -q # compact outputpytest test_calculations.py # a single filepytest -k addition # only tests whose name contains "addition"pytest -x # stops at the first failureCover 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) == expectedpytest then counts three distinct tests, one per line, and names each one by its values:
test_calculations.py::test_addition[2-3-5] PASSEDtest_calculations.py::test_addition[-1-1-0] PASSEDtest_calculations.py::test_addition[0-0-0] PASSEDIf 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.fixturedef 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:
pip install pytest-covpytest --cov=calculations --cov-report=term-missingName 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 theassertkeyword, with no class. - The
pytestcommand discovers test files and functions by itself. - On failure, the report shows the compared values and the faulty line.
@pytest.mark.parametrizereplays a test on several cases without duplicating it.- A fixture prepares a reusable context that is independent between tests.
pytest.raiseschecks exceptions,pytest.approxcompares floats.pytest-covmeasures 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
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
Review
(0/0)Score by domain
A domain groups several guides and gets several questions, so its score is more reliable than a per-topic score, which often rests on a single question.
Summary
Strengths
No topic passed at 80% on at least two questions yet.
Weak areas
No topic below the pass mark.
Recommended next
Hints before you try again?
Continue the course: The work loop with a code agent: specify, test, review the diff
A new full quiz with random questions
Work again only on the questions you missed
FAQ: pytest in Python
A very widespread testing framework for Python
pytest is a very widespread testing framework in the Python ecosystem. Its principle: a test is a plain function that uses the built-inassert keyword, with no class and no ceremony.# test_calculations.py
def test_addition():
assert addition(2, 3) == 5
In practice, pytest is used to:- Check automatically that your code produces the right result.
- Detect regressions before they reach production.
- Secure a CI/CD pipeline: a failing test blocks the delivery.
unittest (built into Python but more verbose) thanks to its conciseness, its detailed failure messages and its rich ecosystem of plugins.assert keyword:# test_calculations.py
from calculations import addition
def test_addition():
assert addition(2, 3) == 5
Discovery rules: the file and the function start with test_. Then run:pytest
pytest discovers and runs all the tests automatically, with no class and no configuration. That is what makes it more concise than unittest.| unittest | pytest | |
|---|---|---|
| Availability | built into Python | to be installed |
| Structure | TestCase classes |
plain functions |
| Checks | assertEqual, assertTrue |
built-in assert |
| Failure messages | basic | detailed (compared values) |
pytest test_calculations.py # one file
pytest test_calculations.py::test_addition # one specific test
pytest -k addition # tests whose name contains addition
pytest -v # details each test
pytest -x # stops at the first failure
pytest --lf # reruns only the last failures
These options can be combined and save a lot of time during development, by rerunning only what interests you.import pytest
@pytest.fixture
def user():
return {"name": "Alice", "roles": ["admin"]}
def test_rights(user):
assert "admin" in user["roles"]
The test receives the fixture by naming it as a parameter. Each test gets a fresh instance, which guarantees their independence. Shared fixtures go in conftest.py, which is loaded automatically.pytest.raises context manager checks that a block raises the expected exception:import pytest
def test_division_by_zero():
with pytest.raises(ValueError, match="division by zero"):
divide(10, 0)
The match argument checks the message (regular expression). The test passes if the exception is raised and fails otherwise. It is essential for testing the error path, not just the nominal case.pytest-cov plugin adds coverage to pytest:pip install pytest-cov
pytest --cov=calculations --cov-report=term-missing
Name Stmts Miss Cover Missing
calculations.py 6 0 100%
The Missing column lists the lines never executed. Beware: 100% proves that the lines are executed, not that the assertions really check the behavior. Coverage measures a quantity, not a quality.