[英]pytest: How to pass in values and create a test fixture from command line?
[英]Pytest - How to override fixture parameter list from command line?
考虑以下夹具
@pytest.fixture(params=['current', 'legacy'])
def baseline(request):
return request.param
我想知道是否有办法启动 pytest 以便它使用命令行上给出的值覆盖夹具参数列表,即:
pytest --baseline legacy tests/
以上应该有效地导致 params=['legacy']。
通过Metafunc.parametrize
进行动态参数化:
# conftest.py
import pytest
@pytest.fixture
def baseline(request):
return request.param
def pytest_addoption(parser):
parser.addoption('--baseline', action='append', default=[],
help='baseline (one or more possible)')
def pytest_generate_tests(metafunc):
default_opts = ['current', 'legacy']
baseline_opts = metafunc.config.getoption('baseline') or default_opts
if 'baseline' in metafunc.fixturenames:
metafunc.parametrize('baseline', baseline_opts, indirect=True)
不带参数的使用会产生两个默认测试:
$ pytest test_spam.py -sv
...
test_spam.py::test_eggs[current] PASSED
test_spam.py::test_eggs[legacy] PASSED
传递--baseline
覆盖默认值:
$ pytest test_spam.py -sv --baseline=foo --baseline=bar --baseline=baz
...
test_spam.py::test_eggs[foo] PASSED
test_spam.py::test_eggs[bar] PASSED
test_spam.py::test_eggs[baz] PASSED
您还可以实现“始终在使用”的默认值,因此总是向它们添加额外的参数:
def pytest_addoption(parser):
parser.addoption('--baseline', action='append', default=['current', 'legacy'],
help='baseline (one or more possible)')
def pytest_generate_tests(metafunc):
baseline_opts = metafunc.config.getoption('baseline')
if 'baseline' in metafunc.fixturenames and baseline_opts:
metafunc.parametrize('baseline', baseline_opts, indirect=True)
现在测试调用将始终包括current
和legacy
参数:
$ pytest test_spam.py -sv --baseline=foo --baseline=bar --baseline=baz
...
test_spam.py::test_eggs[current] PASSED
test_spam.py::test_eggs[legacy] PASSED
test_spam.py::test_eggs[foo] PASSED
test_spam.py::test_eggs[bar] PASSED
test_spam.py::test_eggs[baz] PASSED
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.