Python Glossary Русский

Python 3.3+unittestterm

MagicMock

mocks

A general-purpose mock object that supports the magic methods (__len__, __iter__ and so on). It can stand in for any object, so a real dependency is not needed.

Syntax

from unittest.mock import MagicMock
m = MagicMock()
m.method.return_value = 42

Every attribute of a MagicMock is created on first access, so a misspelled method name does not fail the test — it just yields another mock and the check quietly passes; pass spec= or build the mock with create_autospec() from the real object to catch that. The difference from a plain Mock is the preconfigured magic methods: length is 0, iteration is empty, truthiness is True, whereas Mock would raise TypeError on len() and iteration.

Examples

from unittest.mock import MagicMock
db = MagicMock()
db.query.return_value = [1, 2, 3]
result = db.query('SELECT *')
print(result)  # [1, 2, 3]
db.query.assert_called_with('SELECT *')
print(len(db))  # 0 (магический метод)

See also

Open in the full glossarydocs.python.orgReport an inaccuracy