python - 使用 pytest.lazy_fixture 列表值作为另一个 fixture 中的参数

标签 python automated-tests pytest fixtures

我试图将一个 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/

相关文章:

python - 如何在 scipy.spatial.qhull.Delaunay 中禁用控制台输出异常?

python - 如何从 .env 文件为 pytests 加载变量

python - telnetlib.write() 不复制 telnet.interact()

version-control - 在源代码控制中存储自动化测试的位置

javascript - 运行 phantomjs casperjs 时手动输入

python - 我可以修补 Python 的断言以获得 py.test 提供的输出吗?

python - py.test 更改测试类中的测试顺序

python - 将 Python “requests” 与现有套接字连接一起使用

python - 使用预定义文本进行情感分析

python - 在 multiprocessing.Process() 中调用 subprocess.Popen() 时管道损坏