pytest-如何从命令行覆盖灯具参数列表?

时间:2018-08-23 18:55:23

标签: python testing pytest

考虑以下灯具

<CallOut param={List} param={BoxRight} />

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

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

以上内容应有效地导致params = ['legacy']。

1 个答案:

答案 0 :(得分:2)

通过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