Pytest is the most widely used Python testing framework. You write tests as plain functions that use the assert keyword, and pytest adds fixtures, parametrization, markers and a large plugin ecosystem on top. This guide runs from installation to parallel runs, coverage and CI. Below the original walkthrough you will find a project layout that works when you copy it, corrected mocking and fixture examples, and fixes for the errors people hit most often.
A project layout that imports correctly
The example above imports with from src.my_code import add. If you have no extra configuration and run plain pytest, that import usually fails with ModuleNotFoundError: No module named 'src'. In its default import mode, pytest puts the test file's directory (tests/) on sys.path, not the project root. The fix is to tell pytest where the source code lives. You can do this with the pythonpath ini option, which pytest has supported since version 7.0.
my_project/
โโโ pytest.ini
โโโ src/
โ โโโ my_code.py
โโโ tests/
โโโ conftest.py
โโโ test_my_code.py
[pytest]
testpaths = tests
pythonpath = src
addopts = -ra --strict-markers
markers =
slow: marks tests as slow (deselect with -m "not slow")Code language: JavaScript (javascript)
With pythonpath = src, tests import modules directly: from my_code import add. testpaths limits discovery to tests/. -ra prints a short summary of every test that did not pass. --strict-markers turns a misspelled marker into an error, so it cannot silently select nothing. If you would rather use pyproject.toml, the same settings go under [tool.pytest.ini_options]:
[tool.pytest.ini_options]
testpaths = ["tests"]
pythonpath = ["src"]
addopts = "-ra --strict-markers"
markers = ["slow: marks tests as slow"]Code language: JavaScript (javascript)
Note: Install pytest and its plugins inside a virtual environment (python -m venv .venv and then activate it), so that the project's versions do not clash with system packages. Running python -m pytest instead of pytest also puts the current directory on sys.path and makes sure you use the interpreter from your venv.
A successful first run looks like this (the header lines are trimmed):
$ pytest
============================= test session starts ==============================
collected 1 item
tests/test_my_code.py . [100%]
============================== 1 passed in 0.01s ===============================
Assertions beyond equality
Pytest rewrites assert statements, so a failure shows the actual values on both sides. Two helpers cover cases that a plain assert handles badly: checking that an exception is raised, and comparing floating-point numbers.
import pytest
def divide(a, b):
return a / b
def test_divide_by_zero_raises():
# match is a regex searched against str(exception)
with pytest.raises(ZeroDivisionError, match="division by zero"):
divide(1, 0)
def test_float_sum():
# 0.1 + 0.2 == 0.3 is False in Python; approx allows a small tolerance
assert 0.1 + 0.2 == pytest.approx(0.3)Code language: PHP (php)
Fixtures in depth: conftest.py, scope and teardown
Put fixtures that several test files share in tests/conftest.py. Pytest loads that file automatically, and you never import it. The code before yield is setup and the code after it is teardown. The teardown runs even when the test fails. Here is a complete, runnable version of the database fixture from the example above, using SQLite from the standard library:
# tests/conftest.py
import sqlite3
import pytest
@pytest.fixture(scope="module")
def db_connection():
conn = sqlite3.connect(":memory:")
conn.execute("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)")
yield conn # tests in one module share this connection
conn.close() # teardown runs after the last test in the module
# tests/test_db.py
def test_insert_user(db_connection):
db_connection.execute("INSERT INTO users (name) VALUES (?)", ("asha",))
row = db_connection.execute("SELECT name FROM users").fetchone()
assert row == ("asha",)Code language: PHP (php)
- Scopes:
function(the default) creates a new fixture for every test.class,module,packageandsessionreuse it for longer. Use a wider scope only for expensive resources, because shared state can make tests depend on each other. tmp_pathgives each test its own temporary directory as apathlib.Path.monkeypatchsets environment variables or attributes and undoes the change automatically after the test.capsyscaptures stdout and stderr, so you can assert on printed output.- Run
pytest --fixturesto list every fixture available in the project, including the ones plugins provide.
Mocking that actually tests your code
The mocking example above patches src.my_code.external_function, which does not exist in my_code.py, so mocker.patch raises AttributeError. Even if the patch worked, the test only calls the mock itself and never runs any real code. The mocker fixture also needs pip install pytest-mock. Below is a corrected example that patches a dependency where it is used and then checks how your function called it.
# src/my_code.py
import os
import requests
def get_user_name(user_id):
resp = requests.get(f"https://api.example.com/users/{user_id}", timeout=5)
resp.raise_for_status()
return resp.json()["name"]
def get_env():
return os.environ.get("APP_ENV", "dev")Code language: PHP (php)
# tests/test_mocking.py
from my_code import get_env, get_user_name
def test_get_user_name(mocker):
fake_resp = mocker.Mock()
fake_resp.json.return_value = {"name": "Asha"}
# Patch requests.get as seen from my_code, not where it is defined
mock_get = mocker.patch("my_code.requests.get", return_value=fake_resp)
assert get_user_name(7) == "Asha"
mock_get.assert_called_once_with("https://api.example.com/users/7", timeout=5)
def test_get_env(monkeypatch):
# Built-in fixture, no plugin needed
monkeypatch.setenv("APP_ENV", "prod")
assert get_env() == "prod"Code language: PHP (php)
Note: Patch the name in the namespace where your code looks it up. If my_code.py used from requests import get, the patch target would be my_code.get, not requests.get. For more on making HTTP calls, see How to Send a POST Request with Python.
Parametrize IDs, skip and xfail
You can wrap parametrized cases in pytest.param to give them readable IDs and to attach markers to a single case. Use skipif for tests that cannot run in a given environment. Use xfail for known failures that should not break the build.
import sys
import pytest
from my_code import add
@pytest.mark.parametrize(
("a", "b", "expected"),
[
pytest.param(1, 2, 3, id="positive"),
pytest.param(-1, -1, -2, id="negative"),
pytest.param(0.1, 0.2, 0.3, id="float-exact",
marks=pytest.mark.xfail(reason="float rounding")),
],
)
def test_add(a, b, expected):
assert add(a, b) == expected
@pytest.mark.skipif(sys.platform == "win32", reason="POSIX-only behaviour")
def test_posix_paths():
assert "/".join(["a", "b"]) == "a/b"Code language: JavaScript (javascript)
Run pytest -v -k positive to run only the case with the positive ID. -k matches substrings of test names and IDs, and it accepts and, or and not.
Command-line options worth knowing
| Command | What it does |
|---|---|
pytest -k "add and not float" | Selects tests by name expression |
pytest -m "not slow" | Deselects tests that have the slow marker |
pytest --lf / pytest --ff | Reruns only the last failures, or runs them first |
pytest -x / pytest --maxfail=3 | Stops after the first failure, or after N failures |
pytest -s | Turns off output capture so print() output shows |
pytest --durations=10 | Lists the 10 slowest tests |
pytest --collect-only -q | Lists the tests it collected without running them |
pytest --junitxml=report.xml | Writes a JUnit XML report for CI systems (built in) |
pytest -n auto | Runs tests in parallel, one worker per CPU (needs pytest-xdist) |
pytest --cov=src --cov-report=term-missing | Shows coverage, including line numbers that were not run (needs pytest-cov) |
Pytest's exit codes matter in CI: 0 means all tests passed, 1 means some tests failed, 2 means the run was interrupted, 3 means an internal error, 4 means a command-line usage error, and 5 means no tests were collected.
Running pytest in CI
The example above recommends CI but does not show it. This minimal GitHub Actions workflow runs the suite in parallel, writes a JUnit report and fails the build if coverage drops below 80%:
name: tests
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.12"
- run: pip install pytest pytest-cov pytest-xdist pytest-mock requests
- run: pytest -n auto --cov=src --cov-report=xml --cov-fail-under=80 --junitxml=report.xmlCode language: JavaScript (javascript)
Note: Pin your test dependencies in a requirements-dev.txt file or in the dev extras of pyproject.toml. That way CI and local runs use the same plugin versions.
Common errors and fixes
| Error | Cause | Fix |
|---|---|---|
ModuleNotFoundError: No module named 'src' | The project root is not on sys.path | Set pythonpath = src and import my_code, or install the package with pip install -e . |
error: unrecognized arguments: --html=report.html | pytest-html is not installed | pip install pytest-html |
fixture 'mocker' not found | pytest-mock is not installed | pip install pytest-mock, or use the built-in monkeypatch |
PytestUnknownMarkWarning or 'slow' not found in markers | The marker is not registered | Add it under markers in pytest.ini |
collected 0 items (exit code 5) | File or function names do not match test_*.py, *_test.py and test* | Rename the files and functions, or check testpaths |
import file mismatch | Two test files share a basename in different folders that have no __init__.py | Add __init__.py files, or use --import-mode=importlib |
Corrections to the original guide
from src.my_code import addfails with plainpytestand no configuration. Configurepythonpath = srcand importfrom my_code import add.pytest --html=report.htmlis shown under built-in options, but it only works afterpip install pytest-html.- The mocking example patched a function that does not exist, imported
MagicMockwithout using it, and tested only the mock. A corrected version is shown above. - The
db_connectionfixture had noimport pytestand called an undefinedsetup_database_connection(). A runnable SQLite version is shown above. - Mocking is not built into pytest itself. The built-in option is
monkeypatch, andmockercomes from thepytest-mockplugin. - The
slowmarker should be registered before you usepytest -m slow. Otherwise pytest warns, or errors when--strict-markersis on. - The closing line "Let me know if you'd like detailed examples…" is leftover chat text and is not part of the guide.
Frequently asked questions
What is the difference between pytest and unittest?
unittest is in the standard library and uses classes and methods such as self.assertEqual. Pytest uses plain functions with assert, and adds fixtures, parametrization and plugins. Pytest can also run existing unittest tests without changes.
Where should I put shared fixtures in pytest?
Put them in a conftest.py file. Pytest loads it automatically, and its fixtures are available to every test in that directory and its subdirectories, with no import needed.
How do I run a single test in pytest?
Pass its node ID, for example pytest tests/test_my_code.py::test_add. For a single parametrized case, add the ID in brackets, such as pytest "tests/test_my_code.py::test_add[positive]". You can also select tests by name with -k.
How do I see print output in pytest?
Pytest captures output by default and shows it only for failing tests. Run with -s to turn off capture, or use the capsys fixture to assert on the output instead.
Should I use pytest.ini or pyproject.toml?
Either one works. pyproject.toml with [tool.pytest.ini_options] keeps all project configuration in one file. If a pytest.ini file exists, it takes precedence, even when it is empty.
Related tutorials
- More Python tutorials
- How to Send a POST Request with Python
- Top 50 Python Interview Questions and Answers
- What is Flask and use cases of Flask?
I’m Rajesh Kumar, a DevOps, SRE, DevSecOps, Cloud, and Platform Engineering expert passionate about sharing practical knowledge, real-world experiences, and industry best practices. I have worked at Cotocus and regularly write about technology, travel, investing, health, product reviews, and digital marketing through my various platforms.
I publish technical articles at DevOps School, travel stories at Holiday Landmark, stock market insights at Stocks Mantra, health and fitness guidance at My Medic Plus, product reviews at TrueReviewNow, and SEO and digital marketing strategies at Wizbrand.
Find Trusted Cardiac Hospitals
Compare heart hospitals by city and services โ all in one place.
Explore Hospitals