Python Propertymock in Mock Constructor
I'm Using Michael Foord's Mock Library and Have a Question About It. I Want to Mock a Property, So I Do This: Eggs = Mock. Propertymock(Return_Value='Eggs')...
I'm using Michael Foord's mock library and have a question about it.
I want to mock a property, so I do this:
eggs = mock.PropertyMock(return_value='eggs')
spam = mock.Mock()
type(spam).eggs = eggs
assert spam.eggs == 'eggs'
This works brilliantly. However I find the type() part ugly and would love to do something like this:
eggs = mock.PropertyMock(return_value='eggs')
spam = mock.Mock(eggs = eggs)
assert spam.eggs == 'eggs'
The last example doesn't work as expected, spam.eggs becomes a method instead of a property.
I know I can use mock.Mock(eggs = 'eggs') so eggs is not a method, but I want to be able to assert the property. :-)
I am using Python 2.7, but I assume unittest.Mock works too.
1 Answer
The patch can help you to a degree, the code is taken from official Mock document
>>> class Foo(object):
... @property
... def foo(self):
... return 'something'
... @foo.setter
... def foo(self, value):
... pass
...
>>> with patch('__main__.Foo.foo', new_callable=PropertyMock) as mock_foo:
... mock_foo.return_value = 'mockity-mock'
... this_foo = Foo()
... print this_foo.foo
... this_foo.foo = 6
...
mockity-mock
>>> mock_foo.mock_calls
[call(), call(6)]