pytest 固定装置 - 获取值并避免错误“直接调用固定装置'X'”

2024-04-16

我已将 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 ?


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

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)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

pytest 固定装置 - 获取值并避免错误“直接调用固定装置'X'” 的相关文章

随机推荐