如何在pytest运行中获取所有调用的kw用于生成自定义Xray测试报告
解决方案
核心实现思路
你需要先自定义两个组件:一是步骤装饰器用来标记需要被识别为测试步骤的方法,二是pytest钩子用来存储、收集所有步骤的执行状态,最终在终端总结钩子中可以直接读取。
完整实现代码
1. conftest.py 全局配置(兼容pytest 6.2.4)
import pytest from functools import wraps # 自定义步骤存储结构,挂载到pytest config对象 def pytest_configure(config): config.xray_step_results = {} # 步骤装饰器,标记需要统计的关键字方法 def xray_step(func): @wraps(func) def wrapper(*args, **kwargs): # 获取当前运行的测试用例节点 current_item = pytest.current_test_item step_name = func.__name__ try: result = func(*args, **kwargs) # 记录步骤成功 current_item.xray_steps.append((step_name, "PASSED")) return result except Exception as e: # 记录步骤失败 current_item.xray_steps.append((step_name, "FAILED")) raise e return wrapper # 测试用例运行前初始化当前用例的步骤存储列表 @pytest.hookimpl(tryfirst=True) def pytest_runtest_setup(item): pytest.current_test_item = item item.xray_steps = [] # 测试用例运行结束后将步骤结果存入全局config @pytest.hookimpl(trylast=True) def pytest_runtest_teardown(item): if hasattr(item, "xray_steps"): item.config.xray_step_results[item.nodeid] = { "test_key": item.get_closest_marker("xray").kwargs.get("test_key") if item.get_closest_marker("xray") else None, "steps": item.xray_steps } # 终端总结钩子,可在此处读取所有步骤结果推送到Xray def pytest_terminal_summary(terminalreporter, exitstatus, config): print("\n===== Xray 测试步骤结果 =====") for nodeid, result in config.xray_step_results.items(): if result["test_key"]: print(f"测试用例 {result['test_key']} 步骤结果:") for step_name, status in result["steps"]: print(f"steps : {step_name} : {status}")
2. 改造你的测试用例代码
给需要作为测试步骤的方法加上@xray_step装饰器即可:
import pytest from conftest import xray_step class Test(object): @pytest.mark.xray(test_key='DEMO-1') @pytest.mark.parametrize('param1, param2', [(2, 2), (3, 4), (5, 5), (5, 5), (6, "a"), ("aa", "aa")]) def test_pytest_parametrized_feature_d(self, param1, param2): self.kw_one(param1, param2) self.kw_three(param1, param2) assert param1 == param2 @xray_step def kw_one(self, param1, param2): self.kw_two(param1, param2) @xray_step def kw_two(self, param1, param2): print(param1) print(param2) @xray_step def kw_three(self, param1, param2): assert param1 == param2
运行效果
执行pytest命令后,会在终端输出符合你要求的步骤结果,参数化生成的每个用例实例的步骤状态都会独立统计,所有数据都存储在config.xray_step_results属性中,你可以在pytest_terminal_summary钩子中直接调用该数据构建Xray报告进行推送。
内容的提问来源于stack exchange,提问作者yves
相关产品推荐
相关产品推荐

