测试失败时自动截图并附加到 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
相关推荐
Csvn2 小时前
条件判断与循环结构详解
python
maxmaxma2 小时前
ROS2机器人少年创客营:Python第二课
c++·python·机器人
智算菩萨2 小时前
【Tkinter】10 Tkinter Listbox 列表框控件深度解析:多选模式、滚动条联动与双向选择器实战
python·ai编程
csbysj20202 小时前
SQL CREATE DATABASE 指令详解
开发语言
我命由我123452 小时前
React - useEffect、useRef、Fragment
开发语言·前端·javascript·react.js·前端框架·ecmascript·js
蓝之静云2 小时前
mapper执行sql报空指针,需要传入参数
数据库·python·sql
未来龙皇小蓝2 小时前
Java安全通信:RSA签名 + AES混合加密详解
java·开发语言·安全·web安全
heimeiyingwang2 小时前
【架构实战】混沌工程:让系统更健壮的实践
开发语言·架构·php
cch89182 小时前
PHP vs C#:语言对比与实战选型
开发语言·c#·php