一个会话级别的夹具(fixture)可以有效地访问所有收集到的测试项。以下是一个夹具函数的示例,该函数遍历所有收集到的测试项,检查它们的测试类是否定义了一个名为 callme
的方法,并调用它:
# conftest.py 文件的内容
import pytest
@pytest.fixture(scope="session", autouse=True)
def callattr_ahead_of_alltests(request):
print("callattr_ahead_of_alltests called")
seen = {None} # 用于跟踪已经检查过的类,初始化为包含 None 的集合
session = request.node # 获取当前会话的根节点
for item in session.items: # 遍历会话中的所有测试项
cls = item.getparent(pytest.Class) # 获取测试项所属的测试类(如果存在的话)
if cls not in seen: # 如果这个类还没有被检查过
if hasattr(cls.obj, "callme"): # 检查这个类的实例(cls.obj)是否有 `callme` 方法
cls.obj.callme() # 如果有,就调用它
seen.add(cls) # 将这个类添加到已检查的集合中
现在,测试类可以定义一个 callme
方法,该方法将在运行任何测试之前被调用:
# test_module.py 文件的内容
class TestHello:
@classmethod
def callme(cls):
print("callme called!")
def test_method1(self):
print("test_method1 called")
def test_method2(self):
print("test_method2 called")
class TestOther:
@classmethod
def callme(cls):
print("callme other called")
def test_other(self):
print("test other")
# works with unittest as well ...
import unittest
class SomeTest(unittest.TestCase):
@classmethod
def callme(self):
print("SomeTest callme called")
def test_unit1(self):
print("test_unit1 method called")
如果你在没有捕获输出的情况下运行这个命令:
$ pytest -q -s test_module.py
你将看到以下输出:
callattr_ahead_of_alltests called
callme called!
callme other called
SomeTest callme called
test_method1 called
.test_method2 called
.test other
.test_unit1 method called
.
4 passed in 0.12s