OLD | NEW |
(Empty) | |
| 1 # Copyright (c) 2011 The Chromium Authors. All rights reserved. |
| 2 # Use of this source code is governed by a BSD-style license that can be |
| 3 # found in the LICENSE file. |
| 4 |
| 5 import errno |
| 6 import fnmatch |
| 7 import os |
| 8 import re |
| 9 import StringIO |
| 10 |
| 11 |
| 12 def _RaiseNotFound(path): |
| 13 raise IOError(errno.ENOENT, path, os.strerror(errno.ENOENT)) |
| 14 |
| 15 |
| 16 class MockFileSystem(object): |
| 17 """Stripped-down version of WebKit's webkitpy.common.system.filesystem_mock |
| 18 |
| 19 Implements a filesystem-like interface on top of a dict of filenames -> |
| 20 file contents. A file content value of None indicates that the file should |
| 21 not exist (IOError will be raised if it is opened; |
| 22 reading from a missing key raises a KeyError, not an IOError.""" |
| 23 |
| 24 def __init__(self, files=None): |
| 25 self.files = files or {} |
| 26 self.written_files = {} |
| 27 self._sep = '/' |
| 28 |
| 29 @property |
| 30 def sep(self): |
| 31 return self._sep |
| 32 |
| 33 def _split(self, path): |
| 34 return path.rsplit(self.sep, 1) |
| 35 |
| 36 def abspath(self, path): |
| 37 if path.endswith(self.sep): |
| 38 return path[:-1] |
| 39 return path |
| 40 |
| 41 def dirname(self, path): |
| 42 if self.sep not in path: |
| 43 return '' |
| 44 return self._split(path)[0] or self.sep |
| 45 |
| 46 def exists(self, path): |
| 47 return self.isfile(path) or self.isdir(path) |
| 48 |
| 49 def isabs(self, path): |
| 50 return path.startswith(self.sep) |
| 51 |
| 52 def isfile(self, path): |
| 53 return path in self.files and self.files[path] is not None |
| 54 |
| 55 def isdir(self, path): |
| 56 if path in self.files: |
| 57 return False |
| 58 if not path.endswith(self.sep): |
| 59 path += self.sep |
| 60 |
| 61 # We need to use a copy of the keys here in order to avoid switching |
| 62 # to a different thread and potentially modifying the dict in |
| 63 # mid-iteration. |
| 64 files = self.files.keys()[:] |
| 65 return any(f.startswith(path) for f in files) |
| 66 |
| 67 def join(self, *comps): |
| 68 # TODO: Might want tests for this and/or a better comment about how |
| 69 # it works. |
| 70 return re.sub(re.escape(os.path.sep), self.sep, os.path.join(*comps)) |
| 71 |
| 72 def glob(self, path): |
| 73 return fnmatch.filter(self.files.keys(), path) |
| 74 |
| 75 def open_for_reading(self, path): |
| 76 return StringIO.StringIO(self.read_binary_file(path)) |
| 77 |
| 78 def read_binary_file(self, path): |
| 79 # Intentionally raises KeyError if we don't recognize the path. |
| 80 if self.files[path] is None: |
| 81 _RaiseNotFound(path) |
| 82 return self.files[path] |
| 83 |
| 84 @staticmethod |
| 85 def relpath(path, base): |
| 86 # This implementation is wrong in many ways; assert to check them for now. |
| 87 assert path.startswith(base) |
| 88 assert base.endswith('/') |
| 89 return path[len(base):] |
OLD | NEW |