我有一个打开csv文件并设置 header 的源代码
值(value)关联。源代码如下:

def ParseCsvFile(source):
  """Parse the csv file.
  Args:
    source: file to be parsed

  Returns: the list of dictionary entities; each dictionary contains
             attribute to value mapping or its equivalent.
  """
  global rack_file
  rack_type_file = None
  try:
    rack_file = source
    rack_type_file = open(rack_file)  # Need to mock this line.
    headers = rack_type_file.readline().split(',')
    length = len(headers)
    reader = csv.reader(rack_type_file, delimiter=',')
    attributes_list=[] # list of dictionaries.
    for line in reader:
      # More process to happeng. Converting the rack name to sequence.
      attributes_list.append(dict((headers[i],
                                   line[i]) for i in range(length)))
    return attributes_list
  except IOError, (errno, strerror):
    logging.error("I/O error(%s): %s" % (errno, strerror))
  except IndexError, (errno, strerror):
    logging.error('Index Error(%s), %s' %(errno, strerror))
  finally:
    rack_type_file.close()

我正在尝试模仿以下陈述
rack_type_file = open(rack_file)

如何模拟open(...)函数?

最佳答案

诚然,这是一个老问题,因此某些答案已过时。

在当前版本的mock中,有一个专门用于此目的的便捷功能。运作方式如下:

>>> from mock import mock_open
>>> m = mock_open()
>>> with patch('__main__.open', m, create=True):
...     with open('foo', 'w') as h:
...         h.write('some stuff')
...
>>> m.mock_calls
[call('foo', 'w'),
 call().__enter__(),
 call().write('some stuff'),
 call().__exit__(None, None, None)]
>>> m.assert_called_once_with('foo', 'w')
>>> handle = m()
>>> handle.write.assert_called_once_with('some stuff')

文档为here

关于python - 在单元测试中模拟open(file_name),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5237693/

10-10 17:05