【发布时间】:2020-11-26 22:29:30
【问题描述】:
我正在使用 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
【问题讨论】:
-
如果您使用
store_const,则该选项将作为标志处理并且不能有值,例如你必须使用pytest --option1。如果要设置不同的值,可以改用默认的store操作。 -
我投票关闭这个作为一个骗子,在
pytest已经有很多关于自定义 cli args 的答案,参见例如stackoverflow.com/q/40880259/2650249 和链接的问题。 -
问这个问题可能有点傻:你确定你把这个钩子添加到你的根 conftest.py 中了吗?
-
你的意思是“tests/conftest.py”?是的,我知道它在那里,因为如果我只运行“pytest tests/shared/model/test_crud_functions.py”,我会收到错误,“ValueError:没有名为'--option1'的选项”。令人沮丧的是,当我运行“pytest --option1=abc tests/shared/model/test_crud_functions.py”时,我得到了“pytest: error: unrecognized arguments: --option1=abc”错误。
标签: python-3.x command-line pytest conftest