【问题标题】:pytest fixture with argument带有参数的 pytest 夹具
【发布时间】:2021-12-19 10:33:10
【问题描述】:

似乎可以将参数传递给固定装置:

Pass a parameter to a fixture function

然而,在实现这个最小的例子时,我得到了一个错误。

import pytest

@pytest.fixture
def my_fixture(v):
    print("fixture in")
    yield v+1
    print("fixture out")

@pytest.mark.parametrize("my_fixture",[1], indirect=True)
def test_myfixture(my_fixture):
    print(my_fixture)

@pytest.fixture def my_fixture(v): 未找到 E 夹具“v”

上面的代码有什么问题吗?

(python 3.8.10, pytest-6.2.5)

【问题讨论】:

    标签: python pytest fixtures


    【解决方案1】:

    简要说明 Vince 的回答:通常,fixture 函数的参数被解释为要在定义之前加载的其他fixture 的名称。这就是您收到错误消息 fixture 'v' not found 的原因:pytest 认为您希望 my_fixture 依赖于另一个不存在的名为 v 的夹具。

    request 参数是此一般规则的一个例外。它不是指另一个夹具。相反,它指示 pytest 授予夹具访问 request 对象的权限,该对象包含有关当前正在运行的测试的信息,例如正在测试哪些参数(通过request.param),测试有哪些标记(通过request.node.get_closest_marker())等等。

    因此,要使用间接参数化,您的夹具需要 (i) 接受 request 参数并 (ii) 使用 request.param 执行某些操作。有关详细信息,请参阅文档中的相关页面:

    【讨论】:

      【解决方案2】:

      这行得通:

      @pytest.fixture
      def my_fixture(request):
          print("fixture in")
          yield request.param+1 # difference here !
          print("fixture out")
      
      @pytest.mark.parametrize("my_fixture",[1], indirect=True)
      def test_myfixture(my_fixture):
          print(my_fixture)
      
      
      

      【讨论】:

      【解决方案3】:

      没有错。 Fixtures 用于修复常量,以便在多个测试中相同地重用它们。他们不接受任何争论。顺便说一句,您可以创建一个“常量”函数的 pytest.fixture:

      @pytest.fixture
      def my_fixture():
          return lambda x: x+1
      

      并避免在夹具中使用print(至少在最终版本中)。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-12-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-03
        • 1970-01-01
        相关资源
        最近更新 更多