python-3.x - 当我尝试创建自定义命令行选项时,为什么 pytest 会出现“无法识别的选项”错误?
问题描述
我正在使用 Python 3.8 和 pytest 6.0.1。如何为 pytest 创建自定义命令行选项?我认为这就像将它添加到 conftest.py 一样简单......
def pytest_addoption(parser):
parser.addoption('--option1', action='store_const', const=True)
但是当我 pytest 时,我得到一个无法识别的选项错误
# pytest --option1=Y -c tests/my_test.py
ERROR: usage: pytest [options] [file_or_dir] [file_or_dir] [...]
pytest: error: unrecognized arguments: --option1=Y
添加自定义选项的正确方法是什么?
编辑:我尝试了给出的答案。我在我的 tests/conftest.py 文件中包含了一些其他的东西,以防这些是答案不起作用的原因。文件包含
def pytest_generate_tests(metafunc):
option1value = metafunc.config.getoption("--option1")
print(f'Option1 Value = {option1value}')
def pytest_configure(config):
use_docker = False
try:
use_docker = config.getoption("--docker-compose-remove-volumes")
except:
pass
plugin_name = 'wait_for_docker' if use_docker else 'wait_for_server'
if not config.pluginmanager.has_plugin(plugin_name):
config.pluginmanager.import_plugin("tests.plugins.{}".format(plugin_name))
但是运行时的输出是
$ pytest -s --option1 tests/shared/model/test_crud_functions.py
ERROR: usage: pytest [options] [file_or_dir] [file_or_dir] [...]
pytest: error: unrecognized arguments: --option1
inifile: /Users/davea/Documents/workspace/my_project/pytest.ini
rootdir: /Users/davea/Documents/workspace/my_project
解决方案
正如评论中已经提到的那样, action='store_const'
使您的选项成为标志。如果您在 cli 上指定选项值,则您在读取选项值时收到的值是const
ieTrue
在您的情况下指定的值。
试试这个: 将以下函数添加到 conftest.py
def pytest_generate_tests(metafunc):
option1value = metafunc.config.getoption("--option1")
print(f'Option1 Value = {option1value}')
使用选项调用的 pytest
pytest -s --option1
输出将具有: Option1 值 = True
pytest 不带选项调用
pytest -s
输出将具有: Option1 值 = 无
action=store
可能会给你想要的行为。
解决方案:
# Change the action associated with your option to action='store'
def pytest_addoption(parser):
parser.addoption('--option1', action='store')
def pytest_configure(config):
x = config.getoption('option1')
print(x) # Any logic that uses option value
输出:
pytest -s --option1=Y -c=test.py
Y
============================================================================= test session starts ==============================================================================
platform darwin -- Python 3.8.5, pytest-6.0.1, py-1.9.0, pluggy-0.13.1
您可以在此处找到有关可用操作的详细信息以及更多信息:https ://docs.python.org/3/library/argparse.html#action
推荐阅读
- javascript - 如何将异步函数的返回值分配给变量
- apache-spark - 我可以按百分比为所有 YARN 容器分配内存吗
- javascript - Javascript过滤功能必须始终写在一行上?
- python - 从现有数据框的子集自动创建数据框
- c# - Xamarin Android 服务在 InitializeComponent 完成后才会启动
- javascript - 在“/var”中找不到 Package.json 文件
- r - Ggplot2中的左/右和下/上轴操作
- java - 添加测试依赖项后的 NoClassDefFoundError
- javascript - 如何在反应中显示文本数组?
- php - PHP函数声明增加内存使用