Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the arguments passed to various calls from call_args_list?

I'm trying to use call_args_list to get the arguments passed to a certain function when it is called multiple times. I'm using this:

call_args_list = mock.add_row.call_args_list

Then I get a list that looks like this: [call('A', []), call('B', []), call('C', ['err'])].

If I only want to check that the second call doesn't have an error in the second argument and the third does, I need to somehow access the items within the call. Does anyone know how can I peel these call objects to get the items inside?

like image 685
user3802348 Avatar asked Nov 01 '25 09:11

user3802348


2 Answers

import unittest

import mock


class TestCase(unittest.TestCase):
    def test_my_func(self):
        m = mock.MagicMock()
        m.add_row('A', [])
        m.add_row('B', [])
        m.add_row('C', ['err'])

        calls = m.add_row.call_args_list

        _first_arg, second_arg = calls[1][0]
        self.assertNotEqual(second_arg, ['err'])

        _first_arg, second_arg = calls[2][0]
        self.assertEqual(second_arg, ['err'])


if __name__ == '__main__':
    unittest.main()
like image 56
G_M Avatar answered Nov 03 '25 00:11

G_M


It doesn't appear to be (well) documented, but mock defines a subclass of tuple named _Call, instances of which are what you see in call_args_list. The first element is the name of the function, the second is a tuple of positional arguments, and the third a dict of keyword arguments.

like image 27
chepner Avatar answered Nov 02 '25 23:11

chepner