Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I mock a property to raise an exception?

I'm using MagicMock with Python 2.7 to mock objects. One of the classes that I'm mocking has properties, one of which can raise a TypeError in some cases.

I would like to mock that behavior, but I can't figure out how:

  • del my_mock.my_property will cause an AttributeError if my_property is accessed, but I need a TypeError.
  • my_mock.my_property = MagicMock(side_effect=TypeError) causes a TypeError when my_property is called, but not when it's merely accessed.

How would I do that?

like image 276
zneak Avatar asked May 13 '17 02:05

zneak


1 Answers

You can use PropertyMock for this purpose:

import mock

class A(object):

    @property
    def prop(self):
        pass

a = A()
type(a).prop = mock.PropertyMock(side_effect=TypeError)

If you now access a.prop it'll raise a TypeError.

like image 198
Simeon Visser Avatar answered Nov 14 '22 21:11

Simeon Visser