CodeBlanks Logo Icon CodeBlanks

MagicMock

Learn magic-method mock with MagicMock.

MagicMock

MagicMock extends Mock to also support magic (dunder) methods. It can mimic the behavior of __len__, __iter__, __getitem__ and the rest.

The plain Mock raises errors or returns odd results when these methods are called. MagicMock makes them controllable.

from unittest.mock import MagicMock

m = MagicMock()
m.__len__.return_value = 3
print(len(m))  # 3

This is perfect for mimicking list-like or dict-like objects.

List mimicry with MagicMock

With MagicMock you easily mimic list-like behavior. You set length with __len__ and indexing with __getitem__.

Example: m.__len__.return_value = 2 and m.__getitem__.return_value = "a". Then len(m) returns 2; m[0] returns "a".

This lets you test list interfaces without a real data source. Control over magic methods makes the fake realistic.

Practice Length mimicry with MagicMock

Import MagicMock from unittest.mock. Create m = MagicMock(). Set m.__len__.return_value = 3; call print(len(m)).

Starter code

main.py
# import MagicMock from unittest.mock
# create MagicMock m; set __len__ return value to 3
# print len(m)

Sample solution

main.py
from unittest.mock import MagicMock

m = MagicMock()
m.__len__.return_value = 3
print(len(m))

Expected output

3

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match the MagicMock uses

Term Meaning
MagicMock() Fake with magic methods
m.__len__ len() behavior
m.__iter__ for-loop behavior
m.__getitem__ index behavior

2 Import MagicMock

Question
from unittest.mock import ____

m = MagicMock()
m.__len__.return_value = 3
print(len(m))
Answer
from unittest.mock import MagicMock

m = MagicMock()
m.__len__.return_value = 3
print(len(m))

Explanation: The MagicMock class comes from the unittest.mock module.

3 Which method call causes TROUBLE with the plain Mock?

  • len(m) Correct answer
  • m.attr
  • m.normal_method()
  • m()

Explanation: len() calls the __len__ magic method; the plain Mock does not handle it well. MagicMock is needed.

All lessons in Advanced