Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mock patch multiple

I'm trying to mock multiple functions inside a module, from within a TestCase:

from mock import patch, DEFAULT, Mock

function_a = Mock()
function_a.return_value = ['a', 'list'] 
with patch.multiple('target.module',
                    function_a=function_a,
                    function_b=DEFAULT) as (f_a, f_b):

To my surprise, this is not working, giving me the following Traceback:

ValueError: need more than 1 value to unpack

using: http://www.voidspace.org.uk/python/mock/

like image 809
Jonas Geiregat Avatar asked Oct 20 '25 01:10

Jonas Geiregat


1 Answers

For patch.multiple, assigning the patched function name (function_a) to any value other than DEFAULT, or unittest.mock.DEFAULT, will result in the returned dictionary not containing the mocked function.

In other words,
with patch.multiple('target.module', func_a=SOME_VALUE, func_b=DEFAULT) as mocks: mocks['func_a'] # KeyError: 'func_a'

Also, assigning with patch.multiple(...) as (f_a, f_b) is going to give you two strings, which in your case will be 'function_a' and 'function_b'. This is equivalent to the operation

x = dict(function_a = MagicMock_a, function_b = MagicMock_b)
(f_a, f_b) = x
f_a    # 'function_a'

If you wish to access the MagicMock object, assign it to the dictionary value instead, something like mocks['func_a'] = f_a.

like image 93
Melvin Avatar answered Oct 21 '25 15:10

Melvin