Lazy fixtures let you use test data only when you really need it. This saves time and keeps tests simple.
0
0
Lazy fixtures in PyTest
Introduction
When you want to delay creating test data until a test actually uses it.
When some tests need a fixture but others don't, so you avoid unnecessary setup.
When you want to share fixtures across tests without running them every time.
When you want to improve test speed by not running unused fixtures.
When you want clearer test code by only loading what's needed.
Syntax
PyTest
import pytest from pytest_lazyfixture import lazy_fixture @pytest.mark.parametrize('data', [lazy_fixture('my_fixture')]) def test_example(data): assert data == 'hello'
Use lazy_fixture inside pytest.mark.parametrize to delay fixture use.
Install pytest-lazy-fixture plugin to use this feature.
Examples
This example shows a fixture used lazily in a parameterized test.
PyTest
import pytest from pytest_lazyfixture import lazy_fixture @pytest.fixture def my_fixture(): return 'hello' @pytest.mark.parametrize('value', [lazy_fixture('my_fixture')]) def test_value(value): assert value == 'hello'
Here, the fixture
number is used lazily to supply test data.PyTest
import pytest from pytest_lazyfixture import lazy_fixture @pytest.fixture def number(): return 42 @pytest.mark.parametrize('num', [lazy_fixture('number')]) def test_number(num): assert num == 42
Sample Program
This test script shows how the greeting fixture runs only when used lazily in test_greeting. The test_simple test does not use the fixture.
PyTest
import pytest from pytest_lazyfixture import lazy_fixture @pytest.fixture def greeting(): print('Setup greeting') return 'hello' @pytest.mark.parametrize('msg', [lazy_fixture('greeting')]) def test_greeting(msg): assert msg == 'hello' @pytest.mark.parametrize('msg', ['hi']) def test_simple(msg): assert msg == 'hi'
OutputSuccess
Important Notes
Lazy fixtures require the pytest-lazy-fixture plugin to work.
Use lazy fixtures to avoid running expensive setup code when not needed.
Lazy fixtures work well with parameterized tests to keep tests fast and clean.
Summary
Lazy fixtures delay fixture setup until the test actually needs it.
They help make tests faster and simpler by avoiding unnecessary setup.
Use the lazy_fixture function inside pytest.mark.parametrize to apply lazy fixtures.