Creating The Readable Mock
To mock a file you can use
StringIO and an input string. Since the
StringIO will only traverse once (like a regular file) it might be convenient to make a mock builder.
def mock_open(data_string):
mock_file = MagicMock(spec=file)
mock_file.return_value = StringIO(data_string)
return mock_file
Using the Mock
To use the mock you patch the built-in open function.
opened = mock_file()
with patch('__builtin__.open', opened, create=True):
run_tests_here()
Checking the Mock
To see if the file was opened correctly:
opened.assert_called_with(filename, r_or_w)
To check write calls look at
opened.write.mock_calls.