Tests can use one or more fixture.
Fixtures themselves can also use one or more fixtures.
I’ll rewrite the example from Using multiple pytest fixtures, but instead of having the tests include all foo, bar, and baz fixtures, I’ll chain them together.
And one more wrinkle, ’test_two’ will only include ‘bar’.
@pytest.fixture(scope="module")
def foo():
print('\nfoo setup - module fixture')
yield
print('foo teardown - module fixture')
@pytest.fixture()
def bar(foo):
print('bar setup - function fixture')
yield
print('bar teardown - function fixture')
@pytest.fixture()
def baz(bar):
print('baz setup - function fixture')
yield
print('baz teardown - function fixture')
def test_one(baz):
print('in test_one()')
def test_two(bar): # only use bar
print('in test_two()')
output
$ pytest -s test_modular.py
================== test session starts ==================
collected 2 items
test_modular.py
foo setup - module fixture
bar setup - function fixture
baz setup - function fixture
in test_one()
.baz teardown - function fixture
bar teardown - function fixture
bar setup - function fixture
in test_two()
.bar teardown - function fixture
foo teardown - module fixture
=================== 2 passed in 0.04s ===================
This post is part of a series on pytest fixtures
- pytest fixtures nuts and bolts
- pytest xunit-style fixtures
- Basic pytest fixtures example
- Using pytest fixtures by naming them
- Using pytest autouse fixtures
- Using pytest fixtures with mark.usefixtures
- pytest fixture return value
- pytest fixture teardown
- pytest fixture scope
- Parametrizing pytest fixtures with param
- Using multiple pytest fixtures
- Modularity: pytest fixtures using other fixtures - this post
- pytest session scoped fixtures
- Mixing pytest fixture scope