This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author florian.brucker
Recipients docs@python, florian.brucker
Date 2020-01-05.14:58:31
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1578236312.03.0.58171840403.issue39222@roundup.psfhosted.org>
In-reply-to
Content
The "parent" attribute of unittest.mock.Mock is either broken or undocumented.

For example, on Python 3.7.4:

>>> from unittest.mock import Mock
>>> m = Mock(x=1, parent=2)
>>> m.x
1
>>> m.parent
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.7/unittest/mock.py", line 659, in __repr__
    name = self._extract_mock_name()
  File "/usr/local/lib/python3.7/unittest/mock.py", line 638, in _extract_mock_name
    _name_list.append(_parent._mock_new_name + dot)
AttributeError: 'int' object has no attribute '_mock_new_name'
>>> parent = Mock()
>>> child = Mock(parent=parent)
>>> child.parent is parent
False

I stumbled upon this while trying to mock an object that has a "parent" attribute.

From the documentation I understand that mocks have built-in parents. However, the documentation never mentions the "parent" attribute specifically, so I always assumed that the built-in parent-child relationship was handled using private or name-mangled attributes. And since the "parent" attribute is not mentioned in the docs, I assumed I could set it by passing an additional kwarg to Mock.

I would have expected one of the following, in order of personal preference:

a) That a private or name-mangled attribute is used for the built-in parent-child relationship, so that I can mock objects which themselves have a "parent" attribute

b) That the special meaning of the "parent" attribute is documented, and that trying to set it directly (via the constructor or via attribute assignment, and without going through attach_mock) triggers a warning.
History
Date User Action Args
2020-01-05 14:58:32florian.bruckersetrecipients: + florian.brucker, docs@python
2020-01-05 14:58:32florian.bruckersetmessageid: <1578236312.03.0.58171840403.issue39222@roundup.psfhosted.org>
2020-01-05 14:58:31florian.bruckerlinkissue39222 messages
2020-01-05 14:58:31florian.bruckercreate