ZetCode

Python pytest

last modified November 18, 2026 Python 3.15

In this article we show how to test Python code with the pytest library. We write tests as plain functions with assert statements, check exceptions and floating-point results, parametrize tests, share setup code with fixtures, group tests with markers, and configure a small project with a pytest.toml file.

Pytest is the most widely used testing framework for Python. Compared to the standard unittest module, it needs no classes and no special assertion methods: a test is a function whose name starts with test, and failures are reported with a detailed breakdown of the compared values. Pytest also runs existing unittest test cases, so a project can switch gradually.

The examples were run with pytest 9.2 on Python 3.15. Pytest is installed from PyPI, preferably into a virtual environment. In a project managed by uv, we add it as a development dependency with uv add --dev pytest instead.

$ pip install pytest

Test discovery

When run without arguments, pytest searches for tests in the directories listed in the testpaths option, if it is configured, or in the current directory and all its subdirectories. Arguments can name directories, files, or individual tests.

In the selected directories, pytest collects files named test_*.py or *_test.py. In these files, it collects functions whose name starts with test, and methods starting with test inside classes whose name starts with Test (the class must not have an __init__ method). The patterns can be changed with the python_files, python_functions, and python_classes options.

Pytest is started with the pytest command or with python -m pytest. The second form also adds the current directory to sys.path, which matters when the tests import modules that are not installed.

Simple example

In the first example we test two simple functions that find the maximum and the minimum of a sequence.

algo.py
def find_max(values):

    if not values:
        raise ValueError('find_max() arg is an empty sequence')

    result = values[0]

    for val in values[1:]:
        if val > result:
            result = val

    return result


def find_min(values):

    if not values:
        raise ValueError('find_min() arg is an empty sequence')

    result = values[0]

    for val in values[1:]:
        if val < result:
            result = val

    return result

The find_max and find_min functions walk the sequence and keep the largest or the smallest value seen so far. For an empty sequence they raise a ValueError, just like the built-in max and min functions.

test_algo.py
from algo import find_max, find_min


def test_find_min():

    values = (2, 3, 1, 4, 6)
    assert find_min(values) == 1


def test_find_max():

    values = (2, 3, 1, 4, 6)
    assert find_max(values) == 6


def test_single_value():

    assert find_min([7]) == 7
    assert find_max([7]) == 7

The test file imports the tested functions and defines three test functions. Each test checks a condition with a plain assert statement; there are no special assertion methods to learn. The module name starts with test_ and so do the functions, so pytest finds them automatically.

$ pytest test_algo.py
============================= test session starts ==============================
platform linux -- Python 3.15.2, pytest-9.2.0, pluggy-1.7.0
rootdir: /home/user/python
collected 3 items

test_algo.py ...                                                         [100%]

============================== 3 passed in 0.02s ===============================

Selecting tests

The -v option prints one line per test with its node ID. A node ID is the file name followed by :: and the test name; we can pass it on the command line to run a single test. The -k option selects tests whose names match an expression; the expression may use and, or, and not. The -q option makes the output shorter.

Other useful options are -x, which stops at the first failure, --lf, which reruns only the tests that failed last time, and --durations=N, which lists the N slowest tests.

$ pytest -v test_algo.py
============================= test session starts ==============================
platform linux -- Python 3.15.2, pytest-9.2.0, pluggy-1.7.0 -- /home/user/python/.venv/bin/python
cachedir: .pytest_cache
rootdir: /home/user/python
collecting ... collected 3 items

test_algo.py::test_find_min PASSED                                       [ 33%]
test_algo.py::test_find_max PASSED                                       [ 66%]
test_algo.py::test_single_value PASSED                                   [100%]

============================== 3 passed in 0.02s ===============================
$ pytest -q test_algo.py::test_find_min
.                                                                        [100%]
1 passed in 0.00s
$ pytest -v -k "max or single" test_algo.py
============================= test session starts ==============================
platform linux -- Python 3.15.2, pytest-9.2.0, pluggy-1.7.0 -- /home/user/python/.venv/bin/python
cachedir: .pytest_cache
rootdir: /home/user/python
collecting ... collected 3 items / 1 deselected / 2 selected

test_algo.py::test_find_max PASSED                                       [ 50%]
test_algo.py::test_single_value PASSED                                   [100%]

======================= 2 passed, 1 deselected in 0.02s ========================

Assertion introspection

Pytest rewrites the assert statements in test modules before they are imported. When an assertion fails, the report shows the values of the subexpressions and, for strings, lists, and dictionaries, a description of the difference.

