Skip to content

Commit 845876e

Browse files
authored
Raise error if any version of patch is used as a context manager (#168)
Raise error if any version of patch is used as a context manager
2 parents ed8216b + d3d10a5 commit 845876e

File tree

2 files changed

+20
-7
lines changed

2 files changed

+20
-7
lines changed

src/pytest_mock/plugin.py

+6-6
Original file line numberDiff line numberDiff line change
@@ -147,21 +147,17 @@ def _start_patch(self, mock_func, *args, **kwargs):
147147
module, registering the patch to stop it later and returns the
148148
mock object resulting from the mock call.
149149
"""
150+
self._enforce_no_with_context(inspect.stack())
150151
p = mock_func(*args, **kwargs)
151152
mocked = p.start()
152153
self._patches.append(p)
153154
if hasattr(mocked, "reset_mock"):
154155
self._mocks.append(mocked)
155156
return mocked
156157

157-
def object(self, *args, **kwargs):
158-
"""API to mock.patch.object"""
159-
self._enforce_no_with_context(inspect.stack())
160-
return self._start_patch(self.mock_module.patch.object, *args, **kwargs)
161-
162158
def _enforce_no_with_context(self, stack):
163159
"""raises a ValueError if mocker is used in a with context"""
164-
caller = stack[1]
160+
caller = stack[2]
165161
frame = caller[0]
166162
info = inspect.getframeinfo(frame)
167163
code_context = " ".join(info.code_context).strip()
@@ -172,6 +168,10 @@ def _enforce_no_with_context(self, stack):
172168
"https://github.com/pytest-dev/pytest-mock#note-about-usage-as-context-manager"
173169
)
174170

171+
def object(self, *args, **kwargs):
172+
"""API to mock.patch.object"""
173+
return self._start_patch(self.mock_module.patch.object, *args, **kwargs)
174+
175175
def multiple(self, *args, **kwargs):
176176
"""API to mock.patch.multiple"""
177177
return self._start_patch(self.mock_module.patch.multiple, *args, **kwargs)

tests/test_pytest_mock.py

+14-1
Original file line numberDiff line numberDiff line change
@@ -723,7 +723,7 @@ def test_get_random_number(mocker):
723723
assert "RuntimeError" not in result.stderr.str()
724724

725725

726-
def test_abort_context_manager(mocker):
726+
def test_abort_patch_object_context_manager(mocker):
727727
class A(object):
728728
def doIt(self):
729729
return False
@@ -740,3 +740,16 @@ def doIt(self):
740740
)
741741

742742
assert str(excinfo.value) == expected_error_msg
743+
744+
745+
def test_abort_patch_context_manager(mocker):
746+
with pytest.raises(ValueError) as excinfo:
747+
with mocker.patch("some_package"):
748+
pass
749+
750+
expected_error_msg = (
751+
"Using mocker in a with context is not supported. "
752+
"https://github.com/pytest-dev/pytest-mock#note-about-usage-as-context-manager"
753+
)
754+
755+
assert str(excinfo.value) == expected_error_msg

0 commit comments

Comments
 (0)