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

pytest-selenium测试失败时pytest_selenium_capture_debug钩子未触发

pytest_selenium_capture_debug钩子不生效解决方案

1. 确认钩子函数签名完全匹配

pytest-selenium 2.0.1版本要求pytest_selenium_capture_debug钩子的参数必须严格为item、report、driver三个,缺少或多写参数都会导致钩子无法被触发,正确的函数定义格式如下:

import os
import shutil

def pytest_selenium_capture_debug(item, report, driver):
    # 仅在测试失败时处理
    if report.failed:
        # 替换为你容器内xvfb录制视频的实际存储路径
        container_video_path = "/tmp/xvfb_recording.mp4"
        # 替换为容器内挂载的宿主机目录路径
        host_mount_path = "/test_failure_artifacts"
        
        if os.path.exists(container_video_path):
            # 用测试用例名命名避免文件覆盖
            save_file_name = f"{item.originalname}_fail_recording.mp4"
            shutil.copy2(container_video_path, os.path.join(host_mount_path, save_file_name))

2. 开启调试捕获开关

该钩子默认不会触发,必须手动开启捕获配置,二选一即可:

  • 运行pytest命令时追加参数:pytest --selenium-capture-debug=failure
  • 在项目根目录的pytest.ini中添加全局配置:
[pytest]
selenium_capture_debug = failure

可选值包括always(无论结果都触发)、failure(仅失败时触发)、never(不触发)。

3. 确认conftest.py被正常加载

  • 确认conftest.py放在pytest运行的工作根目录下,不要放到子测试目录中
  • 可以在conftest.py顶部添加print("conftest loaded"),运行pytest时观察控制台是否有对应输出,确认文件被加载
  • 排查是否存在其他嵌套的conftest.py文件覆盖了钩子定义

4. 确认Docker挂载配置正确

要将容器内的视频导出到宿主机,必须在启动容器时配置目录挂载,示例命令:

docker run -v /宿主机/本地保存路径:/test_failure_artifacts 你的镜像名 测试启动命令

同时要确保容器内运行测试的用户对挂载的/test_failure_artifacts目录有写入权限,对录制的视频文件有读取权限。

5. 排查插件冲突

运行pytest -vv查看控制台输出的钩子注册信息,确认pytest_selenium_capture_debug已被正常注册,没有被其他第三方插件覆盖。如果存在冲突,可以用-p no:插件名临时禁用冲突插件测试。


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

相关产品推荐
方舟 Agent Plan

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

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