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

Pytest无法识别自定义命令行选项--browser_name问题排查

解决pytest无法识别自定义命令行选项--browser_name的问题

问题描述

我在conftest.py中添加了以下代码:

import pytest
from selenium import webdriver


def pytest_addoption(parser):
    parser.addoption(
        "--browser_name", action="store", default="chrome"
    )


@pytest.fixture(scope="class")
def setup(request):
    browser_name = request.config.getoption("--browser_name")
    if browser_name == "chrome":
        driver = webdriver.Chrome()
    elif browser_name == "firefox":
        driver = webdriver.Firefox()
    elif browser_name == "Edge":
        driver = webdriver.Edge()
    driver.get("https://rahulshettyacademy.com/angularpractice/")
    driver.maximize_window()
    request.cls.driver = driver
    yield
    driver.close()

执行命令pytest --browser_name firefox时,pytest报错无法识别该选项:

ERROR: usage: pytest [options] [file_or_dir] [file_or_dir] [...]
pytest: error: unrecognized arguments: --browser_name
  inifile: None
  rootdir: /home/*****/PycharmProjects/SeleniumFramework

可能的原因及解决办法

  • conftest.py位置不正确
    pytest只会自动加载测试根目录下的conftest.py文件。确认该文件是否放在报错信息里显示的rootdir路径(/home/*****/PycharmProjects/SeleniumFramework)下,而非子文件夹中。如果放在子目录,pytest无法读取其中的pytest_addoption配置,自然识别不了自定义选项。

  • 环境或pytest版本不匹配
    检查当前执行pytest的环境是否和编写代码的环境一致。比如使用虚拟环境时,可能误激活了其他环境,导致pytest加载不到项目里的conftest.py。可以执行which pytest(Linux/macOS)或where pytest(Windows)查看当前pytest的路径,确认是否属于项目对应的虚拟环境。

  • 命令执行路径错误
    确保你是在conftest.py所在的目录下执行pytest命令,或者执行时明确指定了正确的测试目录/文件。如果在子目录里跑命令,pytest可能找不到根目录下的conftest.py。

  • 选项名称拼写不一致
    检查命令中的--browser_name和代码里定义的选项名称是否完全一致,包括下划线、大小写。比如别把命令写成--browser-name或者--Browser_Name。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 02:10:39