0
0
PyTesttesting~5 mins

Context manager fixtures in PyTest - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
Areturn
Bbreak
Cyield
Dcontinue
When is the code after yield in a pytest fixture executed?
AAfter the test finishes
BBefore the test runs
CDuring the test
DNever
Which decorator is used to create a fixture in pytest?
A@pytest.test
B@pytest.fixture
C@pytest.context
D@pytest.setup
Why is it better to use context manager fixtures for resource cleanup?
AThey run faster
BThey skip tests
CThey require less code
DThey automatically handle setup and teardown in one place
What happens if you forget to close a resource in a pytest fixture?
AResources may leak and cause errors in other tests
BPytest closes it automatically
CThe test will always pass
DNothing happens
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.