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

如何在pytest终端会话头部显示Playwright浏览器名称?

解决方法

因为pytest_report_header属于会话级钩子,执行时机早于fixture初始化,所以无法直接在钩子中调用browser_name fixture。可以通过读取命令行参数或Playwright配置的方式获取浏览器信息,添加到报告头部。

方法一:从命令行参数提取

在项目的conftest.py中添加以下代码:

def pytest_report_header(config):
    # 获取命令行指定的浏览器通道
    browser_channel = config.getoption("--browser-channel")
    # 获取指定的浏览器类型(如未指定则默认chromium)
    browser = config.getoption("--browser") or "chromium"
    
    header_content = [f"Browser: {browser}"]
    if browser_channel:
        header_content[0] += f" ({browser_channel})"
    return header_content

运行你的测试命令后,报告头部会新增浏览器信息,类似:

============================ test session starts =============================
platform linux -- Python 3.12.6, pytest-8.3.3, pluggy-1.5.0
Browser: chromium (chrome)
rootdir: /tests
plugins: base-url-2.1.0, playwright-0.5.2
collected 1 item

tests/test_example.py . [100%]

============================= 1 passed in 0.02s ==============================

方法二:兼容Playwright配置文件

如果你的浏览器配置写在playwright.config.py中,可以同时读取配置文件和命令行参数,优先使用命令行指定的值:

from playwright.config import PlaywrightConfig

def pytest_report_header(config):
    # 读取Playwright配置文件
    try:
        pw_config = PlaywrightConfig.from_file("playwright.config.py")
        default_browser = pw_config.browser_type or "chromium"
        default_channel = pw_config.channel
    except FileNotFoundError:
        default_browser = "chromium"
        default_channel = None

    # 命令行参数优先
    browser = config.getoption("--browser") or default_browser
    browser_channel = config.getoption("--browser-channel") or default_channel

    header_content = [f"Browser: {browser}"]
    if browser_channel:
        header_content[0] += f" ({browser_channel})"
    return header_content

这样不管是通过命令行指定还是配置文件设置,都能正确显示当前使用的浏览器信息。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 16:22:11