pytest 截图功能

pytest 中,将截图功能放在 conftest.py 中实现并将截图添加到测试报告中是一种常见的做法。这样可以确保在任何测试失败时自动执行截图操作,同时将截图信息添加到测试报告中,以便于后续查看和分析。

以下是详细步骤和代码示例,说明如何在 conftest.py 中实现截图功能,并将截图添加到测试报告中。

步骤:

  1. conftest.py 中实现截图功能

    • 使用 pytest 的钩子函数 pytest_runtest_makereport 来判断测试是否失败。
    • 如果测试失败,通过 Selenium 的 driver.save_screenshot() 方法进行截图。
    • 使用 allure 插件将截图添加到测试报告中。
  2. 配置文件 pytest.ini

    • 配置 pytest 插件、测试报告输出路径等。

代码示例:

1. conftest.py 文件实现
python 复制代码
import pytest
import os
import time
from selenium import webdriver
import allure

# 配置截图保存路径
SCREENSHOT_DIR = './screenshots/'
if not os.path.exists(SCREENSHOT_DIR):
    os.makedirs(SCREENSHOT_DIR)

# 设置 WebDriver
@pytest.fixture(scope='function')
def driver():
    # 启动浏览器
    driver = webdriver.Chrome()
    yield driver
    driver.quit()

# 截图函数
def take_screenshot(driver, test_name):
    """将截图保存到指定路径"""
    screenshot_path = os.path.join(SCREENSHOT_DIR, f"{test_name}_{int(time.time())}.png")
    driver.save_screenshot(screenshot_path)
    return screenshot_path

# 监听测试报告,并在失败时截图
def pytest_runtest_makereport(item, call):
    """在测试失败时执行截图"""
    if call.when == 'call' and call.excinfo is not None:
        # 获取测试名称
        test_name = item.name
        driver = item.funcargs.get('driver')  # 获取 driver 实例
        if driver:
            # 获取截图路径
            screenshot_path = take_screenshot(driver, test_name)
            # 将截图添加到 Allure 报告
            allure.attach.file(screenshot_path, name="Screenshot", attachment_type=allure.attachment_type.PNG)
            print(f"截图已保存到: {screenshot_path}")
2. pytest.ini 配置文件

确保你的项目根目录下有一个 pytest.ini 文件,并包含以下配置来启用 Allure 报告功能。

复制代码
[pytest]
# 指定 Allure 的输出目录
alluredir = allure_results
3. 示例测试代码

test_example.py 中编写一个简单的测试,故意让其失败,从而触发截图功能。

python 复制代码
def test_example(driver):
    driver.get("https://www.google.com")
    assert driver.title == "Incorrect Title"  # 故意断言失败,触发截图
4. 运行测试
  1. 运行测试 : 使用 pytest 运行测试,测试失败时截图将会自动保存到 ./screenshots/ 目录,同时 Allure 报告中会包含截图信息。

    bash 复制代码
    pytest --alluredir=allure_results
  2. 生成 Allure 报告: 使用 Allure 生成并查看测试报告:

    bash 复制代码
    allure serve allure_results

说明:

  • pytest_runtest_makereport 钩子函数:用于在每个测试执行后生成报告。此函数判断测试是否失败,如果失败则触发截图保存操作。
  • take_screenshot(driver, test_name):此函数负责将失败的测试截图保存到指定目录。
  • allure.attach.file:此方法将截图添加到 Allure 报告中,确保每次测试失败时,可以在报告中查看到截图。
  • pytest.ini 配置:配置了 Allure 报告的输出目录,确保可以正确生成报告。

优点:

  • 集中化管理 :将截图和报告逻辑放在 conftest.py 中,避免了在每个测试中重复编写截图逻辑。
  • 增强可维护性 :如果需要更改截图的路径或其他相关逻辑,只需修改 conftest.py 中的内容,所有测试都会自动使用最新的配置。
  • 测试报告完备:将截图直接添加到 Allure 等测试报告中,有助于问题的快速定位和修复。

扩展:

  • 你还可以根据需要调整截图保存的路径或在 pytest_runtest_makereport 中添加更多的截图细节(例如页面 HTML、浏览器控制台日志等),以便更好地帮助调试。
相关推荐
SomeB1oody4 分钟前
【Rust中级教程】2.7. API设计原则之灵活性(flexible) Pt.3:借用 vs. 拥有、`Cow`类型、可失败和阻塞的析构函数及解决办法
开发语言·后端·性能优化·rust
java1234_小锋6 分钟前
一周学会Flask3 Python Web开发-flask3上下文全局变量session,g和current_app
python·flask·flask3
larance13 分钟前
Flask 发送邮件
后端·python·flask
m0_7482402515 分钟前
python轻量级框架-flask
开发语言·python·flask
论迹27 分钟前
【JavaEE】-- 多线程(初阶)2
java·开发语言·java-ee
pk_xz12345628 分钟前
基于Python和Neo4j开发的医疗辅助诊断系统的详细实现步骤和代码示例
python·oracle·neo4j
+72037 分钟前
如何在java中用httpclient实现rpc post 请求
java·开发语言·rpc
学习两年半的Javaer1 小时前
Rust语言基础知识详解【一】
开发语言·rust
PyAIGCMaster1 小时前
50周学习go语言:第四周 函数与错误处理深度解析
开发语言·学习·golang
全栈开发圈1 小时前
新书速览|Rust汽车电子开发实践
开发语言·rust·汽车