pytest中--runslow命令行参数未被识别,如何解决?
问题描述
我按照pytest官方文档实现了测试用例跳过功能,仅执行pytest命令时,标记的测试用例可正常跳过;但执行pytest --runslow命令时,出现如下错误:
ERROR: usage: pytest [options] [file_or_dir] [file_or_dir] [...]
pytest: error: unrecognized arguments: --runslow
inifile: /app/pyproject.toml
rootdir: /app
我的测试文件路径为project/myapp/tests/tests.py,conftest文件路径为project/conftest.py,需要让pytest正确识别该命令行参数。
修复步骤
1. 确认conftest.py的加载范围
pytest会从执行命令的当前工作目录向上查找conftest.py文件。确保你执行pytest时的工作目录是project/(或其上级目录,能让pytest遍历到该conftest文件)。如果当前工作目录是project/myapp/tests/,pytest可能无法找到project/conftest.py,导致自定义参数未注册。
2. 检查conftest.py的代码正确性
确保你在conftest.py中正确注册了--runslow参数,代码示例如下(注意导入pytest):
import pytest def pytest_addoption(parser): parser.addoption( "--runslow", action="store_true", default=False, help="运行慢测试用例" ) def pytest_configure(config): # 注册slow标记 config.addinivalue_line("markers", "slow: 标记为慢执行的测试用例") def pytest_collection_modifyitems(config, items): if not config.getoption("--runslow"): skip_slow = pytest.mark.skip(reason="需要--runslow参数才能执行") for item in items: if "slow" in item.keywords: item.add_marker(skip_slow)
如果缺少pytest导入,或者参数注册逻辑错误,都会导致pytest无法识别--runslow。
3. 排查pyproject.toml的干扰配置
错误提示显示使用了/app/pyproject.toml作为配置文件,检查该文件中的pytest配置:
- 确认
[tool.pytest.ini_options]下没有设置冲突的addopts参数 - 没有禁用自定义插件或参数注册的相关配置
如果有冲突配置,调整后重新执行命令。
4. 手动指定项目根目录
如果pytest仍无法找到conftest.py,执行命令时通过--rootdir指定项目根目录:
pytest --rootdir=/path/to/project --runslow
或者直接切换到project/目录下执行pytest --runslow。
内容的提问来源于stack exchange,提问作者user2712231

