How do you mock a python property setter while wrapping it (i.e. calling the original setter)? The most straightward way is to access __set__
, but it's read-only for properties so doesn't work.
from unittest import TestCase
from unittest.mock import patch, PropertyMock
class SomeClass:
def __init__(self, value):
self._value = value
@property
def value(self):
return self._value + 1
@value.setter
def value(self, value):
self._value = value + 1
class TestSomeClass(TestCase):
def test_value_setter(self):
instance = SomeClass(0)
with patch.object(SomeClass.value, '__set__', wraps=SomeClass.value.__set__) as value_setter:
instance.value = 1
value_setter.assert_called_with(instance, 1)
self.assertEquals(instance.value, 3)
There's also the new_callable=PropertyMock
in the docs, I've tried to combine it with wrap
but haven't gotten it to work yet.