Test Overview
This test uses a pytest fixture implemented as a context manager to set up and tear down a resource. It verifies that the resource is correctly initialized and cleaned up after the test.
Jump into concepts and practice - no test required
This test uses a pytest fixture implemented as a context manager to set up and tear down a resource. It verifies that the resource is correctly initialized and cleaned up after the test.
import pytest class Resource: def __init__(self): self.active = False def start(self): self.active = True def stop(self): self.active = False @pytest.fixture def resource(): res = Resource() res.start() yield res res.stop() def test_resource_active(resource): assert resource.active is True
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | pytest starts test execution | pytest test runner initialized | — | PASS |
| 2 | pytest calls the 'resource' fixture before the test | Resource instance created with active = False | — | PASS |
| 3 | Resource.start() is called inside fixture, setting active = True | Resource active state is True | — | PASS |
| 4 | Fixture yields the resource instance to the test | Test receives resource with active = True | — | PASS |
| 5 | Test asserts resource.active is True | resource.active is True | assert resource.active is True | PASS |
| 6 | Test completes, pytest resumes fixture teardown | Resource active state still True | — | PASS |
| 7 | Resource.stop() is called in fixture teardown, setting active = False | Resource active state is False | — | PASS |
| 8 | pytest finishes test execution | All resources cleaned up | — | PASS |
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.