0
0
PyTesttesting~10 mins

Fixture finalization (request.addfinalizer) in PyTest - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test uses a pytest fixture with request.addfinalizer to run cleanup code after the test finishes. It verifies that the finalizer runs and changes a variable as expected.

Test Code - pytest
PyTest
import pytest

@pytest.fixture
def resource(request):
    state = {"cleaned": False}
    def cleanup():
        state["cleaned"] = True
    request.addfinalizer(cleanup)
    return state

def test_resource_cleanup(resource):
    assert resource["cleaned"] is False

# After test ends, finalizer sets resource["cleaned"] to True
Execution Trace - 7 Steps
StepActionSystem StateAssertionResult
1Test startspytest test runner initialized-PASS
2Fixture 'resource' is called with 'request' parameterFixture creates state dictionary {'cleaned': False}-PASS
3Fixture adds finalizer function 'cleanup' using request.addfinalizerFinalizer registered to set state['cleaned'] = True after test-PASS
4Test function 'test_resource_cleanup' runs with fixture 'resource'state['cleaned'] is False at test startAssert resource['cleaned'] is FalsePASS
5Test function completesTest function finished without errors-PASS
6pytest runs finalizer 'cleanup' registered by fixturestate['cleaned'] is set to True by finalizer-PASS
7Test ends with all assertions passed and finalizer executedTest environment cleaned up-PASS
Failure Scenario
Failing Condition: Finalizer function is not called or does not set 'cleaned' to True
Execution Trace Quiz - 3 Questions
Test your understanding
What does request.addfinalizer do in this pytest fixture?
ARuns the cleanup function before the test starts
BRegisters a cleanup function to run after the test finishes
CSkips the test if cleanup fails
DRuns the cleanup function during the test
Key Result
Using request.addfinalizer in pytest fixtures ensures cleanup code runs after tests, keeping tests isolated and preventing side effects.