Search code examples
pythonmockingwith-statement

How do I mock an open used in a with statement (using the Mock framework in Python)?


How do I test the following code with unittest.mock:

def testme(filepath):
    with open(filepath) as f:
        return f.read()

Solution

  • The way to do this has changed in mock 0.7.0 which finally supports mocking the python protocol methods (magic methods), particularly using the MagicMock:

    http://www.voidspace.org.uk/python/mock/magicmock.html

    An example of mocking open as a context manager (from the examples page in the mock documentation):

    >>> open_name = '%s.open' % __name__
    >>> with patch(open_name, create=True) as mock_open:
    ...     mock_open.return_value = MagicMock(spec=file)
    ...
    ...     with open('/some/path', 'w') as f:
    ...         f.write('something')
    ...
    <mock.Mock object at 0x...>
    >>> file_handle = mock_open.return_value.__enter__.return_value
    >>> file_handle.write.assert_called_with('something')