Source From Here
Question
I'm having some trouble dealing with the nested tuple which Mock.call_args_list returns:
How-To
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:
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)
- test.py
Execution output:
Question
I'm having some trouble dealing with the nested tuple which Mock.call_args_list returns:
- from unittest.mock import Mock
- def test_foo():
- def foo(fn):
- fn('PASS and some other stuff')
- f = Mock(return_value=None)
- foo(f)
- foo(f)
- foo(f)
- for call in f.call_args_list:
- pass
- # make assertion here
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
- test.py
- from unittest.mock import Mock
- cnt = 0
- names = ['John', 'Ken', 'Mary']
- def test_foo():
- def foo(fn):
- global cnt
- fn('PASS and some other stuff ' + str(cnt), name=names[cnt])
- cnt += 1
- f = Mock(return_value=None)
- foo(f)
- foo(f)
- foo(f)
- for call in f.call_args_list:
- args, kwargs = call
- print('args={}; kwargs={}'.format(args, kwargs))
沒有留言:
張貼留言