我已经将pytest更新到4.3.0,现在我需要重新测试代码,因为不推荐直接调用fixture。
我对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。你可以通读或参考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)