在python中通过pytest hook函数统计测试耗时,最直接的方法是在 pytest_runtest_makereport 钩子中获取当前测试阶段的持续时间,并将其挂载到报告对象上。具体做法是检查 item 的 nodeid 或阶段名称,当处于 call 阶段时,利用 report.duration 属性即可拿到该测试用例的执行秒数,随后可以将其存入 request.node.stash 以便后续使用。

如何区分setup、call和teardown各阶段的耗时
要分别统计各个阶段的耗时,需要在 pytest_runtest_makereport 钩子中判断 report.when 的值。该值是一个字符串,分别为 'setup'、'call' 和 'teardown'。通过条件分支处理不同的阶段,可以将每个阶段的耗时独立存储。例如,将 call 阶段的耗时单独提取,用于衡量业务逻辑执行时间,而忽略 setup 和 teardown 的开销。

import pytest
def pytest_runtest_makereport(item, call, report):
if report.when == 'call':
# 将调用阶段的耗时存入 stash
item.stash['call_duration'] = report.duration
elif report.when == 'setup':
item.stash['setup_duration'] = report.duration
elif report.when == 'teardown':
item.stash['teardown_duration'] = report.duration
# 在测试结束后打印结果
def pytest_terminal_summary(terminalreporter, exitstatus, config):
for rep in terminalreporter.stats.get('passed', []):
node = rep.node
call_dur = node.stash.get('call_duration', 0)
print(f"Test {rep.node.nodeid} call duration: {call_dur:.4f}s")
如何在终端报告中展示慢速测试用例
为了快速定位性能瓶颈,可以在 pytest_terminal_summary 钩子中遍历所有通过的测试报告,筛选出耗时超过特定阈值(如0.5秒)的用例并打印出来。这需要结合前一步存储在 stash 中的耗时数据。通过这种方式,开发者可以在测试运行结束后立即看到哪些测试用例拖慢了整体进度,从而针对性地进行优化。
立即学习“Python免费学习笔记(深入)”;

def pytest_terminal_summary(terminalreporter, exitstatus, config):
slow_threshold = 0.5 # 设定慢速阈值为0.5秒
slow_tests = []
# 遍历所有通过的测试报告
for rep in terminalreporter.stats.get('passed', []):
node = rep.node
call_dur = node.stash.get('call_duration', 0)
if call_dur > slow_threshold:
slow_tests.append((rep.node.nodeid, call_dur))
if slow_tests:
terminalreporter.write_sep("=", "SLOW TESTS")
for nodeid, duration in slow_tests:
terminalreporter.write_line(f"{nodeid}: {duration:.4f}s")
基于程序中某个输入、条件或结果的具体问题
当测试用例中包含参数化数据(@pytest.mark.parametrize)时,每个参数组合都会生成一个独立的节点ID。上述代码能够准确统计每一个参数化变体的耗时,因为 pytest_runtest_makereport 会为每个具体的测试实例触发一次。这意味着即使同一个函数被多次调用,只要输入不同,就能得到精确到每个变体的耗时统计,无需额外处理参数映射。


















