【发布时间】:2019-07-03 21:20:44
【问题描述】:
我想用一个由夹具动态创建的列表对测试进行参数化,如下所示:
@pytest.fixture
def my_list_returning_fixture(depends_on_other_fixtures):
return ["a dynamically created list which", depends_on_other_fixtures]
我怎样才能做到这一点?或者,我怎样才能确保a certain fixture gets called first - 这甚至可以在它发生之前解决这个问题。
我已经尝试过的
-
我尝试使用夹具对测试进行参数化(这只会导致错误,因为 python 认为我想交出函数本身):
@pytest.mark.parametrize( "an_element_from_the_list_of_my_fixture", my_list_returning_fixture ) def test_the_list(an_element_from_the_list_of_my_fixture): print(an_element_from_the_list_of_my_fixture)像
my_list_returning_fixture()这样的普通函数调用fixture 也会导致错误! Python 不知道如何填充夹具的“参数”(实际上只是其他夹具)并显示有关传递参数太少的错误消息...因此我需要 pytest 来注入
depends_on_other_fixtures依赖项,所以我不能像普通函数一样调用它。 -
我还尝试在列表夹具和测试之间插入另一个夹具,如下所示:
@pytest.fixture(params=my_list_returning_fixture) def my_interposed_parametrized_fixture(request): return request.param def test_the_list(my_interposed_parametrized_fixture): ... 我也尝试过使用间接参数化,但也没有用...
使用静态列表很容易
我知道使用给定的list 参数化测试很容易,如下所示:
the_list = [1, 2, 3]
@pytest.mark.parametrize("an_element_from_the_list", the_list)
def test_the_list(an_element_from_the_list):
print(an_element_from_the_list)
这将导致三个测试。列表中的每个元素一个。
【问题讨论】:
-
与您的其他问题相同的问题 - 在
fixture/mark.parametrize装饰器中评估夹具/测试参数时,尚未执行任何夹具,并且内部缓存中没有夹具结果。如果夹具没有其他依赖项,直接的解决方法是将夹具简单地调用为普通函数,例如@pytest.mark.parametrize('arg', fixturefunc()),但那不是你的情况。 -
顺便说一句,有一个旧的open issue 用于将固定装置作为参数传递给
mark.parametrize。 -
@hoefling。而且它看起来不会很快得到解决:github.com/pytest-dev/pytest/issues/2155