From 8241dd624f8ca481fe15a44f7d3fed10be7ae937 Mon Sep 17 00:00:00 2001 From: Claudiu Belu Date: Fri, 13 Apr 2018 10:33:12 -0700 Subject: [PATCH] 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 --- oslotest/mock_fixture.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/oslotest/mock_fixture.py b/oslotest/mock_fixture.py index ba53dd8..56d6516 100644 --- a/oslotest/mock_fixture.py +++ b/oslotest/mock_fixture.py @@ -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,