forked from swiftlang/swift-corelibs-foundation
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTestFileManager.swift
1829 lines (1552 loc) · 79.9 KB
/
TestFileManager.swift
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
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
#if NS_FOUNDATION_ALLOWS_TESTABLE_IMPORT
#if canImport(SwiftFoundation) && !DEPLOYMENT_RUNTIME_OBJC
@testable import SwiftFoundation
#else
@testable import Foundation
#endif
#endif
class TestFileManager : XCTestCase {
#if os(Windows)
let pathSep = "\\"
#else
let pathSep = "/"
#endif
func test_createDirectory() {
let fm = FileManager.default
let path = NSTemporaryDirectory() + "testdir\(NSUUID().uuidString)"
try? fm.removeItem(atPath: path)
do {
try fm.createDirectory(atPath: path, withIntermediateDirectories: false, attributes: nil)
} catch {
XCTFail()
}
// Ensure attempting to create the directory again fails gracefully.
XCTAssertNil(try? fm.createDirectory(atPath: path, withIntermediateDirectories:false, attributes:nil))
var isDir: ObjCBool = false
let exists = fm.fileExists(atPath: path, isDirectory: &isDir)
XCTAssertTrue(exists)
XCTAssertTrue(isDir.boolValue)
do {
try fm.removeItem(atPath: path)
} catch {
XCTFail("Failed to clean up file")
}
}
func test_createFile() {
let fm = FileManager.default
let path = NSTemporaryDirectory() + "testfile\(NSUUID().uuidString)"
try? fm.removeItem(atPath: path)
XCTAssertTrue(fm.createFile(atPath: path, contents: Data(), attributes: nil))
var isDir: ObjCBool = false
let exists = fm.fileExists(atPath: path, isDirectory: &isDir)
XCTAssertTrue(exists)
XCTAssertFalse(isDir.boolValue)
do {
try fm.removeItem(atPath: path)
} catch {
XCTFail("Failed to clean up file")
}
#if os(Windows)
let permissions = NSNumber(value: Int16(0o700))
#else
let permissions = NSNumber(value: Int16(0o753))
#endif
let attributes = [FileAttributeKey.posixPermissions: permissions]
XCTAssertTrue(fm.createFile(atPath: path, contents: Data(),
attributes: attributes))
guard let retrievedAtributes = try? fm.attributesOfItem(atPath: path) else {
XCTFail("Failed to retrieve file attributes from created file")
return
}
XCTAssertTrue(retrievedAtributes.contains(where: { (attribute) -> Bool in
guard let attributeValue = attribute.value as? NSNumber else {
return false
}
return (attribute.key == .posixPermissions)
&& (attributeValue == permissions)
}))
do {
try fm.removeItem(atPath: path)
} catch {
XCTFail("Failed to clean up file")
}
}
func test_creatingDirectoryWithShortIntermediatePath() {
let fileManager = FileManager.default
fileManager.changeCurrentDirectoryPath(NSTemporaryDirectory())
let relativePath = NSUUID().uuidString
do {
try fileManager.createDirectory(atPath: relativePath, withIntermediateDirectories: true, attributes: nil)
try fileManager.removeItem(atPath: relativePath)
} catch {
XCTFail("Failed to create and clean up directory")
}
}
func test_moveFile() {
let fm = FileManager.default
let path = NSTemporaryDirectory() + "testfile\(NSUUID().uuidString)"
let path2 = NSTemporaryDirectory() + "testfile2\(NSUUID().uuidString)"
func cleanup() {
try? fm.removeItem(atPath: path)
try? fm.removeItem(atPath: path2)
}
cleanup()
XCTAssertTrue(fm.createFile(atPath: path, contents: Data(), attributes: nil))
defer { cleanup() }
do {
try fm.moveItem(atPath: path, toPath: path2)
} catch {
XCTFail("Failed to move file: \(error)")
}
}
func test_fileSystemRepresentation() {
let str = "☃"
let result = FileManager.default.fileSystemRepresentation(withPath: str)
XCTAssertEqual(UInt8(bitPattern: result[0]), 0xE2)
XCTAssertEqual(UInt8(bitPattern: result[1]), 0x98)
XCTAssertEqual(UInt8(bitPattern: result[2]), 0x83)
#if !DARWIN_COMPATIBILITY_TESTS // auto-released by Darwin's Foundation
result.deallocate()
#endif
}
func test_fileExists() {
let fm = FileManager.default
let tmpDir = fm.temporaryDirectory.appendingPathComponent("testFileExistsDir")
let testFile = tmpDir.appendingPathComponent("testFile")
let goodSymLink = tmpDir.appendingPathComponent("goodSymLink")
let badSymLink = tmpDir.appendingPathComponent("badSymLink")
let dirSymLink = tmpDir.appendingPathComponent("dirSymlink")
try? fm.removeItem(atPath: tmpDir.path)
do {
try fm.createDirectory(atPath: tmpDir.path, withIntermediateDirectories: false, attributes: nil)
XCTAssertTrue(fm.createFile(atPath: testFile.path, contents: Data()))
try fm.createSymbolicLink(atPath: goodSymLink.path, withDestinationPath: testFile.path)
#if os(Windows)
// Creating a broken symlink is expected to fail on Windows
XCTAssertNil(try? fm.createSymbolicLink(atPath: badSymLink.path, withDestinationPath: "no_such_file"))
#else
try fm.createSymbolicLink(atPath: badSymLink.path, withDestinationPath: "no_such_file")
#endif
try fm.createSymbolicLink(atPath: dirSymLink.path, withDestinationPath: "..")
var isDirFlag: ObjCBool = false
XCTAssertTrue(fm.fileExists(atPath: tmpDir.path))
XCTAssertTrue(fm.fileExists(atPath: tmpDir.path, isDirectory: &isDirFlag))
XCTAssertTrue(isDirFlag.boolValue)
isDirFlag = true
XCTAssertTrue(fm.fileExists(atPath: testFile.path))
XCTAssertTrue(fm.fileExists(atPath: testFile.path, isDirectory: &isDirFlag))
XCTAssertFalse(isDirFlag.boolValue)
isDirFlag = true
XCTAssertTrue(fm.fileExists(atPath: goodSymLink.path))
XCTAssertTrue(fm.fileExists(atPath: goodSymLink.path, isDirectory: &isDirFlag))
XCTAssertFalse(isDirFlag.boolValue)
isDirFlag = true
XCTAssertFalse(fm.fileExists(atPath: badSymLink.path))
XCTAssertFalse(fm.fileExists(atPath: badSymLink.path, isDirectory: &isDirFlag))
isDirFlag = false
XCTAssertTrue(fm.fileExists(atPath: dirSymLink.path))
XCTAssertTrue(fm.fileExists(atPath: dirSymLink.path, isDirectory: &isDirFlag))
XCTAssertTrue(isDirFlag.boolValue)
} catch {
XCTFail(String(describing: error))
}
try? fm.removeItem(atPath: tmpDir.path)
}
func test_isReadableFile() {
let fm = FileManager.default
let path = NSTemporaryDirectory() + "test_isReadableFile\(NSUUID().uuidString)"
do {
// create test file
XCTAssertTrue(fm.createFile(atPath: path, contents: Data()))
// test unReadable if file has no permissions
try fm.setAttributes([.posixPermissions : NSNumber(value: Int16(0o0000))], ofItemAtPath: path)
#if os(Windows)
// Files are always readable on Windows
XCTAssertTrue(fm.isReadableFile(atPath: path))
#else
XCTAssertFalse(fm.isReadableFile(atPath: path))
#endif
// test readable if file has read permissions
try fm.setAttributes([.posixPermissions : NSNumber(value: Int16(0o0400))], ofItemAtPath: path)
XCTAssertTrue(fm.isReadableFile(atPath: path))
} catch let e {
XCTFail("\(e)")
}
}
func test_isWritableFile() {
let fm = FileManager.default
let path = NSTemporaryDirectory() + "test_isWritableFile\(NSUUID().uuidString)"
do {
// create test file
XCTAssertTrue(fm.createFile(atPath: path, contents: Data()))
// test unWritable if file has no permissions
try fm.setAttributes([.posixPermissions : NSNumber(value: Int16(0o0000))], ofItemAtPath: path)
XCTAssertFalse(fm.isWritableFile(atPath: path))
// test writable if file has write permissions
try fm.setAttributes([.posixPermissions : NSNumber(value: Int16(0o0200))], ofItemAtPath: path)
XCTAssertTrue(fm.isWritableFile(atPath: path))
} catch let e {
XCTFail("\(e)")
}
}
func test_isExecutableFile() {
let fm = FileManager.default
let path = NSTemporaryDirectory() + "test_isExecutableFile\(NSUUID().uuidString)"
do {
// create test file
XCTAssertTrue(fm.createFile(atPath: path, contents: Data()))
// test unExecutable if file has no permissions
try fm.setAttributes([.posixPermissions : NSNumber(value: Int16(0o0000))], ofItemAtPath: path)
#if os(Windows)
// Files are always executable on Windows
XCTAssertTrue(fm.isExecutableFile(atPath: path))
#else
XCTAssertFalse(fm.isExecutableFile(atPath: path))
#endif
// test executable if file has execute permissions
try fm.setAttributes([.posixPermissions : NSNumber(value: Int16(0o0100))], ofItemAtPath: path)
XCTAssertTrue(fm.isExecutableFile(atPath: path))
} catch let e {
XCTFail("\(e)")
}
}
func test_isDeletableFile() {
let fm = FileManager.default
do {
let dir_path = NSTemporaryDirectory() + "/test_isDeletableFile_dir/"
let file_path = dir_path + "test_isDeletableFile\(NSUUID().uuidString)"
// create test directory
try fm.createDirectory(atPath: dir_path, withIntermediateDirectories: true)
// create test file
XCTAssertTrue(fm.createFile(atPath: file_path, contents: Data()))
// test undeletable if parent directory has no permissions
try fm.setAttributes([.posixPermissions : NSNumber(value: Int16(0o0000))], ofItemAtPath: dir_path)
XCTAssertFalse(fm.isDeletableFile(atPath: file_path))
// test deletable if parent directory has all necessary permissions
try fm.setAttributes([.posixPermissions : NSNumber(value: Int16(0o0755))], ofItemAtPath: dir_path)
XCTAssertTrue(fm.isDeletableFile(atPath: file_path))
}
catch { XCTFail("\(error)") }
// test against known undeletable file
XCTAssertFalse(fm.isDeletableFile(atPath: "/dev/null"))
}
func test_fileAttributes() throws {
let fm = FileManager.default
let path = NSTemporaryDirectory() + "test_fileAttributes\(NSUUID().uuidString)"
try? fm.removeItem(atPath: path)
XCTAssertTrue(fm.createFile(atPath: path, contents: Data(), attributes: nil))
do {
let attrs = try fm.attributesOfItem(atPath: path)
XCTAssertTrue(attrs.count > 0)
let fileSize = attrs[.size] as? NSNumber
XCTAssertEqual(fileSize!.int64Value, 0)
let fileModificationDate = attrs[.modificationDate] as? Date
XCTAssertGreaterThan(Date().timeIntervalSince1970, fileModificationDate!.timeIntervalSince1970)
let filePosixPermissions = attrs[.posixPermissions] as? NSNumber
XCTAssertNotEqual(filePosixPermissions!.int64Value, 0)
let fileReferenceCount = attrs[.referenceCount] as? NSNumber
XCTAssertEqual(fileReferenceCount!.int64Value, 1)
let fileSystemNumber = attrs[.systemNumber] as? NSNumber
XCTAssertNotEqual(fileSystemNumber!.int64Value, 0)
#if !os(Windows)
let fileSystemFileNumber = attrs[.systemFileNumber] as? NSNumber
XCTAssertNotEqual(fileSystemFileNumber!.int64Value, 0)
#endif
let fileType = attrs[.type] as? FileAttributeType
XCTAssertEqual(fileType!, .typeRegular)
let fileOwnerAccountID = attrs[.ownerAccountID] as? NSNumber
XCTAssertNotNil(fileOwnerAccountID)
let fileGroupOwnerAccountID = attrs[.groupOwnerAccountID] as? NSNumber
XCTAssertNotNil(fileGroupOwnerAccountID)
#if os(Linux)
/* ⚠️ */
if shouldAttemptXFailTests("Checking that .creationDate is set is failing on Ubuntu 16.04 when running from a Docker image. https://bugs.swift.org/browse/SR-10512") {
let requiredVersion = OperatingSystemVersion(majorVersion: 4, minorVersion: 11, patchVersion: 0)
let creationDate = attrs[.creationDate] as? Date
if ProcessInfo.processInfo.isOperatingSystemAtLeast(requiredVersion) {
XCTAssertNotNil(creationDate)
XCTAssertGreaterThan(Date().timeIntervalSince1970, try creationDate.unwrapped().timeIntervalSince1970)
} else {
XCTAssertNil(creationDate)
}
}
/* ⚠️ */
#endif
if let fileOwnerAccountName = attrs[.ownerAccountName] {
XCTAssertNotNil(fileOwnerAccountName as? String)
if let fileOwnerAccountNameStr = fileOwnerAccountName as? String {
XCTAssertFalse(fileOwnerAccountNameStr.isEmpty)
}
}
if let fileGroupOwnerAccountName = attrs[.groupOwnerAccountName] {
XCTAssertNotNil(fileGroupOwnerAccountName as? String)
if let fileGroupOwnerAccountNameStr = fileGroupOwnerAccountName as? String {
XCTAssertFalse(fileGroupOwnerAccountNameStr.isEmpty)
}
}
} catch {
XCTFail("\(error)")
}
do {
try fm.removeItem(atPath: path)
} catch {
XCTFail("Failed to clean up files")
}
}
func test_fileSystemAttributes() {
let fm = FileManager.default
let path = NSTemporaryDirectory()
do {
let attrs = try fm.attributesOfFileSystem(forPath: path)
XCTAssertTrue(attrs.count > 0)
let systemNumber = attrs[.systemNumber] as? NSNumber
XCTAssertNotNil(systemNumber)
let systemFreeSize = attrs[.systemFreeSize] as? NSNumber
XCTAssertNotNil(systemFreeSize)
XCTAssertNotEqual(systemFreeSize!.uint64Value, 0)
let systemSize = attrs[.systemSize] as? NSNumber
XCTAssertNotNil(systemSize)
XCTAssertGreaterThan(systemSize!.uint64Value, systemFreeSize!.uint64Value)
if shouldAttemptWindowsXFailTests("FileAttributes[.systemFreeNodes], FileAttributes[.systemNodes] not implemented") {
let systemFreeNodes = attrs[.systemFreeNodes] as? NSNumber
XCTAssertNotNil(systemFreeNodes)
XCTAssertNotEqual(systemFreeNodes!.uint64Value, 0)
let systemNodes = attrs[.systemNodes] as? NSNumber
XCTAssertNotNil(systemNodes)
XCTAssertGreaterThan(systemNodes!.uint64Value, systemFreeNodes!.uint64Value)
}
} catch {
XCTFail("\(error)")
}
}
func test_setFileAttributes() {
let path = NSTemporaryDirectory() + "test_setFileAttributes\(NSUUID().uuidString)"
let fm = FileManager.default
try? fm.removeItem(atPath: path)
XCTAssertTrue(fm.createFile(atPath: path, contents: Data(), attributes: nil))
do {
try fm.setAttributes([.posixPermissions : NSNumber(value: Int16(0o0600))], ofItemAtPath: path)
}
catch { XCTFail("\(error)") }
//read back the attributes
do {
let attributes = try fm.attributesOfItem(atPath: path)
#if os(Windows)
XCTAssert((attributes[.posixPermissions] as? NSNumber)?.int16Value == 0o0700)
#else
XCTAssert((attributes[.posixPermissions] as? NSNumber)?.int16Value == 0o0600)
#endif
}
catch { XCTFail("\(error)") }
do {
try fm.removeItem(atPath: path)
} catch {
XCTFail("Failed to clean up files")
}
// test non existent file
let noSuchFile = NSTemporaryDirectory() + "fileThatDoesntExist"
try? fm.removeItem(atPath: noSuchFile)
do {
try fm.setAttributes([.posixPermissions: 0], ofItemAtPath: noSuchFile)
XCTFail("Setting permissions of non-existent file should throw")
} catch {
}
}
func test_pathEnumerator() {
let fm = FileManager.default
let testDirName = "testdir\(NSUUID().uuidString)"
let basePath = NSTemporaryDirectory() + "\(testDirName)"
let itemPath = NSTemporaryDirectory() + "\(testDirName)/item"
let basePath2 = NSTemporaryDirectory() + "\(testDirName)/path2"
let itemPath2 = NSTemporaryDirectory() + "\(testDirName)/path2/item"
try? fm.removeItem(atPath: basePath)
do {
try fm.createDirectory(atPath: basePath, withIntermediateDirectories: false, attributes: nil)
try fm.createDirectory(atPath: basePath2, withIntermediateDirectories: false, attributes: nil)
let _ = fm.createFile(atPath: itemPath, contents: Data(count: 123), attributes: nil)
let _ = fm.createFile(atPath: itemPath2, contents: Data(count: 456), attributes: nil)
} catch {
XCTFail()
}
var item1FileAttributes: [FileAttributeKey: Any]!
var item2FileAttributes: [FileAttributeKey: Any]!
if let e = FileManager.default.enumerator(atPath: basePath) {
let attrs = e.directoryAttributes
XCTAssertNotNil(attrs)
XCTAssertEqual(attrs?[.type] as? FileAttributeType, .typeDirectory)
var foundItems = Set<String>()
while let item = e.nextObject() as? String {
foundItems.insert(item)
if item == "item" {
item1FileAttributes = e.fileAttributes
} else if item == "path2\(pathSep)item" {
item2FileAttributes = e.fileAttributes
}
}
XCTAssertEqual(foundItems, Set(["item", "path2", "path2\(pathSep)item"]))
} else {
XCTFail()
}
XCTAssertNotNil(item1FileAttributes)
if let size = item1FileAttributes[.size] as? NSNumber {
XCTAssertEqual(size.int64Value, 123)
} else {
XCTFail("Cant get file size for 'item'")
}
XCTAssertNotNil(item2FileAttributes)
if let size = item2FileAttributes[.size] as? NSNumber {
XCTAssertEqual(size.int64Value, 456)
} else {
XCTFail("Cant get file size for 'path2/item'")
}
if let e2 = FileManager.default.enumerator(atPath: basePath) {
var foundItems = Set<String>()
while let item = e2.nextObject() as? String {
foundItems.insert(item)
if item == "path2" {
e2.skipDescendants()
XCTAssertEqual(e2.level, 1)
XCTAssertNotNil(e2.fileAttributes)
}
}
XCTAssertEqual(foundItems, Set(["item", "path2"]))
} else {
XCTFail()
}
}
func test_directoryEnumerator() {
let fm = FileManager.default
let basePath = NSTemporaryDirectory() + "testdir\(NSUUID().uuidString)/"
let hiddenDir1 = basePath + "subdir1/subdir2/.hiddenDir/"
let subDirs1 = hiddenDir1 + "subdir3/"
let itemPath1 = basePath + "itemFile1"
#if os(Windows)
// Filenames ending with '.' are not valid on Windows, so don't bother testing them
let hiddenDir2 = basePath + "subdir1/subdir2/subdir4.app/subdir5/.subdir6.ext/"
let subDirs2 = hiddenDir2 + "subdir7.ext/"
let itemPath2 = subDirs1 + "itemFile2"
let itemPath3 = subDirs1 + "itemFile3.ext"
#else
let hiddenDir2 = basePath + "subdir1/subdir2/subdir4.app/subdir5./.subdir6.ext/"
let subDirs2 = hiddenDir2 + "subdir7.ext./"
let itemPath2 = subDirs1 + "itemFile2."
let itemPath3 = subDirs1 + "itemFile3.ext."
#endif
let hiddenItem1 = basePath + ".hiddenFile1"
let hiddenItem2 = subDirs1 + ".hiddenFile2"
let hiddenItem3 = subDirs2 + ".hiddenFile3"
let hiddenItem4 = subDirs2 + ".hiddenFile4.ext"
var fileLevels: [String: Int] = [
"itemFile1": 1,
".hiddenFile1": 1,
"subdir1": 1,
"subdir2": 2,
"subdir4.app": 3,
".subdir6.ext": 5,
".hiddenFile4.ext": 7,
".hiddenFile3": 7,
".hiddenDir": 3,
"subdir3": 4,
".hiddenFile2": 5,
]
#if os(Windows)
fileLevels["itemFile2"] = 5
fileLevels["subdir5"] = 4
fileLevels["subdir7.ext"] = 6
fileLevels["itemFile3.ext"] = 5
#else
fileLevels["itemFile2."] = 5
fileLevels["subdir5."] = 4
fileLevels["subdir7.ext."] = 6
fileLevels["itemFile3.ext."] = 5
#endif
func directoryItems(options: FileManager.DirectoryEnumerationOptions) -> [String: Int]? {
if let e = FileManager.default.enumerator(at: URL(fileURLWithPath: basePath), includingPropertiesForKeys: nil, options: options, errorHandler: nil) {
var foundItems = [String:Int]()
while let item = e.nextObject() as? URL {
foundItems[item.lastPathComponent] = e.level
}
return foundItems
} else {
return nil
}
}
try? fm.removeItem(atPath: basePath)
defer { try? fm.removeItem(atPath: basePath) }
XCTAssertNotNil(try? fm.createDirectory(atPath: subDirs1, withIntermediateDirectories: true, attributes: nil))
XCTAssertNotNil(try? fm.createDirectory(atPath: subDirs2, withIntermediateDirectories: true, attributes: nil))
for filename in [itemPath1, itemPath2, itemPath3] {
XCTAssertTrue(fm.createFile(atPath: filename, contents: Data(), attributes: nil), "Cant create file '\(filename)'")
}
var resourceValues = URLResourceValues()
resourceValues.isHidden = true
for filename in [ hiddenItem1, hiddenItem2, hiddenItem3, hiddenItem4] {
XCTAssertTrue(fm.createFile(atPath: filename, contents: Data(), attributes: nil), "Cant create file '\(filename)'")
#if os(Windows)
do {
var url = URL(fileURLWithPath: filename)
try url.setResourceValues(resourceValues)
} catch {
XCTFail("Couldn't make \(filename) a hidden file")
}
#endif
}
#if os(Windows)
do {
var hiddenURL1 = URL(fileURLWithPath: hiddenDir1)
var hiddenURL2 = URL(fileURLWithPath: hiddenDir2)
try hiddenURL1.setResourceValues(resourceValues)
try hiddenURL2.setResourceValues(resourceValues)
} catch {
XCTFail("Couldn't make \(hiddenDir1) and \(hiddenDir2) hidden directories")
}
#endif
if let foundItems = directoryItems(options: []) {
XCTAssertEqual(foundItems.count, fileLevels.count)
for (name, level) in foundItems {
XCTAssertEqual(fileLevels[name], level, "File level for \(name) is wrong")
}
} else {
XCTFail("Cant enumerate directory at \(basePath) with options: []")
}
if let foundItems = directoryItems(options: [.skipsHiddenFiles]) {
XCTAssertEqual(foundItems.count, 5)
} else {
XCTFail("Cant enumerate directory at \(basePath) with options: [.skipsHiddenFiles]")
}
if let foundItems = directoryItems(options: [.skipsSubdirectoryDescendants]) {
XCTAssertEqual(foundItems.count, 3)
} else {
XCTFail("Cant enumerate directory at \(basePath) with options: [.skipsSubdirectoryDescendants]")
}
if let foundItems = directoryItems(options: [.skipsHiddenFiles, .skipsSubdirectoryDescendants]) {
XCTAssertEqual(foundItems.count, 2)
} else {
XCTFail("Cant enumerate directory at \(basePath) with options: [.skipsHiddenFiles, .skipsSubdirectoryDescendants]")
}
if let foundItems = directoryItems(options: [.skipsPackageDescendants]) {
#if DARWIN_COMPATIBILITY_TESTS
XCTAssertEqual(foundItems.count, 10) // Only native Foundation does not gnore .skipsPackageDescendants
#else
XCTAssertEqual(foundItems.count, 15)
#endif
} else {
XCTFail("Cant enumerate directory at \(basePath) with options: [.skipsHiddenFiles, .skipsSubdirectoryDescendants]")
}
var didGetError = false
let handler : (URL, Error) -> Bool = { (URL, Error) in
didGetError = true
return true
}
if let e = FileManager.default.enumerator(at: URL(fileURLWithPath: "/nonexistent-path"), includingPropertiesForKeys: nil, options: [], errorHandler: handler) {
XCTAssertNil(e.nextObject())
} else {
XCTFail()
}
XCTAssertTrue(didGetError)
do {
let contents = try FileManager.default.contentsOfDirectory(at: URL(fileURLWithPath: basePath), includingPropertiesForKeys: nil, options: []).map {
return $0.path
}
XCTAssertEqual(contents.count, 3)
} catch {
XCTFail()
}
}
func test_contentsOfDirectoryAtPath() {
let fm = FileManager.default
let testDirName = "testdir\(NSUUID().uuidString)"
let path = NSTemporaryDirectory() + "\(testDirName)"
let itemPath1 = NSTemporaryDirectory() + "\(testDirName)/item"
let itemPath2 = NSTemporaryDirectory() + "\(testDirName)/item2"
try? fm.removeItem(atPath: path)
do {
try fm.createDirectory(atPath: path, withIntermediateDirectories: false, attributes: nil)
let _ = fm.createFile(atPath: itemPath1, contents: Data(), attributes: nil)
let _ = fm.createFile(atPath: itemPath2, contents: Data(), attributes: nil)
} catch {
XCTFail()
}
do {
let entries = try fm.contentsOfDirectory(atPath: path)
XCTAssertEqual(2, entries.count)
XCTAssertTrue(entries.contains("item"))
XCTAssertTrue(entries.contains("item2"))
}
catch {
XCTFail()
}
do {
// Check a bad path fails
let _ = try fm.contentsOfDirectory(atPath: "/...")
XCTFail()
}
catch {
// Invalid directories should fail.
}
do {
try fm.removeItem(atPath: path)
} catch {
XCTFail("Failed to clean up files")
}
}
func test_subpathsOfDirectoryAtPath() {
let fm = FileManager.default
let path = NSTemporaryDirectory() + "testdir"
let path2 = NSTemporaryDirectory() + "testdir/sub"
let itemPath1 = NSTemporaryDirectory() + "testdir/item"
let itemPath2 = NSTemporaryDirectory() + "testdir/item2"
let itemPath3 = NSTemporaryDirectory() + "testdir/sub/item3"
try? fm.removeItem(atPath: path)
do {
try fm.createDirectory(atPath: path, withIntermediateDirectories: false, attributes: nil)
let _ = fm.createFile(atPath: itemPath1, contents: Data(), attributes: nil)
let _ = fm.createFile(atPath: itemPath2, contents: Data(), attributes: nil)
try fm.createDirectory(atPath: path2, withIntermediateDirectories: false, attributes: nil)
let _ = fm.createFile(atPath: itemPath3, contents: Data(), attributes: nil)
} catch {
XCTFail()
}
do {
let entries = try fm.subpathsOfDirectory(atPath: path)
XCTAssertEqual(4, entries.count)
XCTAssertTrue(entries.contains("item"))
XCTAssertTrue(entries.contains("item2"))
XCTAssertTrue(entries.contains("sub"))
XCTAssertTrue(entries.contains("sub/item3"))
XCTAssertEqual(fm.subpaths(atPath: path), entries)
}
catch {
XCTFail()
}
do {
// Check a bad path fails
XCTAssertNil(fm.subpaths(atPath: "/..."))
let _ = try fm.subpathsOfDirectory(atPath: "/...")
XCTFail()
}
catch {
// Invalid directories should fail.
}
do {
try fm.removeItem(atPath: path)
} catch {
XCTFail("Failed to clean up files")
}
}
private func directoryExists(atPath path: String) -> Bool {
var isDir: ObjCBool = false
let exists = FileManager.default.fileExists(atPath: path, isDirectory: &isDir)
return exists && isDir.boolValue
}
func test_copyItemAtPathToPath() {
let fm = FileManager.default
let srcPath = NSTemporaryDirectory() + "testdir\(NSUUID().uuidString)"
let destPath = NSTemporaryDirectory() + "testdir\(NSUUID().uuidString)"
func cleanup() {
try? fm.removeItem(atPath: srcPath)
try? fm.removeItem(atPath: destPath)
}
func createDirectory(atPath path: String) {
do {
try fm.createDirectory(atPath: path, withIntermediateDirectories: false, attributes: nil)
} catch {
XCTFail("Unable to create directory: \(error)")
}
XCTAssertTrue(directoryExists(atPath: path))
}
func createFile(atPath path: String) {
XCTAssertTrue(fm.createFile(atPath: path, contents: Data(), attributes: nil))
}
cleanup()
createFile(atPath: srcPath)
do {
try fm.copyItem(atPath: srcPath, toPath: destPath)
} catch {
XCTFail("Failed to copy file: \(error)")
}
cleanup()
createDirectory(atPath: srcPath)
createDirectory(atPath: "\(srcPath)/tempdir")
createDirectory(atPath: "\(srcPath)/tempdir/subdir")
createDirectory(atPath: "\(srcPath)/tempdir/subdir/otherdir")
createDirectory(atPath: "\(srcPath)/tempdir/subdir/otherdir/extradir")
createFile(atPath: "\(srcPath)/tempdir/tempfile")
createFile(atPath: "\(srcPath)/tempdir/tempfile2")
createFile(atPath: "\(srcPath)/tempdir/subdir/otherdir/extradir/tempfile2")
do {
try fm.copyItem(atPath: srcPath, toPath: destPath)
} catch {
XCTFail("Unable to copy directory: \(error)")
}
XCTAssertTrue(directoryExists(atPath: destPath))
XCTAssertTrue(directoryExists(atPath: "\(destPath)/tempdir"))
XCTAssertTrue(fm.fileExists(atPath: "\(destPath)/tempdir/tempfile"))
XCTAssertTrue(fm.fileExists(atPath: "\(destPath)/tempdir/tempfile2"))
XCTAssertTrue(directoryExists(atPath: "\(destPath)/tempdir/subdir/otherdir/extradir"))
XCTAssertTrue(fm.fileExists(atPath: "\(destPath)/tempdir/subdir/otherdir/extradir/tempfile2"))
if (false == directoryExists(atPath: destPath)) {
return
}
do {
try fm.copyItem(atPath: srcPath, toPath: destPath)
XCTFail("Copy overwrites a file/folder that already exists")
} catch {
// ignore
}
// Test copying a symlink
let srcLink = srcPath + "/testlink"
let destLink = destPath + "/testlink"
do {
#if os(Windows)
fm.createFile(atPath: srcPath.appendingPathComponent("linkdest"), contents: Data(), attributes: nil)
#endif
try fm.createSymbolicLink(atPath: srcLink, withDestinationPath: "linkdest")
try fm.copyItem(atPath: srcLink, toPath: destLink)
XCTAssertEqual(try fm.destinationOfSymbolicLink(atPath: destLink), "linkdest")
} catch {
XCTFail("\(error)")
}
do {
try fm.copyItem(atPath: srcLink, toPath: destLink)
XCTFail("Creating link where one already exists")
} catch {
// ignore
}
}
func test_linkItemAtPathToPath() {
let fm = FileManager.default
let basePath = NSTemporaryDirectory() + "linkItemAtPathToPath/"
let srcPath = basePath + "testdir\(NSUUID().uuidString)"
let destPath = basePath + "testdir\(NSUUID().uuidString)"
defer { try? fm.removeItem(atPath: basePath) }
func getFileInfo(atPath path: String, _ body: (String, Bool, UInt64, UInt64) -> ()) {
guard let enumerator = fm.enumerator(atPath: path) else {
XCTFail("Cant enumerate \(path)")
return
}
while let item = enumerator.nextObject() as? String {
let fname = "\(path)/\(item)"
do {
let attrs = try fm.attributesOfItem(atPath: fname)
let inode = (attrs[.systemFileNumber] as? NSNumber)?.uint64Value
let linkCount = (attrs[.referenceCount] as? NSNumber)?.uint64Value
let ftype = attrs[.type] as? FileAttributeType
if inode == nil || linkCount == nil || ftype == nil {
XCTFail("Unable to get attributes of \(fname)")
return
}
let isDir = (ftype == .typeDirectory)
body(item, isDir, inode!, linkCount!)
} catch {
XCTFail("Unable to get attributes of \(fname): \(error)")
return
}
}
}
try? fm.removeItem(atPath: basePath)
XCTAssertNotNil(try? fm.createDirectory(atPath: "\(srcPath)/tempdir/subdir/otherdir/extradir", withIntermediateDirectories: true, attributes: nil))
XCTAssertTrue(fm.createFile(atPath: "\(srcPath)/tempdir/tempfile", contents: Data(), attributes: nil))
XCTAssertTrue(fm.createFile(atPath: "\(srcPath)/tempdir/tempfile2", contents: Data(), attributes: nil))
XCTAssertTrue(fm.createFile(atPath: "\(srcPath)/tempdir/subdir/otherdir/extradir/tempfile2", contents: Data(), attributes: nil))
var fileInfos: [String: (Bool, UInt64, UInt64)] = [:]
getFileInfo(atPath: srcPath, { name, isDir, inode, linkCount in
fileInfos[name] = (isDir, inode, linkCount)
})
XCTAssertEqual(fileInfos.count, 7)
XCTAssertNotNil(try? fm.linkItem(atPath: srcPath, toPath: destPath), "Unable to link directory")
getFileInfo(atPath: destPath, { name, isDir, inode, linkCount in
guard let srcFileInfo = fileInfos.removeValue(forKey: name) else {
XCTFail("Cant find \(name) in \(destPath)")
return
}
let (srcIsDir, srcInode, srcLinkCount) = srcFileInfo
XCTAssertEqual(srcIsDir, isDir, "Directory/File type mismatch")
if isDir {
XCTAssertEqual(srcLinkCount, linkCount)
} else {
XCTAssertEqual(srcInode, inode)
XCTAssertEqual(srcLinkCount + 1, linkCount)
}
})
XCTAssertEqual(fileInfos.count, 0)
// linkItem should fail a 2nd time
XCTAssertNil(try? fm.linkItem(atPath: srcPath, toPath: destPath), "Copy overwrites a file/folder that already exists")
// Test 'linking' a symlink, which actually does a copy
let srcLink = srcPath + "/testlink"
let destLink = destPath + "/testlink"
do {
#if os(Windows)
fm.createFile(atPath: srcPath.appendingPathComponent("linkdest"), contents: Data(), attributes: nil)
#endif
try fm.createSymbolicLink(atPath: srcLink, withDestinationPath: "linkdest")
try fm.linkItem(atPath: srcLink, toPath: destLink)
XCTAssertEqual(try fm.destinationOfSymbolicLink(atPath: destLink), "linkdest")
} catch {
XCTFail("\(error)")
}
XCTAssertNil(try? fm.linkItem(atPath: srcLink, toPath: destLink), "Creating link where one already exists")
}
func test_homedirectoryForUser() {
let filemanger = FileManager.default
XCTAssertNil(filemanger.homeDirectory(forUser: "someuser"))
XCTAssertNil(filemanger.homeDirectory(forUser: ""))
XCTAssertNotNil(filemanger.homeDirectoryForCurrentUser)
}
func test_temporaryDirectoryForUser() {
let filemanger = FileManager.default
let tmpDir = filemanger.temporaryDirectory
let tmpFileUrl = tmpDir.appendingPathComponent("test.bin")
let tmpFilePath = tmpFileUrl.path
do {
if filemanger.fileExists(atPath: tmpFilePath) {
try filemanger.removeItem(at: tmpFileUrl)
}
try "hello world".write(to: tmpFileUrl, atomically: false, encoding: .utf8)
XCTAssert(filemanger.fileExists(atPath: tmpFilePath))
try filemanger.removeItem(at: tmpFileUrl)
} catch {
XCTFail("Unable to write a file to the temporary directory: \(tmpDir), err: \(error)")
}
}
func test_mountedVolumeURLs() {
guard let volumes = FileManager.default.mountedVolumeURLs(includingResourceValuesForKeys:[], options: []) else {
XCTFail("mountedVolumeURLs returned nil")
return
}
XCTAssertNotEqual(0, volumes.count)
XCTAssertTrue(volumes.contains(URL(fileURLWithPath: "/")))
#if os(macOS)
// On macOS, .skipHiddenVolumes should hide 'nobrowse' volumes of which there should be at least one
guard let visibleVolumes = FileManager.default.mountedVolumeURLs(includingResourceValuesForKeys: [], options: [.skipHiddenVolumes]) else {
XCTFail("mountedVolumeURLs returned nil")
return
}
XCTAssertTrue(visibleVolumes.count > 0)
XCTAssertTrue(visibleVolumes.count < volumes.count)
#endif
}
func test_contentsEqual() {
let fm = FileManager.default
let tmpParentDirURL = URL(fileURLWithPath: NSTemporaryDirectory() + "test_contentsEqualdir", isDirectory: true)
let testDir1 = tmpParentDirURL.appendingPathComponent("testDir1")
let testDir2 = tmpParentDirURL.appendingPathComponent("testDir2")
let testDir3 = testDir1.appendingPathComponent("subDir/anotherDir/extraDir/lastDir")
defer { try? fm.removeItem(atPath: tmpParentDirURL.path) }
func testFileURL(_ name: String, _ ext: String) -> URL? {
guard let url = testBundle().url(forResource: name, withExtension: ext) else {
XCTFail("Cant open \(name).\(ext)")
return nil