You need to enable JavaScript to run this app. pytest测试失败时如何在pytest_runtest_teardown钩子中跳过fixture销毁
优惠活动
大模型
产品
解决方案
定价
更多

pytest测试失败时如何在pytest_runtest_teardown钩子中跳过fixture销毁

答案

结论

可以实现,根据你是否需要终止整个测试执行,有两种常用实现方案:

方案1:全局终止所有测试与fixture销毁

适合测试失败后不需要继续执行后续任何用例的场景,直接调用pytest.exit()强制终止进程即可,所有未执行的fixture销毁逻辑、后续测试用例都会直接跳过。
修改后的conftest.py代码如下:

import pytest

@pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_makereport(item, call):
  outcome = yield
  rep = outcome.get_result()
  setattr(item, 'rep_' + rep.when, rep)

def pytest_runtest_teardown(item, nextitem):
  # 判断当前测试用例执行阶段是否失败
  if hasattr(item, 'rep_call') and item.rep_call.failed:
    print('测试用例执行失败,终止所有操作并退出', item.nodeid)
    pytest.exit("测试失败终止执行", returncode=1)

方案2:仅跳过当前失败用例关联的fixture销毁

如果需要继续执行后续其他测试用例,只跳过当前失败用例对应的fixture销毁逻辑,直接清空当前测试节点绑定的销毁回调队列即可。
修改后的conftest.py代码如下:

import pytest

@pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_makereport(item, call):
  outcome = yield
  rep = outcome.get_result()
  setattr(item, 'rep_' + rep.when, rep)

def pytest_runtest_teardown(item, nextitem):
  if hasattr(item, 'rep_call') and item.rep_call.failed:
    print('测试用例执行失败,跳过当前用例关联的fixture销毁', item.nodeid)
    # 清空当前测试绑定的所有fixture销毁回调
    item._finalizers = []
    # 如果需要连会话/模块级的fixture销毁也跳过,可以加下面这行
    # item.session._setupstate._finalizers = []

注意事项

  • 两种方案都会导致fixture的teardown逻辑不执行,如果你的fixture中包含资源释放(比如关闭数据库连接、删除临时文件、停止远程服务等)操作,可能会出现资源泄漏,需要结合业务场景评估风险。
  • 方案1的returncode可以自定义,用于CI/CD pipeline识别测试失败状态。

内容的提问来源于stack exchange,提问作者Daniel Maizel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.21 11:06:06