unittest.mock Quick Guide – return_value and side_effect from unittest.mock import Mock # import the Mock class from unittest.mock import MagicMock # import the MagicMock class class ProductionClass(): def __init__(self): pass # Mock and MagicMock objects create all attributes and methods as you access them and store details # of how they have been used. You can configure them, to specify return values or limit what # attributes are available, and then make assertions about how they have been used thing = ProductionClass() thing.method = MagicMock(return_value = 3) # calling method() will return 3 print(thing.method()) # print the return_value thing.method(3, 4, 5, key = 'value') thing.method.assert_called_with(3, 4, 5, key ='value') # AssertionError if different than expected call print(dir(Mock())) # show all the default mock methods / attributes # side_effect allows you to perform side effects, including raising an exception when a mock is called my_mock = Mock(side_effect = KeyError('foo')) # create a new mock object with KeyError exception # my_mock() # mock -> side_effect = KeyError exception values = {'a': 1, 'b': 2, 'c': 3} def side_effect_func(arg): return values[arg] my_mock.side_effect = side_effect_func # mock -> side_effect_func print(my_mock('a'), my_mock('b'), my_mock('c')) # print values side_effect_func(arg) my_mock.side_effect = [5, 4, 3, 2, 1] # change side_effect again for x in range(0, 5): # side_effect now returns array one by one print(my_mock()) quick_guide_mock1.py # output thing.method(): 3 dir(Mock()): ['assert_any_call', 'assert_called', 'assert_called_once', 'assert_called_once_with', 'assert_called_with', 'assert_has_calls', 'assert_not_called', 'attach_mock', 'call_args', 'call_args_list', 'call_count', 'called', 'configure_mock', 'method_calls', 'mock_add_spec', 'mock_calls', 'reset_mock', 'return_value', 'side_effect'] dict: 1 2 3 range: 5 4 3 2 1