测试失败时自动截图并附加到 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
相关推荐
用户83562907805114 小时前
Python 实现 PDF 文件加密与解密方法
后端·python
用户83562907805115 小时前
使用 Python 冻结与拆分 Excel 窗格教程
后端·python
你好潘先生1 天前
别再记命令了,用 yeero do 说句人话就能跑脚本,而且不烧 token
服务器·python·命令行
Agent_大师1 天前
WebSocket 行情重连成功,K线缺口不会自动消失
python
荣码1 天前
LLM结构化输出:让AI返回JSON而不是废话,我踩了4个坑
java·python
copyer_xyf1 天前
FastAPI 如何连接 MySQL
后端·python
apocelipes2 天前
常用编程语言和库的正则表达式性能对比
c语言·c++·python·性能优化·golang·开发工具和环境
用户8356290780512 天前
使用 Python 在 PDF 中创建与管理书签
后端·python
MeixianAgent2 天前
Python 回测数据入口怎么验?历史 K 线入库前先做 5 个检查
后端·python
咕白m6252 天前
用 Python 实现一键批量查找与替换 Excel 数据
后端·python