我有一个有一些属性的类。在我的测试中,我需要设置一个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_fixture
printthis name should not matter
中的第二个print函数,这意味着propertyMock在这里不起作用。你知道为什么会这样吗?怎么解决?在
你有三个问题。首先,您正在修补fixture函数,但您应该修补test函数。这是因为您编写它的方式,断言不在修补的范围之内。在
其次,你应该抛弃多余的
mkname
。在第三,您的
return_value
位置不正确;它需要应用于修补程序返回的PropertyMock
对象,而不是作为修补函数的参数。使用new_callable
时,需要在测试设置中设置它,例如:但是,您可以在decorator中使用}。下面是一个工作版本,它展示了这种方法:
^{pr2}$new
,而不是{如果您想要monkeypatch
pytest
中的某些内容,可以使用它们的内置fixturemonkeypatch
,它可以用scope = function
插入到所有fixture中。下面是我的代码库中的一个示例:如果我把它应用到你的例子中,我认为这样的方法应该有效:
^{pr2}$相关问题 更多 >
编程相关推荐