如何在py.test执行完毕后获取所有TestReport对象列表?
当然可以实现!在pytest里,你可以通过组合几个钩子函数,在conftest.py中轻松完成这个需求。下面给你两种实用的方案,按需选择:
方案一:直接通过会话对象获取完整测试集合与结果
pytest_sessionfinish钩子会在整个测试会话结束前触发,此时你可以从会话对象中拿到所有测试用例的信息,再结合缓存的测试报告获取结果:
def pytest_sessionfinish(session, exitstatus): # 遍历所有被收集到的测试用例 print("所有测试用例列表:") for item in session.items: # item.nodeid 是测试用例的唯一标识(比如模块名::测试函数名) print(f"- {item.nodeid}") # 获取每个测试用例的详细报告(结合pytest缓存) print("\n所有测试用例的执行结果:") for item in session.items: # 从缓存中取出之前生成的测试报告 report = session.config.cache.get(f"pytest_report_{item.nodeid}", None) if report: status = report.outcome duration = report.duration print(f"- {item.nodeid}: {status} (耗时: {duration:.2f}s)") if status == "failed": print(f" 失败详情: {report.longreprtext}")
方案二:自定义收集所有TestReport对象
这种方式更灵活,你可以在每个测试生成报告时就保存下来,最后在会话结束时统一处理:
# 定义一个全局列表,用来存储所有测试的报告和对应测试ID all_test_reports = [] def pytest_runtest_makereport(item, call): # 获取当前测试的TestReport对象 report = call.get_result() # 将测试ID和报告存入列表 all_test_reports.append((item.nodeid, report)) return report def pytest_sessionfinish(session, exitstatus): # 此时all_test_reports中已包含所有测试的完整报告 print("\n完整测试报告汇总:") for test_id, report in all_test_reports: print(f"测试ID: {test_id}") print(f"执行状态: {report.outcome}") print(f"执行耗时: {report.duration:.2f}s") if report.skipped: print(f"跳过原因: {report.wasxfail if report.wasxfail else report.longreprtext}") elif report.failed: print(f"失败详情:\n{report.longreprtext}") print("-" * 50)
补充说明:
- 方案二中的
report是标准的pytest.TestReport实例,包含了你需要的所有核心信息:执行状态、耗时、失败/跳过原因等。 - 如果不需要缓存,方案二更直接,能确保拿到每个测试的完整报告。
session.items会包含所有被pytest收集到的测试用例,哪怕是被跳过或者标记为xfail的用例也会在列。
内容的提问来源于stack exchange,提问作者Alex
相关产品推荐
相关产品推荐

