Skip to content

Commit 540c17b

Browse files
authored
Merge pull request #138 from nicoddemus/release-1.10.2
Fix RuntimeError if user code calls patcher.stopall
2 parents 35ade1c + 24bce30 commit 540c17b

File tree

4 files changed

+44
-1
lines changed

4 files changed

+44
-1
lines changed

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

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

test_pytest_mock.py

+21
Original file line numberDiff line numberDiff line change
@@ -610,3 +610,24 @@ 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+
import random
620+
621+
def get_random_number():
622+
return random.randint(0, 100)
623+
624+
def test_get_random_number(mocker):
625+
patcher = mocker.mock_module.patch("random.randint", lambda x, y: 5)
626+
patcher.start()
627+
assert get_random_number() == 5
628+
mocker.mock_module.patch.stopall()
629+
"""
630+
)
631+
result = testdir.runpytest_subprocess()
632+
result.stdout.fnmatch_lines("* 1 passed in *")
633+
assert "RuntimeError" not in result.stderr.str()

tox.ini

+3
Original file line numberDiff line numberDiff line change
@@ -18,3 +18,6 @@ usedevelop = True
1818
extras = dev
1919
basepython = python3.6
2020
commands = pre-commit run --all-files --show-diff-on-failure
21+
22+
[pytest]
23+
addopts = -ra

0 commit comments

Comments
 (0)