]> granicus.if.org Git - python/commitdiff
bpo-36366: Return None on stopping unstarted patch object (GH-12472)
authorXtreak <tir.karthi@gmail.com>
Thu, 28 Mar 2019 21:08:43 +0000 (02:38 +0530)
committerMiss Islington (bot) <31488909+miss-islington@users.noreply.github.com>
Thu, 28 Mar 2019 21:08:43 +0000 (14:08 -0700)
Return None after calling unittest.mock.patch.object.stop() regardless of whether the object was started. This makes the method idempotent.

https://bugs.python.org/issue36366

Lib/unittest/mock.py
Lib/unittest/test/testmock/testpatch.py
Misc/NEWS.d/next/Library/2019-03-20-15-13-18.bpo-36366.n0eav_.rst [new file with mode: 0644]

index fdde16be03a395c0da48c72f90f43d371da01fa0..8684f1dfa5729f5566c6d3b0ff4f5581eee9dff6 100644 (file)
@@ -1398,7 +1398,7 @@ class _patch(object):
     def __exit__(self, *exc_info):
         """Undo the patch."""
         if not _is_started(self):
-            raise RuntimeError('stop called on unstarted patcher')
+            return
 
         if self.is_local and self.temp_original is not DEFAULT:
             setattr(self.target, self.attribute, self.temp_original)
index c484adb605086a576b4bc84f802d0d9dddde540d..2c14360b2df530f269873eb780ca4d0b5ede6b58 100644 (file)
@@ -772,10 +772,18 @@ class PatchTest(unittest.TestCase):
 
 
     def test_stop_without_start(self):
+        # bpo-36366: calling stop without start will return None.
         patcher = patch(foo_name, 'bar', 3)
+        self.assertIsNone(patcher.stop())
 
-        # calling stop without start used to produce a very obscure error
-        self.assertRaises(RuntimeError, patcher.stop)
+
+    def test_stop_idempotent(self):
+        # bpo-36366: calling stop on an already stopped patch will return None.
+        patcher = patch(foo_name, 'bar', 3)
+
+        patcher.start()
+        patcher.stop()
+        self.assertIsNone(patcher.stop())
 
 
     def test_patchobject_start_stop(self):
diff --git a/Misc/NEWS.d/next/Library/2019-03-20-15-13-18.bpo-36366.n0eav_.rst b/Misc/NEWS.d/next/Library/2019-03-20-15-13-18.bpo-36366.n0eav_.rst
new file mode 100644 (file)
index 0000000..a435048
--- /dev/null
@@ -0,0 +1,4 @@
+Calling ``stop()`` on an unstarted or stopped :func:`unittest.mock.patch`
+object will now return `None` instead of raising :exc:`RuntimeError`,
+making the method idempotent.
+Patch byKarthikeyan Singaravelan.