如何仅在pytest测试出错或失败时才执行fixture的清理操作
实现方案
1. 新增运行结果捕获钩子
首先在项目的conftest.py文件中添加pytest钩子函数,用于捕获测试各阶段的运行结果,方便后续在fixture中读取:
import pytest @pytest.hookimpl(tryfirst=True, hookwrapper=True) def pytest_runtest_makereport(item, call): # 执行所有其他钩子获取测试报告对象 outcome = yield rep = outcome.get_result() # 将各阶段的测试报告存储到测试节点对象中 setattr(item, f"rep_{rep.when}", rep)
2. 改造日志收集fixture
修改你的get_logs fixture,注入pytest内置的request对象,在yield之后读取之前存储的各阶段运行结果,判断是否需要复制日志:
@pytest.fixture def get_logs(request): yield test_failed = False # 判断fixture设置阶段是否出错 if hasattr(request.node, "rep_setup") and request.node.rep_setup.failed: test_failed = True # 判断测试用例本身执行阶段是否失败 if hasattr(request.node, "rep_call") and request.node.rep_call.failed: test_failed = True if test_failed: copy_log_files()
说明
- 该逻辑完全覆盖你需要的两种失败场景:
rep_setup.failed对应fixture设置阶段出错,rep_call.failed对应测试用例本身运行失败 - 只要任意一个阶段出现失败,就会触发
copy_log_files()执行 - 测试正常运行通过的场景下不会执行日志拷贝逻辑
内容的提问来源于stack exchange,提问作者KyleL
相关产品推荐
相关产品推荐

