mock: Perform patch's autospec checks on __enter__

Currently we're doing the autospec checks on __init__ (if the
target is autospecable), which will require importing modules
in some cases.

The mock.patch's constructor is called when a test module is being
loaded, before any set up could have been run, which can be problematic
in some cases (e.g.: some tested modules are importing platform specific
modules, and they couldn't have been mocked yet).

This patch moves the autospec checks to __enter__, which is executed
after the setUp.

Related-Bug: #1735588

Change-Id: I9e10b34092ad795c7f9e58596fcccf4f37856225
This commit is contained in:
Claudiu Belu 2018-04-13 10:33:12 -07:00
parent 9837c5ef98
commit 8241dd624f
1 changed files with 5 additions and 5 deletions

View File

@ -122,8 +122,10 @@ class _patch(mock.mock._patch):
https://github.com/testing-cabal/mock/issues/396
"""
def __init__(self, *args, **kwargs):
super(_patch, self).__init__(*args, **kwargs)
def __enter__(self):
# NOTE(claudiub): we're doing the autospec checks here so unit tests
# have a chance to set up mocks in advance (e.g.: mocking platform
# specific libraries, which would cause the patch to fail otherwise).
# By default, autospec is None. We will consider it as True.
autospec = True if self.autospec is None else self.autospec
@ -146,11 +148,9 @@ class _patch(mock.mock._patch):
# NOTE(claudiub): reset the self.autospec property, so we can handle
# the autospec scenario ourselves.
self._autospec = autospec
self.autospec = None
def __enter__(self):
if self._autospec:
if autospec:
target = self.getter()
original_attr = getattr(target, self.attribute)
eat_self = mock.mock._must_skip(target, self.attribute,