本文介绍了在单元测试中模拟open(file_name)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个源代码,可以打开一个csv文件并设置一个标头来价值关联.源代码如下:

I have a source code that opens a csv file and sets up a header tovalue association. The source code is given below:

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()

我正在尝试模拟以下语句

I am trying to mock the following statement

rack_type_file = open(rack_file)

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

How do I mock open(...) function?

推荐答案

这是一个古老的问题,因此某些答案已过时.

This is admittedly an old question, hence some of the answers are outdated.

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

In the current version of the mock library there is a convenience function designed for precisely this purpose. Here's how it works:

>>> 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')

文档位于此处.

这篇关于在单元测试中模拟open(file_name)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-03 20:09
查看更多