[Python-checkins] cpython: unittest.mock.PropertyMock return value and attributes are now standard

michael.foord python-checkins at python.org
Fri Apr 13 17:57:32 CEST 2012


http://hg.python.org/cpython/rev/a6236a68212e
changeset: 76284:a6236a68212e
user: Michael Foord <michael at voidspace.org.uk>
date: Fri Apr 13 16:57:22 2012 +0100
summary:
 unittest.mock.PropertyMock return value and attributes are now standard MagicMocks
files:
 Doc/library/unittest.mock.rst | 11 +++++++++++
 Lib/unittest/mock.py | 3 +++
 Lib/unittest/test/testmock/testhelpers.py | 11 +++++++++++
 3 files changed, 25 insertions(+), 0 deletions(-)
diff --git a/Doc/library/unittest.mock.rst b/Doc/library/unittest.mock.rst
--- a/Doc/library/unittest.mock.rst
+++ b/Doc/library/unittest.mock.rst
@@ -712,6 +712,17 @@
 >>> mock_foo.mock_calls
 [call(), call(6)]
 
+Because of the way mock attributes are stored you can't directly attach a
+`PropertyMock` to a mock object. Instead you can attach it to the mock type
+object::
+
+ >>> m = MagicMock()
+ >>> p = PropertyMock(return_value=3)
+ >>> type(m).foo = p
+ >>> m.foo
+ 3
+ >>> p.assert_called_once_with()
+
 
 Calling
 ~~~~~~~
diff --git a/Lib/unittest/mock.py b/Lib/unittest/mock.py
--- a/Lib/unittest/mock.py
+++ b/Lib/unittest/mock.py
@@ -2166,6 +2166,9 @@
 Fetching a `PropertyMock` instance from an object calls the mock, with
 no args. Setting it calls the mock with the value being set.
 """
+ def _get_child_mock(self, **kwargs):
+ return MagicMock(**kwargs)
+
 def __get__(self, obj, obj_type):
 return self()
 def __set__(self, obj, val):
diff --git a/Lib/unittest/test/testmock/testhelpers.py b/Lib/unittest/test/testmock/testhelpers.py
--- a/Lib/unittest/test/testmock/testhelpers.py
+++ b/Lib/unittest/test/testmock/testhelpers.py
@@ -831,5 +831,16 @@
 p.stop()
 
 
+ def test_propertymock_returnvalue(self):
+ m = MagicMock()
+ p = PropertyMock()
+ type(m).foo = p
+
+ returned = m.foo
+ p.assert_called_once_with()
+ self.assertIsInstance(returned, MagicMock)
+ self.assertNotIsInstance(returned, PropertyMock)
+
+
 if __name__ == '__main__':
 unittest.main()
-- 
Repository URL: http://hg.python.org/cpython


More information about the Python-checkins mailing list

AltStyle によって変換されたページ (->オリジナル) /