0
0
PyTesttesting~15 mins

Autouse fixtures in PyTest - Build an Automation Script

Choose your learning style9 modes available
Verify autouse fixture runs automatically before each test
Preconditions (2)
Step 1: Create a fixture with autouse=True that prints 'Setup running' before each test
Step 2: Write two test functions that each assert True is True
Step 3: Run the tests using pytest
Step 4: Observe the output to confirm the fixture runs before each test automatically
✅ Expected Result: The fixture's print statement 'Setup running' appears before each test output without explicitly calling the fixture
Automation Requirements - pytest
Assertions Needed:
Verify both tests pass
Verify the fixture runs automatically before each test (can be confirmed by capturing output)
Best Practices:
Use autouse=True in fixture decorator
Use capsys fixture to capture printed output for assertion
Keep fixtures simple and reusable
Automated Solution
PyTest
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.

Common Mistakes - 3 Pitfalls
{'mistake': 'Not setting autouse=True in the fixture decorator', 'why_bad': "The fixture will not run automatically before tests, so the setup code won't execute unless explicitly used.", 'correct_approach': 'Always add autouse=True in @pytest.fixture decorator to make the fixture run automatically.'}
{'mistake': 'Trying to assert fixture output without capturing it', 'why_bad': "Print statements won't be captured by default, so assertions on output will fail.", 'correct_approach': "Use pytest's capsys fixture to capture printed output for assertions."}
{'mistake': 'Calling test functions directly without pytest runner', 'why_bad': "Calling test functions directly bypasses pytest's fixture management and hooks.", 'correct_approach': 'Use pytest runner or parametrize tests properly; for demonstration, use capsys carefully.'}
Bonus Challenge

Now add a data-driven test that uses the autouse fixture and runs with three different input values

Show Hint