Python: Mock side_effect on object attribute

It's worth noting that there is now the PropertyMock class:

>>> m = MagicMock()
>>> p = PropertyMock(side_effect=ValueError)
>>> type(m).foo = p
>>> m.foo
Traceback (most recent call last):
....
ValueError

That example was taken from the official site.


You can also try to patch the related field using a PropertyMock as new_callable argument.

Example:

from unittest import TestCase
import mock
from django import models
from django.core.exceptions import ObjectDoesNotExist

class Foo(models.Model):
    # ...
    @property
    def has_pending_related(self):
        try:
            return self.related_field.is_pending
        except ObjectDoesNotExist:
            return False

class FooTestCase(TestCase):
    # ...
    @mock.patch.object(Foo, 'related_field', new_callable=mock.PropertyMock)
    def test_pending_related(self, related_field):
        related_field.side_effect = ObjectDoesNotExist
        foo = Foo()
        self.assertFalse(foo.has_pending_related)

Tags:

Python