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 ?
So what is the difference between them? MagicMock is a subclass of Mock . It contains all magic methods pre-created and ready to use (e.g. __str__ , __len__ , etc.). Therefore, you should use MagicMock when you need magic methods, and Mock if you don't need them.
To mock objects, you use the unittest. mock module. The unittest. mock module provides the Mock class that allows you to mock other objects.
Mocking ClassesInstances are created by calling the class. This means you access the “mock instance” by looking at the return value of the mocked class. In the example below we have a function some_function that instantiates Foo and calls a method on it. The call to patch() replaces the class Foo with a mock.
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
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With