Python 怎么做到 pytest 中一个 fixture 的返回值,作为另一个 fixture 中 params 值来做参数化

陈平安 · 2023年07月16日 · 最后由 木屋 回复于 2024年04月08日 · 6209 次阅读


大概意思就是,我希望 test02 的 param 的值是 test01 的返回列表

共收到 13 条回复 时间 点赞

params 中传入几个值,在调用 test02 的时候 对应的测试用例就会运行几次

直接把 test1 放到 test2()的括号内

王中 回复

不是我要实现的目的,可能我没说清楚,我的目的是一个 fixture 的返回列表,用来做另一个 fixture 的参数化,而不是直接把列表全传给他

10楼 已删除

首先你这个逻辑就是错的,夹具函数本身只返回一个值或者不返回,即使是加入 yield,也不能实现分批次返回。“When using yield the code block after the yield statement is executed as teardown code regardless of the test outcome, and must yield exactly once.”

所以,你要把夹具函数当成@pytest.mark.parametrize用?夹具函数本身就不具备参数化的能力,重新设计你的脚本逻辑,再深刻点理解一下夹具函数的定义

Decorator to mark a fixture factory function.
This decorator can be used, with or without parameters, to define a fixture function.
The name of the fixture function can later be referenced to cause its invocation ahead of running tests: test modules or classes can use the pytest.mark.usefixtures(fixturename) marker.
Test functions can directly use fixture names as input arguments in which case the fixture instance returned from the fixture function will be injected.
Fixtures can provide their values to test functions using return or yield statements. When using yield the code block after the yield statement is executed as teardown code regardless of the test outcome, and must yield exactly once.

在 pytest 中,可以使用 fixture 的返回值作为另一个 fixture 的参数化值。可以通过使用 pytest 的 parametrize 装饰器来实现。

下面是一个示例代码:

import pytest

@pytest.fixture
def my_fixture():
    # 返回一个列表作为参数化的值
    return [1, 2, 3]

@pytest.fixture(params=pytest.fixture('my_fixture'))
def my_parametrized_fixture(request):
    return request.param

def test_my_test(my_parametrized_fixture):
    print(my_parametrized_fixture)

在上述示例中,my_fixture 作为一个 fixture,返回了一个列表 [1, 2, 3]。然后,my_parametrized_fixture 使用 params 参数指定为 pytest.fixture('my_fixture'),意味着它的参数值来自于 my_fixture 的返回值。在 test_my_test 中,my_parametrized_fixture 就会被自动作为参数传入。

注意,在 @pytest.fixture(params=pytest.fixture('my_fixture')) 中,my_fixture 是一个字符串,表示引用 my_fixture 这个 fixture 的返回值。

这样,每个参数会依次传递给 test_my_test 函数,并执行相应的测试用例。

大海 回复

pytest.fixture('my_fixture') 这种方式不行的

我理解你的意思,但是我觉得你的思路不是特别好。不过下面的代码是能够在另一个 fixture 中获取前一个 fixture 的返回值,不过他依然不是参数化的形式,因为你在另外一个测试用例中调用它,它不是参数化的形式执行的。

import pytest

@pytest.fixture
def f_01():
    return [1, 3, 5]

@pytest.fixture(params=["f_01"])
def f_02(request):

    print(request.getfixturevalue(request.param))

测试游记 回复

哈喽哈喽,看了下确实有用,但是是不是有版本要求啊,我最新的 pytest 是 7.0.2 没法使用

回复内容未通过审核,暂不显示
测试游记 回复


谢谢,不过我想的是能够根据一个 fixture 的返回列表来做参数化,pytest-lazy-fixtures 只能在用例执行时,被解析成具体的返回值,而在初始化 fixture 时,会报 TypeError: 'LazyFixture' object is not iterable,有什么好办法解决吗

@ 陈平安 我也有相同的问题,请问你解决了嘛?

需要 登录 后方可回复, 如果你还没有账号请点击这里 注册