Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 ?

like image 971
Andriy Ivaneyko Avatar asked Jun 24 '20 09:06

Andriy Ivaneyko


People also ask

What is the difference between MagicMock and mock?

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.

How do you mock a class in Unittest Python?

To mock objects, you use the unittest. mock module. The unittest. mock module provides the Mock class that allows you to mock other objects.

How do I mock a function in Unittest?

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.


1 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
...
like image 164
Andriy Ivaneyko Avatar answered Oct 16 '22 21:10

Andriy Ivaneyko