- Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathTestURL.swift
814 lines (710 loc) · 37.1 KB
/
TestURL.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
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
#if canImport(Android)
@preconcurrencyimport Android
#endif
letkURLTestParsingTestsKey="ParsingTests"
letkURLTestTitleKey="In-Title"
letkURLTestUrlKey="In-Url"
letkURLTestBaseKey="In-Base"
letkURLTestURLCreatorKey="In-URLCreator"
letkURLTestPathComponentKey="In-PathComponent"
letkURLTestPathExtensionKey="In-PathExtension"
letkURLTestCFResultsKey="Out-CFResults"
letkURLTestNSResultsKey="Out-NSResults"
letkNSURLWithStringCreator="NSURLWithString"
letkCFURLCreateWithStringCreator="CFURLCreateWithString"
letkCFURLCreateWithBytesCreator="CFURLCreateWithBytes"
letkCFURLCreateAbsoluteURLWithBytesCreator="CFURLCreateAbsoluteURLWithBytes"
letkNullURLString="<null url>"
letkNullString="<null>"
func XCTAssertEqualFileSystemPaths(_ lhs:String?, _ rhs:String?, _ message:@autoclosure()->String="", file:StaticString= #filePath, line:UInt= #line){
#if os(Windows)
letmappedLHS= lhs?.replacingOccurrences(of:"\\", with:"/")
letmappedRHS= rhs?.replacingOccurrences(of:"\\", with:"/")
XCTAssertEqual(mappedLHS, mappedRHS,message(), file: file, line: line)
#else
XCTAssertEqual(lhs, rhs,message(), file: file, line: line)
#endif
}
/// Reads the test data plist file and returns the list of objects
privatefunc getTestData()->[Any]?{
lettestFilePath=testBundle().url(forResource:"NSURLTestData", withExtension:"plist")
letdata=try!Data(contentsOf: testFilePath!)
guardlet plist =try?PropertyListSerialization.propertyList(from: data, options:[], format:nil)else{
XCTFail("Unable to deserialize property list data")
returnnil
}
guardlet testRoot = plist as?[String:Any]else{
XCTFail("Unable to deserialize property list data")
returnnil
}
guardlet parsingTests =testRoot[kURLTestParsingTestsKey]as?[Any]else{
XCTFail("Unable to create the parsingTests dictionary")
returnnil
}
return parsingTests
}
classTestURL:XCTestCase{
#if os(Windows)
func test_WindowsPathSeparator(){
// ensure that the mixed slashes are handled properly
// e.g. NOT file:///S:/b/u1%2/
letu1=URL(fileURLWithPath:"S:\\b\\u1/")
XCTAssertEqual(u1.absoluteString,"file:///S:/b/u1/")
// ensure that the regular conversion works
letu4=URL(fileURLWithPath:"S:\\b\\u4")
XCTAssertEqual(u4.absoluteString,"file:///S:/b/u4")
// ensure that the trailing slash is added
letu5=URL(fileURLWithPath:"S:\\b\\u5", isDirectory:true)
XCTAssertEqual(u5.absoluteString,"file:///S:/b/u5/")
// ensure that the trailing slash is preserved
letu6=URL(fileURLWithPath:"S:\\b\\u6\\")
XCTAssertEqual(u6.absoluteString,"file:///S:/b/u6/")
// ensure that we do not index beyond the start of the string
// NOTE: explicitly mark `S:\b` as a directory as this test expects the
// directory to exist to determine that it is a directory.
letu7=URL(fileURLWithPath:"eh",
relativeTo:URL(fileURLWithPath:"S:\\b", isDirectory:true))
XCTAssertEqual(u7.absoluteString,"file:///S:/b/eh")
letu8=URL(fileURLWithPath:"eh",
relativeTo:URL(fileURLWithPath:"S:\\b", isDirectory:false))
XCTAssertEqual(u8.absoluteString,"file:///S:/eh")
// ensure that / is handled properly
letu9=URL(fileURLWithPath:"/")
XCTAssertEqual(u9.absoluteString,"file:///")
}
func test_WindowsPathSeparator2(){
letu1=URL(fileURLWithPath:"S:\\b\\u1\\", isDirectory:false)
XCTAssertEqual(u1.absoluteString,"file:///S:/b/u1")
letu2=URL(fileURLWithPath:"/", isDirectory:false)
XCTAssertEqual(u2.absoluteString,"file:///")
letu3=URL(fileURLWithPath:"\\", isDirectory:false)
XCTAssertEqual(u3.absoluteString,"file:///")
// ensure leading slash doesn't break everything
letu5=URL(fileURLWithPath:"\\abs\\path")
XCTAssertEqual(u5.absoluteString,"file:///abs/path")
XCTAssertEqual(u5.path,"/abs/path")
letu6= u5.appendingPathComponent("test")
XCTAssertEqual(u6.absoluteString,"file:///abs/path/test")
XCTAssertEqual(u6.path,"/abs/path/test")
letu7= u6.deletingLastPathComponent()
XCTAssertEqual(u7.absoluteString,"file:///abs/path/")
XCTAssertEqual(u7.path,"/abs/path")
}
#endif
func test_fileURLWithPath_relativeTo(){
lethomeDirectory=NSHomeDirectory()
lethomeURL=URL(fileURLWithPath: homeDirectory, isDirectory:true)
XCTAssertEqualFileSystemPaths(homeDirectory, homeURL.withUnsafeFileSystemRepresentation{String(cString: $0!)})
#if os(macOS)
letbaseURL=URL(fileURLWithPath: homeDirectory, isDirectory:true)
letrelativePath="Documents"
#elseif os(Android)
letbaseURL=URL(fileURLWithPath:"/data", isDirectory:true)
letrelativePath="local"
#elseif os(Linux) || os(OpenBSD)
letbaseURL=URL(fileURLWithPath:"/usr", isDirectory:true)
letrelativePath="include"
#elseif os(Windows)
letbaseURL=URL(fileURLWithPath: homeDirectory, isDirectory:true)
letrelativePath="Documents"
#endif
// we're telling fileURLWithPath:isDirectory:relativeTo: Documents is a directory
leturl1=URL(fileURLWithFileSystemRepresentation: relativePath, isDirectory:true, relativeTo: baseURL)
// we're letting fileURLWithPath:relativeTo: determine Documents is a directory with I/O
leturl2=URL(fileURLWithPath: relativePath, relativeTo: baseURL)
XCTAssertEqual(url1, url2,"\(url1) was not equal to \(url2)")
// we're telling fileURLWithPath:relativeTo: Documents is a directory with a trailing slash
leturl3=URL(fileURLWithPath: relativePath +"/", relativeTo: baseURL)
XCTAssertEqual(url1, url3,"\(url1) was not equal to \(url3)")
}
func test_relativeFilePath(){
leturl1=URL(fileURLWithPath:"/this/is/absolute", relativeTo:nil)
XCTAssertNil(url1.baseURL,"Absolute URLs should have no base URL")
XCTAssertEqual(url1.path, url1.relativePath,"URLs without base path should have equal path and relativePath")
leturl2=URL(fileURLWithPath:"this/is/relative", relativeTo:nil)
XCTAssertNotNil(url2.baseURL,"Relative URLs should have base URL assigned")
XCTAssertNotEqual(url2.path, url2.relativePath,"URLs without base path should have different path and relativePath")
#if os(Windows)
leturl3=URL(fileURLWithPath:"C:\\this\\is\\absolute", relativeTo:nil)
XCTAssertNil(url3.baseURL,"Absolute URLs should have no base URL")
XCTAssertEqual(url3.path, url3.relativePath,"URLs without base path should have equal path and relativePath")
#endif
}
/// Returns a URL from the given url string and base
privatefunc URLWithString(_ urlString :String, baseString :String?)->URL?{
iflet baseString = baseString {
letbaseURL=URL(string: baseString)
returnURL(string: urlString, relativeTo: baseURL)
}else{
returnURL(string: urlString)
}
}
internalfunc generateResults(_ url:URL, pathComponent:String?, pathExtension :String?)->[String:Any]{
varresult=[String : Any]()
iflet pathComponent = pathComponent {
letnewFileURL= url.appendingPathComponent(pathComponent, isDirectory:false)
result["appendingPathComponent-File"]= newFileURL.relativeString
result["appendingPathComponent-File-BaseURL"]= newFileURL.baseURL?.relativeString ?? kNullString
letnewDirURL= url.appendingPathComponent(pathComponent, isDirectory:true)
result["appendingPathComponent-Directory"]= newDirURL.relativeString
result["appendingPathComponent-Directory-BaseURL"]= newDirURL.baseURL?.relativeString ?? kNullString
}elseiflet pathExtension = pathExtension {
letnewURL= url.appendingPathExtension(pathExtension)
result["appendingPathExtension"]= newURL.relativeString
result["appendingPathExtension-BaseURL"]= newURL.baseURL?.relativeString ?? kNullString
}else{
result["relativeString"]= url.relativeString
result["baseURLString"]= url.baseURL?.relativeString ?? kNullString
result["absoluteString"]= url.absoluteString
result["absoluteURLString"]= url.absoluteURL.relativeString
result["scheme"]= url.scheme ?? kNullString
result["host"]= url.host(percentEncoded:false)?? kNullString
result["port"]= url.port ?? kNullString
result["user"]= url.user(percentEncoded:false)?? kNullString
result["password"]= url.password ?? kNullString
result["path"]= url.path
result["query"]= url.query ?? kNullString
result["fragment"]= url.fragment ?? kNullString
result["relativePath"]= url.relativePath
result["isFileURL"]= url.isFileURL ?"YES":"NO"
result["standardizedURL"]= url.standardized.relativeString
result["pathComponents"]= url.pathComponents
result["lastPathComponent"]= url.lastPathComponent
result["pathExtension"]= url.pathExtension
result["deletingLastPathComponent"]= url.deletingLastPathComponent().relativeString
result["deletingLastPathExtension"]= url.deletingPathExtension().relativeString
}
return result
}
internalfunc compareResults(_ url :URL, expected :[String:Any], got :[String:Any])->(Bool,[String]){
vardifferences=[String]()
for(key, expectation)in expected {
// Skip non-string expected results
if["port","standardizedURL","pathComponents"].contains(key){
continue
}
varobj:Any?= expectation
if obj as?String== kNullString {
obj =nil
}
iflet expectedValue = obj as?String{
iflet testedValue =got[key]as?String{
if expectedValue != testedValue {
differences.append("\(key) Expected = '\(expectedValue)', Got = '\(testedValue)'")
}
}else{
differences.append("\(key) Expected = '\(expectedValue)', Got = '\(String(describing:got[key]))'")
}
}elseiflet expectedValue = obj as?[String]{
iflet testedValue =got[key]as?[String]{
if expectedValue != testedValue {
differences.append("\(key) Expected = '\(expectedValue)', Got = '\(testedValue)'")
}
}else{
differences.append("\(key) Expected = '\(expectedValue)', Got = '\(String(describing:got[key]))'")
}
}elseiflet expectedValue = obj as?Int{
iflet testedValue =got[key]as?Int{
if expectedValue != testedValue {
differences.append("\(key) Expected = '\(expectedValue)', Got = '\(testedValue)'")
}
}else{
differences.append("\(key) Expected = '\(expectedValue)', Got = '\(String(describing:got[key]))'")
}
}elseif obj ==nil{
ifgot[key]!=nil && got[key]as?String!= kNullString {
differences.append("\(key) Expected = '\(String(describing: obj))', Got = '\(String(describing:got[key]))'")
}
}
}
for(key, obj)in got {
ifexpected[key]==nil{
differences.append("\(key) Expected = 'nil', Got = '\(obj)'")
}
}
if differences.count >0{
differences.sort()
differences.insert(" url: '\(url)' ", at:0)
return(false, differences)
}else{
return(true,[])
}
}
// TODO: Disabled until it is updated to the new parser in swift-foundation
#if false
func test_URLStrings(){
forobjingetTestData()! {
lettestDict= obj as![String:Any]
lettitle=testDict[kURLTestTitleKey]as!String
letinURL=testDict[kURLTestUrlKey]! as!String
letinBase=testDict[kURLTestBaseKey]as!String?
letinPathComponent=testDict[kURLTestPathComponentKey]as!String?
letinPathExtension=testDict[kURLTestPathExtensionKey]as!String?
letexpectedNSResult=testDict[kURLTestNSResultsKey]!
varurl:URL?=nil
switch(testDict[kURLTestURLCreatorKey]! as!String){
case kNSURLWithStringCreator:
url =URLWithString(inURL, baseString: inBase)
case kCFURLCreateWithStringCreator, kCFURLCreateWithBytesCreator, kCFURLCreateAbsoluteURLWithBytesCreator:
// TODO: Not supported right now
continue
default:
XCTFail()
}
#if os(Windows)
// On Windows, pipes are valid charcters which can be used
// to replace a ':'. See RFC 8089 Section E.2.2 for
// details.
//
// Skip the test which expects pipes to be invalid
letskippedPipeTest="NSURLWithString-parse-absolute-escape-006-pipe-invalid"
#else
// On other platforms, pipes are not valid
//
// Skip the test which expects pipes to be valid
letskippedPipeTest="NSURLWithString-parse-absolute-escape-006-pipe-valid"
#endif
letskippedTests=[
"NSURLWithString-parse-ambiguous-url-001", // TODO: Fix Test
skippedPipeTest,
]
if skippedTests.contains(title){continue}
iflet url = url {
letresults=generateResults(url, pathComponent: inPathComponent, pathExtension: inPathExtension)
iflet expected = expectedNSResult as?[String:Any]{
let(isEqual, differences)=compareResults(url, expected: expected, got: results)
XCTAssertTrue(isEqual,"\(title): \(differences.joined(separator:"\n"))")
}else{
XCTFail("\(url) should not be a valid url")
}
}else{
XCTAssertEqual(expectedNSResult as?String, kNullURLString)
}
}
}
#endif
staticnonisolatedletgBaseTemporaryDirectoryPath=(NSTemporaryDirectory()asNSString).appendingPathComponent("org.swift.foundation.TestFoundation.TestURL.\(ProcessInfo.processInfo.processIdentifier)")
staticvargBaseCurrentWorkingDirectoryPath:String{
returnFileManager.default.currentDirectoryPath
}
staticnonisolated(unsafe)var gSavedPath =""
staticnonisolated(unsafe)var gRelativeOffsetFromBaseCurrentWorkingDirectory:UInt=0
staticletgFileExistsName="TestCFURL_file_exists\(ProcessInfo.processInfo.globallyUniqueString)"
staticletgFileDoesNotExistName="TestCFURL_file_does_not_exist"
staticletgDirectoryExistsName="TestCFURL_directory_exists\(ProcessInfo.processInfo.globallyUniqueString)"
staticletgDirectoryDoesNotExistName="TestCFURL_directory_does_not_exist"
staticletgFileExistsPath= gBaseTemporaryDirectoryPath + gFileExistsName
staticletgFileDoesNotExistPath= gBaseTemporaryDirectoryPath + gFileDoesNotExistName
staticletgDirectoryExistsPath= gBaseTemporaryDirectoryPath + gDirectoryExistsName
staticletgDirectoryDoesNotExistPath= gBaseTemporaryDirectoryPath + gDirectoryDoesNotExistName
overrideclassfunc tearDown(){
letpath=TestURL.gBaseTemporaryDirectoryPath
if(try?FileManager.default.attributesOfItem(atPath: path))!=nil{
do{
tryFileManager.default.removeItem(atPath: path)
}catch{
NSLog("Could not remove test directory at path \(path): \(error)")
}
}
super.tearDown()
}
staticfunc setup_test_paths()->Bool{
_ =FileManager.default.createFile(atPath: gFileExistsPath, contents:nil)
do{
tryFileManager.default.removeItem(atPath: gFileDoesNotExistPath)
}catch{
// The error code is a CocoaError
if(error asNSError).code !=CocoaError.fileNoSuchFile.rawValue {
returnfalse
}
}
do{
tryFileManager.default.createDirectory(atPath: gDirectoryExistsPath, withIntermediateDirectories:false)
}catch{
// The error code is a CocoaError
if(error asNSError).code !=CocoaError.fileWriteFileExists.rawValue {
returnfalse
}
}
do{
tryFileManager.default.removeItem(atPath: gDirectoryDoesNotExistPath)
}catch{
// The error code is a CocoaError
if(error asNSError).code !=CocoaError.fileNoSuchFile.rawValue {
returnfalse
}
}
TestURL.gSavedPath =FileManager.default.currentDirectoryPath
_ =FileManager.default.changeCurrentDirectoryPath(NSTemporaryDirectory())
letcwd=FileManager.default.currentDirectoryPath
letcwdURL=URL(fileURLWithPath: cwd, isDirectory:true)
// 1 for path separator
cwdURL.withUnsafeFileSystemRepresentation{
gRelativeOffsetFromBaseCurrentWorkingDirectory =UInt(strlen($0!)+1)
}
returntrue
}
func test_fileURLWithPath(){
if !TestURL.setup_test_paths(){
leterror=strerror(errno)!
XCTFail("Failed to set up test paths: \(String(cString: error))")
}
defer{ _ =FileManager.default.changeCurrentDirectoryPath(TestURL.gSavedPath)}
// test with file that exists
varpath=TestURL.gFileExistsPath
varurl=NSURL(fileURLWithPath: path)
XCTAssertFalse(url.hasDirectoryPath,"did not expect URL with directory path: \(url)")
XCTAssertEqualFileSystemPaths(path, url.path,"path from file path URL is wrong")
// test with file that doesn't exist
path =TestURL.gFileDoesNotExistPath
url =NSURL(fileURLWithPath: path)
XCTAssertFalse(url.hasDirectoryPath,"did not expect URL with directory path: \(url)")
XCTAssertEqualFileSystemPaths(path, url.path,"path from file path URL is wrong")
// test with directory that exists
path =TestURL.gDirectoryExistsPath
url =NSURL(fileURLWithPath: path)
XCTAssertTrue(url.hasDirectoryPath,"expected URL with directory path: \(url)")
XCTAssertEqualFileSystemPaths(path, url.path,"path from file path URL is wrong")
// test with directory that doesn't exist
path =TestURL.gDirectoryDoesNotExistPath
url =NSURL(fileURLWithPath: path)
XCTAssertFalse(url.hasDirectoryPath,"did not expect URL with directory path: \(url)")
XCTAssertEqualFileSystemPaths(path, url.path,"path from file path URL is wrong")
// test with name relative to current working directory
path =TestURL.gFileDoesNotExistName
url =NSURL(fileURLWithPath: path)
XCTAssertFalse(url.hasDirectoryPath,"did not expect URL with directory path: \(url)")
letfileSystemRep= url.fileSystemRepresentation
letactualLength=strlen(fileSystemRep)
// 1 for path separator
letexpectedLength=UInt(strlen(TestURL.gFileDoesNotExistName))+ TestURL.gRelativeOffsetFromBaseCurrentWorkingDirectory
XCTAssertEqual(UInt(actualLength), expectedLength,"fileSystemRepresentation was too short")
#if os(Windows)
// On Windows, the URL path should have `/` separators and the
// fileSystemRepresentation should have `\` separators.
XCTAssertTrue(strncmp(String(TestURL.gBaseCurrentWorkingDirectoryPath.map{ $0 =="/"?"\\": $0 }),
fileSystemRep,
Int(strlen(TestURL.gBaseCurrentWorkingDirectoryPath)))==0,
"fileSystemRepresentation of base path is wrong")
#else
XCTAssertTrue(strncmp(TestURL.gBaseCurrentWorkingDirectoryPath, fileSystemRep,Int(strlen(TestURL.gBaseCurrentWorkingDirectoryPath)))==0,"fileSystemRepresentation of base path is wrong")
#endif
letlengthOfRelativePath=Int(strlen(TestURL.gFileDoesNotExistName))
letrelativePath= fileSystemRep.advanced(by:Int(TestURL.gRelativeOffsetFromBaseCurrentWorkingDirectory))
XCTAssertTrue(strncmp(TestURL.gFileDoesNotExistName, relativePath, lengthOfRelativePath)==0,"fileSystemRepresentation of file path is wrong")
// SR-12366
leturl1=URL(fileURLWithPath:"/path/to/b/folder", isDirectory:true).standardizedFileURL.absoluteString
leturl2=URL(fileURLWithPath:"/path/to/b/folder", isDirectory:true).absoluteString
XCTAssertEqual(url1, url2)
}
func test_fileURLWithPath_isDirectory(){
if !TestURL.setup_test_paths(){
leterror=strerror(errno)!
XCTFail("Failed to set up test paths: \(String(cString: error))")
}
defer{ _ =FileManager.default.changeCurrentDirectoryPath(TestURL.gSavedPath)}
// test with file that exists
varpath=TestURL.gFileExistsPath
varurl=NSURL(fileURLWithPath: path, isDirectory:true)
XCTAssertTrue(url.hasDirectoryPath,"expected URL with directory path: \(url)")
url =NSURL(fileURLWithPath: path, isDirectory:false)
XCTAssertFalse(url.hasDirectoryPath,"did not expect URL with directory path: \(url)")
XCTAssertEqualFileSystemPaths(path, url.path,"path from file path URL is wrong")
// test with file that doesn't exist
path =TestURL.gFileDoesNotExistPath
url =NSURL(fileURLWithPath: path, isDirectory:true)
XCTAssertTrue(url.hasDirectoryPath,"expected URL with directory path: \(url)")
url =NSURL(fileURLWithPath: path, isDirectory:false)
XCTAssertFalse(url.hasDirectoryPath,"did not expect URL with directory path: \(url)")
XCTAssertEqualFileSystemPaths(path, url.path,"path from file path URL is wrong")
// test with directory that exists
path =TestURL.gDirectoryExistsPath
url =NSURL(fileURLWithPath: path, isDirectory:false)
XCTAssertFalse(url.hasDirectoryPath,"did not expect URL with directory path: \(url)")
url =NSURL(fileURLWithPath: path, isDirectory:true)
XCTAssertTrue(url.hasDirectoryPath,"expected URL with directory path: \(url)")
XCTAssertEqualFileSystemPaths(path, url.path,"path from file path URL is wrong")
// test with directory that doesn't exist
path =TestURL.gDirectoryDoesNotExistPath
url =NSURL(fileURLWithPath: path, isDirectory:false)
XCTAssertFalse(url.hasDirectoryPath,"did not expect URL with directory path: \(url)")
url =NSURL(fileURLWithPath: path, isDirectory:true)
XCTAssertTrue(url.hasDirectoryPath,"expected URL with directory path: \(url)")
XCTAssertEqualFileSystemPaths(path, url.path,"path from file path URL is wrong")
// test with name relative to current working directory
path =TestURL.gFileDoesNotExistName
url =NSURL(fileURLWithPath: path, isDirectory:false)
XCTAssertFalse(url.hasDirectoryPath,"did not expect URL with directory path: \(url)")
url =NSURL(fileURLWithPath: path, isDirectory:true)
XCTAssertTrue(url.hasDirectoryPath,"expected URL with directory path: \(url)")
letfileSystemRep= url.fileSystemRepresentation
letactualLength=UInt(strlen(fileSystemRep))
// 1 for path separator
letexpectedLength=UInt(strlen(TestURL.gFileDoesNotExistName))+ TestURL.gRelativeOffsetFromBaseCurrentWorkingDirectory
XCTAssertEqual(actualLength, expectedLength,"fileSystemRepresentation was too short")
#if os(Windows)
// On Windows, the URL path should have `/` separators and the
// fileSystemRepresentation should have `\` separators.
XCTAssertTrue(strncmp(String(TestURL.gBaseCurrentWorkingDirectoryPath.map{ $0 =="/"?"\\": $0 }),
fileSystemRep,
Int(strlen(TestURL.gBaseCurrentWorkingDirectoryPath)))==0,
"fileSystemRepresentation of base path is wrong")
#else
XCTAssertTrue(strncmp(TestURL.gBaseCurrentWorkingDirectoryPath, fileSystemRep,Int(strlen(TestURL.gBaseCurrentWorkingDirectoryPath)))==0,"fileSystemRepresentation of base path is wrong")
#endif
letlengthOfRelativePath=Int(strlen(TestURL.gFileDoesNotExistName))
letrelativePath= fileSystemRep.advanced(by:Int(TestURL.gRelativeOffsetFromBaseCurrentWorkingDirectory))
XCTAssertTrue(strncmp(TestURL.gFileDoesNotExistName, relativePath, lengthOfRelativePath)==0,"fileSystemRepresentation of file path is wrong")
}
func test_URLByResolvingSymlinksInPathShouldRemoveDuplicatedPathSeparators(){
leturl=URL(fileURLWithPath:"//foo///bar////baz/")
letresult= url.resolvingSymlinksInPath()
XCTAssertEqual(result,URL(fileURLWithPath:"/foo/bar/baz/"))
}
func test_URLByResolvingSymlinksInPathShouldRemoveSingleDotsBetweenSeparators(){
leturl=URL(fileURLWithPath:"/./foo/./.bar/./baz/./")
letresult= url.resolvingSymlinksInPath()
XCTAssertEqual(result,URL(fileURLWithPath:"/foo/.bar/baz/"))
}
func test_URLByResolvingSymlinksInPathShouldCompressDoubleDotsBetweenSeparators(){
leturl=URL(fileURLWithPath:"/foo/../..bar/../baz/")
letresult= url.resolvingSymlinksInPath()
XCTAssertEqual(result,URL(fileURLWithPath:"/baz/"))
}
func test_URLByResolvingSymlinksInPathShouldUseTheCurrentDirectory()throws{
letfileManager=FileManager.default
try fileManager.createDirectory(at: writableTestDirectoryURL, withIntermediateDirectories:true)
defer{try? fileManager.removeItem(at: writableTestDirectoryURL)}
letpreviousCurrentDirectory= fileManager.currentDirectoryPath
_ = fileManager.changeCurrentDirectoryPath(writableTestDirectoryURL.path)
defer{ _ = fileManager.changeCurrentDirectoryPath(previousCurrentDirectory)}
// In Darwin, because temporary directory is inside /private,
// writableTestDirectoryURL will be something like /var/folders/...,
// but /var points to /private/var, which is only removed if the
// destination exists, so we create the destination to avoid having to
// compare against /private in Darwin.
try fileManager.createDirectory(at: writableTestDirectoryURL.appendingPathComponent("foo/bar"), withIntermediateDirectories:true)
try"".write(to: writableTestDirectoryURL.appendingPathComponent("foo/bar/baz"), atomically:true, encoding:.utf8)
leturl=URL(fileURLWithPath:"foo/bar/baz")
letresult= url.resolvingSymlinksInPath()
XCTAssertEqual(result,URL(fileURLWithPath: writableTestDirectoryURL.path +"/foo/bar/baz").resolvingSymlinksInPath())
}
func test_resolvingSymlinksInPathShouldAppendTrailingSlashWhenExistingDirectory()throws{
letfileManager=FileManager.default
try fileManager.createDirectory(at: writableTestDirectoryURL, withIntermediateDirectories:true)
defer{try? fileManager.removeItem(at: writableTestDirectoryURL)}
varpath= writableTestDirectoryURL.path
if path.hasSuffix("/"){
path.remove(at: path.index(path.endIndex, offsetBy:-1))
}
leturl=URL(fileURLWithPath: path)
letresult= url.resolvingSymlinksInPath()
XCTAssertEqual(result,URL(fileURLWithPath: path +"/").resolvingSymlinksInPath())
}
func test_resolvingSymlinksInPathShouldResolveSymlinks()throws{
// NOTE: this test only works on file systems that support symlinks.
letfileManager=FileManager.default
try fileManager.createDirectory(at: writableTestDirectoryURL, withIntermediateDirectories:true)
defer{try? fileManager.removeItem(at: writableTestDirectoryURL)}
letsymbolicLink= writableTestDirectoryURL.appendingPathComponent("origin")
letdestination= writableTestDirectoryURL.appendingPathComponent("destination")
try"".write(to: destination, atomically:true, encoding:.utf8)
try fileManager.createSymbolicLink(at: symbolicLink, withDestinationURL: destination)
letresult= symbolicLink.resolvingSymlinksInPath()
XCTAssertEqual(result,URL(fileURLWithPath: writableTestDirectoryURL.path +"/destination").resolvingSymlinksInPath())
}
func test_resolvingSymlinksInPathShouldRemovePrivatePrefix()throws{
#if !canImport(Darwin)
throwXCTSkip("This test is only supported on Darwin")
#else
// NOTE: this test only works on Darwin, since the code that removes
// /private relies on /private/tmp existing.
leturl=URL(fileURLWithPath:"/private/tmp")
letresult= url.resolvingSymlinksInPath()
XCTAssertEqual(result,URL(fileURLWithPath:"/tmp"))
#endif
}
func test_resolvingSymlinksInPathShouldNotRemovePrivatePrefixIfOnlyComponent()throws{
#if !canImport(Darwin)
throwXCTSkip("This test is only supported on Darwin")
#else
// NOTE: this test only works on Darwin, since only there /tmp is
// symlinked to /private/tmp.
leturl=URL(fileURLWithPath:"/tmp/..")
letresult= url.resolvingSymlinksInPath()
XCTAssertEqual(result,URL(fileURLWithPath:"/private"))
#endif
}
func test_resolvingSymlinksInPathShouldNotChangeNonFileURLs()throws{
leturl=tryXCTUnwrap(URL(string:"myscheme://server/foo/bar/baz"))
letresult= url.resolvingSymlinksInPath().absoluteString
XCTAssertEqual(result,"myscheme://server/foo/bar/baz")
}
func test_resolvingSymlinksInPathShouldNotChangePathlessURLs()throws{
leturl=tryXCTUnwrap(URL(string:"file://"))
letresult= url.resolvingSymlinksInPath().absoluteString
XCTAssertEqual(result,"file://")
}
func test_reachable(){
#if os(Android)
varurl=URL(fileURLWithPath:"/data")
#elseif os(Windows)
varurl=URL(fileURLWithPath:NSHomeDirectory())
#else
varurl=URL(fileURLWithPath:"/usr")
#endif
XCTAssertEqual(true,try? url.checkResourceIsReachable())
url =URL(string:"https://www.swift.org")!
do{
_ =try url.checkResourceIsReachable()
XCTFail()
}catchlet error as NSError{
XCTAssertEqual(NSCocoaErrorDomain, error.domain)
XCTAssertEqual(CocoaError.Code.fileReadUnsupportedScheme.rawValue, error.code)
}catch{
XCTFail()
}
url =URL(fileURLWithPath:"/some_random_path")
do{
_ =try url.checkResourceIsReachable()
XCTFail()
}catchlet error as NSError{
XCTAssertEqual(NSCocoaErrorDomain, error.domain)
XCTAssertEqual(CocoaError.Code.fileReadNoSuchFile.rawValue, error.code)
}catch{
XCTFail()
}
#if os(Android)
varnsURL=NSURL(fileURLWithPath:"/data")
#elseif os(Windows)
varnsURL=NSURL(fileURLWithPath:NSHomeDirectory())
#else
varnsURL=NSURL(fileURLWithPath:"/usr")
#endif
XCTAssertEqual(true,try? nsURL.checkResourceIsReachable())
nsURL =NSURL(string:"https://www.swift.org")!
do{
_ =try nsURL.checkResourceIsReachable()
XCTFail()
}catchlet error as NSError{
XCTAssertEqual(NSCocoaErrorDomain, error.domain)
XCTAssertEqual(CocoaError.Code.fileReadUnsupportedScheme.rawValue, error.code)
}catch{
XCTFail()
}
nsURL =NSURL(fileURLWithPath:"/some_random_path")
do{
_ =try nsURL.checkResourceIsReachable()
XCTFail()
}catchlet error as NSError{
XCTAssertEqual(NSCocoaErrorDomain, error.domain)
XCTAssertEqual(CocoaError.Code.fileReadNoSuchFile.rawValue, error.code)
}catch{
XCTFail()
}
}
func test_copy(){
leturl=NSURL(string:"https://www.swift.org")
leturlCopy= url!.copy()as!NSURL
XCTAssertTrue(url!.isEqual(urlCopy))
letqueryItem=NSURLQueryItem(name:"id", value:"23")
letqueryItemCopy= queryItem.copy()as!NSURLQueryItem
XCTAssertTrue(queryItem.isEqual(queryItemCopy))
}
func test_itemNSCoding(){
letqueryItemA=NSURLQueryItem(name:"id", value:"23")
letqueryItemB=NSKeyedUnarchiver.unarchiveObject(with:NSKeyedArchiver.archivedData(withRootObject: queryItemA))as!NSURLQueryItem
XCTAssertEqual(queryItemA, queryItemB,"Archived then unarchived query item must be equal.")
}
func test_dataRepresentation(){
leturl=NSURL(fileURLWithPath:"/tmp/foo")
leturl2=NSURL(dataRepresentation: url.dataRepresentation,
relativeTo:nil)
XCTAssertEqual(url, url2)
}
func test_description(){
leturl=URL(string:"http://amazon.in")!
XCTAssertEqual(url.description,"http://amazon.in")
varurlComponents=URLComponents()
urlComponents.port =8080
urlComponents.host ="amazon.in"
urlComponents.password ="abcd"
letrelativeURL= urlComponents.url(relativeTo: url)
XCTAssertEqual(relativeURL?.description,"//:abcd@amazon.in:8080 -- http://amazon.in")
}
// MARK: Resource values.
func test_URLResourceValues()throws{
do{
tryFileManager.default.createDirectory(at: writableTestDirectoryURL, withIntermediateDirectories:true)
vara= writableTestDirectoryURL.appendingPathComponent("a")
tryData().write(to: a)
// Not all OSes support fractions of a second; remove the fractional part.
let(roughlyAYearFromNowInterval, _)=modf(Date(timeIntervalSinceNow:1*365*24*60*60).timeIntervalSinceReferenceDate)
letroughlyAYearFromNow=Date(timeIntervalSinceReferenceDate: roughlyAYearFromNowInterval)
varvalues=URLResourceValues()
values.contentModificationDate = roughlyAYearFromNow
try a.setResourceValues(values)
letkeys:Set<URLResourceKey>=[
.contentModificationDateKey,
]
func assertRelevantValuesAreEqual(in newValues:URLResourceValues){
XCTAssertEqual(values.contentModificationDate, newValues.contentModificationDate)
}
do{
letnewValues=try a.resourceValues(forKeys: keys)
assertRelevantValuesAreEqual(in: newValues)
}
do{
a.removeAllCachedResourceValues()
letnewValues=try a.resourceValues(forKeys: keys)
assertRelevantValuesAreEqual(in: newValues)
}
do{
letseparateA= writableTestDirectoryURL.appendingPathComponent("a")
letnewValues=try separateA.resourceValues(forKeys: keys)
assertRelevantValuesAreEqual(in: newValues)
}
}catch{
leterror= error asNSError
print("error: \(error.description) - \(error.userInfo)")
throw error
}
}
func test_dataFromNonFileURL(){
do{
// Tests the up-call to FoundationNetworking to perform the network request
tryData(contentsOf:URL(string:"https://swift.org")!)
}catch{
iflet cocoaCode =(error as?CocoaError)?.code {
// Just ensure that we supported this feature, even if the request failed
XCTAssertNotEqual(cocoaCode,.featureUnsupported)
}
}
}
// MARK: -
nonisolated(unsafe)var writableTestDirectoryURL:URL!
overridefunc setUp(){
super.setUp()
letpid=ProcessInfo.processInfo.processIdentifier
writableTestDirectoryURL =URL(fileURLWithPath:NSTemporaryDirectory()).appendingPathComponent("org.swift.TestFoundation.TestURL.resourceValues.\(pid)")
}
overridefunc tearDown(){
iflet directoryURL = writableTestDirectoryURL,
(try?FileManager.default.attributesOfItem(atPath: directoryURL.path))!=nil{
do{
tryFileManager.default.removeItem(at: directoryURL)
}catch{
NSLog("Could not remove test directory at URL \(directoryURL): \(error)")
}
}
super.tearDown()
}
}