遇到的问题:使用playwright框架编写UI自动化脚本运行报错,显示的报错信息是
test_add_ht_template.py::TestAddHtTemplate::test_add_ht_template[共建类-产品购销-其他]
INTERNALERROR> Traceback (most recent call last):
INTERNALERROR> File "D:\lib\site-packages\_pytest\main.py", line 269, in wrap_session
INTERNALERROR> session.exitstatus = doit(config, session) or 0
INTERNALERROR> File "D:\lib\site-packages\_pytest\main.py", line 323, in _main
INTERNALERROR> config.hook.pytest_runtestloop(session=session)
INTERNALERROR> File "D:\lib\site-packages\pluggy\hooks.py", line 286, in __call__
INTERNALERROR> return self._hookexec(self, self.get_hookimpls(), kwargs)
INTERNALERROR> File "D:\lib\site-packages\pluggy\manager.py", line 93, in _hookexec
INTERNALERROR> return self._inner_hookexec(hook, methods, kwargs)
INTERNALERROR> File "D:\lib\site-packages\pluggy\manager.py", line 84, in <lambda>
INTERNALERROR> self._inner_hookexec = lambda hook, methods, kwargs: hook.multicall(
INTERNALERROR> File "D:\lib\site-packages\pluggy\callers.py", line 208, in _multicall
INTERNALERROR> return outcome.get_result()
INTERNALERROR> File "D:\lib\site-packages\pluggy\callers.py", line 80, in get_result
INTERNALERROR> raise ex[1].with_traceback(ex[2])
INTERNALERROR> File "D:\lib\site-packages\pluggy\callers.py", line 187, in _multicall
INTERNALERROR> res = hook_impl.function(*args)
INTERNALERROR> File "D:\lib\site-packages\_pytest\main.py", line 348, in pytest_runtestloop
INTERNALERROR> item.config.hook.pytest_runtest_protocol(item=item, nextitem=nextitem)
INTERNALERROR> File "D:\lib\site-packages\pluggy\hooks.py", line 286, in __call__
INTERNALERROR> return self._hookexec(self, self.get_hookimpls(), kwargs)
INTERNALERROR> File "D:\lib\site-packages\pluggy\manager.py", line 93, in _hookexec
INTERNALERROR> return self._inner_hookexec(hook, methods, kwargs)
INTERNALERROR> File "D:\lib\site-packages\pluggy\manager.py", line 84, in <lambda>
INTERNALERROR> self._inner_hookexec = lambda hook, methods, kwargs: hook.multicall(
INTERNALERROR> File "D:\lib\site-packages\pluggy\callers.py", line 208, in _multicall
INTERNALERROR> return outcome.get_result()
INTERNALERROR> File "D:\lib\site-packages\pluggy\callers.py", line 80, in get_result
INTERNALERROR> raise ex[1].with_traceback(ex[2])
INTERNALERROR> File "D:\lib\site-packages\pluggy\callers.py", line 187, in _multicall
INTERNALERROR> res = hook_impl.function(*args)
INTERNALERROR> File "D:\lib\site-packages\_pytest\runner.py", line 109, in pytest_runtest_protocol
INTERNALERROR> runtestprotocol(item, nextitem=nextitem)
INTERNALERROR> File "D:\lib\site-packages\_pytest\runner.py", line 120, in runtestprotocol
INTERNALERROR> rep = call_and_report(item, "setup", log)
INTERNALERROR> File "D:\lib\site-packages\_pytest\runner.py", line 217, in call_and_report
INTERNALERROR> report: TestReport = hook.pytest_runtest_makereport(item=item, call=call)
INTERNALERROR> File "D:\lib\site-packages\pluggy\hooks.py", line 286, in __call__
INTERNALERROR> return self._hookexec(self, self.get_hookimpls(), kwargs)
INTERNALERROR> File "D:\lib\site-packages\pluggy\manager.py", line 93, in _hookexec
INTERNALERROR> return self._inner_hookexec(hook, methods, kwargs)
INTERNALERROR> File "D:\lib\site-packages\pluggy\manager.py", line 84, in <lambda>
INTERNALERROR> self._inner_hookexec = lambda hook, methods, kwargs: hook.multicall(
INTERNALERROR> File "D:\lib\site-packages\pluggy\callers.py", line 203, in _multicall
INTERNALERROR> gen.send(outcome)
2024-02-23 17:10:55 logger.py INTERNALERROR> File "C:\Users\Administrator\Desktop\playweight-test\playwright-ss\conftest.py", line 48, in pytest_runtest_makereport
INTERNALERROR> img_base64 = capture_screenshots(item.function.__doc__)
| ERROR | 测试用例执行失败,测试用例描述为===========>
INTERNALERROR> File "C:\Users\Administrator\Desktop\playweight-test\playwright-ss\conftest.py", line 95, in capture_screenshots
新增模板验证
:return:
INTERNALERROR> img_bytes = page.screenshot()
INTERNALERROR> NameError: name 'page' is not defined
============================ no tests ran in 2.32s ============================
进程已结束,退出代码3
```python
求助这个问题的解决方法
错误涉及的源码:
```python
import base64
from playwright.sync_api import sync_playwright
from py.xml import html
import pytest
from utils import Fake, logging, highlight_element
from config import Config, MsgResult
CONFIG = Config()
global page
@pytest.fixture(autouse=True, scope='session')
def bp():
"""
实例化浏览器驱动,进行系统登录操作
:return: 实例化页面
"""
with sync_playwright() as driver:
browser = driver.chromium.launch(**CONFIG.LAUNCH_INFO)
context = browser.new_context(no_viewport=True)
global page
page = context.new_page()
logging.debug(page)
page.set_default_timeout(30000)
yield page
@pytest.fixture(autouse=True, scope='session')
def mock():
return Fake()
@pytest.mark.hookwrapper
def pytest_runtest_makereport(item):
"""
用于向测试用例中添加用例的开始时间、内部注释,和失败截图等.
:param item:执行用例
"""
pytest_html = item.config.pluginmanager.getplugin('html')
outcome = yield
report = outcome.get_result()
report.description = description_html(item.function.__doc__)
extra = getattr(report, 'extra', [])
if report.when == 'call' or report.when == "setup":
xfail = hasattr(report, 'wasxfail')
if (report.skipped and xfail) or (report.failed and not xfail):
img_base64 = capture_screenshots(item.function.__doc__)
html = """<div><img src="data:image/png;base64,%s" alt="screenshot" style="width:304px;height:228px;"
onclick="const img = new Image()
img.src = 'data:image/png;base64,%s'
const newWin = window.open('', '_blank')
newWin.document.write(img.outerHTML)
newWin.document.close()"
align="right"/></div>""" % (img_base64, img_base64)
extra.append(pytest_html.extras.html(html))
report.extra = extra
def description_html(desc):
"""
将用例中的描述转成HTML对象
:param desc: 描述
:return:
"""
if desc is None:
return "没有描述信息!"
desc_ = ""
for i in range(len(desc)):
if i == 0:
pass
elif desc[i] == '\n':
desc_ = desc_ + ";"
else:
desc_ = desc_ + desc[i]
desc_lines = desc_.split(";")
desc_html = html.html(
html.head(
html.meta(name="Content-Type", value="text/html; charset=latin1")),
html.body(
[html.p(line) for line in desc_lines]))
return desc_html
def capture_screenshots(failed_case):
"""
配置用例失败截图路径
:return:
"""
logging.error(f'测试用例执行失败,测试用例描述为===========>{failed_case}')
if CONFIG.REPORT_PATH is None:
raise NameError('没有初始化测试报告目录')
else:
img_bytes = page.screenshot()
return str(base64.b64encode(img_bytes), 'utf-8')
def pytest_html_results_table_header(cells):
cells.insert(2, html.th('description'))
cells.pop()
# 设置用例描述表格
def pytest_html_results_table_row(report, cells):
cells.insert(2, html.td(report.description))
cells.pop()
def pytest_collection_modifyitems(items):
"""
测试用例收集完成时,将收集到的item的name和nodeid的中文显示在控制台上
:return:
"""
for item in items:
item.name = item.name.encode("utf-8").decode("unicode_escape")
item._nodeid = item.nodeid.encode("utf-8").decode("unicode_escape")