AttributeError: __exit__ when I try to mock assembly functions

I am currently trying to mock an open () built-in method in Python for a test. However, I always get crash and this message:

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__ 

Here is my test code:

 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() 
+7
python unit-testing mocking mox
source share
1 answer

__exit__ is the method that is called when trying to close the file. Your mock file does not handle mock_file.close() , just open() . You need to make fun of the close method as well.


Edit:

Secondly, why do you want to make fun of open ? AFAIK, you should not do this method. The test method should accept an open stream (for example, instead of a file name). In production code, clients are responsible for opening the file (for example, pickle.dump ). In your tests, you pass a StringIO or a mock object that supports writing.


Edit 2: I would split your method into two parts and check each bit separately.

  • file creation: check that the file does not exist before calling this method, and it does it after that. It can be argued that such a one-line method is not worth testing.
  • write to file: see above. Create a StringIO and write to this so your tests can verify the spelling.
+4
source share

All Articles