Python PropertyMock副作用与AttributeError和ValueE

2024-09-27 07:21:11 发布

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

我试图模仿一个类(@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

Tags: namefromimportself属性valuetypedecorator
2条回答

我知道这个问题很古老,但我也遇到过同样的问题,找到了这个问题。而且,两年前提交的bug report似乎没有引起任何注意,所以我想我会分享我发现的解决方案,以防其他人会有这个问题。在

因此,如上所述,PropertyMock不能与设置为side_effect的{}一起工作。解决方法是创建一个简单的Mock,并将spec属性设置为空list,如下所示:

>>> from mock import Mock
>>> m = Mock(spec=[])
>>> m.p
Traceback (most recent call last)
[...]
AttributeError

docs中所述:

spec: This can be either a list of strings or an existing object (a class or instance) that acts as the specification for the mock object. If you pass in an object then a list of strings is formed by calling dir on the object (excluding unsupported magic attributes and methods). Accessing any attribute not in this list will raise an AttributeError.

呃,别挂电话。这包括你的用例吗?在

>>> import mock
>>> m = mock.MagicMock()
>>> m.p
<MagicMock name='mock.p' id='139756843423248'>
>>> del m.p #!
>>> m.p
Traceback (most recent call last):
     File "<stdin>", line 1, in <module>
     File "/home/ahammel/bin/python/mock-1.0.1-py2.6.egg/mock.py", line 664, in __getattr__
         raise AttributeError(name)
     AttributeError: p

我在寻找完全不同的东西时偶然发现了这个。在

相关问题 更多 >

    热门问题