Labs ICT
โญ Pro Login

setUpModule & tearDownModule

Module-level setup and teardown functions

setUpModule & tearDownModule

setUpModule and tearDownModule are module-level functions that run once before and after all tests in a module. They provide the highest level of test fixture management.

Basic Usage

# test_database.py
import unittest
import database

def setUpModule():
    """Runs once before all tests in this module."""
    database.connect()
    database.create_tables()

def tearDownModule():
    """Runs once after all tests in this module."""
    database.drop_all_tables()
    database.disconnect()

class TestUserQueries(unittest.TestCase):
    def test_insert(self):
        database.insert("users", {"name": "Alice"})

    def test_select(self):
        result = database.query("SELECT * FROM users")
        self.assertIsNotNone(result)

class TestOrderQueries(unittest.TestCase):
    def test_create_order(self):
        database.insert("orders", {"item": "laptop"})

Execution Order

# For a module with 2 test classes:
# 1. setUpModule()           โ†’ runs ONCE
# 2. TestUserQueries.setUp  โ†’ runs before each test
#    ... test methods ...
#    TestUserQueries.tearDown
# 3. TestOrderQueries.setUp  โ†’ runs before each test
#    ... test methods ...
#    TestOrderQueries.tearDown
# 4. tearDownModule()        โ†’ runs ONCE

When to Use

  • Module-wide database connections or API clients.
  • Creating shared test data that all classes in the module need.
  • Starting/stopping external services used by multiple test classes.
  • Loading configuration files needed by the entire test module.

Key Takeaway

setUpModule/tearDownModule are plain functions (not methods) that run once per module. Use them for module-wide expensive setup and teardown operations.

๐Ÿงช Quick Quiz

setUpModule is: