Python Propertymock in Mock Constructor

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')
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)]
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

James H. Sterling
Author

James H. Sterling

James Sterling reports on renewable energy developments, climate policy, ecological conservation, and green tech innovations around the globe.