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

时间:2018-09-21 11:33:14

标签: python python-3.x python-2.7

我有一个python代码,需要同时在Python 2和3中运行。 在python 2 dict.values()中返回列表,而在python 3中返回dict_val对象。为了使其兼容,我放置了list(dict.values())。工作正常。但是当我使用python模拟进行单元测试时,有一个错误。我在嘲笑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()

这里的list方法使魔术模拟对象为空列表,因此失败了。 下面是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方法使模拟对象为空列表。列表方法不应使模拟对象为空列表

2 个答案:

答案 0 :(得分:1)

更改:

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

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

修补程序目标应采用“ module.object_name”的形式,您错过了命名空间,其余错误都是错别字。

答案 1 :(得分:0)

尝试@patch(__name__ + '.get_dict', MagicMock(return_value={'key': {}) 给您的模拟对象一个合适的目标。