Coding

Automated Testing in Python: Getting Started with pytest

Automated testing in Python means writing small programs that call your code and check the results, so a single command tells you whether anything broke. The most common tool for it is pytest: install it with pip install -U pytest, put tests in files named test_*.py, and run pytest.

This guide builds a small tested module from scratch, then covers the three features that matter most in practice: parametrized tests, fixtures and exception checks. It ends with how pytest compares to the standard library's unittest.

Install pytest

Install it inside a virtual environment so it does not touch your system Python. The pytest documentation gives these steps:

python3 -m venv .venv
source .venv/bin/activate
pip install -U pytest
pytest --version

On Windows, activate with .venv\Scripts\activate instead of the source line. The last command prints the installed version, which confirms the install worked.

Write your first automated test in Python

Start with a function worth testing. Save this as pricing.py:

def apply_discount(price, percent):
    """Return price reduced by percent (0 to 100)."""
    if not 0 <= percent <= 100:
        raise ValueError("percent must be between 0 and 100")
    return price * (100 - percent) / 100

Now save a test next to it as test_pricing.py:

from pricing import apply_discount


def test_discount_reduces_price():
    assert apply_discount(100.0, 25) == 75.0

Run pytest in the same folder. A test is just a function whose name starts with test_, and a check is just the assert statement. There is nothing to subclass and no special assertion methods to learn. A passing run ends with a summary line like this (example output; timing and version lines will differ):

test_pricing.py .                                                    [100%]
1 passed in 0.01s

When an assertion fails, pytest shows the values on both sides. The pytest docs use a deliberately wrong check, assert func(3) == 5 where func returns x + 1, and the report looks like this:

>       assert func(3) == 5
E       assert 4 == 5
E        +  where 4 = func(3)

test_sample.py:6: AssertionError
FAILED test_sample.py::test_answer - assert 4 == 5

The where 4 = func(3) line is the useful part: pytest rewrites plain assert statements so it can show the intermediate values without you writing a message.

How pytest finds tests

With no arguments, pytest runs tests in files named test_*.py or *_test.py in the current directory and its subdirectories. Inside those files it collects functions starting with test_. If you want classes, prefix the class name with Test and the method names with test_; the class does not inherit from anything. Each test gets its own instance of the class, so state set in one test does not leak into another through self.

A file that does not match the naming pattern is silently not collected. If pytest reports no tests ran, check the file and function names first.

Run one test or a subset

These selection forms come from the pytest usage documentation:

GoalCommand
One functionpytest tests/test_mod.py::test_func
One classpytest tests/test_mod.py::TestClass
One methodpytest tests/test_mod.py::TestClass::test_method
One parametrized casepytest "tests/test_mod.py::test_func[x1,y2]"
By name expressionpytest -k "MyClass and not method"
By markerpytest -m slow

The docs note that on Windows the -k expression should use double quotes rather than single quotes. Quoting the node ID that contains brackets is a good habit in any shell, because brackets can be treated as glob characters.

Test many inputs with parametrize

Copy-pasting a test for each input gets old quickly. @pytest.mark.parametrize runs one test function once per set of arguments. Extend test_pricing.py:

import pytest

from pricing import apply_discount


@pytest.mark.parametrize(
    "price,percent,expected",
    [(100.0, 25, 75.0), (80.0, 0, 80.0), (80.0, 100, 0.0)],
)
def test_discount_values(price, percent, expected):
    assert apply_discount(price, percent) == expected

pytest reports each row as its own test, so a failure names the exact case. In the pytest documentation's own example, three rows produce test_eval[6*9-42] as the failing ID, with 1 failed, 2 passed in the summary. You can rerun just that row with the node ID form above. Edge values such as 0 and 100 belong in the table; boundaries are where discount code usually breaks.

Check that code raises an error

A function that rejects bad input needs a test for the rejection. Use pytest.raises as a context manager:

def test_discount_rejects_bad_percent():
    with pytest.raises(ValueError):
        apply_discount(100.0, 101)

The test passes only if the block raises ValueError. If nothing is raised, or a different exception type is raised, the test fails. Add a test for -1 as well, since that is the other side of the boundary.

