xunit_setup.rst
Overview
This document explains how to implement **xunit-style setup and teardown** methods within test modules, classes, and functions when using the pytest testing framework. It covers a classic and widely recognized pattern for managing test fixtures on a per-module, per-class, and per-function/method basis.
The xunit-style setup/teardown approach is particularly familiar to developers coming from `unittest` or `nose` testing frameworks. Although pytest provides a more powerful and flexible fixture mechanism leveraging dependency injection, xunit-style setup remains useful for simple and direct test state management or for gradual migration between testing styles.
This file describes:
Module-level setup/teardown:
setup_module/teardown_moduleClass-level setup/teardown:
setup_class/teardown_classMethod/function-level setup/teardown:
setup_method/teardown_methodandsetup_function/teardown_function
It explains their expected behavior, parameters, and interaction with pytest’s fixture system.
Module Level Setup/Teardown
Functions
def setup_module(module):
"""Setup any state specific to the execution of the given module."""
Parameters:
module(optional as of pytest 3.0) — the module object containing the tests.Purpose:
Called once before any tests or fixtures in the module are run. Use this to set up module-wide test state.Example Usage:
def setup_module(module): print(f"Setting up module: {module.__name__}") # Initialize database connection, create test data, etc.
def teardown_module(module):
"""Teardown any state previously setup by setup_module."""
Parameters:
module(optional as of pytest 3.0)Purpose:
Called once after all tests in the module have completed, to clean up any resources initialized insetup_module.Example Usage:
def teardown_module(module): print(f"Tearing down module: {module.__name__}") # Close database connections, delete test data, etc.
Class Level Setup/Teardown
Methods
@classmethod
def setup_class(cls):
"""Setup any state specific to the execution of the given test class."""
Parameters:
cls— the test class object.Purpose:
Called once before any test methods in the class are run. Good for setting up resources shared by all tests in the class.Example Usage:
class TestExample: @classmethod def setup_class(cls): cls.shared_resource = create_resource()
@classmethod
def teardown_class(cls):
"""Teardown any state previously setup by setup_class."""
Parameters:
cls— the test class object.Purpose:
Called once after all test methods in the class have completed, to release or clean up resources allocated insetup_class.Example Usage:
class TestExample: @classmethod def teardown_class(cls): cls.shared_resource.close()
Method and Function Level Setup/Teardown
For Test Classes
def setup_method(self, method):
"""Setup any state tied to the specific test method."""
Parameters:
self— instance of the test class.method(optional as of pytest 3.0) — the method object representing the test.Purpose:
Called before each test method invocation in the class. Use to prepare per-test state.Example Usage:
class TestExample: def setup_method(self, method): self.temp_file = create_temp_file()
def teardown_method(self, method):
"""Teardown any state previously setup by setup_method."""
Parameters:
self— instance of the test class.method(optional as of pytest 3.0)Purpose:
Called after each test method to clean up.Example Usage:
class TestExample: def teardown_method(self, method): self.temp_file.delete()
For Module-level Test Functions
def setup_function(function):
"""Setup any state tied to the specific test function."""
Parameters:
function(optional as of pytest 3.0) — the test function object.Purpose:
Called before each standalone test function (not within a class) in the module.Example Usage:
def setup_function(function): print(f"Setting up for {function.__name__}")
def teardown_function(function):
"""Teardown any state previously setup by setup_function."""
Parameters:
function(optional as of pytest 3.0)Purpose:
Called after each standalone test function finishes.Example Usage:
def teardown_function(function): print(f"Tearing down for {function.__name__}")
Important Implementation Details and Remarks
Multiple Invocations:
Setup/teardown pairs may be called multiple times within a single test run depending on the number of tests and test classes.Failure Behavior:
Teardown functions are not called if the corresponding setup function failed or was skipped.Integration With Fixtures:
Since pytest 4.2, xunit-style setup/teardown functions obey fixture scope rules. For example,setup_methodwill be called respecting the scope of fixtures used in the test method. This ensures consistent and predictable test resource management.Mixing Styles:
It is possible to mix xunit-style setup with pytest’s fixture mechanism in the same test file. However, test methods insideunittest.TestCasesubclasses cannot accept pytest fixture parameters.
Interaction with Other Parts of the System
pytest Fixture Mechanism:
xunit-style setup and teardown serve as a simpler alternative to pytest fixtures but are fully integrated with pytest’s internal fixture handling since version 4.2. They provide lifecycle hooks that pytest calls automatically during test collection and execution.Test Discovery:
The pytest test runner detects these setup/teardown functions by name convention. For example,setup_moduleis recognized as a module-scoped setup hook.Compatibility:
The use of these functions and methods can coexist with pytest’s advanced fixtures, allowing incremental migration or mixed use.Legacy Support:
This approach supports developers familiar withunittestornosewho want similar lifecycle hooks without fully adopting pytest fixtures.
Visual Diagram: xUnit-Style Setup/Teardown Structure
flowchart TD
subgraph Module
A[setup_module(module)?] -->|runs once before module tests| B[Test functions/classes]
B --> C[teardown_module(module)?]
end
subgraph Class
D[setup_class(cls)?] -->|runs once before class tests| E[Test methods]
E --> F[teardown_class(cls)?]
end
subgraph Method/Function
G[setup_method(self, method)?] -->|runs before each test method| H[Test method]
H --> I[teardown_method(self, method)?]
J[setup_function(function)?] -->|runs before each test function| K[Test function]
K --> L[teardown_function(function)?]
end
B -- contains --> D
B -- contains --> J
E -- contains --> G
H -- is --> L
Legend:
Boxes with
?indicate optional parameters since pytest 3.0.Arrows indicate the order of execution and scope (module > class > method/function).
Summary
This file documents the classic xunit-style setup and teardown methods available in pytest to manage test resources and states at different scopes:
Module:
setup_module,teardown_moduleClass:
setup_class,teardown_classMethod:
setup_method,teardown_methodFunction:
setup_function,teardown_function
While pytest fixtures offer more flexibility, these traditional hooks remain useful for straightforward test setups and for teams transitioning from other test frameworks.
Use these hooks to prepare and cleanup test state, ensuring test isolation and resource management, with full compatibility and integration into pytest’s test lifecycle from version 4.2 onwards.