Python Testing and Debugging · Lesson 129 of 149

Python Testing with pytest

What you will learn

  • Installing and running pytest
  • Tests as plain functions with plain assert
  • pytest.raises and pytest.approx
  • parametrize for many inputs
  • Fixtures and the built-in ones: tmp_path, capsys, monkeypatch
  • Selecting tests and markers

1. Why pytest?

unittest (lesson 18.2) works, but needs classes and many self.assertSomething methods. pytest is a third-party testing tool that keeps tests short:

  • tests are plain functions;
  • you use the ordinary assert statement, and pytest explains failures in detail;
  • fixtures and parametrization remove repetition;
  • it also runs unittest tests.

Install it into the project's virtual environment (lessons 16.5 and 16.6):

python -m pip install pytest

The checks for this lesson used pytest 9.1.1 on Python 3.13.7. Run it with python -m pytest (the python -m form uses the right Python, as with pip).

2. A first test file

pytest finds files named test_*.py (or *_test.py) and, inside them, functions named test_*. Using the shop.py module from lesson 18.2:

import pytest
from shop import add, divide, is_palindrome, Cart


def test_add():
    assert add(2, 3) == 5


def test_divide_by_zero():
    with pytest.raises(ValueError, match="zero"):
        divide(1, 0)


def test_float():
    assert divide(1, 3) == pytest.approx(0.3333, abs=1e-4)
  • A test passes if it finishes without an exception; a failed assert raises AssertionError.
  • pytest.raises(ErrorType) checks that a block raises an error; match="zero" also checks the message with a regular expression (lesson 17.6).
  • pytest.approx(x) compares floats with a tolerance (lesson 3.4).
Quick check: how does a pytest test say "this must be true"?

With a plain assert statement, for example assert add(2, 3) == 5.

3. Running and reading results

python -m pytest

The final lines of a run of the whole file below (14 tests):

collected 14 items

test_shop.py ..........s...                                              [100%]

======================== 13 passed, 1 skipped in 0.08s ========================

A dot is a pass, s a skip, F a failure, E an error. Useful options:

Option Meaning
-v one line per test, with the test name
-q quieter output
-x stop at the first failure
-k "palindrome and not ab" only tests whose name matches the expression
test_shop.py::test_add one particular test
--lf re-run only the tests that failed last time
-s show print output (normally captured)
--pdb open the debugger at a failure (lesson 18.1)

For example -k "palindrome and not ab" ran 3 of the 17 tests collected in one check, and test_shop.py::test_add ran just 1.

Failures explain themselves

This file has three wrong tests:

def total(prices):
    return sum(prices)


def test_total_wrong():
    prices = [1, 2, 3]
    expected = 7
    assert total(prices) == expected


def test_dict():
    assert {"a": 1, "b": 2} == {"a": 1, "b": 3}


def test_str():
    assert "hello world".startswith("world")

pytest rewrites the assert so it can show the values that were compared:

    def test_total_wrong():
        prices = [1, 2, 3]
        expected = 7
>       assert total(prices) == expected
E       assert 6 == 7
E        +  where 6 = total([1, 2, 3])

test_bad.py:7: AssertionError
___________________________ test_dict ___________________________

    def test_dict():
>       assert {"a": 1, "b": 2} == {"a": 1, "b": 3}
E       AssertionError: assert {'a': 1, 'b': 2} == {'a': 1, 'b': 3}
E         Omitting 1 identical items, use -vv to show
E         Differing items:
E         {'b': 2} != {'b': 3}

and ends with a summary:

