Mocking open(file_name) in unit tests [duplicate]

This is admittedly an old question, hence some of the answers are outdated. In the current version of the mock library there is a convenience function designed for precisely this purpose. Here’s how it works: >>> from mock import mock_open >>> m = mock_open() >>> with patch(‘__main__.open’, m, create=True): … with open(‘foo’, ‘w’) as h: … Read more