Skip to content

bpo-45756: do not execute @property descrs while creating mock autospecs #29901

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

Closed
wants to merge 4 commits into from
Closed
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
4 changes: 4 additions & 0 deletions Lib/unittest/mock.py
Original file line number Diff line number Diff line change
Expand Up @@ -494,6 +494,10 @@ def _mock_add_spec(self, spec, spec_set, _spec_as_instance=False,
_spec_asyncs = []

for attr in dir(spec):
if isinstance(inspect.getattr_static(spec, attr, None), property):
# Don't execute `property` decorators with `getattr`.
# It might affect user's code in unknown way.
continue
if iscoroutinefunction(getattr(spec, attr, None)):
_spec_asyncs.append(attr)

Expand Down
30 changes: 30 additions & 0 deletions Lib/unittest/test/testmock/testmock.py
Original file line number Diff line number Diff line change
Expand Up @@ -896,6 +896,36 @@ def set_attr():
self.assertRaises(AttributeError, set_attr)


def test_class_with_property(self):
class X:
@property
def some(self):
raise ValueError('Should not be raised')

mock = Mock(spec=X)
self.assertIsInstance(mock, X)

mock = Mock(spec=X())
self.assertIsInstance(mock, X)


def test_class_with_settable_property(self):
class X:
@property
def some(self):
raise ValueError('Should not be raised')

@some.setter
def some(self, value):
raise TypeError('Should not be raised')

mock = Mock(spec=X)
self.assertIsInstance(mock, X)

mock = Mock(spec=X())
self.assertIsInstance(mock, X)


def test_copy(self):
current = sys.getrecursionlimit()
self.addCleanup(sys.setrecursionlimit, current)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Do not execute ``@property`` descriptors while creating autospecs in :mod:`unittest.mock`.
This was not safe and could affect users' code in unknown way.