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.
mock_file = MagicMock(spec=file)
mock_file.return_value = StringIO(data_string)
Using the Mock
To use the mock you patch the built-in open function.
opened = mock_file()
with patch('__builtin__.open', opened, create=True):
Checking the Mock
To see if the file was opened correctly:
To check write calls look at opened.write.mock_calls