playwright 怎么在conftest中设置用例错误截屏python
时间: 2024-10-16 21:20:40 浏览: 64
playwright-python:Playwright测试和自动化库的Python版本
5星 · 资源好评率100%
Playwright是一个用于自动化浏览器测试的库,主要用于Node.js、Python和JavaScript环境中。如果你想在Conftest(Pytest插件文件中常用于组织共享 fixtures 和配置)中设置用例失败时捕获并保存截图,你可以这样做:
首先,确保你安装了`playwright-python`和相关的pytest插件。然后,在`conftest.py`中,你可以创建一个fixture来初始化浏览器,并在遇到错误时自动捕获屏幕截图。
```python
import os
from playwright.sync_api import Playwright, BrowserType
def pytest_configure(config):
# 初始化Playwright实例
config.cache.set('playwright', Playwright())
def pytest_unconfigure(config):
# 关闭Playwright实例
playwright = config.cache.get('playwright')
if playwright is not None:
playwright.close()
def pytest_runtest_protocol(item, nextitem):
# 当测试运行出错时触发
def _take_screenshot_and_report(error):
browser_type = 'chrome' or 'firefox' or 'webkit' # 根据需要选择浏览器类型
with playwright.start_default_context() as context:
browser = context.launch_headlessBrowser(browser_type)
page = browser.new_page()
try:
page.goto(item.location['url'])
error.was_caught = True
except Exception as e:
error.traceback = str(e)
screenshot_path = os.path.join(os.getcwd(), f'screenshots/{item.nodeid}.png')
page.screenshot(path=screenshot_path)
item._html_report.add_failure_info(f"Screenshot saved at {screenshot_path}")
# 如果有error标记,使用自定义处理函数
if 'error_capture_screen' in item.keywords:
item.runtestprotocol = _take_screenshot_and_report
# 使用该标记来启用截图捕获
@pytest.mark.error_capture_screen
def test_failing_case():
# 这里编写可能会失败的测试代码
assert False
```
在这个例子中,我们定义了一个`pytest_runtest_protocol`钩子,它会在测试失败时启动一个新的无头浏览器,尝试访问测试页面,如果出现异常就会捕获当前页面的截图,并将截图路径添加到失败报告中。
阅读全文