如何在pytest-html报告中添加失败用例截图?代码报错求助
解决pytest-html生成报告时添加失败截图出现KeyError: 'request'的问题
我来帮你排查下问题所在,顺便给出可行的修正方案:
问题根源
你遇到的KeyError: 'request',是因为在pytest_runtest_makereport钩子函数里错误地尝试从item.funcargs中获取request fixture——request并不是直接存放在funcargs里的,而且你获取driver的路径也绕远了。另外还有几个小问题:
- 测试用例是类中的方法,缺少
self参数,不符合Python类方法的规范 - 截图逻辑是在所有测试的
call阶段都执行,会生成多余的截图,应该只在测试失败时触发 - 没有确保
Screenshots目录存在,直接保存截图可能会抛出文件不存在的错误
修正步骤及代码
1. 修正conftest.py代码
这里调整了driver的获取方式、截图触发逻辑,还添加了目录创建的逻辑:
import pytest from datetime import datetime from selenium import webdriver import os @pytest.hookimpl(hookwrapper=True) def pytest_runtest_makereport(item, call): timestamp = datetime.now().strftime('%H-%M-%S') pytest_html = item.config.pluginmanager.getplugin('html') outcome = yield report = outcome.get_result() extra = getattr(report, 'extra', []) # 只在测试失败时执行截图逻辑 if report.when == 'call' and report.failed: # 正确获取request对象 request = item.request # 获取你的setup fixture返回的driver driver = request.getfixturevalue('setup') # 确保Screenshots目录存在 screenshot_dir = 'Screenshots' if not os.path.exists(screenshot_dir): os.makedirs(screenshot_dir) # 保存截图 screenshot_path = f'{screenshot_dir}/scr_{timestamp}.png' driver.save_screenshot(screenshot_path) # 添加截图到报告 extra.append(pytest_html.extras.image(screenshot_path)) # 可以额外添加其他信息,比如测试页面URL extra.append(pytest_html.extras.url(driver.current_url)) # 处理xfail的情况(如果需要的话) xfail = hasattr(report, 'wasxfail') if (report.skipped and xfail) or (report.failed and not xfail): extra.append(pytest_html.extras.html('<div>测试失败额外信息</div>')) report.extra = extra @pytest.fixture(scope='session') def setup(): print('Starting test session') url = 'https://www.google.com/' driver = webdriver.Firefox() driver.get(url) yield driver # 用yield而不是return,方便后续关闭driver # 测试会话结束后关闭浏览器 driver.quit() print('Test session ended')
2. 修正test_google.py代码
类中的测试方法需要添加self参数:
class Test_One(): def test_login(self, setup): print('Opened google') # 模拟测试失败 assert False
修正后的逻辑说明
- 获取driver的正确方式:通过
item.request拿到request对象,再用request.getfixturevalue('setup')获取到你在setupfixture中初始化的driver,这是pytest获取fixture的标准方式 - 按需截图:只有当测试进入
call阶段且失败时,才会执行截图操作,避免生成无用截图 - 目录安全:提前检查并创建
Screenshots目录,防止保存截图时出现文件路径不存在的错误 - 资源清理:把
setupfixture中的return改成yield,这样可以在测试会话结束后自动关闭浏览器,避免资源泄漏
现在运行你的测试,失败的用例就会自动把截图添加到pytest-html的报告里了。
内容的提问来源于stack exchange,提问作者devpreethh
相关产品推荐
相关产品推荐

