title: How to unit test with a mocked file object in Python?
body: <p>I have a class which I instantiate by giving a file name like <code>parser = ParserClass('/path/to/file')</code>, then I call <code>parser.parse()</code> method which opens and reads the file.<br>
  Now I want to unit test that if something bad happening inside:</p>
  
  <pre><code>with open(filename, 'rb') as fp:
      // do something
  </code></pre>
  
  <p>the correct Exception will be raised, so I want to mock the <code>__builtin__.open</code> like this:</p>
  
  <pre><code>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()
  </code></pre>
  
  <p>but this gives me an <code>AttributeError: StringIO instance has no attribute '__exit__'</code>.<br>
  I tought StringIO behaves exactly like a file object, but it seems, this is not the case.</p>
  
  <p>How could I test this method with a given content (test_lines) with mock objects? What should I use instead?</p>