Skip to main content
 首页 » 编程设计

python之当我们传递魔术模拟对象时,python 中的 List 方法返回空列表

2024年12月31日10落叶

我有一个 python 代码需要在 Python 2 和 3 中运行。 在 python 2 dict.values()返回列表,但在 python 3 中它返回 dict_val目的。所以为了让它兼容我放了list(dict.values()) .它工作正常。但是当我使用 python mock 进行单元测试时,出现一个错误。我在 mock dict.values()它给出这样的输出 <MagicMock name='mock().values()' id='1099587993168'> ,但是当我使用列表时,它会生成这个空列表。下面是示例。

函数文件:

class abc():     
 def get_dict(self, key):#i want to mock this as its depends on other method also 
    dic = {'key': {'smaplekey': 'samplevalue'}}# its sample -  
    return dic['key'] 
 
 def run_method(self, val): 
    print val 
 
 def a(self,key): 
  print 'before list' 
  print self.get_dict(key).values() 
  print list(self.get_dict(key).values()) 
  b = list(self.get_dict(key).values())[0] 
  print 'after list' 
  self.run_method(b) 

测试文件:

import unittest 
from mock import Mock, patch, MagicMock, ANY 
import function_file 
class TestA(unittest.TestCase): 
  @patch('function_file.abc.run_method') 
  @patch('function_file.abc.get_dict',MagicMock(return_vlaue={'key': {}})) 
  def test_a(self, mock_run_method): 
    manager = function_file.abc() 
    result = manager.a('key') 
    mock_run_method.assert_called_once_with(ANY, create=True) 
 
if __name__ == '__main__': 
    unittest.main() 

这里的列表方法使魔术模拟对象成为空列表,因此它失败了。 下面是python错误

 before list 
<MagicMock name='mock().values()' id='1099803145040'> 
[] 
E 
====================================================================== 
ERROR: test_a (__main__.TestA) 
---------------------------------------------------------------------- 
Traceback (most recent call last): 
  File "/usr/lib/python2.7/site-packages/mock/mock.py", line 1305, in patched 
    return func(*args, **keywargs) 
  File "test_manager.py", line 9, in test_a 
    result = manager.a('key') 
  File "/usr/lib/python2.7/site-packages/abcd/function_file.py", line 13, in a 
    b = list(self.get_dict(key).values())[0] 
IndexError: list index out of range 
 
---------------------------------------------------------------------- 
Ran 1 test in 0.004s 
 
FAILED (errors=1) 

这里它进入 'a' 方法并打印,但是 list 方法使模拟对象为空列表。列表方法不应使模拟对象为空列表

请您参考如下方法:

改变:

@patch('get_dict',MagicMock(return_vlaue={'key': {}})) 

到

@patch('__main__.get_dict', MagicMock(return_value={'key': 1})) 

补丁目标应该是“module.object_name”的形式,你错过了命名空间,剩下的错误是拼写错误。