Verify autouse fixture runs automatically before each test
Preconditions (2)
✅ Expected Result: The fixture's print statement 'Setup running' appears before each test output without explicitly calling the fixture
import pytest @pytest.fixture(autouse=True) def setup_fixture(): print('Setup running') def test_one(): assert True def test_two(): assert True def test_autouse_runs(capsys): # Run test_one and capture output test_one() captured = capsys.readouterr() assert 'Setup running' in captured.out # Run test_two and capture output test_two() captured = capsys.readouterr() assert 'Setup running' in captured.out
This code defines a fixture setup_fixture with autouse=True. This means pytest runs it automatically before each test without needing to mention it.
The fixture prints 'Setup running' before each test.
Two simple tests test_one and test_two just assert True.
The test_autouse_runs function uses pytest's capsys to capture printed output when calling the tests manually. It asserts that 'Setup running' appears in the output, confirming the fixture ran automatically.
This approach shows how autouse fixtures work and how to verify their execution.
Now add a data-driven test that uses the autouse fixture and runs with three different input values
autouse fixture in pytest?pytest?
import pytest
@pytest.fixture(autouse=True)
def setup():
print('Setup runs')
def test_one():
print('Test one running')
def test_two():
print('Test two running')import pytest
@pytest.fixture(autouse=True)
def setup():
print('Setup')
@pytest.fixture
def test_data():
return 42
def test_example(test_data):
assert test_data == 42scope value should you use with @pytest.fixture(autouse=True)?Pass the test and this pattern moves unknown