我目前正在尝试用Python模拟open()内置方法进行测试。但是,我总是最终得到一个崩溃,结果就是这样的消息:
File "/opt/home/venv/lib/python2.7/site-packages/nose-1.3.0-py2.7.egg/nose/result.py", line 187, in _exc_info_to_string
return _TextTestResult._exc_info_to_string(self, err, test)
File "/opt/python-2.7.3/lib/python2.7/unittest/result.py", line 164, in _exc_info_to_string
msgLines = traceback.format_exception(exctype, value, tb)
File "/opt/python-2.7.3/lib/python2.7/traceback.py", line 141, in format_exception
list = list + format_tb(tb, limit)
File "/opt/python-2.7.3/lib/python2.7/traceback.py", line 76, in format_tb
return format_list(extract_tb(tb, limit))
File "/opt/python-2.7.3/lib/python2.7/traceback.py", line 101, in extract_tb
line = linecache.getline(filename, lineno, f.f_globals)
File "/opt/home/venv/lib/python2.7/linecache.py", line 14, in getline
lines = getlines(filename, module_globals)
File "/opt/home/venv/lib/python2.7/linecache.py", line 40, in getlines
return updatecache(filename, module_globals)
File "/opt/home/venv/lib/python2.7/linecache.py", line 127, in updatecache
with open(fullname, 'rU') as fp:
AttributeError: __exit__
这是我的测试代码:
m = mox.Mox()
m.StubOutWithMock(__builtin__, 'open')
mock_file = m.CreateMock(__builtin__.file)
open(mox.IgnoreArg(), mox.IgnoreArg()).AndReturn(mock_file)
mock_file.write(mox.IgnoreArg()).MultipleTimes()
mock_file.close()
write_file_method()
答案 0 :(得分:4)
__exit__
是尝试关闭文件时调用的方法。您的模拟文件无法处理mock_file.close()
,仅处理open()
。您还需要模拟close
方法。
编辑:
第二,你为什么要模仿open
? AFAIK你不应该做那种方法。测试中的方法应采用开放流(例如,而不是文件名)。在生产代码中,客户负责打开文件(例如pickle.dump
)。在测试中,您传入StringIO
或支持书写的模拟对象。
编辑2: 我将你的方法分成两部分并分别测试每一位。
StringIO
并写入,以便您的测试可以验证是否已写入正确的内容。