8000 bpo-36366: Return None on stopping unstarted patch object (GH-12472) · python/cpython@02b84cb · GitHub
[go: up one dir, main page]

Skip to content

Commit 02b84cb

Browse files
tirkarthimiss-islington
authored andcommitted
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
1 parent 3d78c4a commit 02b84cb

File tree

3 files changed

+15
-3
lines changed

3 files changed

+15
-3
lines changed

Lib/unittest/mock.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1398,7 +1398,7 @@ def __enter__(self):
13981398
def __exit__(self, *exc_info):
13991399
"""Undo the patch."""
14001400
if not _is_started(self):
1401-
raise RuntimeError('stop called on unstarted patcher')
1401+
return
14021402

14031403
if self.is_local and self.temp_original is not DEFAULT:
14041404
setattr(self.target, self.attribute, self.temp_original)

Lib/unittest/test/testmock/testpatch.py

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -772,10 +772,18 @@ def test_patch_start_stop(self):
772772

773773

774774
def test_stop_without_start(self):
775+
# bpo-36366: calling stop without start will return None.
775776
patcher = patch(foo_name, 'bar', 3)
777+
self.assertIsNone(patcher.stop())
776778

777-
# calling stop without start used to produce a very obscure error
778-
self.assertRaises(RuntimeError, patcher.stop)
779+
780+
def test_stop_idempotent(self):
781+
# bpo-36366: calling stop on an already stopped patch will return None.
782+
patcher = patch(foo_name, 'bar', 3)
783+
784+
patcher.start()
785+
patcher.stop()
786+
self.assertIsNone(patcher.stop())
779787

780788

781789
def test_patchobject_start_stop(self):
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
Calling ``stop()`` on an unstarted or stopped :func:`unittest.mock.patch`
2+
object will now return `None` instead of raising :exc:`RuntimeError`,
3+
making the method idempotent.
4+
Patch byKarthikeyan Singaravelan.

0 commit comments

Comments
 (0)
0