2018年8月15日 星期三

[ Python 常見問題 ] Python mock call_args_list unpacking tuples for assertion on arguments

Source From Here 
Question 
I'm having some trouble dealing with the nested tuple which Mock.call_args_list returns: 
  1. from unittest.mock import Mock  
  2.   
  3. def test_foo():  
  4.     def foo(fn):  
  5.         fn('PASS and some other stuff')  
  6.   
  7.     f = Mock(return_value=None)  
  8.     foo(f)  
  9.     foo(f)  
  10.     foo(f)  
  11.   
  12.     for call in f.call_args_list:  
  13.         pass  
  14.         # make assertion here  
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: 
  1. 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) 
- test.py 
  1. from unittest.mock import Mock  
  2.   
  3. cnt = 0  
  4. names = ['John', 'Ken', 'Mary']  
  5.   
  6. def test_foo():  
  7.     def foo(fn):  
  8.         global cnt  
  9.         fn('PASS and some other stuff ' + str(cnt), name=names[cnt])  
  10.         cnt += 1  
  11.   
  12.     f = Mock(return_value=None)  
  13.     foo(f)  
  14.     foo(f)  
  15.     foo(f)  
  16.   
  17.     for call in f.call_args_list:  
  18.         args, kwargs = call  
  19.         print('args={}; kwargs={}'.format(args, kwargs))  
Execution output: 
$ pytest -s test.py 
================================================================= test session starts ================================================================== 
platform linux -- Python 3.5.0, pytest-3.2.1, py-1.4.34, pluggy-0.4.0 
rootdir: /tmp, inifile: 
collected 1 item 

test.py args=('PASS and some other stuff 0',); kwargs={'name': 'John'} 
args=('PASS and some other stuff 1',); kwargs={'name': 'Ken'} 
args=('PASS and some other stuff 2',); kwargs={'name': 'Mary'}


沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...