0
0
PyTesttesting~15 mins

Fixture finalization (request.addfinalizer) in PyTest - Build an Automation Script

Choose your learning style9 modes available
Verify resource cleanup using pytest fixture finalizer
Preconditions (2)
Step 1: Create a pytest fixture that sets up a resource (e.g., opens a file or creates a list)
Step 2: Use request.addfinalizer inside the fixture to add a cleanup function that releases the resource
Step 3: Write a test function that uses this fixture
Step 4: Run the test
Step 5: Verify that the cleanup function runs after the test completes
✅ Expected Result: The test passes and the cleanup function is executed after the test, releasing the resource properly
Automation Requirements - pytest
Assertions Needed:
Assert the resource is set up correctly in the fixture
Assert the cleanup function is called after the test
Best Practices:
Use request.addfinalizer to register cleanup functions
Keep setup and teardown logic inside fixtures
Avoid side effects outside fixtures
Use assert statements for validation
Automated Solution
PyTest
import pytest

class Resource:
    def __init__(self):
        self.active = False
    def open(self):
        self.active = True
    def close(self):
        self.active = False

@pytest.fixture
def resource_fixture(request):
    res = Resource()
    res.open()

    def cleanup():
        res.close()
        print("Cleanup called: resource closed")

    request.addfinalizer(cleanup)
    return res

def test_resource_usage(resource_fixture):
    # Assert resource is active during test
    assert resource_fixture.active is True

    # The cleanup will run after this test finishes

This code defines a Resource class to simulate a resource that can be opened and closed.

The resource_fixture fixture creates and opens the resource. It uses request.addfinalizer to register a cleanup function that closes the resource after the test finishes.

The test test_resource_usage uses the fixture and asserts the resource is active during the test.

After the test completes, pytest automatically calls the cleanup function to close the resource, ensuring proper cleanup.

Common Mistakes - 3 Pitfalls
Not using request.addfinalizer and instead trying to cleanup inside the test
Forgetting to call the cleanup function inside addfinalizer
Modifying shared state in cleanup without isolation
Bonus Challenge

Now add a second fixture that depends on the first fixture and also uses addfinalizer for cleanup

Show Hint