我试图将一个 fixture 值列表用作另一个 fixture 值的参数。这是我的设置:
import pytest
d = {
"first": [1, 2, 3],
"second": [4, 5, 6]
}
@pytest.fixture(params=['first', 'second'])
def foo(request):
return d.get(request.param)
@pytest.fixture(params=[pytest.lazy_fixture('foo')])
def bar(request):
return request.param
def test_1(bar):
pass
问题是
bar()
始终获取完整列表为 request.param
([1, 2, 3] 不是列表的值。如果在 params
of bar()
fixture 中直接发送数据,例如:@pytest.fixture(params=[1, 2, 3])
def bar(request):
return request.param
def test_1(bar):
pass
然后参数请求将正常工作(测试开始 3 次)。同样的情况,如果我将参数传递给
params
不是直接的,而是来自没有 fixture 装饰器的任何方法,即:def some():
return [1, 2, 3]
@pytest.fixture(params=some())
def more(request):
return request.param
def test_2(more):
logging.error(more)
pass
那么,我的问题是否可以从列表中一一获取数据然后在我的测试中使用它?我尝试“解析”列表:
@pytest.fixture(params=[i for i in i pytest.lazy_fixture('foo')])
def bar(request):
return request.param
但在这种情况下,我得到
TypeError: 'LazyFixture' object is not iterable
最佳答案
见 this answer to a very similar question :根据设计, fixture 值不能用作参数化测试的参数列表。实际上,在 pytest 收集阶段解析参数,而在 pytest 节点执行期间稍后解析 fixture 。
您可以用 lazy_fixture
做的最好的事情或与 pytest_cases.fixture_ref
是使用 单例 fixture 值作为参数。与 lazy_fixture
在使用 pytest_cases
时,您有限制(如果我没记错的话, fixture 无法参数化)您几乎可以做任何事情(在参数元组中使用 fixture_ref
,使用多个 fixture_ref
,每个都具有不同的参数化等)。我是pytest_cases
的作者顺便一提 ;)
另见 this thread .
关于python - 使用 pytest.lazy_fixture 列表值作为另一个 fixture 中的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50482416/