Joh*_*opM 4 python fixtures pytest
我已将 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
Run Code Online (Sandbox Code Playgroud)
如何在 test_simple_in_class() 方法中获取 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)
Run Code Online (Sandbox Code Playgroud)
在你设计的例子中,这似乎就是答案:
@pytest.fixture(name="test_value")
def test_simple_in_class(self):
print(test_value())
Run Code Online (Sandbox Code Playgroud)
不过,我建议检查文档。另一个例子可能就是你想要的。您可以阅读我链接的讨论来了解一些推理。不过,争论有点激烈。