gpt4 book ai didi

python - Pytest - 如何从命令行覆盖 fixture 参数列表?

转载 作者:太空宇宙 更新时间:2023-11-04 02:19:14 26 4
gpt4 key购买 nike

考虑以下 fixture

@pytest.fixture(params=['current', 'legacy'])
def baseline(request):
return request.param

我想知道是否有启动 pytest 的方法,以便它使用命令行上给出的值覆盖 fixture 参数列表,即:

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)

现在测试调用将始终包含 currentlegacy 参数:

$ 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

关于python - Pytest - 如何从命令行覆盖 fixture 参数列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51992562/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com