pytest-subtests
pytest-subtests is a pytest plugin that provides support for the `unittest.TestCase.subTest()` context manager, allowing developers to write test functions that run multiple distinct checks while reporting individual failures. It introduces a `subtests` fixture for this purpose. The current version is 0.15.0, and it follows the pytest ecosystem's release cadence, often updating to ensure compatibility with new pytest versions.
Warnings
- breaking Compatibility with pytest core versions can be an issue. For example, version 0.13.0 was released specifically to fix compatibility with pytest 8.1. Using an older `pytest-subtests` with a newer `pytest` (or vice-versa) might lead to unexpected errors or test failures.
- gotcha Understanding subtest failure reporting: When a `subtests.test()` block fails, the *parent test function continues to execute subsequent subtests*. The main test function only fails *after* all subtests have run and at least one has failed. This differs from standard `pytest` assertions which immediately stop the current test function on failure.
- gotcha Confusing `pytest-subtests` with `unittest.TestCase.subTest()`: `pytest-subtests` provides the `subtests` fixture primarily for *plain pytest functions* (not inherited from `unittest.TestCase`). If you are writing tests using `unittest.TestCase` inheritance, you should use `self.subTest()` directly, as `pytest-subtests` won't automatically provide that exact behavior to `TestCase` methods.
Install
-
pip install pytest-subtests
Imports
- subtests
def test_example(subtests): ...
- SubTests
from pytest_subtests import SubTests
Quickstart
import pytest
def test_multiple_checks(subtests):
values = [1, 2, 3]
for i, value in enumerate(values):
with subtests.test(f"Check value {value}", index=i):
# This subtest will fail for value=2
assert value % 2 != 0
# To run this test, save it as a .py file (e.g., test_example.py)
# and execute pytest from your terminal:
# pytest test_example.py