What will be the output order of the print statements when running this pytest test?
import pytest def test_example(request): print("Start test") request.addfinalizer(lambda: print("First finalizer")) request.addfinalizer(lambda: print("Second finalizer")) print("End test")
Remember that finalizers added later run first.
Pytest runs finalizers in reverse order of addition. So the last added finalizer runs first.
You want to test that a finalizer function was called after the test. Which assertion correctly verifies this?
import pytest called = [] def test_finalizer_called(request): def cleanup(): called.append(True) request.addfinalizer(cleanup) assert ???
Finalizers run after the test function finishes.
The finalizer runs after the test function completes, so during the test the list is still empty.
What error will this pytest fixture cause?
import pytest @pytest.fixture def resource(request): print("Setup resource") request.addfinalizer("cleanup") return "resource"
Check what type addfinalizer expects as argument.
addfinalizer expects a callable (function), but a string was passed, causing a TypeError.
Which reason best explains when to prefer request.addfinalizer over yield in pytest fixtures?
Think about multiple cleanup steps and their order.
request.addfinalizer allows adding multiple cleanup functions that run in reverse order, which yield cannot do easily.
Given this pytest test, what is the exact printed output?
import pytest def test_nested_finalizers(request): print("Test start") def first_cleanup(): print("First cleanup start") def second_cleanup(): print("Second cleanup") request.addfinalizer(second_cleanup) print("First cleanup end") request.addfinalizer(first_cleanup) print("Test end")
Remember that finalizers run after the test, and added finalizers run in reverse order.
After the test ends, first_cleanup runs and adds second_cleanup as a finalizer. second_cleanup runs last.