python-3.x - 如何在当前测试中使用 fixture 转换后的数据进行参数化?

标签 python-3.x pytest parametrized-testing pytest-fixtures parametrize

我有下一个 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/

相关文章:

python - 如何不计算单词之间的标点符号

python - 使用 loc 的 Pandas 浮点值问题

python - 如何使用 PropertyMock 在 pytest 单元测试中返回请求响应属性?

python - py.test fixture 创建最佳实践

python - Pytest 插件打开 GUI

java - 如何使用 CsvFileSource 在 Junit 5 参数化测试中转义双引号

python-3.x - 尝试使用 cron 运行 Python 脚本,得到 [Errno 1] 不允许操作

python - 如何复制列表中的项目(保留第一个和最后一个项目)并将列表转换为两个项目的列表列表

java - 使用 @MethodSource 和返回 ArrayList 的方法进行参数化 JUnit 测试

kotlin - 使用纯 Kotlin 函数作为 Junit5 方法源