Skip to content

Commit

Permalink
Raise error on every patch context manager
Browse files Browse the repository at this point in the history
On pytest-dev#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
  • Loading branch information
AlexGascon committed Oct 30, 2019
1 parent 1c5e8e9 commit 6587f79
Showing 1 changed file with 6 additions and 6 deletions.
12 changes: 6 additions & 6 deletions src/pytest_mock/plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -147,21 +147,17 @@ def _start_patch(self, mock_func, *args, **kwargs):
module, registering the patch to stop it later and returns the
mock object resulting from the mock call.
"""
self._enforce_no_with_context(inspect.stack())
p = mock_func(*args, **kwargs)
mocked = p.start()
self._patches.append(p)
if hasattr(mocked, "reset_mock"):
self._mocks.append(mocked)
return mocked

def object(self, *args, **kwargs):
"""API to mock.patch.object"""
self._enforce_no_with_context(inspect.stack())
return self._start_patch(self.mock_module.patch.object, *args, **kwargs)

def _enforce_no_with_context(self, stack):
"""raises a ValueError if mocker is used in a with context"""
caller = stack[1]
caller = stack[2]
frame = caller[0]
info = inspect.getframeinfo(frame)
code_context = " ".join(info.code_context).strip()
Expand All @@ -172,6 +168,10 @@ def _enforce_no_with_context(self, stack):
"https://github.com/pytest-dev/pytest-mock#note-about-usage-as-context-manager"
)

def object(self, *args, **kwargs):
"""API to mock.patch.object"""
return self._start_patch(self.mock_module.patch.object, *args, **kwargs)

def multiple(self, *args, **kwargs):
"""API to mock.patch.multiple"""
return self._start_patch(self.mock_module.patch.multiple, *args, **kwargs)
Expand Down

0 comments on commit 6587f79

Please sign in to comment.