Skip to content

Commit 6587f79

Browse files
committed
Raise error on every patch context manager
On #165, a change was added to raise an Exception when trying to use `mocker.patch.object` as a context manager, as its behavior is not supported in the plugin. However, the context managers for the remaining patch options (dict, multiple, and normal patch) still work as usual. With this change, we check if we are in a context manager when starting the patch, so all the methods will raise the exception if corresponds
1 parent 1c5e8e9 commit 6587f79

File tree

1 file changed

+6
-6
lines changed

1 file changed

+6
-6
lines changed

src/pytest_mock/plugin.py

Lines changed: 6 additions & 6 deletions
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)

0 commit comments

Comments
 (0)