Isolate Test State with Fixtures and Cleanup
Core idea
A fixture is the state needed for a test. unittest calls setUp before each test method and tearDown after a successful setUp, even if the test fails. addCleanup registers actions in last-in first-out order, including when setUp raises after registration. Prefer fresh mutable state per test.
import unittestclass CartTest(unittest.TestCase): def setUp(self): self.cart = [] def test_add(self): self.cart.append('tea') self.assertEqual(len(self.cart), 1) def test_empty(self): self.assertEqual(self.cart, [])r = unittest.TestResult()unittest.defaultTestLoader.loadTestsFromTestCase(CartTest).run(r)print(r.testsRun, r.wasSuccessful())Each case gets an empty list regardless of execution order.
Clean up after setup fails
import unittestevents = []class SetupTest(unittest.TestCase): def setUp(self): self.addCleanup(events.append, 'closed') raise RuntimeError('setup failed') def tearDown(self): events.append('teardown') def test_work(self): events.append('test')r = SetupTest('test_work').run()print(events, len(r.errors))Only registered cleanup runs here; the test and tearDown are skipped because setup failed.
Common mistake
Do not put mutable test state on a class unless sharing is deliberate. Register cleanup immediately after acquisition; later setup steps may fail.
Practice
Register two cleanup callbacks that append labels, trigger a setup error and verify reverse registration order.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Fixtures and teardown
Check your understanding of fixtures and teardown.
What is printed?
import unittestclass T(unittest.TestCase): def setUp(self): self.x=4 def test_a(self): self.assertEqual(self.x,4)print(T('test_a').run().wasSuccessful())What is printed?
import unittesta=[]class T(unittest.TestCase): def test_a(self): self.addCleanup(a.append,1) self.addCleanup(a.append,2)T('test_a').run()print(a)What runs if setUp raises after registering cleanup?
Why create a fresh list in setUp?