Python mock call_args_list unpacking tuples for assertion on arguments

I think that many of the difficulties here are wrapped up in the treatment of the “call” object. It can be thought of as a tuple with 2 members (args, kwargs) and so it’s frequently nice to unpack it:

args, kwargs = call

Once it’s unpacked, then you can make your assertions separately for args and kwargs (since one is a tuple and the other a dict)

def test_foo(self):
    def foo(fn):
        fn('PASS and some other stuff')

    f = Mock()
    foo(f)
    foo(f)
    foo(f)

    for call in f.call_args_list:
        args, kwargs = call
        self.assertTrue(all(a.startswith('PASS') for a in args))

Note that sometimes the terseness isn’t helpful (e.g. if there is an error):

for call in f.call_args_list:
    args, kwargs = call
    for a in args:
        self.assertTrue(a.startswith('PASS'), msg="%s doesn't start with PASS" % a)

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)