Recall & Review
beginner
What is the purpose of using
yield in a pytest fixture?Using
yield in a pytest fixture allows you to separate setup and teardown code. The code before yield runs before the test, and the code after yield runs after the test to clean up.Click to reveal answer
beginner
How does pytest know when to run the teardown code in a fixture using
yield?Pytest runs the code after
yield automatically after the test that uses the fixture finishes, even if the test fails or raises an error.Click to reveal answer
beginner
Write a simple pytest fixture using
yield that prints 'Setup' before the test and 'Teardown' after the test.import pytest
@pytest.fixture
def my_fixture():
print('Setup')
yield
print('Teardown')Click to reveal answer
intermediate
Why is using
yield in fixtures better than using request.addfinalizer() for teardown?Using
yield keeps setup and teardown code together in one place, making the fixture easier to read and maintain. It also works naturally with Python's generator syntax.Click to reveal answer
intermediate
Can the teardown code after
yield in a pytest fixture modify the value returned to the test?No. The value yielded is sent to the test function before the teardown code runs. The teardown code runs after the test and cannot change the yielded value.
Click to reveal answer
What happens to the code after
yield in a pytest fixture?✗ Incorrect
The code after
yield runs after the test finishes, regardless of test outcome.Which keyword is used in pytest fixtures to separate setup and teardown code?
✗ Incorrect
yield separates setup (before) and teardown (after) code in pytest fixtures.If a pytest fixture uses
yield, when is the setup code executed?✗ Incorrect
Setup code runs before the test, before the
yield statement.What is a benefit of using
yield in pytest fixtures?✗ Incorrect
yield lets you write setup and teardown code together in one fixture function.Can teardown code after
yield modify the fixture value used by the test?✗ Incorrect
Teardown code runs after the test uses the yielded value, so it cannot change it.
Explain how to use
yield in a pytest fixture to handle setup and teardown.Think of yield as a pause between setup and cleanup.
You got /4 concepts.
Describe why using
yield in fixtures is preferred over request.addfinalizer().Focus on code clarity and maintenance.
You got /4 concepts.