You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

pytest如何仅在出现错误而非测试失败时终止运行

实现pytest遇错误即终止、遇失败继续执行的方案

核心思路

借助pytest内置的钩子函数pytest_runtest_makereport识别测试结果类型:当检测到环境/配置类错误(Error)时直接终止测试会话;若为测试用例断言失败(Failure),则继续执行后续用例。

具体实现

在项目根目录创建conftest.py文件,添加以下代码:

import pytest
from _pytest.runner import TestReport

def pytest_runtest_makereport(item, call):
    report = TestReport.from_item_and_call(item, call)
    # 区分错误与失败:排除断言失败的情况,仅在其他异常时终止
    if (report.outcome == "failed" 
        and hasattr(report, "excinfo") 
        and report.excinfo.typename != "AssertionError"):
        item.session.shouldstop = "检测到测试错误,终止测试套件"

代码说明

  • report.outcome == "failed":pytest会将错误和失败统一标记为failed,需进一步区分类型
  • report.excinfo.typename != "AssertionError":断言失败属于测试用例本身问题,其他异常(如模块导入失败、数据库连接错误)属于环境/配置错误
  • session.shouldstop:设置该属性后,pytest会在当前测试结束后立即终止整个测试流程

验证示例

编写测试文件test_demo.py:

def test_case_failure():
    assert 1 == 2  # 断言失败,测试会继续执行

def test_env_error():
    import non_existent_module  # 环境错误,触发测试终止

运行pytest命令,会看到test_case_failure执行失败后,test_env_error触发错误,随后整个测试套件立即停止。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 02:52:07