1.模块级:setup_module() 和 teardown_module()
作用范围:整个模块(文件)运行前后各执行一次。
def setup_module():
print("\n[模块级前置]:只在整个文件开始前执行一次")
def teardown_module():
print("[模块级后置]:只在整个文件结束后执行一次")
def test_case01():
print("执行 test_case01")
def test_case02():
print("执行 test_case02")
2. 函数级:setup_function(func) 和 teardown_function(func)
作用范围:类外的每个测试函数前后都会执行。
def setup_function(function):
print(f"\n[函数级前置]:开始执行 {function.__name__}")
def teardown_function(function):
print(f"[函数级后置]:结束执行 {function.__name__}")
def test_case01():
print("运行 test_case01")
def test_case02():
print("运行 test_case02")
3. 类级:setup_class(cls) 和 teardown_class(cls)
作用范围:类中每个测试方法前后都会执行。
class TestClassLevel:
@classmethod
def setup_class(cls):
print("\n[类级前置]:在整个类测试开始前执行一次")
@classmethod
def teardown_class(cls):
print("[类级后置]:在整个类测试完成后执行一次")
def test_a(self):
print("运行 test_a")
def test_b(self):
print("运行 test_b")
4. 方法级:setup_method(self, method) 和 teardown_method(self, method)
作用范围:类中每个测试方法前后都会执行。
class TestMethodLevel:
def setup_method(self, method):
print(f"\n[方法级前置]:开始执行 {method.__name__}")
def teardown_method(self, method):
print(f"[方法级后置]:结束执行 {method.__name__}")
def test_x(self):
print("运行 test_x")
def test_y(self):
print("运行 test_y")