How can I use unittest cleanup to prevent one test affecting another?
Quick answer
Before changing shared or temporary state in a unittest, save its current value and register a function that restores it with self.addCleanup(...). The registered cleanup runs after tearDown() and still runs if setUp() fails; cleanups run in last-in, first-out order. Register restoration as soon as you have captured the old state, so the test does not depend on reaching its final line to undo the change. [S1]
The question, the details, the next step.
A practical checklist
Identify the exact shared or temporary state the test changes.
Capture its current value before changing it.
Register a callback with
self.addCleanupimmediately after capturing the value.Make the temporary change only after restoration is registered.
For changes in
setUp(), register cleanup there before later setup work can fail.For multiple changes, check that each callback restores its intended state and account for last-in, first-out order.
A few more useful answers
Does addCleanup run before or after tearDown?
Registered cleanups run after tearDown(). They run in last-in, first-out order. [S1]
Will a cleanup registered in setUp run if setUp fails?
Yes. Registered cleanups still run if setUp() fails, even though tearDown() is not called. Register the cleanup before the setup operation that might fail. [S1]
Does addCleanup automatically restore every change a test makes?
No. It runs the callback you register; that callback must explicitly restore the state or effect you want undone.
Sources
References used for this guide.
- [S1] unittest — Unit testing framework (Python 3.15 documentation) docs.python.org · Checked
