Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit c287062

Browse files
committed
unittest.mock.PropertyMock return value and attributes are now standard MagicMocks
1 parent 633b32a commit c287062

3 files changed

Lines changed: 25 additions & 0 deletions

File tree

Doc/library/unittest.mock.rst

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -712,6 +712,17 @@ have to create a dictionary and unpack it using `**`:
712712
>>> mock_foo.mock_calls
713713
[call(), call(6)]
714714

715+
Because of the way mock attributes are stored you can't directly attach a
716+
`PropertyMock` to a mock object. Instead you can attach it to the mock type
717+
object::
718+
719+
>>> m = MagicMock()
720+
>>> p = PropertyMock(return_value=3)
721+
>>> type(m).foo = p
722+
>>> m.foo
723+
3
724+
>>> p.assert_called_once_with()
725+
715726

716727
Calling
717728
~~~~~~~

Lib/unittest/mock.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2166,6 +2166,9 @@ class PropertyMock(Mock):
21662166
Fetching a `PropertyMock` instance from an object calls the mock, with
21672167
no args. Setting it calls the mock with the value being set.
21682168
"""
2169+
def _get_child_mock(self, **kwargs):
2170+
return MagicMock(**kwargs)
2171+
21692172
def __get__(self, obj, obj_type):
21702173
return self()
21712174
def __set__(self, obj, val):

Lib/unittest/test/testmock/testhelpers.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -831,5 +831,16 @@ def test_propertymock(self):
831831
p.stop()
832832

833833

834+
def test_propertymock_returnvalue(self):
835+
m = MagicMock()
836+
p = PropertyMock()
837+
type(m).foo = p
838+
839+
returned = m.foo
840+
p.assert_called_once_with()
841+
self.assertIsInstance(returned, MagicMock)
842+
self.assertNotIsInstance(returned, PropertyMock)
843+
844+
834845
if __name__ == '__main__':
835846
unittest.main()

0 commit comments

Comments
 (0)