Test resource setup and cleanup using a context manager fixture
Preconditions (2)
✅ Expected Result: The test passes, confirming the resource was set up before the test and cleaned up after the test
Jump into concepts and practice - no test required
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
yield to run setup code before the test and cleanup code after the test finishes.yield runs as setup, and the code after yield runs as cleanup.setup() before yield and cleanup() after. Others have wrong order.@pytest.fixture
def file_resource():
print('Setup file')
yield
print('Cleanup file')
def test_example(file_resource):
print('Running test')@pytest.fixture
def db_connection():
conn = connect_db()
yield conn
conn.close()conn.close() will run properly after the test.