简体   繁体   English

Pytest - 如何从命令行覆盖夹具参数列表?

[英]Pytest - How to override fixture parameter list from command line?

Consider the following fixture考虑以下夹具

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

I wonder if there is a way to launch pytest so it overrides the fixture parameter list with the value(s) given on the command line, ie:我想知道是否有办法启动 pytest 以便它使用命令行上给出的值覆盖夹具参数列表,即:

pytest --baseline legacy tests/

The above should effectively result in params=['legacy'].以上应该有效地导致 params=['legacy']。

Go with dynamic parametrization via Metafunc.parametrize :通过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)

Usage without parameters yields two default tests:不带参数的使用会产生两个默认测试:

$ pytest test_spam.py -sv
...
test_spam.py::test_eggs[current] PASSED
test_spam.py::test_eggs[legacy] PASSED

Passing --baseline overwrites the defaults:传递--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

You can also implement "always-in-use" defaults, so additional params are always added to them:您还可以实现“始终在使用”的默认值,因此总是向它们添加额外的参数:

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)

Now the test invocation will always include current and legacy params:现在测试调用将始终包括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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM