Skip to content Skip to sidebar Skip to footer

Python Propertymock Side Effect With Attributeerror And Valueerror

I am trying to mock a property of a class (@property decorator) and have bumped into this incorrect behaviour:  >>> from mock import MagicMock, PropertyMock  >>&

Solution 1:

I know this question is old, but I've just had the same problem and found this question. Also the bug report submitted almost two years ago didn't seem to get any attention, so I thought I'll share the solution I found just in case anybody else will have this problem.

So, as stated PropertyMock doesn't work with AttributeError set as a side_effect. The workaround is to create a simple Mock with a spec attribute set to an empty list like this:

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

As stated in the 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.

Solution 2:

Er, hold the phone. Does this cover your use case?

>>> 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

I stumbled across that in the docs while looking for something entirely different.

Post a Comment for "Python Propertymock Side Effect With Attributeerror And Valueerror"