-
Notifications
You must be signed in to change notification settings - Fork 3
/
fake_filesystem.py
2196 lines (1825 loc) · 71.4 KB
/
fake_filesystem.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright 2009 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# pylint: disable-msg=W0612,W0613,C6409
"""A fake filesystem implementation for unit testing.
Includes:
FakeFile: Provides the appearance of a real file.
FakeDirectory: Provides the appearance of a real dir.
FakeFilesystem: Provides the appearance of a real directory hierarchy.
FakeOsModule: Uses FakeFilesystem to provide a fake os module replacement.
FakePathModule: Faked os.path module replacement.
FakeFileOpen: Faked file() and open() function replacements.
Usage:
>>> import fake_filesystem
>>> filesystem = fake_filesystem.FakeFilesystem()
>>> os_module = fake_filesystem.FakeOsModule(filesystem)
>>> pathname = '/a/new/dir/new-file'
Create a new file object, creating parent directory objects as needed:
>>> os_module.path.exists(pathname)
False
>>> new_file = filesystem.CreateFile(pathname)
File objects can't be overwritten:
>>> os_module.path.exists(pathname)
True
>>> try:
... filesystem.CreateFile(pathname)
... except IOError as e:
... assert e.errno == errno.EEXIST, 'unexpected errno: %d' % e.errno
... assert e.strerror == 'File already exists in fake filesystem'
Remove a file object:
>>> filesystem.RemoveObject(pathname)
>>> os_module.path.exists(pathname)
False
Create a new file object at the previous path:
>>> beatles_file = filesystem.CreateFile(pathname,
... contents='Dear Prudence\\nWon\\'t you come out to play?\\n')
>>> os_module.path.exists(pathname)
True
Use the FakeFileOpen class to read fake file objects:
>>> file_module = fake_filesystem.FakeFileOpen(filesystem)
>>> for line in file_module(pathname):
... print line.rstrip()
...
Dear Prudence
Won't you come out to play?
File objects cannot be treated like directory objects:
>>> os_module.listdir(pathname) #doctest: +NORMALIZE_WHITESPACE
Traceback (most recent call last):
File "fake_filesystem.py", line 291, in listdir
raise OSError(errno.ENOTDIR,
OSError: [Errno 20] Fake os module: not a directory: '/a/new/dir/new-file'
The FakeOsModule can list fake directory objects:
>>> os_module.listdir(os_module.path.dirname(pathname))
['new-file']
The FakeOsModule also supports stat operations:
>>> import stat
>>> stat.S_ISREG(os_module.stat(pathname).st_mode)
True
>>> stat.S_ISDIR(os_module.stat(os_module.path.dirname(pathname)).st_mode)
True
"""
import errno
import heapq
import os
import stat
import sys
import time
import warnings
try:
import cStringIO as io # pylint: disable-msg=C6204
except ImportError:
import io # pylint: disable-msg=C6204
__pychecker__ = 'no-reimportself'
__version__ = '2.4'
PERM_READ = 0o400 # Read permission bit.
PERM_WRITE = 0o200 # Write permission bit.
PERM_EXE = 0o100 # Write permission bit.
PERM_DEF = 0o777 # Default permission bits.
PERM_DEF_FILE = 0o666 # Default permission bits (regular file)
PERM_ALL = 0o7777 # All permission bits.
_OPEN_MODE_MAP = {
# mode name:(file must exist, need read, need write,
# truncate [implies need write], append)
'r': (True, True, False, False, False),
'w': (False, False, True, True, False),
'a': (False, False, True, False, True),
'r+': (True, True, True, False, False),
'w+': (False, True, True, True, False),
'a+': (False, True, True, False, True),
}
_MAX_LINK_DEPTH = 20
FAKE_PATH_MODULE_DEPRECATION = ('Do not instantiate a FakePathModule directly; '
'let FakeOsModule instantiate it. See the '
'FakeOsModule docstring for details.')
class Error(Exception):
pass
if sys.platform.startswith('win'):
# On Windows, raise WindowsError instead of OSError
OSError = WindowsError # pylint: disable-msg=E0602,W0622
class FakeLargeFileIoException(Error):
def __init__(self, file_path):
Error.__init__(self,
'Read and write operations not supported for '
'fake large file: %s' % file_path)
def CopyModule(old):
"""Recompiles and creates new module object."""
saved = sys.modules.pop(old.__name__, None)
new = __import__(old.__name__)
sys.modules[old.__name__] = saved
return new
class FakeFile(object):
"""Provides the appearance of a real file.
Attributes currently faked out:
st_mode: user-specified, otherwise S_IFREG
st_ctime: the time.time() timestamp when the file is created.
st_size: the size of the file
Other attributes needed by os.stat are assigned default value of None
these include: st_ino, st_dev, st_nlink, st_uid, st_gid, st_atime,
st_mtime
"""
def __init__(self, name, st_mode=stat.S_IFREG | PERM_DEF_FILE,
contents=None):
"""init.
Args:
name: name of the file/directory, without parent path information
st_mode: the stat.S_IF* constant representing the file type (i.e.
stat.S_IFREG, stat.SIFDIR)
contents: the contents of the filesystem object; should be a string for
regular files, and a list of other FakeFile or FakeDirectory objects
for FakeDirectory objects
"""
self.name = name
self.st_mode = st_mode
self.contents = contents
self.epoch = 0
self.st_ctime = int(time.time())
self.st_atime = self.st_ctime
self.st_mtime = self.st_ctime
if contents:
self.st_size = len(contents)
else:
self.st_size = 0
# Non faked features, write setter methods for fakeing them
self.st_ino = None
self.st_dev = None
self.st_nlink = None
self.st_uid = None
self.st_gid = None
def SetLargeFileSize(self, st_size):
"""Sets the self.st_size attribute and replaces self.content with None.
Provided specifically to simulate very large files without regards
to their content (which wouldn't fit in memory)
Args:
st_size: The desired file size
Raises:
IOError: if the st_size is not a non-negative integer
"""
# the st_size should be an positive integer value
if not isinstance(st_size, int) or st_size < 0:
raise IOError(errno.ENOSPC,
'Fake file object: can not create non negative integer '
'size=%r fake file' % st_size,
self.name)
self.st_size = st_size
self.contents = None
def IsLargeFile(self):
"""Return True if this file was initialized with size but no contents."""
return self.contents is None
def SetContents(self, contents):
"""Sets the file contents and size.
Args:
contents: string, new content of file.
"""
# convert a byte array to a string
if sys.version_info >= (3, 0) and isinstance(contents, bytes):
contents = ''.join(chr(i) for i in contents)
self.contents = contents
self.st_size = len(contents)
self.epoch += 1
def SetSize(self, st_size):
"""Resizes file content, padding with nulls if new size exceeds the old.
Args:
st_size: The desired size for the file.
Raises:
IOError: if the st_size arg is not a non-negative integer
"""
if not isinstance(st_size, int) or st_size < 0:
raise IOError(errno.ENOSPC,
'Fake file object: can not create non negative integer '
'size=%r fake file' % st_size,
self.name)
current_size = len(self.contents)
if st_size < current_size:
self.contents = self.contents[:st_size]
else:
self.contents = '%s%s' % (self.contents, '\0' * (st_size - current_size))
self.st_size = len(self.contents)
self.epoch += 1
def SetATime(self, st_atime):
"""Set the self.st_atime attribute.
Args:
st_atime: The desired atime.
"""
self.st_atime = st_atime
def SetMTime(self, st_mtime):
"""Set the self.st_mtime attribute.
Args:
st_mtime: The desired mtime.
"""
self.st_mtime = st_mtime
def __str__(self):
return '%s(%o)' % (self.name, self.st_mode)
def SetIno(self, st_ino):
"""Set the self.st_ino attribute.
Args:
st_ino: The desired inode.
"""
self.st_ino = st_ino
class FakeDirectory(FakeFile):
"""Provides the appearance of a real dir."""
def __init__(self, name, perm_bits=PERM_DEF):
"""init.
Args:
name: name of the file/directory, without parent path information
perm_bits: permission bits. defaults to 0o777.
"""
FakeFile.__init__(self, name, stat.S_IFDIR | perm_bits, {})
def AddEntry(self, pathname):
"""Adds a child FakeFile to this directory.
Args:
pathname: FakeFile instance to add as a child of this directory
"""
self.contents[pathname.name] = pathname
def GetEntry(self, pathname_name):
"""Retrieves the specified child file or directory.
Args:
pathname_name: basename of the child object to retrieve
Returns:
string, file contents
Raises:
KeyError: if no child exists by the specified name
"""
return self.contents[pathname_name]
def RemoveEntry(self, pathname_name):
"""Removes the specified child file or directory.
Args:
pathname_name: basename of the child object to remove
Raises:
KeyError: if no child exists by the specified name
"""
del self.contents[pathname_name]
def __str__(self):
rc = super(FakeDirectory, self).__str__() + ':\n'
for item in self.contents:
item_desc = self.contents[item].__str__()
for line in item_desc.split('\n'):
if line:
rc = rc + ' ' + line + '\n'
return rc
class FakeFilesystem(object):
"""Provides the appearance of a real directory tree for unit testing."""
def __init__(self, path_separator=os.path.sep):
"""init.
Args:
path_separator: optional substitute for os.path.sep
"""
self.path_separator = path_separator
self.root = FakeDirectory(self.path_separator)
self.cwd = self.root.name
# We can't query the current value without changing it:
self.umask = os.umask(0o22)
os.umask(self.umask)
# A list of open file objects. Their position in the list is their
# file descriptor number
self.open_files = []
# A heap containing all free positions in self.open_files list
self.free_fd_heap = []
def SetIno(self, path, st_ino):
"""Set the self.st_ino attribute of file at 'path'.
Args:
path: Path to file.
st_ino: The desired inode.
"""
self.GetObject(path).SetIno(st_ino)
def AddOpenFile(self, file_obj):
"""Adds file_obj to the list of open files on the filesystem.
The position in the self.open_files array is the file descriptor number
Args:
file_obj: file object to be added to open files list.
Returns:
File descriptor number for the file object.
"""
if self.free_fd_heap:
open_fd = heapq.heappop(self.free_fd_heap)
self.open_files[open_fd] = file_obj
return open_fd
self.open_files.append(file_obj)
return len(self.open_files) - 1
def CloseOpenFile(self, file_obj):
"""Removes file_obj from the list of open files on the filesystem.
Sets the entry in open_files to None.
Args:
file_obj: file object to be removed to open files list.
"""
self.open_files[file_obj.filedes] = None
heapq.heappush(self.free_fd_heap, file_obj.filedes)
def GetOpenFile(self, file_des):
"""Returns an open file.
Args:
file_des: file descriptor of the open file.
Raises:
OSError: an invalid file descriptor.
TypeError: filedes is not an integer.
Returns:
Open file object.
"""
if not isinstance(file_des, int):
raise TypeError('an integer is required')
if (file_des >= len(self.open_files) or
self.open_files[file_des] is None):
raise OSError(errno.EBADF, 'Bad file descriptor', file_des)
return self.open_files[file_des]
def CollapsePath(self, path):
"""Mimics os.path.normpath using the specified path_separator.
Mimics os.path.normpath using the path_separator that was specified
for this FakeFilesystem. Normalizes the path, but unlike the method
NormalizePath, does not make it absolute. Eliminates dot components
(. and ..) and combines repeated path separators (//). Initial ..
components are left in place for relative paths. If the result is an empty
path, '.' is returned instead. Unlike the real os.path.normpath, this does
not replace '/' with '\\' on Windows.
Args:
path: (str) The path to normalize.
Returns:
(str) A copy of path with empty components and dot components removed.
"""
is_absolute_path = path.startswith(self.path_separator)
path_components = path.split(self.path_separator)
collapsed_path_components = []
for component in path_components:
if (not component) or (component == '.'):
continue
if component == '..':
if collapsed_path_components and (
collapsed_path_components[-1] != '..'):
# Remove an up-reference: directory/..
collapsed_path_components.pop()
continue
elif is_absolute_path:
# Ignore leading .. components if starting from the root directory.
continue
collapsed_path_components.append(component)
collapsed_path = self.path_separator.join(collapsed_path_components)
if is_absolute_path:
collapsed_path = self.path_separator + collapsed_path
return collapsed_path or '.'
def NormalizePath(self, path):
"""Absolutize and minimalize the given path.
Forces all relative paths to be absolute, and normalizes the path to
eliminate dot and empty components.
Args:
path: path to normalize
Returns:
The normalized path relative to the current working directory, or the root
directory if path is empty.
"""
if not path:
path = self.path_separator
elif not path.startswith(self.path_separator):
# Prefix relative paths with cwd, if cwd is not root.
path = self.path_separator.join(
(self.cwd != self.root.name and self.cwd or '',
path))
if path == '.':
path = self.cwd
return self.CollapsePath(path)
def SplitPath(self, path):
"""Mimics os.path.split using the specified path_separator.
Mimics os.path.split using the path_separator that was specified
for this FakeFilesystem.
Args:
path: (str) The path to split.
Returns:
(str) A duple (pathname, basename) for which pathname does not
end with a slash, and basename does not contain a slash.
"""
path_components = path.split(self.path_separator)
if not path_components:
return ('', '')
basename = path_components.pop()
if not path_components:
return ('', basename)
for component in path_components:
if component:
# The path is not the root; it contains a non-separator component.
# Strip all trailing separators.
while not path_components[-1]:
path_components.pop()
return (self.path_separator.join(path_components), basename)
# Root path. Collapse all leading separators.
return (self.path_separator, basename)
def JoinPaths(self, *paths):
"""Mimics os.path.join using the specified path_separator.
Mimics os.path.join using the path_separator that was specified
for this FakeFilesystem.
Args:
*paths: (str) Zero or more paths to join.
Returns:
(str) The paths joined by the path separator, starting with the last
absolute path in paths.
"""
if len(paths) == 1:
return paths[0]
joined_path_segments = []
for path_segment in paths:
if path_segment.startswith(self.path_separator):
# An absolute path
joined_path_segments = [path_segment]
else:
if (joined_path_segments and
not joined_path_segments[-1].endswith(self.path_separator)):
joined_path_segments.append(self.path_separator)
if path_segment:
joined_path_segments.append(path_segment)
return ''.join(joined_path_segments)
def GetPathComponents(self, path):
"""Breaks the path into a list of component names.
Does not include the root directory as a component, as all paths
are considered relative to the root directory for the FakeFilesystem.
Callers should basically follow this pattern:
file_path = self.NormalizePath(file_path)
path_components = self.GetPathComponents(file_path)
current_dir = self.root
for component in path_components:
if component not in current_dir.contents:
raise IOError
DoStuffWithComponent(curent_dir, component)
current_dir = current_dir.GetEntry(component)
Args:
path: path to tokenize
Returns:
The list of names split from path
"""
if not path or path == self.root.name:
return []
path_components = path.split(self.path_separator)
assert path_components
if not path_components[0]:
# This is an absolute path.
path_components = path_components[1:]
return path_components
def Exists(self, file_path):
"""True if a path points to an existing file system object.
Args:
file_path: path to examine
Returns:
bool(if object exists)
Raises:
TypeError: if file_path is None
"""
if file_path is None:
raise TypeError
if not file_path:
return False
try:
file_path = self.ResolvePath(file_path)
except IOError:
return False
if file_path == self.root.name:
return True
path_components = self.GetPathComponents(file_path)
current_dir = self.root
for component in path_components:
if component not in current_dir.contents:
return False
current_dir = current_dir.contents[component]
return True
def ResolvePath(self, file_path):
"""Follow a path, resolving symlinks.
ResolvePath traverses the filesystem along the specified file path,
resolving file names and symbolic links until all elements of the path are
exhausted, or we reach a file which does not exist. If all the elements
are not consumed, they just get appended to the path resolved so far.
This gives us the path which is as resolved as it can be, even if the file
does not exist.
This behavior mimics Unix semantics, and is best shown by example. Given a
file system that looks like this:
/a/b/
/a/b/c -> /a/b2 c is a symlink to /a/b2
/a/b2/x
/a/c -> ../d
/a/x -> y
Then:
/a/b/x => /a/b/x
/a/c => /a/d
/a/x => /a/y
/a/b/c/d/e => /a/b2/d/e
Args:
file_path: path to examine
Returns:
resolved_path (string) or None
Raises:
TypeError: if file_path is None
IOError: if file_path is '' or a part of the path doesn't exist
"""
def _ComponentsToPath(component_folders):
return '%s%s' % (self.path_separator,
self.path_separator.join(component_folders))
def _ValidRelativePath(file_path):
while file_path and '/..' in file_path:
file_path = file_path[:file_path.rfind('/..')]
if not self.Exists(self.NormalizePath(file_path)):
return False
return True
def _FollowLink(link_path_components, link):
"""Follow a link w.r.t. a path resolved so far.
The component is either a real file, which is a no-op, or a symlink.
In the case of a symlink, we have to modify the path as built up so far
/a/b => ../c should yield /a/../c (which will normalize to /a/c)
/a/b => x should yield /a/x
/a/b => /x/y/z should yield /x/y/z
The modified path may land us in a new spot which is itself a
link, so we may repeat the process.
Args:
link_path_components: The resolved path built up to the link so far.
link: The link object itself.
Returns:
(string) the updated path resolved after following the link.
Raises:
IOError: if there are too many levels of symbolic link
"""
link_path = link.contents
# For links to absolute paths, we want to throw out everything in the
# path built so far and replace with the link. For relative links, we
# have to append the link to what we have so far,
if not link_path.startswith(self.path_separator):
# Relative path. Append remainder of path to what we have processed
# so far, excluding the name of the link itself.
# /a/b => ../c should yield /a/../c (which will normalize to /c)
# /a/b => d should yield a/d
components = link_path_components[:-1]
components.append(link_path)
link_path = self.path_separator.join(components)
# Don't call self.NormalizePath(), as we don't want to prepend self.cwd.
return self.CollapsePath(link_path)
if file_path is None:
# file.open(None) raises TypeError, so mimic that.
raise TypeError('Expected file system path string, received None')
if not file_path or not _ValidRelativePath(file_path):
# file.open('') raises IOError, so mimic that, and validate that all
# parts of a relative path exist.
raise IOError(errno.ENOENT,
'No such file or directory: \'%s\'' % file_path)
file_path = self.NormalizePath(file_path)
if file_path == self.root.name:
return file_path
current_dir = self.root
path_components = self.GetPathComponents(file_path)
resolved_components = []
link_depth = 0
while path_components:
component = path_components.pop(0)
resolved_components.append(component)
if component not in current_dir.contents:
# The component of the path at this point does not actually exist in
# the folder. We can't resolve the path any more. It is legal to link
# to a file that does not yet exist, so rather than raise an error, we
# just append the remaining components to what return path we have built
# so far and return that.
resolved_components.extend(path_components)
break
current_dir = current_dir.contents[component]
# Resolve any possible symlinks in the current path component.
if stat.S_ISLNK(current_dir.st_mode):
# This link_depth check is not really meant to be an accurate check.
# It is just a quick hack to prevent us from looping forever on
# cycles.
link_depth += 1
if link_depth > _MAX_LINK_DEPTH:
raise IOError(errno.EMLINK,
'Too many levels of symbolic links: \'%s\'' %
_ComponentsToPath(resolved_components))
link_path = _FollowLink(resolved_components, current_dir)
# Following the link might result in the complete replacement of the
# current_dir, so we evaluate the entire resulting path.
target_components = self.GetPathComponents(link_path)
path_components = target_components + path_components
resolved_components = []
current_dir = self.root
return _ComponentsToPath(resolved_components)
def GetObjectFromNormalizedPath(self, file_path):
"""Searches for the specified filesystem object within the fake filesystem.
Args:
file_path: specifies target FakeFile object to retrieve, with a
path that has already been normalized/resolved
Returns:
the FakeFile object corresponding to file_path
Raises:
IOError: if the object is not found
"""
if file_path == self.root.name:
return self.root
path_components = self.GetPathComponents(file_path)
target_object = self.root
try:
for component in path_components:
if not isinstance(target_object, FakeDirectory):
raise IOError(errno.ENOENT,
'No such file or directory in fake filesystem',
file_path)
target_object = target_object.GetEntry(component)
except KeyError:
raise IOError(errno.ENOENT,
'No such file or directory in fake filesystem',
file_path)
return target_object
def GetObject(self, file_path):
"""Searches for the specified filesystem object within the fake filesystem.
Args:
file_path: specifies target FakeFile object to retrieve
Returns:
the FakeFile object corresponding to file_path
Raises:
IOError: if the object is not found
"""
file_path = self.NormalizePath(file_path)
return self.GetObjectFromNormalizedPath(file_path)
def ResolveObject(self, file_path):
"""Searches for the specified filesystem object, resolving all links.
Args:
file_path: specifies target FakeFile object to retrieve
Returns:
the FakeFile object corresponding to file_path
Raises:
IOError: if the object is not found
"""
return self.GetObjectFromNormalizedPath(self.ResolvePath(file_path))
def LResolveObject(self, path):
"""Searches for the specified object, resolving only parent links.
This is analogous to the stat/lstat difference. This resolves links *to*
the object but not of the final object itself.
Args:
path: specifies target FakeFile object to retrieve
Returns:
the FakeFile object corresponding to path
Raises:
IOError: if the object is not found
"""
if path == self.root.name:
# The root directory will never be a link
return self.root
parent_directory, child_name = self.SplitPath(path)
if not parent_directory:
parent_directory = self.cwd
try:
parent_obj = self.ResolveObject(parent_directory)
assert parent_obj
if not isinstance(parent_obj, FakeDirectory):
raise IOError(errno.ENOENT,
'No such file or directory in fake filesystem',
path)
return parent_obj.GetEntry(child_name)
except KeyError:
raise IOError(errno.ENOENT,
'No such file or directory in the fake filesystem',
path)
def AddObject(self, file_path, file_object):
"""Add a fake file or directory into the filesystem at file_path.
Args:
file_path: the path to the file to be added relative to self
file_object: file or directory to add
Raises:
IOError: if file_path does not correspond to a directory
"""
try:
target_directory = self.GetObject(file_path)
target_directory.AddEntry(file_object)
except AttributeError:
raise IOError(errno.ENOTDIR,
'Not a directory in the fake filesystem',
file_path)
def RemoveObject(self, file_path):
"""Remove an existing file or directory.
Args:
file_path: the path to the file relative to self
Raises:
IOError: if file_path does not correspond to an existing file, or if part
of the path refers to something other than a directory
OSError: if the directory is in use (eg, if it is '/')
"""
if file_path == self.root.name:
raise OSError(errno.EBUSY, 'Fake device or resource busy',
file_path)
try:
dirname, basename = self.SplitPath(file_path)
target_directory = self.GetObject(dirname)
target_directory.RemoveEntry(basename)
except KeyError:
raise IOError(errno.ENOENT,
'No such file or directory in the fake filesystem',
file_path)
except AttributeError:
raise IOError(errno.ENOTDIR,
'Not a directory in the fake filesystem',
file_path)
def CreateDirectory(self, directory_path, perm_bits=PERM_DEF, inode=None):
"""Creates directory_path, and all the parent directories.
Helper method to set up your test faster
Args:
directory_path: directory to create
perm_bits: permission bits
inode: inode of directory
Returns:
the newly created FakeDirectory object
Raises:
OSError: if the directory already exists
"""
directory_path = self.NormalizePath(directory_path)
if self.Exists(directory_path):
raise OSError(errno.EEXIST,
'Directory exists in fake filesystem',
directory_path)
path_components = self.GetPathComponents(directory_path)
current_dir = self.root
for component in path_components:
if component not in current_dir.contents:
new_dir = FakeDirectory(component, perm_bits)
current_dir.AddEntry(new_dir)
current_dir = new_dir
else:
current_dir = current_dir.contents[component]
current_dir.SetIno(inode)
return current_dir
def CreateFile(self, file_path, st_mode=stat.S_IFREG | PERM_DEF_FILE,
contents='', st_size=None, create_missing_dirs=True,
apply_umask=False, inode=None):
"""Creates file_path, including all the parent directories along the way.
Helper method to set up your test faster.
Args:
file_path: path to the file to create
st_mode: the stat.S_IF constant representing the file type
contents: the contents of the file
st_size: file size; only valid if contents=None
create_missing_dirs: if True, auto create missing directories
apply_umask: whether or not the current umask must be applied on st_mode
inode: inode of the file
Returns:
the newly created FakeFile object
Raises:
IOError: if the file already exists
IOError: if the containing directory is required and missing
"""
file_path = self.NormalizePath(file_path)
if self.Exists(file_path):
raise IOError(errno.EEXIST,
'File already exists in fake filesystem',
file_path)
parent_directory, new_file = self.SplitPath(file_path)
if not parent_directory:
parent_directory = self.cwd
if not self.Exists(parent_directory):
if not create_missing_dirs:
raise IOError(errno.ENOENT, 'No such fake directory', parent_directory)
self.CreateDirectory(parent_directory)
if apply_umask:
st_mode &= ~self.umask
file_object = FakeFile(new_file, st_mode, contents)
file_object.SetIno(inode)
self.AddObject(parent_directory, file_object)
# set the size if st_size is given
if not contents and st_size is not None:
try:
file_object.SetLargeFileSize(st_size)
except IOError:
self.RemoveObject(file_path)
raise
return file_object
def CreateLink(self, file_path, link_target):
"""Creates the specified symlink, pointed at the specified link target.
Args:
file_path: path to the symlink to create
link_target: the target of the symlink
Returns:
the newly created FakeFile object
Raises:
IOError: if the file already exists
"""
resolved_file_path = self.ResolvePath(file_path)
return self.CreateFile(resolved_file_path, st_mode=stat.S_IFLNK | PERM_DEF,
contents=link_target)
def __str__(self):
return str(self.root)
class FakePathModule(object):
"""Faked os.path module replacement.
FakePathModule should *only* be instantiated by FakeOsModule. See the
FakeOsModule docstring for details.
"""
_OS_PATH_COPY = CopyModule(os.path)
def __init__(self, filesystem, os_module=None):
"""Init.
Args:
filesystem: FakeFilesystem used to provide file system information
os_module: (deprecated) FakeOsModule to assign to self.os
"""
self.filesystem = filesystem
self._os_path = self._OS_PATH_COPY
if os_module is None:
warnings.warn(FAKE_PATH_MODULE_DEPRECATION, DeprecationWarning,
stacklevel=2)
self._os_path.os = self.os = os_module
self.sep = self.filesystem.path_separator
def exists(self, path):
"""Determines whether the file object exists within the fake filesystem.
Args: