我试图模仿一个类(@property decorator)的属性,却遇到了这种不正确的行为:
>>> from mock import MagicMock, PropertyMock
>>> m = MagicMock()
>>> type(m).p = PropertyMock(side_effect=AttributeError)
>>> m.p
<MagicMock name='mock.p' id='63150736'>
正确的行为是:
^{pr2}$我不明白为什么设置一个不同的例外会给我不同的结果。两种情况下的预期结果都是应引发异常!因此,In[4]行应该引发一个AttributeError
。它没有。在
有人愿意开导我吗?
附录:我尝试检查的属性会进行一些巧妙的检查,看看传递的值是否正常。如果所说的值不正常,它将返回AttributeError,因为我知道这是Python中正确的异常。因此,我需要检查使用该属性的代码是否失败以及是否成功。因此,使用MagicMock模拟属性并引发所述异常。一个简单的例子是:
@x.setter
def x(self, value):
if value < 0:
raise AttributeError("Value cannot be negative!")
self._x = value
我知道这个问题很古老,但我也遇到过同样的问题,找到了这个问题。而且,两年前提交的bug report似乎没有引起任何注意,所以我想我会分享我发现的解决方案,以防其他人会有这个问题。在
因此,如上所述,}一起工作。解决方法是创建一个简单的
PropertyMock
不能与设置为side_effect
的{Mock
,并将spec
属性设置为空list
,如下所示:如docs中所述:
呃,别挂电话。这包括你的用例吗?在
我在寻找完全不同的东西时偶然发现了这个。在
相关问题 更多 >
编程相关推荐