我有下一个 pytest 代码:
import pytest
@pytest.fixture
def my_fixture():
def _method(a_list):
return [num*0.5 for num in a_list]
return _method
# @pytest.mark.parametrize ??
def test_me(my_fixture):
pre_list = [0, 3, 1, 2]
finally_list = my_fixture(pre_list)
for i in finally_list:
assert i < 10
含义如下。我有测试的初始数据(“pre_list”)。首先我需要使用 fixture 转换它们。我通过 fixture 中的附加函数“_method(a_list)”来完成此操作。 但是,从“finally_list”获得的值我想在当前测试中用于参数化。真的可以这样做吗? 使用 fixture 转换测试数据,然后使用它们对同一测试进行参数化
当我运行所有值时:
for i in finally_list: assert i < 10
但这不是我想要的。我想通过参数化对每个值进行单独的测试。
最佳答案
您可以使用Indirect parametrization .
示例:
import pytest
@pytest.fixture
def my_fixture(request):
return request.param * 0.5
@pytest.mark.parametrize('my_fixture', [0, 3, 1, 2], indirect=True)
def test_me(my_fixture):
assert my_fixture < 10
这将确保所有值首先通过您的装置并按照您想要的方式进行修改,然后到达测试用例。
上面的示例应该为 pytest --collect-only <your_test_file.py>
提供大约以下输出(取决于您的插件、运行位置等) :
========================================== test session starts ==========================================
platform linux -- Python 3.10.12, pytest-7.4.0, pluggy-1.3.0
rootdir: /tmp/tests
collected 4 items
<Module t.py>
<Function test_me[0]>
<Function test_me[3]>
<Function test_me[1]>
<Function test_me[2]>
====================================== 4 tests collected in 0.00s =======================================
关于python-3.x - 如何在当前测试中使用 fixture 转换后的数据进行参数化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77010804/