简体   繁体   English

通过 pytest 夹具参数化

[英]Passing pytest fixture in parametrize

I'm getting following error by passing my fixture defined in conftest.py in @pytest.mark.parametrize:通过在@pytest.mark.parametrize 中传递我在conftest.py 中定义的夹具,我得到了以下错误:

pytest --alist="0220,0221" test_1.py -v -s
NameError: name 'alist' is not defined

conftest.py: conftest.py:

def pytest_addoption(parser):
    parser.addoption("--alist", action="store")

@pytest.fixture
def alist(request):
    return request.config.getoption("--alist").split(",")

test_1.py: test_1.py:

@pytest.mark.parametrize("channel", alist, scope="class")
class TestRaIntegrationReplay:

    def test_ra_start_time(self, channel):
        print(channel)

If I am passing alist to the test as fixture like:如果我将 alist 作为夹具传递给测试,例如:

    def test_ra_start_time(self, alist):
        for channel in alist:
            print(channel)

It works well, but it does not work with passing to @pytest.mark.parametrize它运行良好,但不适用于传递给 @pytest.mark.parametrize

As mentioned in the comment, you cannot directly pass a fixture to a mark.parametrize decorator, because the decorator is evaluated at load time.正如评论中提到的,您不能直接将夹具传递给mark.parametrize装饰器,因为装饰器是在加载时评估的。
You can do the parametrization at run time instead by implementing pytest_generate_tests :您可以通过实现pytest_generate_tests在运行时进行参数化:

import pytest

@pytest.hookimpl
def pytest_generate_tests(metafunc):
    if "alist" in metafunc.fixturenames:
        values = metafunc.config.option.alist
        if value is not None:
            metafunc.parametrize("alist", value.split(","))

def test_ra_start_time(alist):
    for channel in alist:
        print(channel)

def test_something_else():
    # will not be parametrized
    pass

The parametrization is done based on the presence of the alist parameter in the test function.参数化是根据测试 function 中是否存在alist参数来完成的。 For parametrization to work, this parameter is needed (otherwise you would get an error because of the missing argument).要使参数化起作用,需要此参数(否则您会因为缺少参数而出错)。

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

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