def mock_open(mock=None, read_data=''):
 def _readlines_side_effect(*args, **kwargs):
  if (handle.readlines.return_value is not None):
   return handle.readlines.return_value
  return list(_data)
 def _read_side_effect(*args, **kwargs):
  if (handle.read.return_value is not None):
   return handle.read.return_value
  return ''.join(_data)
 def _readline_side_effect():
  if (handle.readline.return_value is not None):
   while True:
    (yield handle.readline.return_value)
  for line in _data:
   (yield line)
 global file_spec
 if (file_spec is None):
  import _io
  file_spec = list(set(dir(_io.TextIOWrapper)).union(set(dir(_io.BytesIO))))
 if (mock is None):
  mock = MagicMock(name='open', spec=open)
 handle = MagicMock(spec=file_spec)
 handle.__enter__.return_value = handle
 _data = _iterate_read_data(read_data)
 handle.write.return_value = None
 handle.read.return_value = None
 handle.readline.return_value = None
 handle.readlines.return_value = None
 handle.read.side_effect = _read_side_effect
 handle.readline.side_effect = _readline_side_effect()
 handle.readlines.side_effect = _readlines_side_effect
 mock.return_value = handle
 return mock

def mock_open ( mock = None , read_data = '' ) : def _readlines_side_effect ( * args , ** kwargs ) : if ( handle . readlines . return_value is not None ) : return handle . readlines . return_value return list ( _data ) def _read_side_effect ( * args , ** kwargs ) : if ( handle . read . return_value is not None ) : return handle . read . return_value return '' . join ( _data ) def _readline_side_effect ( ) : if ( handle . readline . return_value is not None ) : while True : ( yield handle . readline . return_value ) for line in _data : ( yield line ) global file_spec if ( file_spec is None ) : import _io file_spec = list ( set ( dir ( _io . TextIOWrapper ) ) . union ( set ( dir ( _io . BytesIO ) ) ) ) if ( mock is None ) : mock = MagicMock ( name = 'open' , spec = open ) handle = MagicMock ( spec = file_spec ) handle . __enter__ . return_value = handle _data = _iterate_read_data ( read_data ) handle . write . return_value = None handle . read . return_value = None handle . readline . return_value = None handle . readlines . return_value = None handle . read . side_effect = _read_side_effect handle . readline . side_effect = _readline_side_effect ( ) handle . readlines . side_effect = _readlines_side_effect mock . return_value = handle return mock
a helper function to create a mock to replace the use of open .