Class-level Setup - setUpClass() and tearDownClass()
flowchart TD A["session fixture -- setup"] --> B["module fixture -- setup"] B --> C["function fixture -- setup"] C --> D["test_one"] D --> E["function fixture -- teardown"] E --> F["function fixture -- setup"] F --> G["test_two"] G --> H["function fixture -- teardown"] H --> I["module fixture -- teardown"] I --> J["session fixture -- teardown"]
Why class-level setup?
Section titled “Why class-level setup?”Sometimes setup is expensive:
- loading a large fixture file
- initializing test data
Use setUpClass to run once per class.
Example
Section titled “Example”import unittest
class TestExpensiveSetup(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.data = list(range(1000))
@classmethod
def tearDownClass(cls):
cls.data = []
def test_sum(self):
self.assertEqual(sum(self.data), sum(range(1000)))
def test_len(self):
self.assertEqual(len(self.data), 1000)Caution
Section titled “Caution”- Don’t share mutable state between tests unless read-only.
- Tests should not depend on run order.
pch.coffeeTagline
pch.coffeeCtapch.feedbackHeading
pch.feedbackSubheading