0
0
PyTesttesting~15 mins

Context manager fixtures in PyTest - Build an Automation Script

Choose your learning style9 modes available
Test resource setup and cleanup using a context manager fixture
Preconditions (2)
Step 1: Create a pytest fixture using the @pytest.fixture decorator with yield to act as a context manager
Step 2: In the fixture, set up a resource before the yield statement
Step 3: After the yield statement, clean up the resource
Step 4: Write a test function that uses this fixture as a parameter
Step 5: Inside the test, verify the resource is set up correctly
Step 6: Run the test using pytest
✅ Expected Result: The test passes, confirming the resource was set up before the test and cleaned up after the test
Automation Requirements - pytest
Assertions Needed:
Assert the resource is correctly set up before test execution
Assert the cleanup code runs after the test
Best Practices:
Use yield in fixtures to separate setup and teardown
Keep fixture scope appropriate (function scope by default)
Use clear and descriptive fixture names
Automated Solution
PyTest
import pytest

@pytest.fixture
def resource():
    # Setup code
    data = {'status': 'initialized'}
    print('Setup resource')
    yield data
    # Teardown code
    data['status'] = 'cleaned'
    print('Cleanup resource')


def test_resource_usage(resource):
    # Assert resource is set up
    assert resource['status'] == 'initialized'
    # Simulate test actions
    resource['status'] = 'used'
    assert resource['status'] == 'used'

The fixture resource uses yield to separate setup and teardown. Before yield, it initializes a dictionary to simulate a resource and prints a setup message. After yield, it modifies the dictionary to indicate cleanup and prints a cleanup message.

The test function test_resource_usage receives the fixture as a parameter. It asserts the resource is initialized before use, modifies it to simulate usage, and asserts the change.

When running with pytest, the setup code runs before the test, and the teardown code runs after, ensuring proper resource management.

Common Mistakes - 3 Pitfalls
Not using yield in fixture and placing teardown code after return
Using print statements instead of assertions to verify setup
Using global variables inside fixture without proper isolation
Bonus Challenge

Now add data-driven testing with 3 different resource initial states using the context manager fixture

Show Hint