test_fail.py
def test_list():

    words = ['sky', 'cup', 'forest', 'war']
    assert sorted(words) == ['cup', 'forest', 'sky', 'war', 'water']


def test_dict():

    user = {'name': 'John Doe', 'occupation': 'gardener', 'age': 34}
    assert user == {'name': 'John Doe', 'occupation': 'driver', 'age': 34}


def test_string():

    msg = 'an old falcon'
    assert msg.upper() == 'AN OLD FALCON!'

All three tests fail on purpose. The first one compares two lists of different lengths, the second one two dictionaries that differ in one item, and the third one two strings.

$ pytest test_fail.py
============================= test session starts ==============================
platform linux -- Python 3.15.2, pytest-9.2.0, pluggy-1.7.0
rootdir: /home/user/python
collected 3 items

test_fail.py FFF                                                         [100%]

=================================== FAILURES ===================================
__________________________________ test_list ___________________________________

    def test_list():

        words = ['sky', 'cup', 'forest', 'war']
>       assert sorted(words) == ['cup', 'forest', 'sky', 'war', 'water']
E       AssertionError: assert ['cup', 'fore... 'sky', 'war'] == ['cup', 'fore...war', 'water']
E
E         Right contains one more item: 'water'
E         Use -v to get more diff

test_fail.py:4: AssertionError
__________________________________ test_dict ___________________________________

    def test_dict():

        user = {'name': 'John Doe', 'occupation': 'gardener', 'age': 34}
>       assert user == {'name': 'John Doe', 'occupation': 'driver', 'age': 34}
E       AssertionError: assert {'name': 'Joh...r', 'age': 34} == {'name': 'Joh...r', 'age': 34}
E
E         Omitting 2 identical items, use -vv to show
E         Differing items:
E         {'occupation': 'gardener'} != {'occupation': 'driver'}
E         Use -v to get more diff

test_fail.py:10: AssertionError
_________________________________ test_string __________________________________

    def test_string():

        msg = 'an old falcon'
>       assert msg.upper() == 'AN OLD FALCON!'
E       AssertionError: assert 'AN OLD FALCON' == 'AN OLD FALCON!'
E
E         - AN OLD FALCON!
E         ?              -
E         + AN OLD FALCON

test_fail.py:16: AssertionError
=========================== short test summary info ============================
FAILED test_fail.py::test_list - AssertionError: assert ['cup', 'fore... 'sky...
FAILED test_fail.py::test_dict - AssertionError: assert {'name': 'Joh...r', '...
FAILED test_fail.py::test_string - AssertionError: assert 'AN OLD FALCON' == ...
============================== 3 failed in 0.03s ===============================

Testing exceptions

The pytest.raises context manager checks that a block of code raises a given exception. The test fails if no exception or an exception of a different type is raised.

test_exceptions.py
import pytest

from algo import find_max


def test_empty():

    with pytest.raises(ValueError, match='empty sequence'):
        find_max([])


def test_division():

    with pytest.raises(ZeroDivisionError) as excinfo:
        1 / 0

    assert str(excinfo.value) == 'division by zero'


def validate(users):

    errors = []

    for user in users:
        if not user.get('name'):
            errors.append(ValueError(f'missing name: {user}'))
        if user.get('age', 0) < 0:
            errors.append(ValueError(f'negative age: {user}'))

    if errors:
        raise ExceptionGroup('invalid users', errors)


def test_group():

    users = [{'name': '', 'age': 23}, {'name': 'Jane', 'age': -1}]

    with pytest.RaisesGroup(ValueError, ValueError, match='invalid users'):
        validate(users)

The match parameter is a regular expression that is searched for in the string representation of the exception. With the as clause we get an ExceptionInfo object; its value attribute holds the raised exception, so we can inspect it after the block.

The validate function collects all problems and raises them together in an ExceptionGroup. Since pytest 8.4, the pytest.RaisesGroup context manager checks the contents of an exception group; here we require exactly two ValueError exceptions and a group message matching invalid users.

$ pytest test_exceptions.py
============================= test session starts ==============================
platform linux -- Python 3.15.2, pytest-9.2.0, pluggy-1.7.0
rootdir: /home/user/python
collected 3 items

test_exceptions.py ...                                                   [100%]

============================== 3 passed in 0.02s ===============================

Comparing floating-point numbers

Floating-point arithmetic is not exact, so results should be compared with a tolerance. The pytest.approx function wraps the expected value and makes the comparison approximate.

test_approx.py
import math
import pytest


def test_sum():

    assert 0.1 + 0.2 == pytest.approx(0.3)


def test_sequence():

    vals = [0.1 * 3, 2 / 3, math.sqrt(2)]
    assert vals == pytest.approx([0.3, 0.6667, 1.4142], rel=1e-4)


def test_float_equality():

    assert 0.1 + 0.2 == 0.3

By default, approx accepts a relative difference of 1e-6. It also works with sequences and dictionaries of numbers; in the second test we compare a whole list and loosen the tolerance with the rel parameter. The third test uses a plain equality check and fails, because 0.1 + 0.2 is 0.30000000000000004.

$ pytest test_approx.py
============================= test session starts ==============================
platform linux -- Python 3.15.2, pytest-9.2.0, pluggy-1.7.0
rootdir: /home/user/python
collected 3 items

test_approx.py ..F                                                       [100%]

=================================== FAILURES ===================================
_____________________________ test_float_equality ______________________________

    def test_float_equality():

>       assert 0.1 + 0.2 == 0.3
E       assert (0.1 + 0.2) == 0.3

test_approx.py:18: AssertionError
=========================== short test summary info ============================
FAILED test_approx.py::test_float_equality - assert (0.1 + 0.2) == 0.3
========================= 1 failed, 2 passed in 0.03s ==========================

Parametrized tests

The @pytest.mark.parametrize decorator runs a test function several times with different arguments. Each set of arguments becomes a separate test with its own ID.

test_params.py
import pytest

from algo import find_max, find_min


@pytest.mark.parametrize('data, expected', [
    ((2, 3, 1, 4, 6), 1),
    ((5, -2, 0, 9, 12), -2),
    ((200, 100, 0, 300, 400), 0),
])
def test_find_min(data, expected):

    assert find_min(data) == expected


@pytest.mark.parametrize('data, expected', [
    pytest.param((2, 3, 1, 4, 6), 6, id='small'),
    pytest.param((5, -2, 0, 9, 12), 12, id='negative'),
    pytest.param(('a', 'B', 'c'), 'c', id='strings'),
    pytest.param((3, 'a'), 3, id='mixed', marks=pytest.mark.xfail(raises=TypeError)),
])
def test_find_max(data, expected):

    assert find_max(data) == expected


@pytest.mark.parametrize('base', [2, 10])
@pytest.mark.parametrize('exp', [0, 1, 2])
def test_power(base, exp):

    assert base ** exp == pow(base, exp)

The first argument of parametrize names the parameters; the second is a list of values. In test_find_min, pytest generates the test IDs from the values. In test_find_max, we wrap the values in pytest.param to give each case a readable ID. A pytest.param can also carry marks: the mixed case is expected to fail with a TypeError, because an integer cannot be compared with a string.

Stacked parametrize decorators produce all combinations of their values, so test_power runs six times. The decorator closest to the function comes first in the generated ID.

$ pytest -v test_params.py
============================= test session starts ==============================
platform linux -- Python 3.15.2, pytest-9.2.0, pluggy-1.7.0 -- /home/user/python/.venv/bin/python
cachedir: .pytest_cache
rootdir: /home/user/python
collecting ... collected 13 items

test_params.py::test_find_min[data0-1] PASSED                            [  7%]
test_params.py::test_find_min[data1--2] PASSED                           [ 15%]
test_params.py::test_find_min[data2-0] PASSED                            [ 23%]
test_params.py::test_find_max[small] PASSED                              [ 30%]
test_params.py::test_find_max[negative] PASSED                           [ 38%]
test_params.py::test_find_max[strings] PASSED                            [ 46%]
test_params.py::test_find_max[mixed] XFAIL                               [ 53%]
test_params.py::test_power[0-2] PASSED                                   [ 61%]
test_params.py::test_power[0-10] PASSED                                  [ 69%]
test_params.py::test_power[1-2] PASSED                                   [ 76%]
test_params.py::test_power[1-10] PASSED                                  [ 84%]
test_params.py::test_power[2-2] PASSED                                   [ 92%]
test_params.py::test_power[2-10] PASSED                                  [100%]

======================== 12 passed, 1 xfailed in 0.03s =========================

Fixtures

A fixture provides a test with the data or resources it needs. It is a function decorated with @pytest.fixture; a test requests it by naming it as a parameter. Fixtures can request other fixtures.

test_fixtures.py
import sqlite3
import pytest


@pytest.fixture
def users():

    return [('John Doe', 'gardener'), ('Roger Roe', 'driver'),
            ('Lucy Smith', 'teacher')]


@pytest.fixture
def con(users):

    con = sqlite3.connect(':memory:')
    con.execute('CREATE TABLE users(name TEXT, occupation TEXT)')
    con.executemany('INSERT INTO users VALUES(?, ?)', users)

    yield con

    con.close()


def test_count(con, users):

    n, = con.execute('SELECT COUNT(*) FROM users').fetchone()
    assert n == len(users)


def test_delete(con):

    con.execute("DELETE FROM users WHERE occupation = 'driver'")
    names = [row[0] for row in con.execute('SELECT name FROM users')]

    assert names == ['John Doe', 'Lucy Smith']

The users fixture returns a list of tuples. The con fixture requests users, creates an in-memory SQLite database, and fills a table with the users. The code before yield is the setup and the code after it is the teardown, which runs after the test even if the test fails.

By default, a fixture has function scope: it is created anew for every test that requests it. Therefore, the row deleted in test_delete does not affect any other test. The --setup-show option prints when each fixture is set up and torn down.

$ pytest --setup-show test_fixtures.py
============================= test session starts ==============================
platform linux -- Python 3.15.2, pytest-9.2.0, pluggy-1.7.0
rootdir: /home/user/python
collected 2 items

test_fixtures.py
        SETUP    F users
        SETUP    F con (fixtures used: users)
        test_fixtures.py::test_count (fixtures used: con, users) .
        TEARDOWN F con
        TEARDOWN F users
        SETUP    F users
        SETUP    F con (fixtures used: users)
        test_fixtures.py::test_delete (fixtures used: con, users) .
        TEARDOWN F con
        TEARDOWN F users

============================== 2 passed in 0.02s ===============================

Fixture scope

Creating some resources is expensive. With the scope parameter, a fixture can live for a whole class, module, package, or session.

test_scope.py
import pytest


@pytest.fixture(scope='module')
def resource():

    print('\nopening resource')
    yield {'name': 'shared'}
    print('\nclosing resource')


def test_first(resource):

    assert resource['name'] == 'shared'


def test_second(resource):

    resource['used'] = True
    assert 'used' in resource

The resource fixture has module scope, so both tests get the same dictionary, and the setup and the teardown run only once. The flip side is that tests sharing a fixture can affect each other: the key added in test_second stays in the dictionary. We run pytest with -s, which turns off output capturing, to see the messages.

$ pytest -s -v test_scope.py
============================= test session starts ==============================
platform linux -- Python 3.15.2, pytest-9.2.0, pluggy-1.7.0 -- /home/user/python/.venv/bin/python
cachedir: .pytest_cache
rootdir: /home/user/python
collecting ... collected 2 items

test_scope.py::test_first
opening resource
PASSED
test_scope.py::test_second PASSED
closing resource


============================== 2 passed in 0.01s ===============================

Built-in fixtures

Pytest comes with a number of ready-made fixtures. The tmp_path fixture is a unique temporary directory as a pathlib.Path. The capsys fixture captures the standard output and error, and the monkeypatch fixture temporarily changes environment variables, attributes, or dictionary items. The pytest --fixtures command lists all available fixtures.

test_builtin.py
import os


def save_words(path, words):

    path.write_text('\n'.join(words) + '\n')


def greet():

    name = os.environ.get('USER_NAME', 'stranger')
    print(f'Hello {name}!')


def test_save(tmp_path):

    path = tmp_path / 'words.txt'
    save_words(path, ['sky', 'cup', 'forest'])

    assert path.read_text().splitlines() == ['sky', 'cup', 'forest']


def test_greet(capsys):

    greet()
    captured = capsys.readouterr()

    assert captured.out == 'Hello stranger!\n'


def test_greet_env(capsys, monkeypatch):

    monkeypatch.setenv('USER_NAME', 'Lucy')
    greet()

    assert capsys.readouterr().out == 'Hello Lucy!\n'

The test_save test writes a file into the temporary directory and reads it back. The test_greet test captures what greet prints with readouterr. In test_greet_env, monkeypatch.setenv sets the USER_NAME variable; the original environment is restored when the test finishes.

$ pytest -v test_builtin.py
============================= test session starts ==============================
platform linux -- Python 3.15.2, pytest-9.2.0, pluggy-1.7.0 -- /home/user/python/.venv/bin/python
cachedir: .pytest_cache
rootdir: /home/user/python
collecting ... collected 3 items

test_builtin.py::test_save PASSED                                        [ 33%]
test_builtin.py::test_greet PASSED                                       [ 66%]
test_builtin.py::test_greet_env PASSED                                   [100%]

============================== 3 passed in 0.02s ===============================

Skipping tests and expected failures

Markers attach metadata to tests. The built-in skip, skipif, and xfail markers control whether a test runs and how its result is counted.

test_markers.py
import sys
import pytest

from algo import find_min


@pytest.mark.skip(reason='not implemented yet')
def test_find_median():

    assert False


@pytest.mark.skipif(sys.platform == 'win32', reason='POSIX paths only')
def test_posix_path():

    assert '/'.join(['usr', 'bin']) == 'usr/bin'


@pytest.mark.xfail(reason='find_min() cannot compare None')
def test_none():

    assert find_min([3, None, 1]) == 1


def test_import():

    yaml = pytest.importorskip('yaml')
    assert yaml.safe_load('a: 1') == {'a': 1}

The skip marker skips a test unconditionally, while skipif skips it only if the condition is true. The xfail marker says that the test is expected to fail; a failure is reported as x and does not break the test run. The pytest.importorskip function imports a module or skips the test if the module is not installed (PyYAML is not installed in our environment).

The -r option adds a short summary of the selected outcomes; s stands for skipped and x for expected failures. In the progress line, a dot means a passed test.

$ pytest -rsx test_markers.py
============================= test session starts ==============================
platform linux -- Python 3.15.2, pytest-9.2.0, pluggy-1.7.0
rootdir: /home/user/python
collected 4 items

test_markers.py s.xs                                                     [100%]

=========================== short test summary info ============================
SKIPPED [1] test_markers.py:7: not implemented yet
SKIPPED [1] test_markers.py:27: could not import 'yaml': No module named 'yaml'
XFAIL test_markers.py::test_none - find_min() cannot compare None
=================== 1 passed, 2 skipped, 1 xfailed in 0.03s ====================

Subtests

A test that checks many values in a loop stops at the first failing assertion. Since pytest 9.0, the built-in subtests fixture reports each iteration as a separate subtest, and the loop continues after a failure.

test_subtests.py
def is_palindrome(word):

    return word == word[::-1]


def test_palindromes(subtests):

    words = ['kayak', 'civic', 'forest', 'level', 'Radar']

    for word in words:
        with subtests.test(word=word):
            assert is_palindrome(word)

Each subtests.test block is a subtest; its keyword arguments are shown in the report. Two words fail the check: forest is not a palindrome and Radar starts with a capital letter. The other words are checked even though the third one fails. The --tb=short option shortens the tracebacks. In the final count, the test itself is reported as failed in addition to its two failed subtests.

Unlike parametrized tests, subtests are created at run time, so the values do not have to be known when the tests are collected.

$ pytest -v --tb=short test_subtests.py
============================= test session starts ==============================
platform linux -- Python 3.15.2, pytest-9.2.0, pluggy-1.7.0 -- /home/user/python/.venv/bin/python
cachedir: .pytest_cache
rootdir: /home/user/python
collecting ... collected 1 item

test_subtests.py::test_palindromes SUBPASSED(word='kayak')               [100%]
test_subtests.py::test_palindromes SUBPASSED(word='civic')               [100%]
test_subtests.py::test_palindromes SUBFAILED(word='forest')              [100%]
test_subtests.py::test_palindromes SUBPASSED(word='level')               [100%]
test_subtests.py::test_palindromes SUBFAILED(word='Radar')               [100%]
test_subtests.py::test_palindromes FAILED                                [100%]

=================================== FAILURES ===================================
_______________________ test_palindromes (word='forest') _______________________
test_subtests.py:12: in test_palindromes
    assert is_palindrome(word)
E   AssertionError: assert False
E    +  where False = is_palindrome('forest')
_______________________ test_palindromes (word='Radar') ________________________
test_subtests.py:12: in test_palindromes
    assert is_palindrome(word)
E   AssertionError: assert False
E    +  where False = is_palindrome('Radar')
_______________________________ test_palindromes _______________________________
contains 2 failed subtests
=========================== short test summary info ============================
SUBFAILED(word='forest') test_subtests.py::test_palindromes - AssertionError:...
SUBFAILED(word='Radar') test_subtests.py::test_palindromes - AssertionError: ...
FAILED test_subtests.py::test_palindromes - contains 2 failed subtests
===================== 3 failed, 3 subtests passed in 0.03s =====================

Project layout

In a real project, the code lives in a package and the tests in a separate directory. The following project uses the src layout: the shop package is in the src directory and the tests are in tests.

$ tree shop
shop
├── pytest.toml
├── src
│   └── shop
│       ├── __init__.py
│       └── cart.py
└── tests
    ├── conftest.py
    └── test_cart.py

3 directories, 5 files

Configuration

Pytest reads its configuration from pytest.toml, pytest.ini, pyproject.toml, tox.ini, or setup.cfg. The pytest.toml file and the native [tool.pytest] table in pyproject.toml are new in pytest 9.0; unlike the older [tool.pytest.ini_options] table, they use real TOML lists and booleans. The directory with the configuration file becomes the root directory of the test run.

pytest.toml
[pytest]
minversion = "9.0"
testpaths = ["tests"]
pythonpath = ["src"]
addopts = ["-ra"]
strict = true
markers = [
    "slow: tests that take a long time",
]

The testpaths option tells pytest where to look for tests when no arguments are given. The pythonpath option adds src to sys.path, so the tests can import the package without installing it. The addopts option adds command-line options to every run; -ra prints a summary of all outcomes except passes.

The strict option, added in pytest 9.0, turns on all strictness checks. Among other things, a marker that is not registered in markers is an error, which catches typos such as @pytest.mark.slwo. The minversion option makes older pytest versions refuse to run the tests.

cart.py
from decimal import Decimal


class Cart:

    def __init__(self):
        self.items = {}

    def add(self, name, price, qty=1):

        if qty < 1:
            raise ValueError(f'invalid quantity: {qty}')

        _, old_qty = self.items.get(name, (price, 0))
        self.items[name] = (price, old_qty + qty)

    def total(self):

        return sum((price * qty for price, qty in self.items.values()),
                   Decimal('0'))

The Cart class stores items with their price and quantity and computes the total price. Prices are Decimal values so that the sums are exact.

conftest.py
from decimal import Decimal

import pytest

from shop.cart import Cart


@pytest.fixture
def cart():

    cart = Cart()
    cart.add('pen', Decimal('1.20'), 3)
    cart.add('book', Decimal('12.50'))

    return cart

Fixtures defined in a conftest.py file are available to all tests in its directory and subdirectories without importing. Pytest loads the file automatically.

test_cart.py
import time
from decimal import Decimal

import pytest


def test_total(cart):

    assert cart.total() == Decimal('16.10')


def test_add_existing(cart):

    cart.add('pen', Decimal('1.20'), 2)
    assert cart.items['pen'] == (Decimal('1.20'), 5)


@pytest.mark.parametrize('qty', [0, -1])
def test_invalid_qty(cart, qty):

    with pytest.raises(ValueError, match='invalid quantity'):
        cart.add('lamp', Decimal('20'), qty)


@pytest.mark.slow
def test_many_items(cart):

    for i in range(1000):
        cart.add(f'item{i}', Decimal('0.01'))
        time.sleep(0.001)

    assert cart.total() == Decimal('26.10')

The tests use the cart fixture from conftest.py. The test_invalid_qty test combines a fixture with a parameter, and the last test is marked with the custom slow marker, which is registered in the configuration.

$ cd shop
$ pytest
============================= test session starts ==============================
platform linux -- Python 3.15.2, pytest-9.2.0, pluggy-1.7.0
rootdir: /home/user/python/shop
configfile: pytest.toml
testpaths: tests
collected 5 items

tests/test_cart.py .....                                                 [100%]

============================== 5 passed in 1.12s ===============================

Running marked tests

The -m option selects tests by markers. It accepts the same and, or, and not operators as -k. We skip the slow test during development and run the full suite before a release.

$ pytest -m "not slow"
============================= test session starts ==============================
platform linux -- Python 3.15.2, pytest-9.2.0, pluggy-1.7.0
rootdir: /home/user/python/shop
configfile: pytest.toml
testpaths: tests
collected 5 items / 1 deselected / 4 selected

tests/test_cart.py ....                                                  [100%]

======================= 4 passed, 1 deselected in 0.02s ========================
$ pytest -q -m slow
.                                                                        [100%]
1 passed, 4 deselected in 1.10s

Source

pytest documentation

How to use fixtures

In this article we have tested Python code with pytest. We have written tests with plain assertions, checked exceptions and floating-point results, used parametrized tests, fixtures, markers, and subtests, and configured a project with pytest.toml. See also the unittest, assert, and Playwright tutorials.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.