Recall & Review
beginner
What is a context manager fixture in pytest?
A context manager fixture in pytest is a fixture that uses the
yield statement to set up a resource before a test and clean it up after the test finishes, similar to how a context manager works with with statements.Click to reveal answer
beginner
How do you define a context manager fixture in pytest?
You define a context manager fixture by using the
@pytest.fixture decorator and including a yield statement inside the fixture function. Code before yield runs before the test, and code after yield runs after the test for cleanup.Click to reveal answer
intermediate
Why use context manager fixtures instead of regular fixtures?
Context manager fixtures help manage setup and cleanup in one place clearly and safely. They ensure resources like files, connections, or temporary data are properly released after tests, preventing side effects.
Click to reveal answer
beginner
Example: What does this pytest fixture do?
@pytest.fixture
def open_file():
f = open('test.txt', 'w')
yield f
f.close()This fixture opens a file named 'test.txt' for writing before the test runs. It yields the file object to the test. After the test finishes, it closes the file to free the resource.
Click to reveal answer
intermediate
How does pytest know when to run the cleanup code in a context manager fixture?
Pytest runs the cleanup code immediately after the test that uses the fixture finishes. It executes the code after the
yield statement in the fixture function, ensuring proper teardown.Click to reveal answer
What keyword is used in pytest fixtures to separate setup and teardown code?
✗ Incorrect
The
yield keyword is used in pytest fixtures to separate setup (before yield) and teardown (after yield) code.When is the code after
yield in a pytest fixture executed?✗ Incorrect
Code after
yield runs after the test finishes, to clean up resources.Which decorator is used to create a fixture in pytest?
✗ Incorrect
The
@pytest.fixture decorator marks a function as a fixture.Why is it better to use context manager fixtures for resource cleanup?
✗ Incorrect
Context manager fixtures handle setup and cleanup clearly and safely in one function.
What happens if you forget to close a resource in a pytest fixture?
✗ Incorrect
Not closing resources can cause leaks and affect other tests negatively.
Explain how a context manager fixture works in pytest and why it is useful.
Think about how 'with' statements work in Python and how pytest fixtures can mimic that.
You got /5 concepts.
Write a simple pytest fixture using a context manager to open and close a file for testing.
Remember to put cleanup code after the yield statement.
You got /4 concepts.