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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With