我正在使用 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