Test Overview
This test uses a pytest fixture with yield to set up and tear down a resource. It verifies that the resource is available during the test and that the teardown code runs after the test finishes.
This test uses a pytest fixture with yield to set up and tear down a resource. It verifies that the resource is available during the test and that the teardown code runs after the test finishes.
import pytest @pytest.fixture def resource(): print("Setup resource") yield "my_resource" print("Teardown resource") def test_using_resource(resource): print(f"Using {resource}") assert resource == "my_resource"
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Pytest starts test run and identifies the fixture 'resource' with yield | Test environment ready, no resource allocated yet | — | PASS |
| 2 | Fixture 'resource' setup code runs, prints 'Setup resource' | Resource setup done, 'my_resource' yielded to test | — | PASS |
| 3 | Test 'test_using_resource' starts, receives 'my_resource' from fixture | Test function running with resource='my_resource' | Assert resource == 'my_resource' | PASS |
| 4 | Test prints 'Using my_resource' and assertion passes | Test function completes successfully | Assertion passed confirming resource value | PASS |
| 5 | Fixture teardown code runs after test, prints 'Teardown resource' | Resource cleaned up, test environment reset | — | PASS |
yield in a pytest fixture?yield in fixtureyield statement splits the fixture into two parts: code before yield runs before the test (setup), and code after yield runs after the test (teardown).yield for teardown?yield, teardown code after yield.yield and teardown after. Others have incorrect order.import pytest
@pytest.fixture
def resource():
print('Setup')
yield
print('Teardown')
def test_example(resource):
print('Test running')yield:
@pytest.fixture
def faulty_fixture():
yield
setup()
teardown()yield for this purpose?Pass the test and this pattern moves unknown