(pytest)为什么属性模拟不能在fixture中工作?

2024-09-27 07:35:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个有一些属性的类。在我的测试中,我需要设置一个fixture,并模拟属性。但是,补丁只在fixture函数中工作,在fixture被调用时不起作用。你知道怎么解决这个问题吗?在

这是问题的简化版本。{假设这是我的类:

class Panda(object):
    def __init__(self, name):
        self.panda_name = name

    @property
    def name(self):
        return self.panda_name

这是我的测试

^{pr2}$

fixture_panda中的第一个print函数将打印yuanyuan,这意味着propertyMock按预期工作。但是test_panda_fixtureprintthis name should not matter中的第二个print函数,这意味着propertyMock在这里不起作用。你知道为什么会这样吗?怎么解决?在


Tags: 函数nameself版本属性objectinitdef
2条回答

你有三个问题。首先,您正在修补fixture函数,但您应该修补test函数。这是因为您编写它的方式,断言不在修补的范围之内。在

其次,你应该抛弃多余的mkname。在

第三,您的return_value位置不正确;它需要应用于修补程序返回的PropertyMock对象,而不是作为修补函数的参数。使用new_callable时,需要在测试设置中设置它,例如:

@patch('tmp.Panda.name', new_callable=PropertyMock)
def test_panda_fixture(mock_name, fixture_panda):
    mock_name.return_value = "yuanyuan"
    ...

但是,您可以在decorator中使用new,而不是{}。下面是一个工作版本,它展示了这种方法:

^{pr2}$

如果您想要monkeypatch pytest中的某些内容,可以使用它们的内置fixture monkeypatch,它可以用scope = function插入到所有fixture中。下面是我的代码库中的一个示例:

@pytest.fixture(scope="function", autouse=True)
def no_jwt(monkeypatch):
  """Monkeypatch the JWT verification functions for tests"""
  monkeypatch.setattr("flask_jwt_extended.verify_jwt_in_request", lambda: print("Verify"))

如果我把它应用到你的例子中,我认为这样的方法应该有效:

^{pr2}$

相关问题 更多 >

    热门问题