Skip to content

[3.12] gh-119600: mock: do not access attributes of original when new_callable is set (GH-119601) #120335

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 11, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions Lib/test/test_unittest/testmock/support.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,14 @@ def wibble(self): pass

class X(object):
pass

# A standin for weurkzeug.local.LocalProxy - issue 119600
def _inaccessible(*args, **kwargs):
raise AttributeError


class OpaqueProxy:
__getattribute__ = _inaccessible


g = OpaqueProxy()
7 changes: 7 additions & 0 deletions Lib/test/test_unittest/testmock/testpatch.py
Original file line number Diff line number Diff line change
Expand Up @@ -2045,6 +2045,13 @@ def test(): pass
with self.assertRaises(TypeError):
test()

def test_patch_proxy_object(self):
@patch("test.test_unittest.testmock.support.g", new_callable=MagicMock())
def test(_):
pass

test()


if __name__ == '__main__':
unittest.main()
14 changes: 9 additions & 5 deletions Lib/unittest/mock.py
Original file line number Diff line number Diff line change
Expand Up @@ -1478,13 +1478,12 @@ def __enter__(self):
if isinstance(original, type):
# If we're patching out a class and there is a spec
inherit = True
if spec is None and _is_async_obj(original):
Klass = AsyncMock
else:
Klass = MagicMock
_kwargs = {}

# Determine the Klass to use
if new_callable is not None:
Klass = new_callable
elif spec is None and _is_async_obj(original):
Klass = AsyncMock
elif spec is not None or spec_set is not None:
this_spec = spec
if spec_set is not None:
Expand All @@ -1497,7 +1496,12 @@ def __enter__(self):
Klass = AsyncMock
elif not_callable:
Klass = NonCallableMagicMock
else:
Klass = MagicMock
else:
Klass = MagicMock

_kwargs = {}
if spec is not None:
_kwargs['spec'] = spec
if spec_set is not None:
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Fix :func:`unittest.mock.patch` to not read attributes of the target when
``new_callable`` is set. Patch by Robert Collins.
Loading