测试失败时自动截图并附加到 Allure 报告

在测试失败时自动截图并附加到 Allure 报告中,需要在 conftest.py 文件中添加以下代码:

python 复制代码
import allure
import pytest
from selenium import webdriver

@pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_makereport(item, call):
    outcome = yield
    rep = outcome.get_result()
    # 仅在测试失败时处理
    if rep.when == "call" and rep.failed:
        # 获取 fixture 中的 driver 对象
        driver = item.funcargs.get("driver")
        if driver:
            # 截图并附加到 allure 报告中
            screenshot = driver.get_screenshot_as_png()
            allure.attach(screenshot, name="失败截图", attachment_type=allure.attachment_type.PNG)

代码可以直接复制使用

运行测试并生成报告

直接在命令行运行:

python 复制代码
pytest tests/ --alluredir=allure-results --clean-alluredir

然后生成并打开报告:

python 复制代码
allure generate allure-results -o allure-report --clean
allure open allure-report
相关推荐
黄贵根2 小时前
JavaScript实现教培行业意向登记系统
开发语言·javascript·ecmascript
小趴蔡ha4 小时前
02 Anaconda、Python 与机器学习开发环境入门
python·机器学习·anaconda
2401_868534785 小时前
RTOS之RT-Thread & Linux:线程/进程管理与调度核心差异分析
c++·python
zzzll11115 小时前
Claude Code离线安装方案揭秘
开发语言·php
数字化转型分享点滴5 小时前
富士康、蓝思科技为何选择四化信息?MES制造执行系统的实践
python·科技
wling03015 小时前
vasp虚频计算-python脚本
开发语言·windows·python·vasp计算
魔镜前的帅比6 小时前
(开源项目)x-claw(总)
python·ai·rust·开源
郝学胜-神的一滴6 小时前
Qt 高级编程 040:按钮悬浮弹出滑块弹窗的完整攻略
开发语言·c++·qt·软件工程·用户界面
xrandzj6 小时前
Python面向对象编程入门:类、实例、初始化与封装实践
开发语言·python
DLYSB_7 小时前
API 网关流量洪峰与突发 CC 攻击:我用 Go 写了个“现场物理防御哨兵”,把故障响应压缩到秒级
开发语言·后端·golang·报警灯