To use mock_open for a simple file read()
(the original mock_open snippet already given on this page is geared more for write):
my_text = "some text to return when read() is called on the file object"
mocked_open_function = mock.mock_open(read_data=my_text)
with mock.patch("__builtin__.open", mocked_open_function):
with open("any_string") as f:
print f.read()
Note as per docs for mock_open, this is specifically for read()
, so won't work with common patterns like for line in f
, for example.
Uses python 2.6.6 / mock 1.0.1