]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
Issue #22138: Fix mock.patch behavior when patching descriptors. Restore
authorSenthil Kumaran <senthil@uthcode.com>
Sat, 9 Jan 2016 07:43:29 +0000 (23:43 -0800)
committerSenthil Kumaran <senthil@uthcode.com>
Sat, 9 Jan 2016 07:43:29 +0000 (23:43 -0800)
original values after patching.

Patch contributed by Sean McCully.

Lib/unittest/mock.py
Lib/unittest/test/testmock/testpatch.py
Misc/NEWS

index 99ce1e2bf45ce6ff0082eea5f9efbcb630e8b3f1..976f663c0a958ab301af1bbc38dd8ebcf3f1e97b 100644 (file)
@@ -1332,7 +1332,10 @@ class _patch(object):
             setattr(self.target, self.attribute, self.temp_original)
         else:
             delattr(self.target, self.attribute)
-            if not self.create and not hasattr(self.target, self.attribute):
+            if not self.create and (not hasattr(self.target, self.attribute) or
+                        self.attribute in ('__doc__', '__module__',
+                                           '__defaults__', '__annotations__',
+                                           '__kwdefaults__')):
                 # needed for proxy objects like django settings
                 setattr(self.target, self.attribute, self.temp_original)
 
index 28fe86b0de99d5bd4fa7743df6db5776d6193ba4..dfce3696d6ab26970af3e37b94f1a8069c2ea390 100644 (file)
@@ -1817,5 +1817,31 @@ class PatchTest(unittest.TestCase):
         self.assertEqual(stopped, ["three", "two", "one"])
 
 
+    def test_special_attrs(self):
+        def foo(x=0):
+            """TEST"""
+            return x
+        with patch.object(foo, '__defaults__', (1, )):
+            self.assertEqual(foo(), 1)
+        self.assertEqual(foo(), 0)
+
+        with patch.object(foo, '__doc__', "FUN"):
+            self.assertEqual(foo.__doc__, "FUN")
+        self.assertEqual(foo.__doc__, "TEST")
+
+        with patch.object(foo, '__module__', "testpatch2"):
+            self.assertEqual(foo.__module__, "testpatch2")
+        self.assertEqual(foo.__module__, 'unittest.test.testmock.testpatch')
+
+        with patch.object(foo, '__annotations__', dict([('s', 1, )])):
+            self.assertEqual(foo.__annotations__, dict([('s', 1, )]))
+        self.assertEqual(foo.__annotations__, dict())
+
+        def foo(*a, x=0):
+            return x
+        with patch.object(foo, '__kwdefaults__', dict([('x', 1, )])):
+            self.assertEqual(foo(), 1)
+        self.assertEqual(foo(), 0)
+
 if __name__ == '__main__':
     unittest.main()
index 61b62f7828fc2e421248f0176c4731f5d07e6ad8..6c8a8fef1265f5b3a92f6fafe1a4581c0dca5cfc 100644 (file)
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -41,6 +41,9 @@ Core and Builtins
 Library
 -------
 
+- Issue #22138: Fix mock.patch behavior when patching descriptors. Restore
+  original values after patching. Patch contributed by Sean McCully.
+
 - Issue #25672: In the ssl module, enable the SSL_MODE_RELEASE_BUFFERS mode
   option if it is safe to do so.