smile baby 2024-02-23 17:33 采纳率: 0%
浏览 11

使用playwright框架编写UI自动化脚本运行报错 NameError: name 'page' is not defined

遇到的问题:使用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")

  • 写回答

1条回答 默认 最新

  • 爱喝兽奶的荒天帝 全栈领域新星创作者 2024-02-23 23:15
    关注

    根据报错信息显示,问题出在 capture_screenshots 函数中,报错提示 NameError: name 'page' is not defined,即没有定义变量 page。

    这是因为在 capture_screenshots 函数中,使用了全局变量 page,但是在函数内部并没有直接引用该变量,导致 Python 报错未定义。解决方法是在函数内部添加 global page,以便在函数内部能够访问到该全局变量。修改后的函数如下所示:

    def capture_screenshots(failed_case):
        """
        配置用例失败截图路径
        :return:
        """
        global page  # 添加全局变量声明
        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')
    

    通过添加 global page 声明,可以解决该报错问题。请尝试修改后重新运行代码,看是否问题得到解决。

    如果该回答解决了您的问题,请采纳一下,谢谢!

    评论

报告相同问题?

问题事件

  • 修改了问题 2月23日
  • 创建了问题 2月23日

悬赏问题

  • ¥20 服务器redhat5.8网络问题
  • ¥15 如何利用c++ MFC绘制复杂网络多层图
  • ¥20 要做柴油机燃烧室优化 需要保持压缩比不变 请问怎么用AVL fire ESE软件里面的 compensation volume 来使用补偿体积来保持压缩比不变
  • ¥15 python螺旋图像
  • ¥15 算能的sail库的运用
  • ¥15 'Content-Type': 'application/x-www-form-urlencoded' 请教 这种post请求参数,该如何填写??重点是下面那个冒号啊
  • ¥15 找代写python里的jango设计在线书店
  • ¥15 请教如何关于Msg文件解析
  • ¥200 sqlite3数据库设置用户名和密码
  • ¥15 AutoDL无法使用docker install吗?