[Python-checkins] bpo-36366: Return None on stopping unstarted patch object (GH-12472)
Miss Islington (bot)
webhook-mailer at python.org
Thu Mar 28 17:08:47 EDT 2019
https://github.com/python/cpython/commit/02b84cb1b4f5407309c81c8b1ae0397355d6e568
commit: 02b84cb1b4f5407309c81c8b1ae0397355d6e568
branch: master
author: Xtreak <tir.karthi at gmail.com>
committer: Miss Islington (bot) <31488909+miss-islington at users.noreply.github.com>
date: 2019-03-28T14:08:43-07:00
summary:
bpo-36366: Return None on stopping unstarted patch object (GH-12472)
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
files:
A Misc/NEWS.d/next/Library/2019-03-20-15-13-18.bpo-36366.n0eav_.rst
M Lib/unittest/mock.py
M Lib/unittest/test/testmock/testpatch.py
diff --git a/Lib/unittest/mock.py b/Lib/unittest/mock.py
index fdde16be03a3..8684f1dfa572 100644
--- a/Lib/unittest/mock.py
+++ b/Lib/unittest/mock.py
@@ -1398,7 +1398,7 @@ def __enter__(self):
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)
diff --git a/Lib/unittest/test/testmock/testpatch.py b/Lib/unittest/test/testmock/testpatch.py
index c484adb60508..2c14360b2df5 100644
--- a/Lib/unittest/test/testmock/testpatch.py
+++ b/Lib/unittest/test/testmock/testpatch.py
@@ -772,10 +772,18 @@ def test_patch_start_stop(self):
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
index 000000000000..a43504839c6f
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2019-03-20-15-13-18.bpo-36366.n0eav_.rst
@@ -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.
More information about the Python-checkins
mailing list