Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Next Next commit
bpo-41768: Use getattr_static when adding mock spec
Since commit 77b3b77, class properties
are being called when adding mock specs and this can introduce side
effects for tests that are verifying state affected by code inside a
@Property.

This replaces the getattr call with a inspect.getattr_static call to
avoid executing class code as part of the mock speccing process.
  • Loading branch information
melwitt committed Aug 19, 2021
commit 0a617700c68c60c097229de337e8c284b8ea2ac4
2 changes: 1 addition & 1 deletion Lib/unittest/mock.py
Original file line number Diff line number Diff line change
Expand Up @@ -494,7 +494,7 @@ def _mock_add_spec(self, spec, spec_set, _spec_as_instance=False,
_spec_asyncs = []

for attr in dir(spec):
if iscoroutinefunction(getattr(spec, attr, None)):
if iscoroutinefunction(inspect.getattr_static(spec, attr, None)):
_spec_asyncs.append(attr)

if spec is not None and not _is_list(spec):
Expand Down
16 changes: 16 additions & 0 deletions Lib/unittest/test/testmock/testmock.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,16 @@ def cmeth(cls, a, b, c, d=None): pass
def smeth(a, b, c, d=None): pass


class SomethingElse(object):
def __init__(self):
self._instance = None

@property
def instance(self):
if not self._instance:
self._instance = 'object'

Comment thread
melwitt marked this conversation as resolved.
Outdated

class Typos():
autospect = None
auto_spec = None
Expand Down Expand Up @@ -2249,6 +2259,12 @@ class Foo():
f'{__name__}.Typos', autospect=True, set_spec=True, auto_spec=True):
pass

def test_property_not_called_with_spec_mock(self):
obj = SomethingElse()
self.assertIsNone(obj._instance)
mock = Mock(spec=obj)
self.assertIsNone(obj._instance)
Comment thread
melwitt marked this conversation as resolved.
Outdated

Comment thread
melwitt marked this conversation as resolved.
Outdated

if __name__ == '__main__':
unittest.main()