Context manager fixtures in PyTest - Build an Automation Script
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.
Now add data-driven testing with 3 different resource initial states using the context manager fixture
Practice
Solution
Step 1: Understand context manager role
Context managers in pytest useyieldto run setup code before the test and cleanup code after the test finishes.Step 2: Identify purpose in testing
This automatic setup and cleanup makes tests safer and cleaner by managing resources like files or connections.Final Answer:
To automatically handle setup and cleanup around a test -> Option BQuick Check:
Context manager fixture = automatic setup and cleanup [OK]
- Thinking context managers speed up tests by skipping setup
- Confusing context managers with parallel test execution
- Using print statements instead of assertions
Solution
Step 1: Recall context manager fixture syntax
In pytest, the code beforeyieldruns as setup, and the code afteryieldruns as cleanup.Step 2: Check each option
@pytest.fixture def resource(): setup() yield cleanup() correctly placessetup()beforeyieldandcleanup()after. Others have wrong order.Final Answer:
@pytest.fixture def resource(): setup() yield cleanup() -> Option AQuick Check:
Setup before yield, cleanup after yield [OK]
- Placing cleanup before yield
- Calling setup after yield
- Putting yield at the end after cleanup
@pytest.fixture
def file_resource():
print('Setup file')
yield
print('Cleanup file')
def test_example(file_resource):
print('Running test')Solution
Step 1: Understand fixture execution order
Before the test runs, the fixture prints 'Setup file'. Then the test prints 'Running test'. After the test finishes, the fixture prints 'Cleanup file'.Step 2: Match output sequence
The output order is: 'Setup file', 'Running test', 'Cleanup file'.Final Answer:
Setup file\nRunning test\nCleanup file -> Option DQuick Check:
Setup -> Test -> Cleanup order [OK]
- Assuming cleanup runs before test
- Thinking test runs before setup
- Mixing order of prints
@pytest.fixture
def db_connection():
conn = connect_db()
yield conn
conn.close()Solution
Step 1: Analyze fixture structure
The fixture creates a connection, yields it for the test, then closes it after the test finishes.Step 2: Confirm cleanup runs after yield
Code after yield runs as cleanup, soconn.close()will run properly after the test.Final Answer:
Nothing is wrong; it is correct -> Option AQuick Check:
Yield passes resource, cleanup runs after yield [OK]
- Thinking cleanup code never runs
- Closing connection before yield
- Not yielding the resource
Solution
Step 1: Setup temporary file before yield
The file must be created before yielding its path so the test can use it.Step 2: Cleanup file after yield
After the test, the file should be deleted to clean up resources.Final Answer:
@pytest.fixture def temp_file(): path = '/tmp/testfile.txt' open(path, 'w').close() yield path os.remove(path) -> Option CQuick Check:
Create file before yield, delete after yield [OK]
- Deleting file before test runs
- Creating file after yield
- Not yielding the file path
Ready to prove it?
Pass the test and this pattern moves unknown
