Test resource setup and teardown using pytest fixture with yield
Preconditions (2)
✅ Expected Result: The test passes, and the console output shows 'Setup resource' before the test and 'Teardown resource' after the test
import pytest @pytest.fixture def resource(): print("Setup resource") yield print("Teardown resource") def test_example(resource): assert True is True
The fixture resource uses yield to separate setup and teardown steps. The code before yield runs before the test, and the code after yield runs after the test finishes.
The test function test_example uses the fixture by naming it as a parameter. It asserts a simple condition True is True to pass.
When running pytest, you will see the print statements in the console showing the setup message before the test and the teardown message after the test, confirming the fixture lifecycle.
Now add a fixture that yields a resource value (like a string) and verify the test uses that value
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