You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PyTest与Allure:如何在Allure报告中添加失败用例截图

为Allure报告添加测试失败时的截图

嘿,我来帮你搞定把失败截图附加到Allure报告的事儿!首先你得确保已经装了allure-pytest插件(没装的话直接跑pip install allure-pytest就行)。接下来咱们把你的代码补全,实现失败自动截图并附加的逻辑:

完整代码示例

import pytest
from selenium import webdriver
import allure

@pytest.hookimpl(hookwrapper=True, tryfirst=True)
def pytest_runtest_makereport(item, call):
    outcome = yield
    rep = outcome.get_result()
    setattr(item, "rep_" + rep.when, rep)
    return rep

@pytest.fixture(scope="function")
def web_browser(request):
    # 启动浏览器(这里用PhantomJS,你也可以换成Chrome/Firefox等)
    b = webdriver.PhantomJS()
    # 把浏览器实例传给测试用例
    yield b
    # 测试用例执行后的清理操作
    if request.node.rep_call.failed:
        # 获取测试失败时的截图(二进制格式,无需存本地)
        screenshot = b.get_screenshot_as_png()
        # 将截图附加到Allure报告中
        allure.attach(
            screenshot,
            name=f"Failure Screenshot: {request.node.name}",
            attachment_type=allure.attachment_type.PNG
        )
    # 最后关闭浏览器
    b.quit()

关键逻辑解释

  • 截图获取:用b.get_screenshot_as_png()直接拿到截图的二进制数据,不用额外存本地文件,直接传给Allure更高效。
  • Allure附加操作:allure.attach()的三个核心参数:
    • 第一个是截图的二进制内容(也可以传本地文件路径)
    • name是报告里显示的截图名称,加上测试用例名方便快速定位问题
    • attachment_type指定附件格式,这里选PNG适配截图场景

验证方法

运行测试时要指定Allure报告的生成目录:

pytest --alluredir=./allure-results

然后生成并查看报告:

allure serve ./allure-results

失败的测试用例下面就会出现对应的截图附件啦!

内容的提问来源于stack exchange,提问作者Timur Nurlygayanov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:13:45