Skip to content

Class-level Setup - setUpClass() and tearDownClass()

diagram pytest fixture scopes, and when each one is torn down mermaid
A fixture's scope decides how often it is built. Session runs once for the whole test run, module once per file, function once per test -- the default. Teardowns unwind in the reverse order, so a function fixture is always cleaned up before the module fixture it depends on.

Sometimes setup is expensive:

  • loading a large fixture file
  • initializing test data

Use setUpClass to run once per class.

setupclass_teardownclass.py
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)
  • Don’t share mutable state between tests unless read-only.
  • Tests should not depend on run order.

pch.coffeeTagline

pch.coffeeCta

pch.feedbackHeading

pch.feedbackSubheading