测试失败时自动截图并附加到 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
相关推荐
程序员zgh4 分钟前
C++ erase() 函数用法
c语言·开发语言·c++·学习
lee_tianbai20 分钟前
Java SSM 电影票预定系统|完整前后端项目,开箱即用(源码分享)
java·开发语言·数据库
砚底藏山河35 分钟前
python量化入门:多周期数据对齐统一时间轴
java·数据库·python·金融·maven
迪丽热爱1 小时前
一、C语言概述与程序结构
c语言·开发语言·算法
HUIBUR科技1 小时前
AI中枢:打破数据孤岛与流程孤岛双重困境
开发语言·ai
毕业设计7031 小时前
(免费领源码)django空气净化器销售系统09218- java、PHP、python、C#、小程序、大数据、单片机、网络工程等)
python·scrapy·mysql·pycharm·django·flask·pandas
鱼宵1 小时前
LangChain4j 结构化输出:让模型吐出 Java 对象,JSON 不再手写解析
java·开发语言·json·langchain4j
w2sfot2 小时前
【JS加密在线】jsjiami.online(让JavaScript 更安全!)
开发语言·javascript·安全
小小张说故事2 小时前
Python 闭包到底捕获了啥?一个计数器例子讲透,别再背定义了
python