Intermediate   Chapter 172 · 35 min read · Module 13: Python Testing and Debugging

pytest Fundamentals

Learning objectives
  • After this chapter you can write pytest tests as plain functions with assert.
  • You can run pytest and read its pass and fail report.
  • You can use fixtures to share setup between tests.
  • You can run one test with many inputs using parametrize.
  • You can test exceptions with pytest.raises and floats with pytest.approx.

pytest is the most popular third-party testing tool for Python. Its main idea is simple: a test is just a function whose name starts with test_, and it uses the ordinary assert statement. There is no class to write and no special assert methods to learn.

When an assert fails, pytest looks inside the expression and shows you the values involved, so the report often tells you the problem without any extra work.

You install it once with pip install pytest. Because installing packages is not possible in every environment, some examples in this chapter are shown as text, and the runnable examples copy the key ideas using only plain Python.

Your first pytest test

Create a file named test_math_tools.py. Write a function that starts with test_ and use assert inside it. Then type pytest in the terminal in the same folder. pytest finds every file named test_*.py or *_test.py, runs every function named test_*, and prints a summary.

A pytest file and its report (not run here)
# test_math_tools.py
def add(a, b):
    return a + b

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

def test_add_negative():
    assert add(-1, -1) == -2

def test_add_wrong():
    assert add(1, 1) == 3
test_math_tools.py ..F def test_add_wrong(): > assert add(1, 1) == 3 E assert 2 == 3 E + where 2 = add(1, 1) 1 failed, 2 passed in 0.01s

Look at the failure report. pytest shows the line of code, marks the failed assert with >, and prints the real values. With plain assert in a normal Python program you would only see AssertionError.

Test discovery: the way pytest automatically finds test files and test functions by their names, so you do not have to list them.

How discovery works

You can see the idea behind discovery with a few lines of plain Python. The function below looks through a dictionary of names, picks those starting with test_, and runs them. pytest does a much more careful version of the same job across many files.

Example 1: discovery by name
def run_all(ns):
    for name in sorted(ns):
        if name.startswith('test_') and callable(ns[name]):
            try:
                ns[name]()
                print(name, 'passed')
            except AssertionError:
                print(name, 'FAILED')

def add(a, b):
    return a + b

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

def test_add_wrong():
    assert add(1, 1) == 3

def helper():
    return 42

run_all(globals())
test_add_positive passed test_add_wrong FAILED

Notice that helper was not run, because its name does not start with test_. Also, test_add_wrong failed but did not stop the other test.

Testing exceptions and floats

In pytest you test an exception with with pytest.raises(ValueError):. The test passes if the block raises that error. You can also check the message with match='text'. For floating point numbers use pytest.approx, as in assert 0.1 + 0.2 == pytest.approx(0.3), which allows a tiny difference.

pytest.raises and approx (needs pytest)
import pytest

def test_zero_division():
    with pytest.raises(ZeroDivisionError):
        1 / 0

def test_float():
    assert 0.1 + 0.2 == pytest.approx(0.3)
test_calc.py .. 2 passed in 0.01s

The same two ideas can be written in plain Python. The next example shows what raises and approx do behind the scenes: catch the expected error, and compare numbers with a tolerance.

Example 2: what raises and approx do
import math

def raises(exc, func, *args):
    try:
        func(*args)
    except exc:
        return True
    return False

print(raises(ZeroDivisionError, lambda a, b: a / b, 1, 0))
print(raises(ValueError, int, '12'))
print(0.1 + 0.2 == 0.3)
print(math.isclose(0.1 + 0.2, 0.3))
True False False True

Fixtures: shared setup

A fixture is a function marked with @pytest.fixture that prepares something a test needs, such as a list, a file or a database connection. A test asks for a fixture simply by naming it as a parameter. pytest runs the fixture and passes the result in. Each test gets its own fresh copy by default, so tests stay independent.

A fixture (needs pytest)
import pytest

@pytest.fixture
def numbers():
    return [1, 2, 3]

def test_sum(numbers):
    assert sum(numbers) == 6

def test_append(numbers):
    numbers.append(4)
    assert len(numbers) == 4
test_fix.py .. 2 passed in 0.01s

Fixtures can also clean up. If the fixture uses yield value instead of return value, the code after the yield runs after the test finishes, which is a good place to close files or connections. Built-in fixtures such as tmp_path (a fresh temporary folder) and capsys (captures printed text) are ready to use.

