传递给 pytest 夹具的参数可以作为变量传入吗? [英] Can params passed to pytest fixture be passed in as a variable?
问题描述
我有两个简单的测试设置,我正在尝试将它们组合在一个夹具中并希望测试函数将参数"传递给夹具.
I have two simple test setups and I'm trying to group them in one fixture and want the test function to pass in the 'params' to the fixture.
这是一个人为的例子,用来解释我的问题.假设我有以下 pytest 夹具:
Here's a contrived example, to explain my question. Say I have the following pytest fixture:
@pytest.fixture(scope="module", params=['param1','param2'])
def myFixture(request):
if request.param == 'param1':
p = 5
elif request.param == 'param2':
p = 10
return p
# would like to set request.param = ['param1'] for myFixture
def test_madeup(myFixture):
assert myFixture == 5
# would like to set request.param = ['param2'] for myFixture
def test_madeup2(myFixture):
assert myFixture == 10
我可以将上述参数作为输入传递给 test_madeup
函数吗?因此,类似于以下内容:
Can I make it so that the params above are passed in as an input to the test_madeup
function?
So, something like the following:
@pytest.fixture(scope="module", params=fixtureParams)
def myFixture(request):
if request.param == 'param1':
return 5
elif request.param == 'param2':
return 10
def test_madeup(myFixture, ['param1']):
assert myFixture == 5
以上当然行不通.实际情况有点复杂,但我只想知道我是否可以通过 params=['param1','param2']
从 test_madeup
函数到夹具.
The above, of course, doesn't work. The real case is a bit more complex,
but I just want to know if I can pass the params=['param1','param2']
to the fixture from the test_madeup
function.
推荐答案
如果我正确理解您的问题,您基本上希望通过提供一些测试信息来选择一个参数化夹具的实例来执行测试.虽然我们可能会考虑一种机制,但这是不可能的.我不确定以下解决方案是否适用于您的整个问题,但这是解决上述具体情况的一种方法:
If i understand your question correctly, you basically want to select one instance of a parametrized fixture for executing with a test, by providing some info with the test. It's not possible although we could probably think about a mechanism. I am not sure if the following solution maps to your whole problem, but here is one way to solve the above concrete case:
import pytest
@pytest.fixture(scope="module")
def myFixture1():
return 5
@pytest.fixture(scope="module")
def myFixture2():
return 2
@pytest.fixture(scope="module", params=["param1", "param2"])
def myFixture(request):
if request.param == 'param1':
return request.getfuncargvalue("myFixture1")
elif request.param == 'param2':
return request.getfuncargvalue("myFixture2")
def test_1(myFixture1):
assert myFixture1 == 5
def test_2(myFixture2):
assert myFixture2 == 2
def test_all(myFixture):
assert myFixture in (2,5)
这运行了四次测试,因为 test_all
用两个夹具执行了两次.
This runs four tests, because the test_all
is executed twice with both fixtures.
如果您的灯具设置并不繁重,您可能还有一个可以生成列表的灯具和一个迭代"参数化的灯具.然后测试可以获取整个列表并将其索引到其中.
If the setup of your fixtures is not heavy, you might also have one fixture that produces a list and an "iterating" parametrized one. A test could then grab the whole list and index it into it.
这篇关于传递给 pytest 夹具的参数可以作为变量传入吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!