pytest如何在控制台打印运行速度最快的测试用例
pytest打印最快测试用例实现方案
报错原因
你遇到的AttributeError是因为terminalreporter.stats中存储的报告对象不只有测试用例执行的TestReport,还包含WarningReport等其他类型的报告,这类对象没有when属性,直接访问就会触发属性错误。
基础修复代码
只需在访问when属性前增加属性存在校验,同时收集所有用例的运行时长排序后即可打印最快的用例:
def pytest_terminal_summary(terminalreporter, exitstatus, config): # 存储所有测试用例call阶段的时长与用例ID test_duration_list = [] for reps in terminalreporter.stats.values(): for rep in reps: # 先校验when属性存在,再匹配测试执行的call阶段 if hasattr(rep, "when") and rep.when == "call": test_duration_list.append((rep.duration, rep.nodeid)) # 按耗时升序排序,取前3个最快的用例打印 test_duration_list.sort() print("\n===== 运行最快的3个测试用例 =====") for dur, nodeid in test_duration_list[:3]: print(f"{dur:.6f}s\t{nodeid}")
你也可以用类型判断替代属性校验,写法更严谨:
from pytest import TestReport def pytest_terminal_summary(terminalreporter, exitstatus, config): test_duration_list = [] for reps in terminalreporter.stats.values(): for rep in reps: if isinstance(rep, TestReport) and rep.when == "call": test_duration_list.append((rep.duration, rep.nodeid)) test_duration_list.sort() print("\n===== 运行最快的3个测试用例 =====") for dur, nodeid in test_duration_list[:3]: print(f"{dur:.6f}s\t{nodeid}")
进阶:支持命令行参数配置打印数量
你可以通过pytest钩子添加自定义参数,和官方--durations参数用法对齐:
def pytest_addoption(parser): parser.addoption( "--fast-durations", action="store", type=int, default=0, help="打印运行最快的N个测试用例,0表示不打印" ) def pytest_terminal_summary(terminalreporter, exitstatus, config): print_count = config.getoption("--fast-durations") if print_count <= 0: return test_duration_list = [] for reps in terminalreporter.stats.values(): for rep in reps: if hasattr(rep, "when") and rep.when == "call": test_duration_list.append((rep.duration, rep.nodeid)) test_duration_list.sort() show_count = min(print_count, len(test_duration_list)) print(f"\n===== 运行最快的{show_count}个测试用例 =====") for dur, nodeid in test_duration_list[:show_count]: print(f"{dur:.6f}s\t{nodeid}")
配置完成后,执行pytest --fast-durations=10即可打印运行最快的10个测试用例。
内容的提问来源于stack exchange,提问作者Ivan
相关产品推荐
相关产品推荐

