Context manager fixtures help set up and clean up resources automatically during tests. They make tests easier to write and keep clean.
0
0
Context manager fixtures in PyTest
Introduction
When you need to open and close a file around a test.
When you want to start and stop a server for a test.
When you need to connect and disconnect from a database during testing.
When you want to prepare some data before a test and remove it after.
When you want to ensure resources are released even if a test fails.
Syntax
PyTest
import pytest @pytest.fixture def resource(): with setup_resource() as res: yield res
The yield keyword pauses the fixture to run the test, then resumes to clean up.
Use with to manage the resource safely inside the fixture.
Examples
This fixture opens a file for writing and yields it to the test. After the test, the file is closed automatically.
PyTest
import pytest @pytest.fixture def open_file(): with open('test.txt', 'w') as f: yield f
This fixture starts a server before the test and stops it after the test finishes.
PyTest
import pytest class Server: def start(self): print('Server started') def stop(self): print('Server stopped') @pytest.fixture def server(): srv = Server() srv.start() yield srv srv.stop()
Sample Program
This test uses a context manager fixture to set up and clean up a resource. The print statements show the order of actions.
PyTest
import pytest class Resource: def __enter__(self): print('Resource setup') return self def __exit__(self, exc_type, exc_val, exc_tb): print('Resource cleanup') @pytest.fixture def resource(): with Resource() as res: yield res def test_example(resource): print('Test is running') assert True
OutputSuccess
Important Notes
Always use yield in context manager fixtures to separate setup and cleanup.
Context manager fixtures help avoid leftover resources that can cause flaky tests.
Summary
Context manager fixtures use with and yield to manage setup and cleanup.
They make tests cleaner and safer by handling resources automatically.
Use them whenever your test needs temporary resources like files, servers, or connections.