pytest
pytest is a test runner and framework for Python that provides test discovery, readable assert failures, powerful fixtures, and an extensible plugin system.
Installation and Setup
Create an isolated environment and install pytest from PyPI:
(venv) $ python -m pip install pytest
Key Features
- Discovers tests automatically in files named
test_*.pyor*_test.pywhen you run pytest. - Rewrites
assertstatements to display rich introspection when an assertion fails. - Provides fixtures for declarative setup and teardown with reusable scopes.
- Supports parametrization to run the same test with multiple inputs.
- Loads plugins automatically and exposes hooks for customization and extension.
- Reads configuration from
pytest.ini,pyproject.toml,tox.ini, orsetup.cfgto control discovery and behavior.
Usage
Write a minimal test and run it:
test_example.py
def inc(x):
return x + 1
def test_inc():
assert inc(2) == 3
Runt the test:
$ pytest -q
.
1 passed in 0.02s
Parametrize a test:
import pytest
@pytest.mark.parametrize(
"a,b,expected",
[
(1, 2, 3),
(0, 0, 0),
(-1, 1, 0),
],
)
def test_add(a, b, expected):
assert a + b == expected
Select specific tests or groups:
test_math.py
import pytest
@pytest.mark.slow
def test_big():
assert sum(range(10_000)) > 0
$ pytest -m slow # Run only tests marked "slow"
$ pytest tests/test_math.py # Run tests in one module
Markers help categorize and select tests on the command line.
Related Resources
Tutorial
Effective Python Testing With pytest
In this tutorial, you'll learn how to take your testing to the next level with pytest. You'll cover intermediate and advanced pytest features such as fixtures, marks, parameters, and plugins. With pytest, you can make your test suites fast, effective, and less painful to maintain.
For additional information on related topics, take a look at the following resources:
- How to Provide Test Fixtures for Django Models in Pytest (Tutorial)
- Testing Your Code With pytest (Course)
- Effective Testing with Pytest (Quiz)
By Leodanis Pozo Ramos • Updated Dec. 17, 2025