pytest-cases

3.10.1 · active · verified Sun Apr 12

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

Install

Imports

Quickstart

This quickstart demonstrates how to define test cases in a separate file using the `@case` decorator and then use `parametrize_with_cases` to inject these cases into a test function. The `cases` argument points to the module containing the case functions. When `pytest` is run, it will automatically discover and execute `test_foo_function` twice, once for each defined case, allowing for clear separation of test logic and test data.

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.

view raw JSON →