How to mock `name` attribute with unittest.mock.MagicMock or Mock classes?

Viewed 3820

I am trying to create MagicMock with mocked name and it seems as not working, but works for other attributes:

from unittest.mock import MagicMock

# Works
assert MagicMock(foo='bar').foo == 'bar'

# Don't work
assert MagicMock(name='bar').name == 'bar'

print(MagicMock(name='bar').name)
<MagicMock name=\'bar.name\' id=\'140031146167376\'>

How to mock name attribute with MagicMock ?

2 Answers

The name attribute cannot be mocked during creation of the mock object, since it has special meaning:

name: If the mock has a name then it will be used in the repr of the mock. This can be useful for debugging. The name is propagated to child mocks.

Python Documentation of Mock

Therefore in order to mock the name it shall be set after creating the Mock or MagicMock object and before passing it forward:

mock_obj = MagicMock()
mock_obj.name = 'bar'

assert mock_obj.name == 'bar'

# Passing mock object forward
...

It's been a while since this question was asked, but the mock's documentation now mentions this case explicitly and suggests two solutions. One of them is to set the name attribute after mock creation, as shown in the other answer; another possible solution is to use configure_mock():

>>> mock = MagicMock()
>>> mock.configure_mock(name='my_name')
>>> mock.name
'my_name'
Related