测试失败时自动截图并附加到 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
相关推荐
伊布拉西莫几秒前
【流畅的Python】第20章:并发执行器 — 学习笔记
笔记·python·学习
njsgcs3 分钟前
c# solidworks 工程图获得展开视图不在固定面螺纹特征的位置
开发语言·c#·solidworks
IT策士6 分钟前
Redis 从入门到精通:Python 操作 Redis
redis·python·bootstrap
编码者卢布12 分钟前
【Azure AI Search】 searchMode=any 和 searchMode=all 有什么区别?
人工智能·python·flask
Samooyou19 分钟前
大模型微调(Fine Tuning)
人工智能·python·ai·语言模型
qq_85730581921 分钟前
python语法
开发语言·python·算法
AI行业学习35 分钟前
CC-Switch v3.16.1 官方下载 | 安装配置详细教程【2026.6.10】
java·开发语言·vue.js·python·mysql·eclipse·html
早起CaiCai1 小时前
【Pytorch 实践1】手写数字
人工智能·pytorch·python
周杰伦的稻香1 小时前
Go + Redis:本地部署高性能图片主色调提取服务
开发语言·redis·golang
吴梓穆1 小时前
Python 语法基础 函数
开发语言·python