Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unit test with a mocked file object in Python?

I have a class which I instantiate by giving a file name like parser = ParserClass('/path/to/file'), then I call parser.parse() method which opens and reads the file.
Now I want to unit test that if something bad happening inside:

with open(filename, 'rb') as fp:
    // do something

the correct Exception will be raised, so I want to mock the __builtin__.open like this:

from mock import MagicMock, patch
from StringIO import StringIO

test_lines = StringIO("""some test lines, emulating a real file content""")
mock_open = MagicMock(return_value=test_lines)
with patch('__builtin__.open', mock_open):
    self.mock.parse()

but this gives me an AttributeError: StringIO instance has no attribute '__exit__'.
I tought StringIO behaves exactly like a file object, but it seems, this is not the case.

How could I test this method with a given content (test_lines) with mock objects? What should I use instead?

like image 756
kissgyorgy Avatar asked Jun 13 '13 14:06

kissgyorgy


1 Answers

There is a provision, specifically for this purpose in the mock library:

It does have an issue in missing support for default iterator (ie. __iter__ method, so you can't do for line in opened_mock_file straight away), but it can be worked around as described here.

I have upvoted @icecrime's answer, but I feel his update part doesn't seem to be highlighted enough.

like image 160
0xc0de Avatar answered Sep 28 '22 09:09

0xc0de