Mock object#
The unittest.mock.Mock and unittest.mock.MagicMock classes allow you to create special objects with defined behaviour and action tracking.
This page considers usefull properties of the mock objects.
import unittest
from unittest import mock
Return value#
You can use the return_value attribute to specify the output in case mock object is called.
The following cell creates the mock_obj and sets its return_value to "this is return".
mock_obj = mock.Mock()
mock_obj.return_value = "this is return"
If you call the mock object, it will return the specified value.
mock_obj()
'this is return'
Series of returns#
If you need to specify different outputs for a series of returns for a mock object, set the side_effect of the mock object as iterable object - each call will return the corresponding element.
The following cell creates mock_obj sets and displays the outputs of the several calls for it.
mock_obj = mock.Mock()
mock_obj.side_effect = [10, 20, 30]
mock_obj(), mock_obj(), mock_obj()
(10, 20, 30)
Note. In case there is no next object, you receive the corresponding message.
mock_obj()
---------------------------------------------------------------------------
StopIteration Traceback (most recent call last)
Cell In[6], line 1
----> 1 mock_obj()
File /usr/local/lib/python3.13/unittest/mock.py:1169, in CallableMixin.__call__(self, *args, **kwargs)
1167 self._mock_check_sig(*args, **kwargs)
1168 self._increment_mock_call(*args, **kwargs)
-> 1169 return self._mock_call(*args, **kwargs)
File /usr/local/lib/python3.13/unittest/mock.py:1173, in CallableMixin._mock_call(self, *args, **kwargs)
1172 def _mock_call(self, /, *args, **kwargs):
-> 1173 return self._execute_mock_call(*args, **kwargs)
File /usr/local/lib/python3.13/unittest/mock.py:1230, in CallableMixin._execute_mock_call(self, *args, **kwargs)
1228 raise effect
1229 elif not _callable(effect):
-> 1230 result = next(effect)
1231 if _is_exception(result):
1232 raise result
StopIteration:
Dynamic attributes#
Mock object automatically attributes that program refers to at the some stage. So you can mock any object and consider how program refers to it at the different stages of the program.
Consider a real-world example - suppose you need to check which query was passed to the cursor of the database.
The following cell creates a mocked cursor mocked object and sets to its execute attribute (which actually wasn’t defined anywhere before) to return_value = "hello".
cursor = mock.Mock()
cursor.execute.return_value = "hello"
cursor.execute.mock_calls = []
The following cell calls the “method” we just defined.
cursor.execute("some input")
'hello'
It returns the value defined in the return_value argument. You can interact with cursor.exexcute just like a normal mock object. For example following cell shows details of the call we created earlier.
cursor.execute.mock_calls
[call('some input')]