0
0
PyTesttesting~15 mins

@pytest.fixture decorator - Build an Automation Script

Choose your learning style9 modes available
Automate test using @pytest.fixture for setup
Preconditions (2)
Step 1: Create a fixture function named 'sample_data' that returns a dictionary with keys 'name' and 'age'
Step 2: Create a test function 'test_sample_data' that uses the 'sample_data' fixture as a parameter
Step 3: Inside the test, assert that 'name' in sample_data equals 'Alice'
Step 4: Assert that 'age' in sample_data equals 30
✅ Expected Result: The test passes confirming the fixture provides correct data
Automation Requirements - pytest
Assertions Needed:
Assert 'name' key in fixture data equals 'Alice'
Assert 'age' key in fixture data equals 30
Best Practices:
Use @pytest.fixture decorator for reusable setup data
Name fixtures clearly to indicate their purpose
Use fixtures as function parameters for automatic injection
Keep fixture scope default (function) unless needed otherwise
Automated Solution
PyTest
import pytest

@pytest.fixture
def sample_data():
    return {"name": "Alice", "age": 30}

def test_sample_data(sample_data):
    assert sample_data["name"] == "Alice"
    assert sample_data["age"] == 30

The @pytest.fixture decorator marks the sample_data function as a fixture. This means pytest will run it before the test that uses it and provide its return value as an argument.

The test function test_sample_data accepts sample_data as a parameter. Pytest automatically calls the fixture and passes its return value.

Assertions check that the fixture data matches expected values. This confirms the fixture setup works correctly.

This approach avoids repeating setup code in multiple tests and keeps tests clean and focused.

Common Mistakes - 3 Pitfalls
{'mistake': 'Not using the @pytest.fixture decorator on the setup function', 'why_bad': "Without the decorator, pytest won't recognize the function as a fixture and won't inject it into tests.", 'correct_approach': 'Always add @pytest.fixture above the setup function to register it as a fixture.'}
Calling the fixture function directly inside the test instead of using it as a parameter
Using mutable default arguments or global variables inside fixtures
Bonus Challenge

Modify the fixture to accept a parameter for 'name' and 'age' and run the test with three different sets of data

Show Hint