Always put the cleanup code after yield to ensure it runs after the test.
Teardown code runs even if the test fails or raises an error.
Using yield in fixtures helps keep setup and teardown code together for clarity.
Summary
Fixture teardown with yield runs cleanup code after a test finishes.
Setup code goes before yield, teardown code goes after.
This keeps tests clean and independent by removing temporary resources.
Practice
(1/5)
1. What is the main purpose of using yield in a pytest fixture?
easy
A. To separate setup and teardown code in the fixture
B. To skip the test execution
C. To run the test multiple times
D. To mark the test as expected to fail
Solution
Step 1: Understand fixture setup and teardown
In pytest, setup code prepares resources before a test, and teardown code cleans up after the test.
Step 2: Role of yield in fixture
The yield statement splits the fixture into two parts: code before yield runs before the test (setup), and code after yield runs after the test (teardown).
Final Answer:
To separate setup and teardown code in the fixture -> Option A
Quick Check:
Yield separates setup and teardown [OK]
Hint: Remember: yield splits setup and cleanup in fixtures [OK]
Common Mistakes:
Thinking yield skips tests
Confusing yield with test repetition
Using yield to mark test outcomes
2. Which of the following is the correct syntax for a pytest fixture using yield for teardown?
easy
A. def my_fixture():
setup()
yield
teardown()
B. def my_fixture():
yield
setup()
teardown()
C. def my_fixture():
setup()
teardown()
yield
D. def my_fixture():
teardown()
yield
setup()
Solution
Step 1: Identify setup and teardown order
Setup code must run before yield, teardown code after yield.
Step 2: Check each option's order
def my_fixture():
setup()
yield
teardown() correctly places setup before yield and teardown after. Others have incorrect order.
Final Answer:
def my_fixture():
setup()
yield
teardown() -> Option A
Quick Check:
Setup before yield, teardown after [OK]
Hint: Setup before yield, teardown after yield in fixture [OK]
Common Mistakes:
Placing teardown before yield
Calling setup after yield
Yield placed at the end after teardown
3. What will be the output when running this pytest fixture and test?