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 os | |
7 import re | |
8 import StringIO | |
9 | |
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 abspath(self, path): | |
36 if path.endswith(self.sep): | |
37 return path[:-1] | |
38 return path | |
39 | |
40 def dirname(self, path): | |
41 if self.sep not in path: | |
42 return '' | |
43 return self._split(path)[0] or self.sep | |
44 | |
45 def exists(self, path): | |
46 return self.isfile(path) or self.isdir(path) | |
47 | |
48 def isfile(self, path): | |
49 return path in self.files and self.files[path] is not None | |
50 | |
51 def isdir(self, path): | |
52 if path in self.files: | |
53 return False | |
54 if not path.endswith(self.sep): | |
55 path += self.sep | |
56 | |
57 # We need to use a copy of the keys here in order to avoid switching | |
58 # to a different thread and potentially modifying the dict in | |
59 # mid-iteration. | |
60 files = self.files.keys()[:] | |
61 return any(f.startswith(path) for f in files) | |
62 | |
63 def join(self, *comps): | |
64 # TODO: Might want tests for this and/or a better comment about how | |
65 # it works. | |
66 return re.sub(re.escape(os.path.sep), self.sep, os.path.join(*comps)) | |
67 | |
68 def open_for_reading(self, path): | |
69 return StringIO.StringIO(self.read_binary_file(path)) | |
70 | |
71 def read_binary_file(self, path): | |
72 # Intentionally raises KeyError if we don't recognize the path. | |
73 if self.files[path] is None: | |
74 _RaiseNotFound(path) | |
75 return self.files[path] | |
OLD | NEW |