How to stub the context manager close method in Python?
Question: I need to do some operations that did not work well using the builtin mock
module. Then I decided to mock this by myself, using:

    
    
    import builtins
    import io
    from unittest import mock
    import my_module
    
    builtins.open = mock.Mock()
    builtins.open.return_value = io.StringIO()
    builtins.open.return_value.__exit__ = lambda a, b, c, d: None 
    my_module.f('foo')
    builtins.open.return_value.seek(0)
    txt = builtins.open.return_value.read()
    print(txt)
    

While, in my_module.py:

    
    
    def f(fname):
       with open(fname) as handle:
           g(handle)
    
    def g(fhandle):
        fhandle.write('bar')
    

Using this approach, I get a ValueError, which message is "I/O operation on
closed file". I expected the lambda to work to stub the **exit** method, why
does not it work? How can I stub it?


Answer: Have you tried using mocks "mock_open" by any chance? This is some code I used
a while back, that I believe should work. Let me know if this helps you:

    
    
    @mock.patch('__builtin__.open', new_callable=mock_open())
    def test_foo(self, m_open):
        self.foo()
    
        m_open.assert_called_once_with("something", 'w')
        m_open().__enter__().write.assert_called_once_with("stuff")
    

Here is some more documentation on
[mock_open](http://www.voidspace.org.uk/python/mock/helpers.html#mock-open)

