pytest fixture - 获取值并避免错误 "Fixture 'X' called directly"

pytest fixture - get value and avoid error "Fixture 'X' called directly"

我已将 pytest 更新到 4.3.0,现在我需要重新编写测试代码,因为不推荐直接调用固定装置。

我在 unittest.TestCase 中使用的固定装置有问题,如何获取从固定装置返回的值而不是对函数本身的引用?

示例:

@pytest.fixture
def test_value():
    return 1

@pytest.mark.usefixtures("test_value")
class test_class(unittest.TestCase):
    def test_simple_in_class(self):
        print(test_value)    # prints the function reference and not the value
        print(test_value())  # fails with Fixtures are not meant to be called directly

def test_simple(test_value):
    print(test_value)  # prints 1

如何在 test_simple_in_class() 方法中获得 test_value?

有一个big discussion on this already. You can read through that or refer to the deprecation documentation

在你设计的例子中,答案似乎是这样的:

@pytest.fixture(name="test_value")
def test_simple_in_class(self):
    print(test_value())

但是,我建议查看文档。另一个例子可能是你想要的。您可以阅读我链接到的讨论以了解一些推理。不过争论有点激烈。

我的简单示例的解决方案,如果有人感兴趣的话。

def my_original_fixture():
    return 1

@pytest.fixture(name="my_original_fixture")
def my_original_fixture_indirect():
    return my_original_fixture()

@pytest.mark.usefixtures("my_original_fixture")
class test_class(unittest.TestCase):
    def test_simple_in_class(self):
        print(my_original_fixture())

def test_simple(my_original_fixture):
    print(my_original_fixture)