在单元测试中模拟open(file_name)

31 投票
8 回答
48307 浏览
提问于 2025-04-16 13:17

我有一段源代码,它可以打开一个csv文件,并设置一个标题和对应值的关系。下面是这段源代码:

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(...)这个函数呢?

8 个回答

11

我有两种方法可以做到这一点,具体取决于情况。

如果你的单元测试会直接调用ParseCsvFile函数,我会给ParseCsvFile添加一个新的可选参数(kwarg):

def ParseCsvFile(source, open=open): 
    # ...
    rack_type_file = open(rack_file)  # Need to mock this line.

这样,你的单元测试就可以传入一个不同的open_func来实现模拟测试。

但如果你的单元测试是调用其他函数,而这些函数又会调用ParseCsvFile,那么为了测试而到处传递open_func就显得很麻烦。在这种情况下,我会使用mock模块。这个模块可以让你通过函数名来修改一个函数,并用一个模拟对象(Mock object)替换它。

# code.py
def open_func(name):
    return open(name)

def ParseCsvFile(source):
    # ...
    rack_type_file = open_func(rack_file)  # Need to mock this line.

# test.py
import unittest
import mock
from StringIO import StringIO

@mock.patch('code.open_func')
class ParseCsvTest(unittest.TestCase):
    def test_parse(self, open_mock):
        open_mock.return_value = StringIO("my,example,input")
        # ...
14

要使用mox来模拟内置的open函数,可以用到__builtin__模块:

import __builtin__ # unlike __builtins__ this must be imported
m = mox.Mox()
m.StubOutWithMock(__builtin__, 'open')
open('ftphelp.yml', 'rb').AndReturn(StringIO("fake file content"))     
m.ReplayAll()
# call the code you want to test that calls `open`
m.VerifyAll()
m.UnsetStubs()

需要注意的是,__builtins__不总是一个模块,它有时是一个字典类型。请使用__builtin__(没有"s")模块来引用系统的内置方法。

关于__builtin__模块的更多信息,可以查看这个链接:http://docs.python.org/library/builtin.html

30

这确实是个老问题,所以有些回答可能已经过时了。

在现在的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')

文档可以在这里找到。

撰写回答