Skip to content
Closed
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-45756: do not execute @property descrs while creating mock auto…
…specs
  • Loading branch information
sobolevn committed Dec 3, 2021
commit 1c545e5fc54391a4c2ca8e6e3747d8f7baf8671c
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):
# We don't want to execute `@property` decorators with `getattr`.
Comment thread
sobolevn marked this conversation as resolved.
Outdated
# 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 @@
We no longer execute ``@property`` descriptors while creating autospecs in
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
We no longer execute ``@property`` descriptors while creating autospecs in
Fixed :class:`property` decorators executing descriptors while creating autospecs in

``mock.py``. This was not safe and could affect user's code in unknown way.
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
``mock.py``. This was not safe and could affect user's code in unknown way.
:mod:`unittest.mock`. This was not safe and could affect user's code in unknown ways.