pytest无法识别命令行传入的--browser、--server自定义参数问题求助
问题原因与修复方案
1. 核心错误:自定义参数钩子函数名错误
pytest规定添加自定义命令行参数必须使用固定钩子函数 pytest_addoption,你当前写的environment_options不会被pytest识别加载,因此你定义的--browser、--server参数完全没有注册,运行时自然会报「无法识别参数」的错误。
2. 次要错误:参数拼写错误
addoption方法里的可选值参数拼写错误,正确写法是choices,你写成了choises,修复钩子名后这个拼写错误也会导致运行报错。
3. 隐藏问题:配置文件未加载
你初始化了configparser.ConfigParser()对象,但没有调用read()方法加载对应的配置文件,直接调用read_config.get()会抛出配置不存在的异常。
修复后的完整conftest.py代码
import pytest import configparser from selenium import webdriver import os # 改为pytest固定钩子名 def pytest_addoption(parser): # 修正choises为choices parser.addoption('--browser', '-B', dest='BROWSER', choices=['chrome', 'chr', 'firefox', 'ff'], help=f"possible values are: {['chrome', 'chr', 'firefox', 'ff']}") parser.addoption('--server', '-S', dest="SERVER") @pytest.fixture(scope='class') def environment_configuration(request): read_config = configparser.ConfigParser() # 新增加载配置文件逻辑,假设配置文件和conftest.py同目录,名为config.ini,可自行修改路径 config_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'config.ini') if os.path.exists(config_path): read_config.read(config_path, encoding='utf-8') # 读取参数逻辑增加fallback默认值,避免配置缺失报错 browser_name = request.config.getoption("BROWSER") or read_config.get("Environments", "browser", fallback="chrome") remote_server = request.config.getoption("SERVER") or read_config.get("Environments", "remote_server", fallback="http://127.0.0.1:4444/wd/hub") try: request.cls.driver = webdriver.Remote( command_executor=remote_server, desired_capabilities={ "browserName": browser_name}) except BaseException as e: print(f"check browser or remote server configs: {str(e)}") raise yield request.cls.driver request.cls.driver.quit()
额外注意事项
你报错里出现server_ip/wd/hub/wd/hub重复路径的问题,是因为你配置文件里的remote_server默认值已经携带了/wd/hub后缀,命令行传参时又加了一次,检查配置文件默认值后统一路径即可。
内容的提问来源于stack exchange,提问作者Akop Akopov
相关产品推荐
相关产品推荐

