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

如何在pytest中按测试结果保存含测试信息的截图

解决方案

要实现测试失败时自动保存带测试信息和状态的截图,可以通过pytest的测试报告钩子结合fixture来实现,具体步骤如下:

1. 修改测试用例,传递测试标识信息

在测试用例中,将city和id赋值给测试实例的属性,让后续钩子能获取这些信息:

# test_example.py
class TestExample(BaseTest):
    def test_example(self):
        self.city = "paris"
        self.id = "testaccount01"
        # ~~ 测试内容 ~~
        # 示例:模拟测试失败可取消注释下面代码
        # assert 1 == 2

2. 配置conftest.py,添加测试结果监听钩子

利用pytest_runtest_makereport钩子捕获测试执行结果,结合浏览器driver在测试失败时生成指定格式的截图:

# conftest.py
import pytest
from pathlib import Path

# 确保截图目录存在,不存在则自动创建
SCREENSHOT_DIR = Path("../Screenshots")
SCREENSHOT_DIR.mkdir(exist_ok=True)

@pytest.fixture()
def get_browser():
    # 补充你的浏览器初始化逻辑,示例为Chrome
    from selenium import webdriver
    driver = webdriver.Chrome()
    yield driver
    driver.quit()

@pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_makereport(item, call):
    # 获取测试执行结果
    outcome = yield
    report = outcome.get_result()
    
    # 仅在测试执行阶段(call)失败时触发截图
    if report.when == "call" and report.failed:
        # 从测试实例中获取city和id,无值则用默认占位符
        test_instance = item.instance
        city = getattr(test_instance, "city", "unknown_city")
        test_id = getattr(test_instance, "id", "unknown_id")
        status = "fail"
        
        # 获取浏览器driver实例
        driver = item.funcargs.get("get_browser")
        if driver:
            # 生成指定格式的截图文件名
            screenshot_name = f"{city}_{test_id}_{status}.png"
            screenshot_path = SCREENSHOT_DIR / screenshot_name
            # 保存截图到指定路径
            driver.get_screenshot_as_file(str(screenshot_path))

3. 保持BaseTest类原有结构

BaseTest类无需修改,继续继承并使用get_browser fixture即可:

# BaseTest.py
import pytest

@pytest.mark.usefixtures("get_browser")
class BaseTest:
    pass

关键说明

  • 自动触发截图:无需手动调用截图方法,测试失败时通过钩子自动执行截图逻辑
  • 动态获取测试信息:通过测试实例对象item.instance,读取提前设置的city和id属性
  • 文件名格式控制:严格按照{city}_{id}_fail.png生成失败截图文件名;若需要保存成功状态的截图,只需在钩子中添加report.passed的判断分支,将status设为pass即可
  • 目录容错处理:用Path模块确保截图目录存在,避免因目录不存在导致截图失败

内容的提问来源于stack exchange,提问作者Tiffany Thompson

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 08:59:20