Chromium Code Reviews| OLD | NEW |
|---|---|
| (Empty) | |
| 1 #!/usr/bin/python | |
| 2 # Copyright (c) 2011 The Chromium Authors. All rights reserved. | |
| 3 # Use of this source code is governed by a BSD-style license that can be | |
| 4 # found in the LICENSE file. | |
| 5 | |
| 6 import errno | |
| 7 import os | |
| 8 import re | |
| 9 import StringIO | |
| 10 import unittest | |
| 11 | |
| 12 | |
| 13 class MockFileSystem(object): | |
| 14 """Stripped-down version of WebKit's webkitpy.common.system.filesystem_mock | |
| 15 | |
| 16 Implements a filesystem-like interface on top of a dict of filenames -> | |
| 17 file contents. A file content value of None indicates that the file should | |
| 18 not exist (IOError will be raised if it is opened; | |
| 19 reading from a missing key raises a KeyError, not an IOError.""" | |
| 20 | |
| 21 def __init__(self, files=None): | |
| 22 self.files = files or {} | |
| 23 self.written_files = {} | |
| 24 self._sep = '/' | |
| 25 | |
| 26 def _get_sep(self): | |
|
M-A Ruel
2011/03/03 21:21:56
you could use:
@property
def sep(self):
return s
| |
| 27 return self._sep | |
| 28 | |
| 29 sep = property(_get_sep, doc='pathname separator') | |
| 30 | |
| 31 def _raise_not_found(self, path): # pylint: disable=R0201 | |
|
M-A Ruel
2011/03/03 21:21:56
you can make it static in fact
| |
| 32 raise IOError(errno.ENOENT, path, os.strerror(errno.ENOENT)) | |
| 33 | |
| 34 def _split(self, path): | |
| 35 return path.rsplit(self.sep, 1) | |
| 36 | |
| 37 def dirname(self, path): | |
| 38 if not self.sep in path: | |
| 39 return '' | |
| 40 return self._split(path)[0] | |
| 41 | |
| 42 def exists(self, path): | |
| 43 return self.isfile(path) or self.isdir(path) | |
| 44 | |
| 45 def isfile(self, path): | |
| 46 return path in self.files and self.files[path] is not None | |
| 47 | |
| 48 def isdir(self, path): | |
| 49 if path in self.files: | |
| 50 return False | |
| 51 if not path.endswith(self.sep): | |
| 52 path += self.sep | |
| 53 | |
| 54 # We need to use a copy of the keys here in order to avoid switching | |
| 55 # to a different thread and potentially modifying the dict in | |
| 56 # mid-iteration. | |
| 57 files = self.files.keys()[:] | |
| 58 return any(f.startswith(path) for f in files) | |
| 59 | |
| 60 def join(self, *comps): | |
| 61 # FIXME: might want tests for this and/or a better comment about how | |
| 62 # it works. | |
| 63 return re.sub(re.escape(os.path.sep), self.sep, os.path.join(*comps)) | |
| 64 | |
| 65 def open_for_reading(self, path): | |
| 66 return StringIO.StringIO(self.read_binary_file(path)) | |
| 67 | |
| 68 def read_binary_file(self, path): | |
| 69 # Intentionally raises KeyError if we don't recognize the path. | |
| 70 if self.files[path] is None: | |
| 71 self._raise_not_found(path) | |
| 72 return self.files[path] | |
| OLD | NEW |