测试失败时自动截图并附加到 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
相关推荐
lhbian19 分钟前
AI编程革命:Codex让脚本开发提速10倍
开发语言·汇编·jvm·c#
jiayong2320 分钟前
第 36 课:任务详情抽屉快捷改状态
开发语言·前端·javascript·vue.js·学习
FFF_6345602325 分钟前
通用 vue 页面 js 下载任何文件的方法
开发语言·前端·javascript
阿奇__32 分钟前
uniapp支付宝 H5 开发踩坑,hash模式下取参要规范!
开发语言·uni-app
eggwyw34 分钟前
PHP搭建开发环境(Windows系统)
开发语言·windows·php
奇牙1 小时前
DeepSeek V4 Agent 开发实战:用 deepseek-v4-pro 搭建多步骤工作流(2026 完整代码)
python
一行代码一行诗++1 小时前
C语言中scanf详解
c语言·开发语言
斯维赤1 小时前
Python学习超简单第八弹:连接Mysql数据库
数据库·python·学习
凤山老林1 小时前
26-Java this 关键字
java·开发语言
ZenosDoron1 小时前
keil软件修改字体,Asm editor,和C/C++ editor的区别
c语言·开发语言·c++