在自动化测试场景中,用例失败时自动保存截图和日志能大幅降低问题复现和排查的成本,pytest结合pytest-selenium可以很方便地实现这个需求,核心是利用pytest提供的钩子函数捕获用例执行状态,在用例失败时触发截图和日志保存逻辑。

环境准备
首先需要安装相关依赖,确保本地已经配置好Python环境,执行以下命令安装所需库:
pip install pytest pytest-selenium selenium
如果是Chrome浏览器,还需要下载对应版本的ChromeDriver,放到系统环境变量可访问的路径中。
核心实现逻辑
pytest提供了pytest_runtest_makereport钩子,这个钩子会在每个测试用例执行完成后被调用,我们可以在这个钩子中判断用例的执行结果,当结果为失败时,调用selenium的截图方法保存页面截图,同时将用例的相关信息写入日志文件。
编写钩子函数
在项目根目录创建conftest.py文件,这个文件会被pytest自动识别加载,在文件中添加以下代码:
import pytest
import os
from datetime import datetime
# 定义截图和日志的存储目录
SCREENSHOT_DIR = "screenshots"
LOG_DIR = "logs"
# 确保目录存在
os.makedirs(SCREENSHOT_DIR, exist_ok=True)
os.makedirs(LOG_DIR, exist_ok=True)
@pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_makereport(item, call):
# 获取用例执行结果
outcome = yield
report = outcome.get_result()
# 判断用例是否失败,且是测试执行阶段的失败
if report.when == "call" and report.failed:
# 获取selenium的driver实例,pytest-selenium会将driver注入到item的funcargs中
driver = item.funcargs.get("driver")
if driver:
# 生成带时间戳的文件名
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
test_name = item.name
# 保存截图
screenshot_path = os.path.join(SCREENSHOT_DIR, f"{test_name}_{timestamp}.png")
driver.save_screenshot(screenshot_path)
# 保存日志
log_path = os.path.join(LOG_DIR, f"{test_name}_{timestamp}.log")
with open(log_path, "w", encoding="utf-8") as f:
f.write(f"用例名称: {test_name}n")
f.write(f"执行时间: {timestamp}n")
f.write(f"失败原因: {report.longreprtext}n")
f.write(f"截图路径: {screenshot_path}n")
编写测试用例
接下来编写使用pytest-selenium的测试用例,验证失败自动保存功能,创建test_demo.py文件:
import pytest
def test_success(driver):
# 访问测试页面
driver.get("https://ipipp.com")
# 断言页面标题包含指定内容,正常情况会通过
assert "ipipp" in driver.title
def test_fail(driver):
# 访问测试页面
driver.get("https://ipipp.com")
# 断言一个不存在的内容,触发用例失败
assert "不存在的内容" in driver.title
执行测试验证效果
在命令行中执行以下命令运行测试:
pytest test_demo.py -v
执行完成后,可以看到screenshots目录下生成了失败用例的截图文件,logs目录下生成了对应的日志文件,日志中包含了用例名称、执行时间、失败原因和截图路径,方便后续排查问题。
注意事项
- 钩子函数中的
report.when需要判断为call,避免用例在setup阶段失败时也触发截图,当然也可以根据需求调整这个判断逻辑。 - 如果项目中使用了自定义的driver fixture,需要确保driver实例能被正确获取到,上述代码中是通过
item.funcargs.get("driver")获取,符合pytest-selenium的默认注入规则。 - 截图和日志的存储路径可以根据项目需求调整,也可以加入更多自定义信息,比如测试环境、测试人员等。
pytestpytest-seleniumselenium自动化测试用例失败截图修改时间:2026-06-18 04:39:44