pytest-cases
pytest-cases is a Python library that extends pytest to enable the separation of test code from test cases, allowing for more modular and reusable tests. It leverages pytest's parametrization capabilities to define test data and expected results in 'case functions,' which are then injected into test functions. The library is actively maintained, with frequent minor and patch releases to ensure compatibility with new pytest and Python versions, as well as to introduce new features.
Warnings
- breaking Support for Python versions earlier than 3.9 and pytest versions earlier than 6 was dropped in `pytest-cases` v3.9.1. Ensure your environment meets these minimum requirements when upgrading.
- breaking Compatibility fixes were required for `pytest` versions 8.4 and 9.0. Users upgrading `pytest` without also updating `pytest-cases` to at least `3.9.1` (for `pytest 8.4`) or `3.10.0` (for `pytest 9`) may encounter `AttributeError` or `ValueError` related to fixture handling and parametrized cases.
- gotcha When a fixture is only required by *some* of your cases, use `@fixture` from `pytest_cases` instead of `@pytest.fixture`. Using `@pytest.fixture` will cause the fixture to be set up and torn down for *all* cases, even those not requiring it, leading to inefficiencies.
- gotcha `pytest-cases` can affect the order of pytest test execution. While this sometimes resolves `pytest#5054`, it can also lead to unexpected test ordering. If test order is critical and implicitly relied upon, this change might cause subtle issues.
- gotcha With `pytest 8`, the warning `PytestRemovedIn9Warning: Marks applied to fixtures have no effect` might occur. `pytest-cases` version `3.8.5` suppressed this warning. On older `pytest-cases` versions with `pytest 8`, you might observe this warning or find that marks on fixtures are not applied as expected.
Install
-
pip install pytest-cases
Imports
- parametrize_with_cases
from pytest_cases import parametrize_with_cases
- case
from pytest_cases import case
- fixture
from pytest_cases import fixture
- current_cases
from pytest_cases import current_cases
Quickstart
import pytest
from pytest_cases import parametrize_with_cases, case
# test_foo_cases.py
@case
def case_positive_int():
return 10
@case
def case_another_positive_int():
return 20
# test_foo.py
def foo(a):
return a + 5
@parametrize_with_cases("a", cases=".test_foo_cases")
def test_foo_function(a):
"""Tests the foo function with various cases."""
expected_result = a + 5
assert foo(a) == expected_result
# To run these tests:
# 1. Save the case functions in a file named `test_foo_cases.py`.
# 2. Save the test function in a file named `test_foo.py`.
# 3. Run `pytest` in the directory containing these files.
# Expected output will show tests passing for both case_positive_int and case_another_positive_int.