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

Python Playwright搭配Pytest能否设置全局脚本超时及实现方法?

Python Playwright + Pytest 全局超时配置实现方案

完全可行,以下是对应你JS版本各项超时配置的具体实现方法:

1. 全局测试用例超时(对应JS配置中的timeout)

控制单个测试用例的最大运行时长,推荐通过pytest.ini配置:

  • 在项目根目录创建或修改pytest.ini文件,添加:
[pytest]
timeout = 900  # 单位:秒,对应你JS里的900*1000毫秒

如果你的环境没装pytest-timeout插件,先执行pip install pytest-timeout完成依赖安装。

2. 全局Expect断言超时(对应JS配置中的expect.timeout)

控制expect(locator).toHave_text()这类断言的等待时长,有两种简单实现方式:

方式一:自动生效的全局Fixture

在项目根目录的conftest.py中添加以下代码,所有测试用例会自动应用这个超时设置:

import pytest
from playwright.sync_api import expect

@pytest.fixture(autouse=True)
def set_global_expect_timeout():
    # 设置断言超时为30秒,单位:毫秒
    expect.set_default_timeout(30000)

方式二:结合上下文配置额外超时

如果需要同时配置页面导航、加载这类全局超时,可以在conftest.py中扩展browser上下文的fixture:

import pytest
from playwright.sync_api import BrowserContext, expect

@pytest.fixture(scope="session")
def context(browser):
    # 创建上下文时配置导航、加载超时
    context: BrowserContext = browser.new_context(
        navigation_timeout=60000,  # 页面导航超时,单位:毫秒
        page_load_timeout=60000    # 页面加载超时,单位:毫秒
    )
    # 全局设置断言超时
    expect.set_default_timeout(30000)
    yield context
    context.close()

3. 其他可选全局超时

  • 元素等待超时:locator.wait_for()这类方法默认会复用expect的全局超时,无需额外配置
  • 浏览器启动超时:在pytest.ini中添加playwright_browser_start_timeout=60000(单位:毫秒)即可控制浏览器启动的最长等待时间

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.11 12:43:13