首页 > 解决方案 > 当我尝试创建自定义命令行选项时,为什么 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

标签: python-3.xcommand-linepytestconftest

解决方案


正如评论中已经提到的那样, action='store_const'使您的选项成为标志。如果您在 cli 上指定选项值,则您在读取选项值时收到的值是constieTrue在您的情况下指定的值。

试试这个: 将以下函数添加到 conftest.py

def pytest_generate_tests(metafunc):
    option1value = metafunc.config.getoption("--option1")
    print(f'Option1 Value = {option1value}')
  1. 使用选项调用的 pytestpytest -s --option1

    输出将具有: Option1 值 = True

  2. 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


推荐阅读