Python mock patch instance method and check call arguments

I am using Mock ( http://mock.readthedocs.org/en/latest/ ) library with Python 2.7. I have a main function that calls several other functions that I am trying to test.

The other functions it calls are other instance methods (eg def _other_function(self, a, b)

.

I am calling my main function and I have other functions that it calls fix. I just added autospec=True

to the patch. However, when I check the call arguments, it shows the argument self

(as expected):

python2.7> _other_function_mock.call_args_list
[call(<some.module.class.method object at 0x9acab90>, 1, 2)]

      

Before setting autospec=True

it will only show the arguments that I actually passed (1 and 2). Since the call args now shows a reference to self

, I can't just call mock_object.assert_any_call(1, 2)

. I will need to select arguments from mock_object.call_args_list

and compare.

Is there a way to still call mock.assert_any_call

without having to manually select the arguments to check if the arguments passed are correct?

Or is there something better in general that I can do to fix the instance methods?

+3


source to share


1 answer


Essentially, there are two ways to play around the self

patch link autospec=True

.



In any case, 2 cannot be used in all cases, sometimes you cannot have an instance of an object in the context of a test method; moreover, this method often makes the test less understandable and more complex. I always prefer using 1 in my tests:

@patch("my_module.MyClass.my_method", autospec=True)
def test_my_test(self, mock_my_method):
    my_module.MyClass().my_method(1,2)
    mock_my_method.assert_any_call(mock.ANY, 1, 2)

      

+9


source







All Articles