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 |
| 11 def _RaiseNotFound(path): |
| 12 raise IOError(errno.ENOENT, path, os.strerror(errno.ENOENT)) |
| 13 |
| 14 |
| 15 class MockFileSystem(object): |
| 16 """Stripped-down version of WebKit's webkitpy.common.system.filesystem_mock |
| 17 |
| 18 Implements a filesystem-like interface on top of a dict of filenames -> |
| 19 file contents. A file content value of None indicates that the file should |
| 20 not exist (IOError will be raised if it is opened; |
| 21 reading from a missing key raises a KeyError, not an IOError.""" |
| 22 |
| 23 def __init__(self, files=None): |
| 24 self.files = files or {} |
| 25 self.written_files = {} |
| 26 self._sep = '/' |
| 27 |
| 28 @property |
| 29 def sep(self): |
| 30 return self._sep |
| 31 |
| 32 def _split(self, path): |
| 33 return path.rsplit(self.sep, 1) |
| 34 |
| 35 def dirname(self, path): |
| 36 if not self.sep in path: |
| 37 return '' |
| 38 return self._split(path)[0] |
| 39 |
| 40 def exists(self, path): |
| 41 return self.isfile(path) or self.isdir(path) |
| 42 |
| 43 def isfile(self, path): |
| 44 return path in self.files and self.files[path] is not None |
| 45 |
| 46 def isdir(self, path): |
| 47 if path in self.files: |
| 48 return False |
| 49 if not path.endswith(self.sep): |
| 50 path += self.sep |
| 51 |
| 52 # We need to use a copy of the keys here in order to avoid switching |
| 53 # to a different thread and potentially modifying the dict in |
| 54 # mid-iteration. |
| 55 files = self.files.keys()[:] |
| 56 return any(f.startswith(path) for f in files) |
| 57 |
| 58 def join(self, *comps): |
| 59 # FIXME: might want tests for this and/or a better comment about how |
| 60 # it works. |
| 61 return re.sub(re.escape(os.path.sep), self.sep, os.path.join(*comps)) |
| 62 |
| 63 def open_for_reading(self, path): |
| 64 return StringIO.StringIO(self.read_binary_file(path)) |
| 65 |
| 66 def read_binary_file(self, path): |
| 67 # Intentionally raises KeyError if we don't recognize the path. |
| 68 if self.files[path] is None: |
| 69 _RaiseNotFound(path) |
| 70 return self.files[path] |
OLD | NEW |