5.2. Test MockΒΆ

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: ')]