pytest-lazy-fixtures
pytest-lazy-fixtures is a pytest plugin that allows the use of fixtures directly within `pytest.mark.parametrize` arguments. It supports injecting fixtures into various data structures and accessing fixture attributes. The library is actively maintained with regular releases and bug fixes, currently at version 1.4.0.
Warnings
- breaking Be aware of two similarly named packages: `pytest-lazy-fixture` (singular) and `pytest-lazy-fixtures` (plural). The singular version is older and often incompatible with `pytest` versions 8.0.0 and newer. Ensure you are installing and importing from `pytest-lazy-fixtures` to avoid compatibility issues and to use the actively maintained library.
- gotcha Starting with version 1.4.0, `lfc` (lazy_fixture_callable) supports implicit fixture injection. If a callable's parameter name matches a fixture name, the fixture will be resolved and passed automatically, provided no explicit value or default is present for that parameter. This might lead to unexpected fixture resolution if not fully understood.
- gotcha When using fixtures within complex data structures (e.g., dictionaries, lists) passed to `@pytest.mark.parametrize`, or when a fixture itself depends on another fixture that needs to be resolved, always wrap the fixture name with `lf()` to ensure proper resolution. Directly passing string names will not work and the fixture will not be evaluated.
- gotcha Avoid relying on `pytest.lazy_fixture` if placed directly in `conftest.py` or at the top level of a test file, as pytest's plugin loading order might cause `pytest.lazy_fixture` (a global attribute added by the plugin) to not exist during early fixture registration. Always import `lf` (or `lazy_fixture` for explicit aliasing) directly from `pytest_lazyfixtures` in all files where it's used.
Install
-
pip install pytest-lazy-fixtures
Imports
- lf
from pytest_lazyfixtures import lf
- lfc
from pytest_lazyfixtures import lfc
Quickstart
import pytest
from pytest_lazyfixtures import lf
@pytest.fixture()
def my_fixture_value():
return 'Hello from fixture!'
@pytest.mark.parametrize('param_name', [lf('my_fixture_value')])
def test_example(param_name):
assert param_name == 'Hello from fixture!'
# Example with a dictionary and attribute access
class MyObject:
def __init__(self, value):
self.value = value
@pytest.fixture()
def an_object():
return MyObject(42)
@pytest.mark.parametrize('data', [
{'key': lf('my_fixture_value')},
{'number': lf('an_object.value')}
])
def test_complex_data(data):
if 'key' in data:
assert data['key'] == 'Hello from fixture!'
if 'number' in data:
assert data['number'] == 42