测试失败时自动截图并附加到 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
相关推荐
2601_966949651 分钟前
如何判断盘中最新价相对昨日收盘涨跌幅,并实时触发止盈止损条件单:QuantDash Python 实战
开发语言·python·量化策略·量化·quantdash
下辈子不要当码农8 分钟前
Day7-Linux软件编程(进程与线程(3))
java·开发语言
桃西西呀12 分钟前
刷短视频越刷越窄?SVD 奇异值分解,把 10 万条电影评分拆成你的品味特征
python·数学·数据可视化
大模型码小白20 分钟前
Spring AI 框架中集成 MCP 的完整指南:从服务端到客户端的全流程实践
大数据·运维·数据库·人工智能·python·sql·spring
青 春 记 忆23 分钟前
零基础入门python29:用 pytest 验收完整 Flask 业务流程
python·flask·后端开发
CarIise24 分钟前
JavaScript进阶与轮播图实现 课堂笔记
开发语言·javascript·笔记
mayaairi30 分钟前
JS DOM节点操作完全指南:增删改查与性能优化
开发语言·javascript·性能优化
Demon--hx31 分钟前
多态实现原理
开发语言·c++
wanglei20070834 分钟前
消息队列的协作模式
开发语言·python
三十岁老牛再出发43 分钟前
8月25-26日总结
python·pandas