Skip to content

Commit fc83682

Browse files
committed
Fix RuntimeError if user code calls patcher.stopall
Fix #137
1 parent 35ade1c commit fc83682

File tree

3 files changed

+42
-1
lines changed

3 files changed

+42
-1
lines changed

Diff for: CHANGELOG.rst

+9
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,12 @@
1+
1.10.2
2+
------
3+
4+
* Fix bug at the end of the test session when a call to ``patch.stopall`` is done explicitly by
5+
user code. Thanks `@craiga`_ for the report (`#137`_).
6+
7+
.. _#137: https://github.com/pytest-dev/pytest-mock/issues/137
8+
.. _@craiga: https://github.com/craiga
9+
110
1.10.1
211
------
312

Diff for: pytest_mock.py

+11-1
Original file line numberDiff line numberDiff line change
@@ -288,7 +288,17 @@ def wrap_assert_methods(config):
288288

289289
def unwrap_assert_methods():
290290
for patcher in _mock_module_patches:
291-
patcher.stop()
291+
try:
292+
patcher.stop()
293+
except RuntimeError as e:
294+
# a patcher might have been stopped by user code (#137)
295+
# so we need to catch this error here and ignore it;
296+
# unfortunately there's no public API to check if a patch
297+
# has been started, so catching the error it is
298+
if text_type(e) == "stop called on unstarted patcher":
299+
pass
300+
else:
301+
raise
292302
_mock_module_patches[:] = []
293303
_mock_module_originals.clear()
294304

Diff for: test_pytest_mock.py

+22
Original file line numberDiff line numberDiff line change
@@ -610,3 +610,25 @@ def test_assert_called_with_unicode_arguments(mocker):
610610

611611
with pytest.raises(AssertionError):
612612
stub.assert_called_with(u"lak")
613+
614+
615+
def test_plain_stopall(testdir):
616+
"""Calling patch.stopall() in a test would cause an error during unconfigure (#137)"""
617+
testdir.makepyfile(
618+
"""
619+
from unittest.mock import patch
620+
import random
621+
622+
def get_random_number():
623+
return random.randint(0, 100)
624+
625+
def test_get_random_number():
626+
patcher = patch("random.randint", lambda x, y: 5)
627+
patcher.start()
628+
assert get_random_number() == 5
629+
patch.stopall()
630+
"""
631+
)
632+
result = testdir.runpytest_subprocess()
633+
result.stdout.fnmatch_lines("* 1 passed in *")
634+
assert "RuntimeError" not in result.stderr.str()

0 commit comments

Comments
 (0)