Overview - Fixture finalization (request.addfinalizer)
What is it?
Fixture finalization in pytest is a way to clean up or undo setup actions after a test finishes. Using request.addfinalizer, you can register functions that run automatically when the test or fixture ends. This ensures resources like files, connections, or temporary data are properly closed or removed. It helps keep tests isolated and prevents side effects.
Why it matters
Without fixture finalization, leftover resources or states from one test could affect others, causing flaky or unreliable tests. Cleaning up after tests keeps the environment stable and predictable. This saves time debugging and increases confidence that tests reflect real behavior.
Where it fits
Before learning fixture finalization, you should understand basic pytest fixtures and test functions. After this, you can explore advanced fixture scopes, autouse fixtures, and pytest hooks to control test lifecycles more deeply.