5.3. Unittest Mock

mock

an object which has more advanced capabilities than Stub, such as: counting number of calls, recording passed arguments etc.

In following example we simulate input() built-in function with MagicMock. Then, usage of input() is as normal.

>>> from unittest.mock import MagicMock
>>>
>>>
>>> input = MagicMock(return_value='Mark Watney')
>>>
>>> input('What is your name?: ')
'Mark Watney'

Using MagicMock you can simulate more than one future input values from user:

>>> from unittest.mock import MagicMock
>>>
>>>
>>> input = MagicMock(side_effect=['red', 'green', 'blue'])
>>>
>>> input('Type color: ')
'red'
>>> input('Type color: ')
'green'
>>> input('Type color: ')
'blue'

Mocks has advantage over stubs, because they collect some diagnostic information.

>>> input.called
True
>>> input.call_count
3
>>> input.mock_calls  
[call('Type color: '),
 call('Type color: '),
 call('Type color: ')]

5.3.1. Case Study B

  • Defining variable with the same name as in outer scope

  • Mock

Shadowing of a global scope is used frequently in Mocks and Stubs. This way, we can simulate user input. Note that Mocks and Stubs will stay until the end of a program.

>>> from unittest.mock import Mock
>>> input = Mock(side_effect=['Mark Watney', '44'])

If we call function input(), it will not ask the user to provide information, but will execute our "overwritten" function (mock), which returns value: 'Mark Watney'.

>>> name = input('Type your name: ')
>>> name
'Mark Watney'

In contrary to the stubs, mocks can be programed to simulate different output for each time the function is called:

>>> age = input('Type your age: ')
>>> age
'44'

However, calling it once again will result in an error. This is because the mock was programmed to answer to only two questions. When calling it for the third time, the StopIteration exception will be raised.

>>> job = input('Type your job: ')
Traceback (most recent call last):
StopIteration

To restore default behavior of input() function use:

>>> from builtins import input