如何为pytest测试类添加自定义类级运行时描述至测试报告?
实现pytest测试类级别的单次长描述输出
完全可行,不需要用到测试类的__init__方法,通过pytest钩子函数结合类属性/自定义标记就能实现每个测试类仅输出一次长描述的需求。
方案一:类属性+钩子函数
1. 给测试类添加长描述属性
直接在测试类中定义类级属性存储专属长描述:
import pytest @pytest.mark.parametrize("year, expected_results", [("2022", "Something-2022"), ("2023", "Something-2023"), ("2024", "Something-2024")]) class TestShortDesc1: # 定义类专属的长描述 long_description = "这是TestShortDesc1类的测试说明:该类验证不同年份下Something生成逻辑的正确性,覆盖2022-2024三个年度,包含3个测试函数分别校验不同场景" @pytest.fixture(scope="function") def calculated(self, year): return f"Something-{year}" def test_short_explanation_1(self, year, expected_results, calculated): pass def test_short_explanation_2(self, year, expected_results, calculated): pass def test_short_explanation_3(self, year, expected_results, calculated): pass
2. 在conftest.py中编写钩子函数
通过钩子函数跟踪已输出描述的类,避免重复打印:
# conftest.py # 记录已输出过描述的测试类 printed_classes = set() def pytest_runtest_setup(item): # 获取当前测试用例所属的测试类 test_class = item.cls if test_class and hasattr(test_class, "long_description"): if test_class not in printed_classes: # 自定义输出格式 print(f"\n===== {test_class.__name__} 测试类描述 =====") print(test_class.long_description) print("===============================") # 将该类标记为已输出 printed_classes.add(test_class)
方案二:自定义标记+钩子函数(更灵活)
如果不想修改测试类属性,可用pytest自定义标记传递描述:
1. 给测试类添加自定义标记
import pytest @pytest.mark.parametrize("year, expected_results", [("2022", "Something-2022"), ("2023", "Something-2023"), ("2024", "Something-2024")]) # 用自定义标记传递长描述 @pytest.mark.class_desc("这是TestShortDesc1类的测试说明:该类验证不同年份下Something生成逻辑的正确性,覆盖2022-2024三个年度,包含3个测试函数分别校验不同场景") class TestShortDesc1: @pytest.fixture(scope="function") def calculated(self, year): return f"Something-{year}" def test_short_explanation_1(self, year, expected_results, calculated): pass def test_short_explanation_2(self, year, expected_results, calculated): pass def test_short_explanation_3(self, year, expected_results, calculated): pass
2. 在conftest.py中编写钩子函数
# conftest.py printed_classes = set() def pytest_runtest_setup(item): test_class = item.cls if test_class and test_class not in printed_classes: # 查找类上的自定义标记 desc_mark = next((m for m in test_class.pytestmark if m.name == "class_desc"), None) if desc_mark: print(f"\n===== {test_class.__name__} 测试类描述 =====") print(desc_mark.args[0]) print("===============================") printed_classes.add(test_class)
效果说明
运行pytest时,每个测试类的第一个测试用例执行前会自动输出一次长描述,后续该类的所有测试用例(包括参数化生成的实例)都不会重复输出,完全匹配需求。
内容的提问来源于stack exchange,提问作者pwnell
相关产品推荐
相关产品推荐

