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

Pytest如何在发生Selenium异常时条件性提前终止全量测试套件运行

实现方案

你可以直接通过pytest内置钩子实现你设想的逻辑,只需要在项目根目录的conftest.py文件中添加如下代码即可:

import pytest
from selenium.common.exceptions import WebDriverException

def pytest_runtest_makereport(item, call):
    # 覆盖测试准备、测试执行两个阶段的异常,按需可调整
    if call.excinfo is not None and call.when in ("setup", "call"):
        # 判断是否为Selenium核心异常
        if isinstance(call.excinfo.value, WebDriverException):
            err_msg = str(call.excinfo.value)
            print(f"\n检测到Selenium环境异常:{err_msg},立即终止全量测试")
            # 直接终止整个测试套件运行
            pytest.exit(f"Selenium异常终止:{err_msg}", returncode=1)

逻辑说明

  • pytest_runtest_makereport是pytest官方提供的原生钩子,每个测试用例执行的各个阶段(准备、执行、清理)完成后都会触发
  • 所有Selenium运行时异常(包括Chrome不可达、会话丢失、实例初始化失败等)都是WebDriverException的子类,用isinstance判断可以覆盖所有你提到的错误场景
  • pytest.exit()会直接终止整个测试进程,不会继续执行后续未跑的测试用例,完全符合你的需求

自定义扩展

如果需要过滤掉业务层面的Selenium异常(比如元素找不到、元素不可点击这类用例逻辑错误),只保留环境级错误触发终止,可以在判断条件中增加异常信息关键词匹配:

# 示例:只在异常信息包含以下关键词时才终止测试
CRITICAL_ERR_KEYWORDS = {"chrome not reachable", "session deleted", "failed to start chrome", "connection refused"}
if isinstance(call.excinfo.value, WebDriverException):
    err_msg = str(call.excinfo.value).lower()
    if any(keyword in err_msg for keyword in CRITICAL_ERR_KEYWORDS):
        pytest.exit(f"Selenium环境异常终止:{err_msg}", returncode=1)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 04:54:05