You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

playwright-pytest如何设置持久上下文为每个测试用例新建独立标签页

解决方案

你遇到的ScopeMismatch报错核心原因是新版本playwright-pytest内置的browser_context_args fixture默认是function级作用域,无法被更高层级的session级fixture直接调用。以下是可行的实现方案:


核心思路

避开依赖内置的function级browser_context_args fixture,自定义session级的启动参数、浏览器上下文fixture,再封装function级的page fixture实现每个用例独立新标签页。


具体实现代码

1. conftest.py 配置

import pytest
from playwright.sync_api import BrowserType, BrowserContext
from typing import Dict

# 自定义session级启动参数,替代默认function级的browser_type_launch_args
@pytest.fixture(scope="session")
def custom_launch_args(pytestconfig) -> Dict:
    launch_args = {}
    # 可按需读取pytest命令行参数配置启动项
    launch_args["headless"] = pytestconfig.getoption("--headless", default=False)
    launch_args["slow_mo"] = int(pytestconfig.getoption("--slowmo", default=0))
    return launch_args

# session级持久上下文,整个测试周期仅创建一次
@pytest.fixture(scope="session")
def context(
        browser_type: BrowserType,
        custom_launch_args: Dict,
):
    context = browser_type.launch_persistent_context(
        "./foobar",
        **custom_launch_args,
        locale="en_GB",
        viewport={"width": 1920, "height": 1080}
        # 其他上下文参数可直接在此处添加
    )
    yield context
    # 测试全量执行完成后关闭上下文和浏览器
    context.close()

# function级page fixture,每个测试用例自动创建新标签页,用例执行完关闭标签页
@pytest.fixture(scope="function")
def page(context: BrowserContext):
    new_page = context.new_page()
    yield new_page
    new_page.close()

2. 测试类适配

你现有测试类代码无需做任何修改,可直接兼容上述fixture配置,自动实现以下效果:

  • 全量测试仅启动1次浏览器
  • 每个测试用例使用独立的新标签页执行,用例之间页面状态互不影响
  • 测试执行效率和旧版本session级上下文方案一致

扩展优化方案

如果不同测试类需要独立的上下文环境(比如不同的登录态、地域配置),可将context fixture的作用域调整为class级别,浏览器实例仍保持session级仅启动1次,在保证用例隔离性的同时仍能维持较高执行效率。


内容的提问来源于stack exchange,提问作者marklane2001

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 20:24:00