What if your tests could clean up after themselves perfectly every time, without you lifting a finger?
Why Fixture finalization (request.addfinalizer) in PyTest? - Purpose & Use Cases
Imagine you run tests that create temporary files or open database connections. After each test, you have to manually delete files or close connections by writing cleanup code everywhere.
This manual cleanup is slow and easy to forget. If you miss cleaning up, leftover files or open connections cause errors in later tests. It's like leaving your kitchen messy after cooking--next time you cook, it's harder and risky.
Using request.addfinalizer in pytest fixtures lets you register cleanup code that runs automatically after the test finishes. This keeps your tests clean and safe without repeating cleanup code everywhere.
def test_example(): resource = open_resource() # test steps resource.close() # manual cleanup
import pytest @pytest.fixture def resource(request): res = open_resource() request.addfinalizer(res.close) return res def test_example(resource): # test steps using resource pass
It enables reliable, automatic cleanup after tests, so your test environment stays fresh and tests don't interfere with each other.
Think of testing a web app that creates temporary user accounts. Using request.addfinalizer, you can automatically delete these accounts after each test, avoiding clutter and conflicts.
Manual cleanup is error-prone and repetitive.
request.addfinalizer automates cleanup after tests.
This keeps tests independent and environment clean.