Share setup with fixtures

A fixture is a function marked with @pytest.fixture that provides something a test needs. A test asks for it by listing its name as an argument, and pytest calls the fixture and passes the result in. This is the example from the pytest docs:

import pytest


@pytest.fixture
def first_entry():
    return "a"


@pytest.fixture
def order(first_entry):
    return [first_entry]


def test_string(order):
    order.append("b")
    assert order == ["a", "b"]

Fixtures can depend on other fixtures, as order does here. For setup that needs cleanup, use yield: everything before the yield is setup, and everything after it runs as teardown once the test finishes, even if the test failed. The docs' email example creates a user, yields it to the test, then deletes the user afterwards.

To share a fixture across several test files, put it in a file named conftest.py. Fixtures defined there are available to tests in that directory without any import.

pytest also ships built-in fixtures. The most useful early on is tmp_path: list it as a test argument and pytest creates a unique temporary directory for that test and passes it in as a pathlib.Path. Tests that write files can use it and never touch your real project folder.

pytest vs unittest

unittest ships with Python, so it needs no install. A test case is a subclass of unittest.TestCase, test methods start with test, and checks use methods such as assertEqual() and assertRaises(). The same discount check looks like this:

import unittest

from pricing import apply_discount


class TestPricing(unittest.TestCase):
    def test_discount_reduces_price(self):
        self.assertEqual(apply_discount(100.0, 25), 75.0)

    def test_discount_rejects_bad_percent(self):
        with self.assertRaises(ValueError):
            apply_discount(100.0, 101)

Run it with python -m unittest, which starts discovery in the current directory using the default file pattern test*.py. Add -v to list each test.

pytestunittest
Installpip install pytestIncluded with Python
Test shapePlain functionMethod on a TestCase subclass
ChecksPlain assertassertEqual() and related methods
Run allpytestpython -m unittest
Discovery patterntest_*.py, *_test.pytest*.py

Both are sound choices. pytest takes less code per test and has the fixture and parametrize features above; unittest avoids a dependency. They are not exclusive, because pytest can also run unittest-style test classes, which lets an existing suite move over a file at a time.

What to test, and where it fits

Tests like the ones above check one function with no outside dependencies. That is a unit test. When a test needs a database, a network service or several modules working together, it becomes an integration test, covered in unit test vs integration test. Tests that drive the whole application through its real interface are covered in end-to-end testing explained. Most projects keep many fast unit tests and fewer of the slower kinds.

Keep tests deterministic. A test that depends on the current time, random numbers or a live network call will fail intermittently, and a suite people do not trust gets ignored. Pass those values in as arguments, or replace the outside dependency in the test.

If pytest finds nothing or fails to import

  • collected 0 items or no tests ran. The file is not named test_*.py or *_test.py, or the functions do not start with test_.
  • ModuleNotFoundError for your own module. The test cannot import the code under test. In the simple layout above, run pytest from the folder that holds pricing.py. For larger projects, install your package into the virtual environment so imports resolve the same way everywhere.
  • pytest is not recognised. The virtual environment is not active, or pytest was installed into a different Python. Try python -m pytest, which uses the interpreter you ran it with.

Frequently asked questions

What is the best framework for automated testing in Python?
For most projects it is pytest. It needs only plain functions and the assert statement, and it has fixtures and parametrization built in. The standard library's unittest also works and needs no install, which matters when you cannot add dependencies. pytest can run unittest-style tests too, so you can switch gradually.
How does pytest find my tests?
Running pytest with no arguments looks for files named test_*.py or *_test.py in the current directory and its subdirectories. Inside those files it collects functions whose names start with test_, and methods starting with test_ inside classes whose names start with Test.
How do I run only one test?
Give pytest the node ID: pytest tests/test_pricing.py::test_discount_rejects_bad_percent. You can also select by name with -k, for example pytest -k discount, which runs every test whose name matches the expression.
Do I need classes to write pytest tests?
No. A plain function named test_something is a test. Classes are optional and only useful for grouping related tests. A pytest test class does not subclass anything and its name must start with Test.

Sources