Dav*_*ave 5 command-line pytest python-3.x conftest
我正在使用 Python 3.8 和 pytest 6.0.1。如何为 pytest 创建自定义命令行选项?我认为这就像将其添加到 conftest.py 一样简单......
\ndef\xc2\xa0pytest_addoption(parser):\n\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0parser.addoption('--option1',\xc2\xa0action='store_const',\xc2\xa0const=True)\nRun Code Online (Sandbox Code Playgroud)\n但是当我进行 pytest 时,出现无法识别的选项错误
\n# pytest --option1=Y -c tests/my_test.py \nERROR: usage: pytest [options] [file_or_dir] [file_or_dir] [...]\npytest: error: unrecognized arguments: --option1=Y\nRun Code Online (Sandbox Code Playgroud)\n添加自定义选项的正确方法是什么?
\n编辑:我尝试了给出的答案。我在我的测试/conftest.py 文件中包含了一些其他内容,以防这些是答案不起作用的原因。文件包含
\ndef pytest_generate_tests(metafunc):\n option1value = metafunc.config.getoption("--option1")\n print(f'Option1 Value = {option1value}')\n\ndef pytest_configure(config):\n use_docker = False\n try:\n use_docker = config.getoption("--docker-compose-remove-volumes")\n except:\n pass\n plugin_name = 'wait_for_docker' if use_docker else 'wait_for_server'\n if not config.pluginmanager.has_plugin(plugin_name):\n config.pluginmanager.import_plugin("tests.plugins.{}".format(plugin_name))\nRun Code Online (Sandbox Code Playgroud)\n但运行时的输出是
\n$ pytest -s --option1 tests/shared/model/test_crud_functions.py\nERROR: usage: pytest [options] [file_or_dir] [file_or_dir] [...]\npytest: error: unrecognized arguments: --option1\n inifile: /Users/davea/Documents/workspace/my_project/pytest.ini\n rootdir: /Users/davea/Documents/workspace/my_project\nRun Code Online (Sandbox Code Playgroud)\n
正如评论中已经提到的, action='store_const'使您的选项成为一个标志。如果在 cli 上指定了选项值,则当您读取选项值时收到的值是constieTrue在您的情况下指定的值。
试试这个: 将以下函数添加到conftest.py
def pytest_generate_tests(metafunc):
option1value = metafunc.config.getoption("--option1")
print(f'Option1 Value = {option1value}')
Run Code Online (Sandbox Code Playgroud)
使用选项调用 pytestpytest -s --option1
输出将有: Option1 Value = True
不带选项调用 pytestpytest -s
输出将有: Option1 Value = None
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
Run Code Online (Sandbox Code Playgroud)
输出:
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
Run Code Online (Sandbox Code Playgroud)
您可以在此处找到有关可用操作的详细信息以及更多信息: https: //docs.python.org/3/library/argparse.html#action
| 归档时间: |
|
| 查看次数: |
18246 次 |
| 最近记录: |