0
0
PyTesttesting~15 mins

Fixture teardown (yield) in PyTest - Build an Automation Script

Choose your learning style9 modes available
Test resource setup and teardown using pytest fixture with yield
Preconditions (2)
Step 1: Create a fixture named 'resource' that prints 'Setup resource' before yield and 'Teardown resource' after yield
Step 2: Write a test function 'test_example' that uses the 'resource' fixture and asserts True is True
Step 3: Run the test using pytest
✅ Expected Result: The test passes, and the console output shows 'Setup resource' before the test and 'Teardown resource' after the test
Automation Requirements - pytest
Assertions Needed:
Assert True is True in the test function
Verify that the fixture setup and teardown messages are printed in correct order
Best Practices:
Use yield in fixture to separate setup and teardown
Keep fixture scope appropriate (function scope by default)
Use print statements or logging to confirm teardown execution
Automated Solution
PyTest
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.

Common Mistakes - 3 Pitfalls
Not using yield and putting all code before yield
Using print statements without running pytest in verbose mode
{'mistake': 'Not including the fixture as a parameter in the test function', 'why_bad': "The fixture will not be invoked, so setup and teardown won't run", 'correct_approach': 'Add the fixture name as a parameter to the test function to use it'}
Bonus Challenge

Now add a fixture that yields a resource value (like a string) and verify the test uses that value

Show Hint