-
Notifications
You must be signed in to change notification settings - Fork 1
/
fake_filesystem_test.py
2880 lines (2447 loc) · 108 KB
/
fake_filesystem_test.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
#!/usr/bin/python2.6
#
# 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.
"""Unittest for fake_filesystem module."""
import errno
import os
import re
import stat
import sys
import time
import unittest
import fake_filesystem
def _GetDummyTime(start_time, increment):
def _DummyTime():
_DummyTime._curr_time += increment
return _DummyTime._curr_time
_DummyTime._curr_time = start_time - increment # pylint: disable-msg=W0612
return _DummyTime
class TestCase(unittest.TestCase):
def assertModeEqual(self, expected, actual):
return self.assertEqual(stat.S_IMODE(expected), stat.S_IMODE(actual))
class FakeDirectoryUnitTest(unittest.TestCase):
def setUp(self):
self.orig_time = time.time
time.time = _GetDummyTime(10, 1)
self.fake_file = fake_filesystem.FakeFile('foobar', contents='dummy_file')
self.fake_dir = fake_filesystem.FakeDirectory('somedir')
def tearDown(self):
time.time = self.orig_time
def testNewFileAndDirectory(self):
self.assertTrue(stat.S_IFREG & self.fake_file.st_mode)
self.assertTrue(stat.S_IFDIR & self.fake_dir.st_mode)
self.assertEqual({}, self.fake_dir.contents)
self.assertEqual(10, self.fake_file.st_ctime)
def testAddEntry(self):
self.fake_dir.AddEntry(self.fake_file)
self.assertEqual({'foobar': self.fake_file}, self.fake_dir.contents)
def testGetEntry(self):
self.fake_dir.AddEntry(self.fake_file)
self.assertEqual(self.fake_file, self.fake_dir.GetEntry('foobar'))
def testRemoveEntry(self):
self.fake_dir.AddEntry(self.fake_file)
self.assertEqual(self.fake_file, self.fake_dir.GetEntry('foobar'))
self.fake_dir.RemoveEntry('foobar')
self.assertRaises(KeyError, self.fake_dir.GetEntry, 'foobar')
def testShouldThrowIfSetSizeIsNotInteger(self):
self.assertRaises(IOError, self.fake_file.SetSize, 0.1)
def testShouldThrowIfSetSizeIsNegative(self):
self.assertRaises(IOError, self.fake_file.SetSize, -1)
def testProduceEmptyFileIfSetSizeIsZero(self):
self.fake_file.SetSize(0)
self.assertEqual('', self.fake_file.contents)
def testSetsContentEmptyIfSetSizeIsZero(self):
self.fake_file.SetSize(0)
self.assertEqual('', self.fake_file.contents)
def testTruncateFileIfSizeIsSmallerThanCurrentSize(self):
self.fake_file.SetSize(6)
self.assertEqual('dummy_', self.fake_file.contents)
def testLeaveFileUnchangedIfSizeIsEqualToCurrentSize(self):
self.fake_file.SetSize(10)
self.assertEqual('dummy_file', self.fake_file.contents)
def testPadsFileContentWithNullBytesIfSizeIsGreaterThanCurrentSize(self):
self.fake_file.SetSize(13)
self.assertEqual('dummy_file\0\0\0', self.fake_file.contents)
def testSetMTime(self):
self.assertEqual(10, self.fake_file.st_mtime)
self.fake_file.SetMTime(13)
self.assertEqual(13, self.fake_file.st_mtime)
self.fake_file.SetMTime(131)
self.assertEqual(131, self.fake_file.st_mtime)
def testFileInode(self):
filesystem = fake_filesystem.FakeFilesystem(path_separator='/')
fake_os = fake_filesystem.FakeOsModule(filesystem)
file_path = 'some_file1'
filesystem.CreateFile(file_path, contents='contents here1', inode=42)
self.assertEqual(42, fake_os.stat(file_path)[stat.ST_INO])
file_obj = filesystem.GetObject(file_path)
file_obj.SetIno(43)
self.assertEqual(43, fake_os.stat(file_path)[stat.ST_INO])
def testDirectoryInode(self):
filesystem = fake_filesystem.FakeFilesystem(path_separator='/')
fake_os = fake_filesystem.FakeOsModule(filesystem)
dirpath = 'testdir'
filesystem.CreateDirectory(dirpath, inode=42)
self.assertEqual(42, fake_os.stat(dirpath)[stat.ST_INO])
dir_obj = filesystem.GetObject(dirpath)
dir_obj.SetIno(43)
self.assertEqual(43, fake_os.stat(dirpath)[stat.ST_INO])
class SetLargeFileSizeTest(FakeDirectoryUnitTest):
def testShouldThrowIfSizeIsNotInteger(self):
self.assertRaises(IOError, self.fake_file.SetLargeFileSize, 0.1)
def testShouldThrowIfSizeIsNegative(self):
self.assertRaises(IOError, self.fake_file.SetLargeFileSize, -1)
def testSetsContentNoneIfSizeIsNonNegativeInteger(self):
self.fake_file.SetLargeFileSize(1000000000)
self.assertEqual(None, self.fake_file.contents)
self.assertEqual(1000000000, self.fake_file.st_size)
class NormalizePathTest(unittest.TestCase):
def setUp(self):
self.filesystem = fake_filesystem.FakeFilesystem(path_separator='/')
self.root_name = '/'
def testEmptyPathShouldGetNormalizedToRootPath(self):
self.assertEqual(self.root_name, self.filesystem.NormalizePath(''))
def testRootPathRemainsUnchanged(self):
self.assertEqual(self.root_name,
self.filesystem.NormalizePath(self.root_name))
def testRelativePathForcedToCwd(self):
path = 'bar'
self.filesystem.cwd = '/foo'
self.assertEqual('/foo/bar', self.filesystem.NormalizePath(path))
def testAbsolutePathRemainsUnchanged(self):
path = '/foo/bar'
self.assertEqual(path, self.filesystem.NormalizePath(path))
def testDottedPathIsNormalized(self):
path = '/foo/..'
self.assertEqual('/', self.filesystem.NormalizePath(path))
path = 'foo/../bar'
self.assertEqual('/bar', self.filesystem.NormalizePath(path))
def testDotPathIsNormalized(self):
path = '.'
self.assertEqual('/', self.filesystem.NormalizePath(path))
class GetPathComponentsTest(unittest.TestCase):
def setUp(self):
self.filesystem = fake_filesystem.FakeFilesystem(path_separator='/')
self.root_name = '/'
def testRootPathShouldReturnEmptyList(self):
self.assertEqual([], self.filesystem.GetPathComponents(self.root_name))
def testEmptyPathShouldReturnEmptyList(self):
self.assertEqual([], self.filesystem.GetPathComponents(''))
def testRelativePathWithOneComponentShouldReturnComponent(self):
self.assertEqual(['foo'], self.filesystem.GetPathComponents('foo'))
def testAbsolutePathWithOneComponentShouldReturnComponent(self):
self.assertEqual(['foo'], self.filesystem.GetPathComponents('/foo'))
def testTwoLevelRelativePathShouldReturnComponents(self):
self.assertEqual(['foo', 'bar'],
self.filesystem.GetPathComponents('foo/bar'))
def testTwoLevelAbsolutePathShouldReturnComponents(self):
self.assertEqual(['foo', 'bar'],
self.filesystem.GetPathComponents('/foo/bar'))
class FakeFilesystemUnitTest(unittest.TestCase):
def setUp(self):
self.filesystem = fake_filesystem.FakeFilesystem(path_separator='/')
self.root_name = '/'
self.fake_file = fake_filesystem.FakeFile('foobar')
self.fake_child = fake_filesystem.FakeDirectory('foobaz')
self.fake_grandchild = fake_filesystem.FakeDirectory('quux')
def testNewFilesystem(self):
self.assertEqual('/', self.filesystem.path_separator)
self.assertTrue(stat.S_IFDIR & self.filesystem.root.st_mode)
self.assertEqual(self.root_name, self.filesystem.root.name)
self.assertEqual({}, self.filesystem.root.contents)
def testNoneRaisesTypeError(self):
self.assertRaises(TypeError, self.filesystem.Exists, None)
def testEmptyStringDoesNotExist(self):
self.assertFalse(self.filesystem.Exists(''))
def testExistsRoot(self):
self.assertTrue(self.filesystem.Exists(self.root_name))
def testExistsUnaddedFile(self):
self.assertFalse(self.filesystem.Exists(self.fake_file.name))
def testGetRootObject(self):
self.assertEqual(self.filesystem.root,
self.filesystem.GetObject(self.root_name))
def testAddObjectToRoot(self):
self.filesystem.AddObject(self.root_name, self.fake_file)
self.assertEqual({'foobar': self.fake_file}, self.filesystem.root.contents)
def testExistsAddedFile(self):
self.filesystem.AddObject(self.root_name, self.fake_file)
self.assertTrue(self.filesystem.Exists(self.fake_file.name))
def testExistsRelativePath(self):
self.filesystem.CreateFile('/a/b/file_one')
self.filesystem.CreateFile('/a/c/file_two')
self.assertTrue(self.filesystem.Exists('a/b/../c/file_two'))
self.assertTrue(self.filesystem.Exists('/a/c/../b/file_one'))
self.assertTrue(self.filesystem.Exists('/a/c/../../a/b/file_one'))
self.assertFalse(self.filesystem.Exists('a/b/../z/d'))
self.assertFalse(self.filesystem.Exists('a/b/../z/../c/file_two'))
self.filesystem.cwd = '/a/c'
self.assertTrue(self.filesystem.Exists('../b/file_one'))
self.assertTrue(self.filesystem.Exists('../../a/b/file_one'))
self.assertTrue(self.filesystem.Exists('../../a/b/../../a/c/file_two'))
self.assertFalse(self.filesystem.Exists('../z/file_one'))
self.assertFalse(self.filesystem.Exists('../z/../c/file_two'))
def testGetObjectFromRoot(self):
self.filesystem.AddObject(self.root_name, self.fake_file)
self.assertEqual(self.fake_file, self.filesystem.GetObject('foobar'))
def testGetNonexistentObjectFromRootError(self):
self.filesystem.AddObject(self.root_name, self.fake_file)
self.assertEqual(self.fake_file, self.filesystem.GetObject('foobar'))
self.assertRaises(IOError, self.filesystem.GetObject,
'some_bogus_filename')
def testRemoveObjectFromRoot(self):
self.filesystem.AddObject(self.root_name, self.fake_file)
self.filesystem.RemoveObject(self.fake_file.name)
self.assertRaises(IOError, self.filesystem.GetObject, self.fake_file.name)
def testRemoveNonexistenObjectFromRootError(self):
self.assertRaises(IOError, self.filesystem.RemoveObject,
'some_bogus_filename')
def testExistsRemovedFile(self):
self.filesystem.AddObject(self.root_name, self.fake_file)
self.filesystem.RemoveObject(self.fake_file.name)
self.assertFalse(self.filesystem.Exists(self.fake_file.name))
def testAddObjectToChild(self):
self.filesystem.AddObject(self.root_name, self.fake_child)
self.filesystem.AddObject(self.fake_child.name, self.fake_file)
self.assertEqual(
{self.fake_file.name: self.fake_file},
self.filesystem.root.GetEntry(self.fake_child.name).contents)
def testAddObjectToRegularFileError(self):
self.filesystem.AddObject(self.root_name, self.fake_file)
self.assertRaises(IOError, self.filesystem.AddObject,
self.fake_file.name, self.fake_file)
def testExistsFileAddedToChild(self):
self.filesystem.AddObject(self.root_name, self.fake_child)
self.filesystem.AddObject(self.fake_child.name, self.fake_file)
path = self.filesystem.JoinPaths(self.fake_child.name,
self.fake_file.name)
self.assertTrue(self.filesystem.Exists(path))
def testGetObjectFromChild(self):
self.filesystem.AddObject(self.root_name, self.fake_child)
self.filesystem.AddObject(self.fake_child.name, self.fake_file)
self.assertEqual(self.fake_file,
self.filesystem.GetObject(
self.filesystem.JoinPaths(self.fake_child.name,
self.fake_file.name)))
def testGetNonexistentObjectFromChildError(self):
self.filesystem.AddObject(self.root_name, self.fake_child)
self.filesystem.AddObject(self.fake_child.name, self.fake_file)
self.assertRaises(IOError, self.filesystem.GetObject,
self.filesystem.JoinPaths(self.fake_child.name,
'some_bogus_filename'))
def testRemoveObjectFromChild(self):
self.filesystem.AddObject(self.root_name, self.fake_child)
self.filesystem.AddObject(self.fake_child.name, self.fake_file)
target_path = self.filesystem.JoinPaths(self.fake_child.name,
self.fake_file.name)
self.filesystem.RemoveObject(target_path)
self.assertRaises(IOError, self.filesystem.GetObject, target_path)
def testRemoveObjectFromChildError(self):
self.filesystem.AddObject(self.root_name, self.fake_child)
self.assertRaises(IOError, self.filesystem.RemoveObject,
self.filesystem.JoinPaths(self.fake_child.name,
'some_bogus_filename'))
def testRemoveObjectFromNonDirectoryError(self):
self.filesystem.AddObject(self.root_name, self.fake_file)
self.assertRaises(
IOError, self.filesystem.RemoveObject,
self.filesystem.JoinPaths(
'%s' % self.fake_file.name,
'file_does_not_matter_since_parent_not_a_directory'))
def testExistsFileRemovedFromChild(self):
self.filesystem.AddObject(self.root_name, self.fake_child)
self.filesystem.AddObject(self.fake_child.name, self.fake_file)
path = self.filesystem.JoinPaths(self.fake_child.name,
self.fake_file.name)
self.filesystem.RemoveObject(path)
self.assertFalse(self.filesystem.Exists(path))
def testOperateOnGrandchildDirectory(self):
self.filesystem.AddObject(self.root_name, self.fake_child)
self.filesystem.AddObject(self.fake_child.name, self.fake_grandchild)
grandchild_directory = self.filesystem.JoinPaths(self.fake_child.name,
self.fake_grandchild.name)
grandchild_file = self.filesystem.JoinPaths(grandchild_directory,
self.fake_file.name)
self.assertRaises(IOError, self.filesystem.GetObject, grandchild_file)
self.filesystem.AddObject(grandchild_directory, self.fake_file)
self.assertEqual(self.fake_file,
self.filesystem.GetObject(grandchild_file))
self.assertTrue(self.filesystem.Exists(grandchild_file))
self.filesystem.RemoveObject(grandchild_file)
self.assertRaises(IOError, self.filesystem.GetObject, grandchild_file)
self.assertFalse(self.filesystem.Exists(grandchild_file))
def testCreateDirectoryInRootDirectory(self):
path = 'foo'
self.filesystem.CreateDirectory(path)
new_dir = self.filesystem.GetObject(path)
self.assertEqual(os.path.basename(path), new_dir.name)
self.assertTrue(stat.S_IFDIR & new_dir.st_mode)
def testCreateDirectoryInRootDirectoryAlreadyExistsError(self):
path = 'foo'
self.filesystem.CreateDirectory(path)
self.assertRaises(OSError, self.filesystem.CreateDirectory, path)
def testCreateDirectory(self):
path = 'foo/bar/baz'
self.filesystem.CreateDirectory(path)
new_dir = self.filesystem.GetObject(path)
self.assertEqual(os.path.basename(path), new_dir.name)
self.assertTrue(stat.S_IFDIR & new_dir.st_mode)
# Create second directory to make sure first is OK.
path = '%s/quux' % path
self.filesystem.CreateDirectory(path)
new_dir = self.filesystem.GetObject(path)
self.assertEqual(os.path.basename(path), new_dir.name)
self.assertTrue(stat.S_IFDIR & new_dir.st_mode)
def testCreateDirectoryAlreadyExistsError(self):
path = 'foo/bar/baz'
self.filesystem.CreateDirectory(path)
self.assertRaises(OSError, self.filesystem.CreateDirectory, path)
def testCreateFileInCurrentDirectory(self):
path = 'foo'
contents = 'dummy data'
self.filesystem.CreateFile(path, contents=contents)
self.assertTrue(self.filesystem.Exists(path))
self.assertFalse(self.filesystem.Exists(os.path.dirname(path)))
path = './%s' % path
self.assertTrue(self.filesystem.Exists(os.path.dirname(path)))
def testCreateFileInRootDirectory(self):
path = '/foo'
contents = 'dummy data'
self.filesystem.CreateFile(path, contents=contents)
new_file = self.filesystem.GetObject(path)
self.assertTrue(self.filesystem.Exists(path))
self.assertTrue(self.filesystem.Exists(os.path.dirname(path)))
self.assertEqual(os.path.basename(path), new_file.name)
self.assertTrue(stat.S_IFREG & new_file.st_mode)
self.assertEqual(contents, new_file.contents)
def testCreateFileWithSizeButNoContentCreatesLargeFile(self):
path = 'large_foo_bar'
self.filesystem.CreateFile(path, st_size=100000000)
new_file = self.filesystem.GetObject(path)
self.assertEqual(None, new_file.contents)
self.assertEqual(100000000, new_file.st_size)
def testCreateFileInRootDirectoryAlreadyExistsError(self):
path = 'foo'
self.filesystem.CreateFile(path)
self.assertRaises(IOError, self.filesystem.CreateFile, path)
def testCreateFile(self):
path = 'foo/bar/baz'
retval = self.filesystem.CreateFile(path, contents='dummy_data')
self.assertTrue(self.filesystem.Exists(path))
self.assertTrue(self.filesystem.Exists(os.path.dirname(path)))
new_file = self.filesystem.GetObject(path)
self.assertEqual(os.path.basename(path), new_file.name)
self.assertTrue(stat.S_IFREG & new_file.st_mode)
self.assertEqual(new_file, retval)
def testCreateFileAlreadyExistsError(self):
path = 'foo/bar/baz'
self.filesystem.CreateFile(path, contents='dummy_data')
self.assertRaises(IOError, self.filesystem.CreateFile, path)
def testCreateLink(self):
path = 'foo/bar/baz'
target_path = 'foo/bar/quux'
new_file = self.filesystem.CreateLink(path, 'quux')
# Neither the path not the final target exists before we actually write to
# one of them, even though the link appears in the file system.
self.assertFalse(self.filesystem.Exists(path))
self.assertFalse(self.filesystem.Exists(target_path))
self.assertTrue(stat.S_IFLNK & new_file.st_mode)
# but once we write the linked to file, they both will exist.
self.filesystem.CreateFile(target_path)
self.assertTrue(self.filesystem.Exists(path))
self.assertTrue(self.filesystem.Exists(target_path))
def testResolveObject(self):
target_path = 'dir/target'
target_contents = '0123456789ABCDEF'
link_name = 'x'
self.filesystem.CreateDirectory('dir')
self.filesystem.CreateFile('dir/target', contents=target_contents)
self.filesystem.CreateLink(link_name, target_path)
obj = self.filesystem.ResolveObject(link_name)
self.assertEqual('target', obj.name)
self.assertEqual(target_contents, obj.contents)
def testLresolveObject(self):
target_path = 'dir/target'
target_contents = '0123456789ABCDEF'
link_name = 'x'
self.filesystem.CreateDirectory('dir')
self.filesystem.CreateFile('dir/target', contents=target_contents)
self.filesystem.CreateLink(link_name, target_path)
obj = self.filesystem.LResolveObject(link_name)
self.assertEqual(link_name, obj.name)
self.assertEqual(target_path, obj.contents)
def testDirectoryAccessOnFile(self):
self.filesystem.CreateFile('not_a_dir')
self.assertRaises(IOError, self.filesystem.ResolveObject, 'not_a_dir/foo')
self.assertRaises(IOError, self.filesystem.ResolveObject,
'not_a_dir/foo/bar')
self.assertRaises(IOError, self.filesystem.LResolveObject, 'not_a_dir/foo')
self.assertRaises(IOError, self.filesystem.LResolveObject,
'not_a_dir/foo/bar')
class FakeOsModuleTest(TestCase):
def setUp(self):
self.filesystem = fake_filesystem.FakeFilesystem(path_separator='/')
self.os = fake_filesystem.FakeOsModule(self.filesystem)
self.rwx = self.os.R_OK | self.os.W_OK | self.os.X_OK
self.rw = self.os.R_OK | self.os.W_OK
self.orig_time = time.time
time.time = _GetDummyTime(200, 20)
def tearDown(self):
time.time = self.orig_time
def assertRaisesWithRegexpMatch(self, expected_exception, expected_regexp,
callable_obj, *args, **kwargs):
"""Asserts that the message in a raised exception matches the given regexp.
Args:
expected_exception: Exception class expected to be raised.
expected_regexp: Regexp (re pattern object or string) expected to be
found in error message.
callable_obj: Function to be called.
*args: Extra args.
**kwargs: Extra kwargs.
"""
try:
callable_obj(*args, **kwargs)
except expected_exception as err:
if isinstance(expected_regexp, str):
expected_regexp = re.compile(expected_regexp)
self.assertTrue(
expected_regexp.search(str(err)),
'"%s" does not match "%s"' % (expected_regexp.pattern, str(err)))
else:
self.fail(expected_exception.__name__ + ' not raised')
def testChdir(self):
"""chdir should work on a directory."""
directory = '/foo'
self.filesystem.CreateDirectory(directory)
self.os.chdir(directory)
def testChdirFailsNonExist(self):
"""chdir should raise OSError if the target does not exist."""
directory = '/no/such/directory'
self.assertRaises(OSError, self.os.chdir, directory)
def testChdirFailsNonDirectory(self):
"""chdir should raies OSError if the target is not a directory."""
filename = '/foo/bar'
self.filesystem.CreateFile(filename)
self.assertRaises(OSError, self.os.chdir, filename)
def testConsecutiveChdir(self):
"""Consecutive relative chdir calls should work."""
dir1 = 'foo'
dir2 = 'bar'
full_dirname = self.os.path.join(dir1, dir2)
self.filesystem.CreateDirectory(full_dirname)
self.os.chdir(dir1)
self.os.chdir(dir2)
self.assertEqual(self.os.getcwd(), self.os.path.sep + full_dirname)
def testBackwardsChdir(self):
"""chdir into '..' should behave appropriately."""
rootdir = self.os.getcwd()
dirname = 'foo'
abs_dirname = self.os.path.abspath(dirname)
self.filesystem.CreateDirectory(dirname)
self.os.chdir(dirname)
self.assertEqual(abs_dirname, self.os.getcwd())
self.os.chdir('..')
self.assertEqual(rootdir, self.os.getcwd())
self.os.chdir(self.os.path.join(dirname, '..'))
self.assertEqual(rootdir, self.os.getcwd())
def testGetCwd(self):
dirname = '/foo/bar'
self.filesystem.CreateDirectory(dirname)
self.assertEqual(self.os.getcwd(), self.os.path.sep)
self.os.chdir(dirname)
self.assertEqual(self.os.getcwd(), dirname)
def testListdir(self):
directory = 'xyzzy/plugh'
files = ['foo', 'bar', 'baz']
for f in files:
self.filesystem.CreateFile('%s/%s' % (directory, f))
files.sort()
self.assertEqual(files, self.os.listdir(directory))
def testListdirOnSymlink(self):
directory = 'xyzzy'
files = ['foo', 'bar', 'baz']
for f in files:
self.filesystem.CreateFile('%s/%s' % (directory, f))
self.filesystem.CreateLink('symlink', 'xyzzy')
files.sort()
self.assertEqual(files, self.os.listdir('symlink'))
def testListdirError(self):
file_path = 'foo/bar/baz'
self.filesystem.CreateFile(file_path)
self.assertRaises(OSError, self.os.listdir, file_path)
def testExistsCurrentDir(self):
self.assertTrue(self.filesystem.Exists('.'))
def testListdirCurrent(self):
files = ['foo', 'bar', 'baz']
for f in files:
self.filesystem.CreateFile('%s' % f)
files.sort()
self.assertEqual(files, self.os.listdir('.'))
def testFdopen(self):
fake_open = fake_filesystem.FakeFileOpen(self.filesystem)
file_path1 = 'some_file1'
self.filesystem.CreateFile(file_path1, contents='contents here1')
fake_file1 = fake_open(file_path1, 'r')
self.assertEqual(0, fake_file1.fileno())
self.assertFalse(self.os.fdopen(0) is fake_file1)
self.assertRaises(TypeError, self.os.fdopen, None)
self.assertRaises(TypeError, self.os.fdopen, 'a string')
def testOutOfRangeFdopen(self):
# We haven't created any files, so even 0 is out of range.
self.assertRaises(OSError, self.os.fdopen, 0)
def testClosedFileDescriptor(self):
fake_open = fake_filesystem.FakeFileOpen(self.filesystem)
first_path = 'some_file1'
second_path = 'some_file2'
third_path = 'some_file3'
self.filesystem.CreateFile(first_path, contents='contents here1')
self.filesystem.CreateFile(second_path, contents='contents here2')
self.filesystem.CreateFile(third_path, contents='contents here3')
fake_file1 = fake_open(first_path, 'r')
fake_file2 = fake_open(second_path, 'r')
fake_file3 = fake_open(third_path, 'r')
self.assertEqual(0, fake_file1.fileno())
self.assertEqual(1, fake_file2.fileno())
self.assertEqual(2, fake_file3.fileno())
fileno2 = fake_file2.fileno()
self.os.close(fileno2)
self.assertRaises(OSError, self.os.close, fileno2)
self.assertEqual(0, fake_file1.fileno())
self.assertEqual(2, fake_file3.fileno())
self.assertFalse(self.os.fdopen(0) is fake_file1)
self.assertFalse(self.os.fdopen(2) is fake_file3)
self.assertRaises(OSError, self.os.fdopen, 1)
def testFdopenMode(self):
fake_open = fake_filesystem.FakeFileOpen(self.filesystem)
file_path1 = 'some_file1'
self.filesystem.CreateFile(file_path1, contents='contents here1',
st_mode=((stat.S_IFREG | 0o666) ^ stat.S_IWRITE))
fake_file1 = fake_open(file_path1, 'r')
self.assertEqual(0, fake_file1.fileno())
self.os.fdopen(0)
self.os.fdopen(0, mode='r')
exception = OSError if sys.version_info < (3, 0) else IOError
self.assertRaises(exception, self.os.fdopen, 0, 'w')
def testLowLevelOpenCreate(self):
file_path = 'file1'
# this is the low-level open, not FakeFileOpen
fileno = self.os.open(file_path, self.os.O_CREAT)
self.assertEqual(0, fileno)
self.assertTrue(self.os.path.exists(file_path))
def testLowLevelOpenCreateMode(self):
file_path = 'file1'
fileno = self.os.open(file_path, self.os.O_CREAT, 0o700)
self.assertEqual(0, fileno)
self.assertTrue(self.os.path.exists(file_path))
self.assertModeEqual(0o700, self.os.stat(file_path).st_mode)
def testLowLevelOpenCreateModeUnsupported(self):
file_path = 'file1'
fake_flag = 0b100000000000000000000000
self.assertRaises(NotImplementedError, self.os.open, file_path, fake_flag)
def testLowLevelWriteRead(self):
file_path = 'file1'
self.filesystem.CreateFile(file_path, contents='orig contents')
new_contents = '1234567890abcdef'
fake_open = fake_filesystem.FakeFileOpen(self.filesystem)
fh = fake_open(file_path, 'w')
fileno = fh.fileno()
self.assertEqual(len(new_contents), self.os.write(fileno, new_contents))
self.assertEqual(new_contents,
self.filesystem.GetObject(file_path).contents)
self.os.close(fileno)
fh = fake_open(file_path, 'r')
fileno = fh.fileno()
self.assertEqual('', self.os.read(fileno, 0))
self.assertEqual(new_contents[0:2], self.os.read(fileno, 2))
self.assertEqual(new_contents[2:10], self.os.read(fileno, 8))
self.assertEqual(new_contents[10:], self.os.read(fileno, 100))
self.assertEqual('', self.os.read(fileno, 10))
self.os.close(fileno)
self.assertRaises(OSError, self.os.write, fileno, new_contents)
self.assertRaises(OSError, self.os.read, fileno, 10)
def testFstat(self):
directory = 'xyzzy'
file_path = '%s/plugh' % directory
self.filesystem.CreateFile(file_path, contents='ABCDE')
fake_open = fake_filesystem.FakeFileOpen(self.filesystem)
file_obj = fake_open(file_path)
fileno = file_obj.fileno()
self.assertTrue(stat.S_IFREG & self.os.fstat(fileno)[stat.ST_MODE])
self.assertTrue(stat.S_IFREG & self.os.fstat(fileno).st_mode)
self.assertEqual(5, self.os.fstat(fileno)[stat.ST_SIZE])
def testStat(self):
directory = 'xyzzy'
file_path = '%s/plugh' % directory
self.filesystem.CreateFile(file_path, contents='ABCDE')
self.assertTrue(stat.S_IFDIR & self.os.stat(directory)[stat.ST_MODE])
self.assertTrue(stat.S_IFREG & self.os.stat(file_path)[stat.ST_MODE])
self.assertTrue(stat.S_IFREG & self.os.stat(file_path).st_mode)
self.assertEqual(5, self.os.stat(file_path)[stat.ST_SIZE])
def testLstat(self):
directory = 'xyzzy'
base_name = 'plugh'
file_contents = 'frobozz'
# Just make sure we didn't accidentally make our test data meaningless.
self.assertNotEqual(len(base_name), len(file_contents))
file_path = '%s/%s' % (directory, base_name)
link_path = '%s/link' % directory
self.filesystem.CreateFile(file_path, contents=file_contents)
self.filesystem.CreateLink(link_path, base_name)
self.assertEqual(len(file_contents), self.os.lstat(file_path)[stat.ST_SIZE])
self.assertEqual(len(base_name), self.os.lstat(link_path)[stat.ST_SIZE])
def testStatNonExistentFile(self):
# set up
file_path = '/non/existent/file'
self.assertFalse(self.filesystem.Exists(file_path))
# actual tests
try:
# Use try-catch to check exception attributes.
self.os.stat(file_path)
self.fail('Exception is expected.') # COV_NF_LINE
except OSError as os_error:
self.assertEqual(errno.ENOENT, os_error.errno)
self.assertEqual(file_path, os_error.filename)
def testReadlink(self):
link_path = 'foo/bar/baz'
target = 'tarJAY'
self.filesystem.CreateLink(link_path, target)
self.assertEqual(self.os.readlink(link_path), target)
def testReadlinkRaisesIfPathIsNotALink(self):
file_path = 'foo/bar/eleventyone'
self.filesystem.CreateFile(file_path)
self.assertRaises(OSError, self.os.readlink, file_path)
def testReadlinkRaisesIfPathDoesNotExist(self):
self.assertRaises(OSError, self.os.readlink, '/this/path/does/not/exist')
def testReadlinkRaisesIfPathIsNone(self):
self.assertRaises(TypeError, self.os.readlink, None)
def testReadlinkWithLinksInPath(self):
self.filesystem.CreateLink('/meyer/lemon/pie', 'yum')
self.filesystem.CreateLink('/geo/metro', '/meyer')
self.assertEqual('yum', self.os.readlink('/geo/metro/lemon/pie'))
def testReadlinkWithChainedLinksInPath(self):
self.filesystem.CreateLink('/eastern/european/wolfhounds/chase', 'cats')
self.filesystem.CreateLink('/russian', '/eastern/european')
self.filesystem.CreateLink('/dogs', '/russian/wolfhounds')
self.assertEqual('cats', self.os.readlink('/dogs/chase'))
def testRemoveDir(self):
directory = 'xyzzy'
dir_path = '/%s/plugh' % directory
self.filesystem.CreateDirectory(dir_path)
self.assertTrue(self.filesystem.Exists(dir_path))
self.assertRaises(OSError, self.os.remove, dir_path)
self.assertTrue(self.filesystem.Exists(dir_path))
self.os.chdir(directory)
self.assertRaises(OSError, self.os.remove, 'plugh')
self.assertTrue(self.filesystem.Exists(dir_path))
self.assertRaises(OSError, self.os.remove, '/plugh')
def testRemoveFile(self):
directory = 'zzy'
file_path = '%s/plugh' % directory
self.filesystem.CreateFile(file_path)
self.assertTrue(self.filesystem.Exists(file_path))
self.os.remove(file_path)
self.assertFalse(self.filesystem.Exists(file_path))
def testRemoveDirRaisesError(self):
directory = 'zzy'
self.filesystem.CreateDirectory(directory)
self.assertRaises(OSError,
self.os.remove,
directory)
def testRemoveSymlinkToDir(self):
directory = 'zzy'
link = 'link_to_dir'
self.filesystem.CreateDirectory(directory)
self.os.symlink(directory, link)
self.assertTrue(self.filesystem.Exists(directory))
self.assertTrue(self.filesystem.Exists(link))
self.os.remove(link)
self.assertTrue(self.filesystem.Exists(directory))
self.assertFalse(self.filesystem.Exists(link))
def testUnlink(self):
self.assertTrue(self.os.unlink == self.os.remove)
def testUnlinkRaisesIfNotExist(self):
file_path = '/file/does/not/exist'
self.assertFalse(self.filesystem.Exists(file_path))
self.assertRaises(OSError, self.os.unlink, file_path)
def testRenameToNonexistentFile(self):
"""Can rename a file to an unused name."""
directory = 'xyzzy'
old_file_path = '%s/plugh_old' % directory
new_file_path = '%s/plugh_new' % directory
self.filesystem.CreateFile(old_file_path, contents='test contents')
self.assertTrue(self.filesystem.Exists(old_file_path))
self.assertFalse(self.filesystem.Exists(new_file_path))
self.os.rename(old_file_path, new_file_path)
self.assertFalse(self.filesystem.Exists(old_file_path))
self.assertTrue(self.filesystem.Exists(new_file_path))
self.assertEqual('test contents',
self.filesystem.GetObject(new_file_path).contents)
def testRenameDirectory(self):
"""Can rename a directory to an unused name."""
for old_path, new_path in [('wxyyw', 'xyzzy'), ('/abccb', 'cdeed')]:
self.filesystem.CreateFile('%s/plugh' % old_path, contents='test')
self.assertTrue(self.filesystem.Exists(old_path))
self.assertFalse(self.filesystem.Exists(new_path))
self.os.rename(old_path, new_path)
self.assertFalse(self.filesystem.Exists(old_path))
self.assertTrue(self.filesystem.Exists(new_path))
self.assertEqual(
'test', self.filesystem.GetObject('%s/plugh' % new_path).contents)
def testRenameToExistentFile(self):
"""Can rename a file to a used name."""
directory = 'xyzzy'
old_file_path = '%s/plugh_old' % directory
new_file_path = '%s/plugh_new' % directory
self.filesystem.CreateFile(old_file_path, contents='test contents 1')
self.filesystem.CreateFile(new_file_path, contents='test contents 2')
self.assertTrue(self.filesystem.Exists(old_file_path))
self.assertTrue(self.filesystem.Exists(new_file_path))
self.os.rename(old_file_path, new_file_path)
self.assertFalse(self.filesystem.Exists(old_file_path))
self.assertTrue(self.filesystem.Exists(new_file_path))
self.assertEqual('test contents 1',
self.filesystem.GetObject(new_file_path).contents)
def testRenameToNonexistentDir(self):
"""Can rename a file to a name in a nonexistent dir."""
directory = 'xyzzy'
old_file_path = '%s/plugh_old' % directory
new_file_path = '%s/no_such_path/plugh_new' % directory
self.filesystem.CreateFile(old_file_path, contents='test contents')
self.assertTrue(self.filesystem.Exists(old_file_path))
self.assertFalse(self.filesystem.Exists(new_file_path))
self.assertRaises(IOError, self.os.rename, old_file_path, new_file_path)
self.assertTrue(self.filesystem.Exists(old_file_path))
self.assertFalse(self.filesystem.Exists(new_file_path))
self.assertEqual('test contents',
self.filesystem.GetObject(old_file_path).contents)
def testRenameNonexistentFileShouldRaiseError(self):
"""Can't rename a file that doesn't exist."""
self.assertRaises(OSError,
self.os.rename,
'nonexistent-foo',
'doesn\'t-matter-bar')
def testRenameEmptyDir(self):
"""Test a rename of an empty directory."""
directory = 'xyzzy'
before_dir = '%s/empty' % directory
after_dir = '%s/unused' % directory
self.filesystem.CreateDirectory(before_dir)
self.assertTrue(self.filesystem.Exists('%s/.' % before_dir))
self.assertFalse(self.filesystem.Exists(after_dir))
self.os.rename(before_dir, after_dir)
self.assertFalse(self.filesystem.Exists(before_dir))
self.assertTrue(self.filesystem.Exists('%s/.' % after_dir))
def testRenameDir(self):
"""Test a rename of a directory."""
directory = 'xyzzy'
before_dir = '%s/before' % directory
before_file = '%s/before/file' % directory
after_dir = '%s/after' % directory
after_file = '%s/after/file' % directory
self.filesystem.CreateDirectory(before_dir)
self.filesystem.CreateFile(before_file, contents='payload')
self.assertTrue(self.filesystem.Exists(before_dir))
self.assertTrue(self.filesystem.Exists(before_file))
self.assertFalse(self.filesystem.Exists(after_dir))
self.assertFalse(self.filesystem.Exists(after_file))
self.os.rename(before_dir, after_dir)
self.assertFalse(self.filesystem.Exists(before_dir))
self.assertFalse(self.filesystem.Exists(before_file))
self.assertTrue(self.filesystem.Exists(after_dir))
self.assertTrue(self.filesystem.Exists(after_file))
self.assertEqual('payload',
self.filesystem.GetObject(after_file).contents)
def testRenamePreservesStat(self):
"""Test if rename preserves mtime."""
directory = 'xyzzy'
old_file_path = '%s/plugh_old' % directory
new_file_path = '%s/plugh_new' % directory
old_file = self.filesystem.CreateFile(old_file_path)
old_file.SetMTime(old_file.st_mtime - 3600)
self.os.chown(old_file_path, 200, 200)
self.os.chmod(old_file_path, 0o222)
new_file = self.filesystem.CreateFile(new_file_path)
self.assertNotEqual(new_file.st_mtime, old_file.st_mtime)
self.os.rename(old_file_path, new_file_path)
new_file = self.filesystem.GetObject(new_file_path)
self.assertEqual(new_file.st_mtime, old_file.st_mtime)
self.assertEqual(new_file.st_mode, old_file.st_mode)
self.assertEqual(new_file.st_uid, old_file.st_uid)
self.assertEqual(new_file.st_gid, old_file.st_gid)
def testRmdir(self):
"""Can remove a directory."""
directory = 'xyzzy'
sub_dir = '/xyzzy/abccd'
other_dir = '/xyzzy/cdeed'
self.filesystem.CreateDirectory(directory)
self.assertTrue(self.filesystem.Exists(directory))
self.os.rmdir(directory)
self.assertFalse(self.filesystem.Exists(directory))
self.filesystem.CreateDirectory(sub_dir)
self.filesystem.CreateDirectory(other_dir)
self.os.chdir(sub_dir)
self.os.rmdir('../cdeed')
self.assertFalse(self.filesystem.Exists(other_dir))
self.os.chdir('..')
self.os.rmdir('abccd')
self.assertFalse(self.filesystem.Exists(sub_dir))
def testRmdirRaisesIfNotEmpty(self):
"""Raises an exception if the target directory is not empty."""
directory = 'xyzzy'
file_path = '%s/plugh' % directory
self.filesystem.CreateFile(file_path)
self.assertTrue(self.filesystem.Exists(file_path))
self.assertRaises(OSError, self.os.rmdir, directory)
def testRmdirRaisesIfNotDirectory(self):
"""Raises an exception if the target is not a directory."""
directory = 'xyzzy'
file_path = '%s/plugh' % directory
self.filesystem.CreateFile(file_path)
self.assertTrue(self.filesystem.Exists(file_path))
self.assertRaises(OSError, self.os.rmdir, file_path)
self.assertRaises(OSError, self.os.rmdir, '.')
def testRmdirRaisesIfNotExist(self):
"""Raises an exception if the target does not exist."""
directory = 'xyzzy'
self.assertFalse(self.filesystem.Exists(directory))
self.assertRaises(OSError, self.os.rmdir, directory)
def RemovedirsCheck(self, directory):
self.assertTrue(self.filesystem.Exists(directory))
self.os.removedirs(directory)
return not self.filesystem.Exists(directory)
def testRemovedirs(self):
data = ['test1', 'test1/test2', 'test1/extra', 'test1/test2/test3']
for directory in data:
self.filesystem.CreateDirectory(directory)
self.assertTrue(self.filesystem.Exists(directory))
self.assertRaises(OSError, self.RemovedirsCheck, data[0])
self.assertRaises(OSError, self.RemovedirsCheck, data[1])
self.assertTrue(self.RemovedirsCheck(data[3]))
self.assertTrue(self.filesystem.Exists(data[0]))
self.assertFalse(self.filesystem.Exists(data[1]))
self.assertTrue(self.filesystem.Exists(data[2]))
# Should raise because '/test1/extra' is all that is left, and
# removedirs('/test1/extra') will eventually try to rmdir('/').
self.assertRaises(OSError, self.RemovedirsCheck, data[2])
# However, it will still delete '/test1') in the process.
self.assertFalse(self.filesystem.Exists(data[0]))
self.filesystem.CreateDirectory('test1/test2')
# Add this to the root directory to avoid raising an exception.
self.filesystem.CreateDirectory('test3')