Fixtures help set up things your tests need. Sometimes one fixture needs another fixture to work. This is called fixture dependency.
0
0
Fixture dependencies (fixture using fixture) in PyTest
Introduction
When you want to reuse setup steps in multiple fixtures.
When one fixture needs data or setup from another fixture.
When you want to keep your test setup organized and avoid repeating code.
When you want to build complex setups step-by-step.
When you want to share common resources between tests safely.
Syntax
PyTest
import pytest @pytest.fixture def fixture_a(): return "data from A" @pytest.fixture def fixture_b(fixture_a): return f"B uses {fixture_a}"
Fixtures can accept other fixtures as parameters by naming them.
pytest automatically runs the dependent fixture first and passes its result.
Examples
Here,
user fixture depends on db_connection fixture.PyTest
import pytest @pytest.fixture def db_connection(): return "db connection" @pytest.fixture def user(db_connection): return f"user with {db_connection}"
client fixture uses config fixture to get URL.PyTest
import pytest @pytest.fixture def config(): return {"url": "http://example.com"} @pytest.fixture def client(config): return f"client using {config['url']}"
Sample Program
This test shows a fixture api_client that depends on base_url. The test checks the combined string and prints it.
PyTest
import pytest @pytest.fixture def base_url(): return "http://testsite.com" @pytest.fixture def api_client(base_url): return f"API client connected to {base_url}" def test_api(api_client): assert api_client == "API client connected to http://testsite.com" print(api_client)
OutputSuccess
Important Notes
Fixture dependencies help keep tests clean and avoid repeating setup code.
pytest resolves fixture dependencies automatically in the right order.
Use descriptive fixture names to make dependencies clear.
Summary
Fixtures can use other fixtures by naming them as parameters.
This helps build reusable and organized test setups.
pytest runs dependent fixtures first and passes their results automatically.