如何让pytest-html报告显示pytest-xdist并行测试的真实耗时?
解决pytest-html结合pytest-xdist时总耗时统计错误的问题
这个问题是因为pytest-xdist并行执行测试时,pytest-html默认会将每个测试用例的执行时间累加,而非计算从测试启动到结束的真实总时长。可以通过自定义pytest hook函数来修正这个统计逻辑:
实现步骤
- 在你的测试根目录下创建(或修改)
conftest.py文件,添加以下代码:
import time def pytest_configure(config): # 记录测试启动的全局时间点 config._global_start_time = time.time() def pytest_unconfigure(config): # 计算真实总耗时并存储到config对象中 config._real_total_duration = time.time() - config._global_start_time def pytest_html_results_summary(prefix, summary, postfix, config): # 遍历报告摘要列表,替换错误的耗时统计行 for idx, line in enumerate(summary): if "took" in line: # 将秒数格式化为 HH:MM:SS 格式 total_sec = config._real_total_duration hours, remainder = divmod(total_sec, 3600) minutes, seconds = divmod(remainder, 60) formatted_time = f"{int(hours):02d}:{int(minutes):02d}:{int(seconds):02d}" # 动态获取总测试数(避免硬编码) test_count = config.session.testscollected summary[idx] = f"{test_count} tests took {formatted_time}." break
- 重新运行你的测试命令(比如
pytest -n auto --html=report.html),生成的报告就会显示真实的总耗时了。
说明
pytest_configure和pytest_unconfigure分别在测试启动和结束时触发,用来记录全局的起止时间pytest_html_results_summary是pytest-html提供的hook,用于修改报告的摘要部分,我们在这里替换掉错误的耗时统计- 代码中用
config.session.testscollected动态获取总测试数,适配不同的测试数量场景
内容的提问来源于stack exchange,提问作者MivaScott
相关产品推荐
相关产品推荐

