0
0
PyTesttesting~5 mins

Fixture finalization (request.addfinalizer) in PyTest - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is the purpose of request.addfinalizer in pytest fixtures?

request.addfinalizer is used to register a cleanup function that runs after the test using the fixture finishes. It helps to release resources or reset states.

Click to reveal answer
intermediate
How does request.addfinalizer differ from using yield in pytest fixtures?

request.addfinalizer registers a cleanup callback explicitly, while yield splits the fixture into setup and teardown parts. Both achieve cleanup but with different syntax.

Click to reveal answer
beginner
Write a simple pytest fixture that opens a file and uses request.addfinalizer to close it.
<pre>import pytest

@pytest.fixture
def open_file(request):
    f = open('test.txt', 'w')
    def close_file():
        f.close()
    request.addfinalizer(close_file)
    return f</pre>
Click to reveal answer
beginner
When is the finalizer function registered by request.addfinalizer executed?

The finalizer function runs after the test function finishes, regardless of whether the test passed or failed. It ensures cleanup always happens.

Click to reveal answer
intermediate
Can multiple finalizers be added with request.addfinalizer in one fixture? What happens?

Yes, you can add multiple finalizers. They run in the reverse order of registration after the test completes.

Click to reveal answer
What does request.addfinalizer do in a pytest fixture?
ARegisters a function to run after the test for cleanup
BStarts the test execution
CSkips the test
DMarks the test as failed
When is the finalizer function executed in pytest fixtures using request.addfinalizer?
AAfter the test finishes
BBefore the test starts
COnly if the test passes
DOnly if the test fails
Which of the following is a correct way to add a finalizer in a pytest fixture?
Arequest.addfinalize(cleanup_function)
Brequest.finalize(cleanup_function)
Crequest.addfinalizer(cleanup_function)
Drequest.cleanup(cleanup_function)
If you add multiple finalizers with request.addfinalizer, in what order do they run?
AIn the order they were added
BIn reverse order of addition
CRandom order
DThey run simultaneously
Which is a benefit of using request.addfinalizer over yield in fixtures?
ARuns cleanup only on test failure
BRuns cleanup before setup
CSkips the test automatically
DAllows multiple cleanup functions
Explain how request.addfinalizer works in pytest fixtures and why it is useful.
Think about cleaning up after using something in a test.
You got /4 concepts.
    Describe the difference between using request.addfinalizer and yield in pytest fixtures for cleanup.
    One uses a function call, the other uses Python's yield keyword.
    You got /4 concepts.