The next runnable example imitates the idea of a fixture in plain Python: a function builds fresh data and each test function receives it as an argument, so changes made in one test never leak into the next.

Example 3: fresh data for every test
def make_numbers():
    return [1, 2, 3]

def test_sum(numbers):
    assert sum(numbers) == 6

def test_append(numbers):
    numbers.append(4)
    assert len(numbers) == 4

for test in (test_sum, test_append, test_sum):
    test(make_numbers())
    print(test.__name__, 'ok')
test_sum ok test_append ok test_sum ok

Parametrized tests

When the same check must run for many inputs, use @pytest.mark.parametrize. You give the names of the arguments and a list of value sets. pytest runs the test once for each set and reports each one separately.

parametrize (needs pytest)
import pytest

@pytest.mark.parametrize('n, expected', [(2, True), (3, False), (0, True)])
def test_is_even(n, expected):
    assert (n % 2 == 0) == expected
test_even.py ... 3 passed in 0.01s
Example 4: the same idea with a loop
def is_even(n):
    return n % 2 == 0

cases = [(2, True), (3, False), (0, True), (7, True)]
for n, expected in cases:
    status = 'pass' if is_even(n) == expected else 'FAIL'
    print(n, expected, status)
2 True pass 3 False pass 0 True pass 7 True FAIL

Useful command line options

  • pytest -v shows one line per test with its name.
  • pytest -x stops after the first failure.
  • pytest -k even runs only tests whose name contains the word even.
  • pytest test_file.py::test_name runs one single test.
  • pytest -q gives a short, quiet report.

pytest can also run tests written with unittest, so you can move to it slowly in an existing project. Many teams keep fixtures that many files need in a special file called conftest.py. pytest loads that file automatically, and every test in the folder can use the fixtures defined there without importing them.

Python syntax

Syntax
def test_name():
    assert actual == expected
Syntax
import pytest
with pytest.raises(ValueError):
    function(bad)
Syntax
@pytest.fixture
def data():
    return [1, 2, 3]
Syntax
@pytest.mark.parametrize('a, b', [(1, 1), (2, 2)])
def test_equal(a, b):
    assert a == b

Real-world applications

  • Testing web APIs and data pipelines in professional projects.
  • Running thousands of tests quickly in continuous integration.
  • Testing with temporary files and folders using tmp_path.
  • Checking many inputs with parametrize without repeating code.

Common mistakes

Mistake: Naming a test file or function without the test prefix, so pytest skips it.
Fix: Use test_*.py files and test_* functions.
Mistake: Forgetting to install pytest and getting ModuleNotFoundError.
Fix: Run pip install pytest in your active environment.
Mistake: Putting the code that should raise outside the pytest.raises block.
Fix: Call the function inside the with block.
Mistake: Comparing floats directly with ==.
Fix: Use pytest.approx.
Mistake: Changing shared module-level data inside tests.
Fix: Create data in a fixture so each test gets its own copy.

Important tips

  • Use short, descriptive test names.
  • Run pytest -x -q while fixing a bug.
  • Keep shared fixtures in conftest.py.
  • Use parametrize instead of copy-pasting similar tests.

Key points summary

  • Tests are plain functions named test_*.
  • Use the normal assert statement.
  • pytest.raises tests exceptions; pytest.approx tests floats.
  • Fixtures provide setup by naming them as parameters.
  • parametrize runs one test with many inputs.

Exam and interview points

  • pytest discovers test_*.py files and test_* functions.
  • Plain assert is used and pytest rewrites it to show values.
  • pytest.raises is a context manager.
  • Fixtures are requested by parameter name.
  • parametrize takes argument names and a list of value tuples.

Quick revision

  • File test_*.py, function test_*.
  • assert actual == expected.
  • pytest.raises(Error), pytest.approx(x).
  • @pytest.fixture gives data to tests.
  • @pytest.mark.parametrize runs many cases.

Frequently asked questions

Do I need classes in pytest?

No. Plain functions work. You can group tests in a class whose name starts with Test if you like, but you do not have to.

How is pytest different from unittest?

pytest needs less code, uses plain assert with detailed reports, and has fixtures and parametrize. unittest is built in and class based.

Where do I install pytest?

Use pip install pytest, preferably in a virtual environment for the project.

What does a dot or F in the pytest output mean?

A dot is a passed test and F is a failed test. E means an error in setup or an unexpected exception.

What is conftest.py?

A special file where you put fixtures shared by many test files. pytest finds it automatically.

Practise this chapter

17 practice questions Take the chapter quiz

Related chapters