FAILED test_bad.py::test_total_wrong - assert 6 == 7
FAILED test_bad.py::test_dict - AssertionError: assert {'a': 1, 'b': 2} == {'...
FAILED test_bad.py::test_str - AssertionError: assert False
============================== 3 failed in 0.11s ==============================

(The test source is shown with the failing line marked > and the explanation lines starting with E.) You see total(...) returned 6 and the dictionaries differed in key b, with no special assert methods needed.

4. Many inputs: parametrize

To run one test with several data sets, use the @pytest.mark.parametrize decorator:

@pytest.mark.parametrize("text, expected", [
    ("racecar", True),
    ("ab", False),
    ("Aa", True),
    ("", True),
])
def test_palindrome(text, expected):
    assert is_palindrome(text) == expected

pytest runs the function four times, once per pair, and reports each separately (with -v):

test_shop.py::test_palindrome[racecar-True] PASSED
test_shop.py::test_palindrome[ab-False] PASSED
test_shop.py::test_palindrome[Aa-True] PASSED
test_shop.py::test_palindrome[-True] PASSED

A failing case names its own inputs, which is clearer than a loop inside one test. Adding a new case is one more line in the list.

5. Fixtures

A fixture is a function that prepares something tests need (an object, a file, a database) and hands it to tests that ask for it by name. It replaces setUp:

@pytest.fixture
def cart():
    c = Cart()
    c.add("pen", 1.5, 2)
    return c


def test_total(cart):
    assert cart.total() == 3.0


def test_add_more(cart):
    cart.add("book", 10)
    assert cart.total() == 13.0


def test_bad_qty(cart):
    with pytest.raises(ValueError):
        cart.add("x", 1, 0)

Writing cart as a test's parameter makes pytest call the fixture and pass in the result. Each test gets its own fresh cart, so tests stay independent. A fixture that needs cleanup uses yield:

@pytest.fixture
def connection():
    con = open_connection()
    yield con          # the test runs here
    con.close()        # cleanup after the test

Fixtures can use other fixtures, and a fixture placed in a file named conftest.py is available to every test file in that folder without importing. scope="module" or "session" creates it once for many tests instead of for every test.

Built-in fixtures

pytest provides useful ones:

def test_tmp(tmp_path):
    f = tmp_path / "a.txt"
    f.write_text("hi")
    assert f.read_text() == "hi"


def test_capture(capsys):
    print("hello")
    assert capsys.readouterr().out == "hello\n"


def test_env(monkeypatch):
    monkeypatch.setenv("MODE", "test")
    import os
    assert os.environ["MODE"] == "test"
Fixture Gives you
tmp_path a fresh temporary folder (a Path, lesson 15.4), deleted later
capsys captured print output
monkeypatch safe temporary changes to variables, environment variables, attributes
caplog captured log messages (lesson 17.9)

monkeypatch undoes its changes after each test. It plays the role of unittest.mock.patch (lesson 18.2), which also works in pytest.

6. Markers

Markers tag tests:

@pytest.mark.skip(reason="not ready")
def test_future():
    assert False
Marker Meaning
skip(reason=...) do not run
skipif(condition, reason=...) skip when the condition is true
xfail expected to fail (a known bug)
parametrize(...) several data sets
your own, e.g. slow run only some tests: pytest -m "not slow" (register custom markers in the configuration)

7. Project layout and settings

A common layout:

project/
├── shop.py            (or a package)
├── tests/
│   ├── conftest.py
│   └── test_shop.py
└── pytest.ini         (optional settings)

Keep tests next to the project, separate from the code, and let pytest run from the project folder. Settings (such as test folders or extra options) can go in pytest.ini or pyproject.toml. If tests cannot import shop, run python -m pytest from the project folder, or install the project in editable mode (lesson 19.5).

pytest also runs unittest tests, so you can adopt it gradually:

import unittest

class T(unittest.TestCase):
    def test_x(self):
        self.assertEqual(1, 1)

running python -m pytest test_unit_compat.py printed 1 passed.

8. unittest or pytest?

unittest pytest
installation built in pip install pytest
style classes, self.assertX functions, plain assert
failure messages good excellent
parameterising subTest parametrize
setup setUp / tearDown fixtures
plug-ins few many (coverage, parallel runs...)

Both are fine. The ideas (small independent tests, edge cases, one behaviour per test) are the same. Many projects use either.

Worked example: a pytest file for the shop

The complete file test_shop.py combines everything above:

import pytest
from shop import add, divide, is_palindrome, Cart


def test_add():
    assert add(2, 3) == 5


def test_divide_by_zero():
    with pytest.raises(ValueError, match="zero"):
        divide(1, 0)


def test_float():
    assert divide(1, 3) == pytest.approx(0.3333, abs=1e-4)


@pytest.mark.parametrize("text, expected", [
    ("racecar", True), ("ab", False), ("Aa", True), ("", True)])
def test_palindrome(text, expected):
    assert is_palindrome(text) == expected


@pytest.fixture
def cart():
    c = Cart()
    c.add("pen", 1.5, 2)
    return c


def test_total(cart):
    assert cart.total() == 3.0


def test_add_more(cart):
    cart.add("book", 10)
    assert cart.total() == 13.0


def test_bad_qty(cart):
    with pytest.raises(ValueError):
        cart.add("x", 1, 0)


@pytest.mark.skip(reason="not ready")
def test_future():
    assert False


def test_tmp(tmp_path):
    f = tmp_path / "a.txt"
    f.write_text("hi")
    assert f.read_text() == "hi"


def test_capture(capsys):
    print("hello")
    assert capsys.readouterr().out == "hello\n"


def test_env(monkeypatch):
    monkeypatch.setenv("MODE", "test")
    import os
    assert os.environ["MODE"] == "test"

python -m pytest -q printed:

..........s...                                                           [100%]
13 passed, 1 skipped in 0.04s
Feature Where
plain assert test_add, test_total
exception check with a message test_divide_by_zero
float comparison test_float with approx
four cases, one function test_palindrome
fixture cart, reused by three tests
built-in fixtures tmp_path, capsys, monkeypatch
skip marker test_future

The data is made up. The test counts (13 passed, 1 skipped) are the ones printed in the check run for this lesson.

Common mistakes

  • Forgetting the test_ prefix on files or functions (tests silently not collected).
  • Comparing floats with == instead of approx.
  • Sharing mutable state between tests instead of using fixtures.
  • Using print to check results instead of assert.
  • Writing assert (a, "message") with parentheses (always true; lesson 14.5).
  • Tests that depend on running order.
  • Installing pytest in the wrong Python; use python -m pytest.
  • Name clashes: two test files with the same name in different folders without __init__.py.

Key takeaways

  • pytest runs plain functions named test_* using plain assert, and shows exactly what differed when one fails.
  • pytest.raises checks errors, pytest.approx floats, @pytest.mark.parametrize many inputs.
  • Fixtures prepare what tests need and replace setUp; conftest.py shares them; tmp_path, capsys and monkeypatch are built in.
  • Select tests with -k, a path, -x or --lf; mark with skip, skipif, xfail.
  • pytest runs unittest tests too, so you can switch gradually.

Practice

1. How do you write "add(1, 2) must equal 3" in pytest?

Show answer
def test_add():
    assert add(1, 2) == 3

2. Which tool checks that a function raises KeyError?

Show answer

with pytest.raises(KeyError): ...

3. How does parametrize help compared with a loop inside a test?

Show answer

Each data set runs as a separate test and is reported separately, with its own inputs in the failure message.

4. What does a test do to receive a fixture called cart?

Show answer

It names it as a parameter: def test_total(cart):.

5. Which built-in fixture gives a temporary folder?

Show answer

tmp_path (a pathlib.Path that is cleaned up automatically).

6. How do you run only the tests with palindrome in their names?

Show answer

python -m pytest -k palindrome