- Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathTestProcess.swift
1013 lines (861 loc) · 36.6 KB
/
TestProcess.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) 2015 - 2016, 2018 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
//
import Synchronization
#if canImport(Android)
@preconcurrencyimport Android
#endif
classTestProcess:XCTestCase{
func test_exit0()throws{
letprocess=Process()
letexecutableURL=tryxdgTestHelperURL()
if #available(macOS 10.13,*){
process.executableURL = executableURL
}else{
// Fallback on earlier versions
process.launchPath = executableURL.path
}
XCTAssertEqual(executableURL.path, process.executableURL?.path)
process.arguments =["--exit","0"]
try process.run()
process.waitUntilExit()
XCTAssertEqual(process.terminationStatus,0)
XCTAssertEqual(process.terminationReason,.exit)
}
func test_exit1()throws{
letprocess=Process()
process.executableURL =tryxdgTestHelperURL()
process.arguments =["--exit","1"]
try process.run()
process.waitUntilExit()
XCTAssertEqual(process.terminationStatus,1)
XCTAssertEqual(process.terminationReason,.exit)
}
func test_exit100()throws{
letprocess=Process()
process.executableURL =tryxdgTestHelperURL()
process.arguments =["--exit","100"]
try process.run()
process.waitUntilExit()
XCTAssertEqual(process.terminationStatus,100)
XCTAssertEqual(process.terminationReason,.exit)
}
func test_sleep2()throws{
letprocess=Process()
process.executableURL =tryxdgTestHelperURL()
process.arguments =["--sleep","2"]
try process.run()
process.waitUntilExit()
XCTAssertEqual(process.terminationStatus,0)
XCTAssertEqual(process.terminationReason,.exit)
}
func test_terminationReason_uncaughtSignal()throws{
letprocess=Process()
process.executableURL =tryxdgTestHelperURL()
process.arguments =["--signal-self",SIGTERM.description]
try process.run()
process.waitUntilExit()
XCTAssertEqual(process.terminationStatus, SIGTERM)
XCTAssertEqual(process.terminationReason,.uncaughtSignal)
}
func test_pipe_stdin()throws{
letprocess=Process()
process.executableURL =tryxdgTestHelperURL()
process.arguments =["--cat"]
letoutputPipe=Pipe()
process.standardOutput = outputPipe
letinputPipe=Pipe()
process.standardInput = inputPipe
process.standardError =FileHandle.nullDevice
try process.run()
letmsg=tryXCTUnwrap("Hello, 🐶.\n".data(using:.utf8))
do{
try inputPipe.fileHandleForWriting.write(contentsOf: msg)
}catch{
XCTFail("Cant write to pipe: \(error)")
return
}
// Close the input pipe to send EOF to cat.
inputPipe.fileHandleForWriting.closeFile()
process.waitUntilExit()
XCTAssertEqual(process.terminationStatus,0)
letdata= outputPipe.fileHandleForReading.availableData
guardlet string =String(data: data, encoding:.utf8)else{
XCTFail("Could not read stdout")
return
}
XCTAssertEqual(string,"Hello, 🐶.\n")
}
func test_pipe_stdout()throws{
letprocess=Process()
process.executableURL =tryxdgTestHelperURL()
process.arguments =["--getcwd"]
letpipe=Pipe()
process.standardOutput = pipe
process.standardError =nil
try process.run()
process.waitUntilExit()
XCTAssertEqual(process.terminationStatus,0)
letdata= pipe.fileHandleForReading.availableData
guardlet string =String(data: data, encoding:.ascii)else{
XCTFail("Could not read stdout")
return
}
XCTAssertEqual(string.trimmingCharacters(in:CharacterSet(["\n","\r"])),FileManager.default.currentDirectoryPath)
}
func test_pipe_stderr()throws{
letprocess=Process()
process.executableURL =tryxdgTestHelperURL()
process.arguments =["--cat","invalid_file_name"]
leterrorPipe=Pipe()
process.standardError = errorPipe
try process.run()
process.waitUntilExit()
XCTAssertEqual(process.terminationStatus,1)
letdata= errorPipe.fileHandleForReading.availableData
guardlet string =String(data: data, encoding:.ascii)else{
XCTFail("Could not read stdout")
return
}
// Ignore messages from malloc debug etc on macOs
leterrMsg= string.trimmingCharacters(in:CharacterSet(["\n"])).components(separatedBy:"\n").last
XCTAssertEqual(errMsg,"cat: invalid_file_name: No such file or directory")
}
func test_pipe_stdout_and_stderr_same_pipe()throws{
letprocess=Process()
process.executableURL =tryxdgTestHelperURL()
process.arguments =["--cat","invalid_file_name"]
letpipe=Pipe()
process.standardOutput = pipe
process.standardError = pipe
// Clear the environment to stop the malloc debug flags used in Xcode debug being
// set in the subprocess.
process.environment =[:]
#if os(Android)
// In Android, we have to provide at least an LD_LIBRARY_PATH, or
// xdgTestHelper will not be able to find the Swift libraries.
iflet ldLibraryPath =ProcessInfo.processInfo.environment["LD_LIBRARY_PATH"]{
process.environment?["LD_LIBRARY_PATH"]= ldLibraryPath
}
#endif
try process.run()
process.waitUntilExit()
XCTAssertEqual(process.terminationStatus,1)
letdata= pipe.fileHandleForReading.availableData
guardlet string =String(data: data, encoding:.ascii)else{
XCTFail("Could not read stdout")
return
}
// Ignore messages from malloc debug etc on macOS
leterrMsg= string.trimmingCharacters(in:CharacterSet(["\n"])).components(separatedBy:"\n").last
XCTAssertEqual(errMsg,"cat: invalid_file_name: No such file or directory")
}
func test_file_stdout()throws{
letprocess=Process()
process.executableURL =tryxdgTestHelperURL()
process.arguments =["--getcwd"]
leturl:URL=URL(fileURLWithPath:NSTemporaryDirectory()).appendingPathComponent(ProcessInfo.processInfo.globallyUniqueString, isDirectory:false)
_ =FileManager.default.createFile(atPath: url.path, contents:Data())
defer{ _ =try?FileManager.default.removeItem(at: url)}
lethandle:FileHandle=FileHandle(forUpdatingAtPath: url.path)!
process.standardOutput = handle
try process.run()
process.waitUntilExit()
XCTAssertEqual(process.terminationStatus,0)
handle.seek(toFileOffset:0)
letdata= handle.readDataToEndOfFile()
guardlet string =String(data: data, encoding:.ascii)else{
XCTFail("Could not read stdout")
return
}
XCTAssertEqual(string.trimmingCharacters(in:CharacterSet(["\r","\n"])),FileManager.default.currentDirectoryPath)
}
func test_passthrough_environment()throws{
let(output, _)=tryrunTask([tryxdgTestHelperURL().path,"--env"], environment:nil)
letenv=tryparseEnv(output)
#if os(Windows)
// On Windows, Path is always passed to the sub process
XCTAssertGreaterThan(env.count,1)
#else
XCTAssertGreaterThan(env.count,0)
#endif
}
func test_no_environment()throws{
let(output, _)=tryrunTask([tryxdgTestHelperURL().path,"--env"], environment:[:])
letenv=tryparseEnv(output)
#if os(Windows)
// On Windows, Path is always passed to the sub process
XCTAssertEqual(env.count,1)
#else
XCTAssertEqual(env.count,0)
#endif
}
func test_custom_environment()throws{
letinput=["HELLO":"WORLD","HOME":"CUPERTINO"]
let(output, _)=tryrunTask([tryxdgTestHelperURL().path,"--env"], environment: input)
varenv=tryparseEnv(output)
#if os(Windows)
// On Windows, Path is always passed to the sub process, remove it
// before comparing.
env.removeValue(forKey:"Path")
#endif
XCTAssertEqual(env, input)
}
func test_current_working_directory()throws{
lettmpDir={()->Stringin
// NSTemporaryDirectory might return a final slash, but
// FileManager.currentDirectoryPath seems to avoid it.
vardir=NSTemporaryDirectory()
if(dir.hasSuffix("/") && dir !="/") || dir.hasSuffix("\\"){
dir.removeLast()
}
return dir.standardizePath()
}()
letfm=FileManager.default
letpreviousWorkingDirectory= fm.currentDirectoryPath
XCTAssertNotEqual(previousWorkingDirectory.standardizePath(), tmpDir)
// Test that getcwd() returns the currentDirectoryPath
do{
let(pwd, _)=tryrunTask([tryxdgTestHelperURL().path,"--getcwd"], currentDirectoryPath: tmpDir)
// Check the sub-process used the correct directory
XCTAssertEqual(pwd.trimmingCharacters(in:.newlines).standardizePath(), tmpDir)
}
// Test that $PWD by default is set to currentDirectoryPath
do{
let(pwd, _)=tryrunTask([tryxdgTestHelperURL().path,"--echo-PWD"], currentDirectoryPath: tmpDir)
// Check the sub-process used the correct directory
letcwd=FileManager.default.currentDirectoryPath.standardizePath()
XCTAssertNotEqual(cwd, tmpDir)
XCTAssertNotEqual(pwd.trimmingCharacters(in:.newlines).standardizePath(), tmpDir)
}
// Test that $PWD can be over-ridden
do{
varenv=ProcessInfo.processInfo.environment
env["PWD"]="/bin"
let(pwd, _)=tryrunTask([tryxdgTestHelperURL().path,"--echo-PWD"], environment: env, currentDirectoryPath: tmpDir)
// Check the sub-process used the correct directory
XCTAssertEqual(pwd.trimmingCharacters(in:.newlines),"/bin")
}
// Test that $PWD can be set to empty
do{
varenv=ProcessInfo.processInfo.environment
env["PWD"]=""
let(pwd, _)=tryrunTask([tryxdgTestHelperURL().path,"--echo-PWD"], environment: env, currentDirectoryPath: tmpDir)
// Check the sub-process used the correct directory
XCTAssertEqual(pwd.trimmingCharacters(in:.newlines),"")
}
XCTAssertEqual(previousWorkingDirectory, fm.currentDirectoryPath)
}
func test_run()throws{
letfm=FileManager.default
letcwd= fm.currentDirectoryPath
do{
letprocess=tryProcess.run(tryxdgTestHelperURL(), arguments:["--exit","123"], terminationHandler:nil)
process.waitUntilExit()
XCTAssertEqual(process.terminationReason,.exit)
XCTAssertEqual(process.terminationStatus,123)
}
XCTAssertEqual(fm.currentDirectoryPath, cwd)
do{
// Check running the process twice throws an error.
letprocess=Process()
process.executableURL =tryxdgTestHelperURL()
process.arguments =["--exit","0"]
XCTAssertNoThrow(try process.run())
process.waitUntilExit()
XCTAssertThrowsError(try process.run()){
letnserror=($0 asNSError)
XCTAssertEqual(nserror.domain, NSCocoaErrorDomain)
letcode=CocoaError(_nsError: nserror).code
XCTAssertEqual(code,.executableLoad)
}
}
do{
letprocess=Process()
process.executableURL =tryxdgTestHelperURL()
process.arguments =["--exit","0"]
process.currentDirectoryURL =URL(fileURLWithPath:"/.../_no_such_directory", isDirectory:true)
XCTAssertThrowsError(try process.run())
}
XCTAssertEqual(fm.currentDirectoryPath, cwd)
do{
letprocess=Process()
process.executableURL =URL(fileURLWithPath:"/..", isDirectory:false)
process.arguments =[]
process.currentDirectoryURL =URL(fileURLWithPath:NSTemporaryDirectory())
XCTAssertThrowsError(try process.run())
}
XCTAssertEqual(fm.currentDirectoryPath, cwd)
_ = fm.changeCurrentDirectoryPath(cwd)
}
func test_preStartEndState()throws{
letprocess=Process()
XCTAssertNil(process.executableURL)
XCTAssertNotNil(process.currentDirectoryURL)
XCTAssertNil(process.arguments)
XCTAssertNil(process.environment)
XCTAssertFalse(process.isRunning)
XCTAssertEqual(process.processIdentifier,0)
XCTAssertEqual(process.qualityOfService,.default)
process.executableURL =tryxdgTestHelperURL()
process.arguments =["--cat"]
_ =try? process.run()
XCTAssertTrue(process.isRunning)
XCTAssertTrue(process.processIdentifier >0)
process.terminate()
process.waitUntilExit()
XCTAssertFalse(process.isRunning)
XCTAssertTrue(process.processIdentifier >0)
XCTAssertEqual(process.terminationReason,.uncaughtSignal)
XCTAssertEqual(process.terminationStatus, SIGTERM)
}
func test_interrupt()throws{
#if os(Windows)
throwXCTSkip("Windows does not have signals")
#else
lethelper=try_SignalHelperRunner()
do{
try helper.start()
}catch{
XCTFail("Cant run xdgTestHelper: \(error)")
return
}
if !helper.waitForReady(){
XCTFail("Didnt receive Ready from sub-process")
return
}
letnow=DispatchTime.now().uptimeNanoseconds
lettimeout=DispatchTime(uptimeNanoseconds: now +2_000_000_000)
varcount=3
while count >0{
helper.process.interrupt()
guard helper.semaphore.wait(timeout: timeout)==.success else{
helper.process.terminate()
XCTFail("Timedout waiting for signal")
return
}
if helper.sigIntCount ==3{
break
}
count -=1
}
helper.process.terminate()
XCTAssertEqual(helper.sigIntCount,3)
helper.process.waitUntilExit()
letterminationReason= helper.process.terminationReason
XCTAssertEqual(terminationReason,Process.TerminationReason.exit)
letstatus= helper.process.terminationStatus
XCTAssertEqual(status,99)
#endif
}
func test_terminate()throws{
letprocess=tryProcess.run(tryxdgTestHelperURL(), arguments:["--cat"])
process.terminate()
process.waitUntilExit()
letterminationReason= process.terminationReason
XCTAssertEqual(terminationReason,Process.TerminationReason.uncaughtSignal)
XCTAssertEqual(process.terminationStatus, SIGTERM)
}
func test_suspend_resume()throws{
#if os(Windows)
throwXCTSkip("Windows does not have signals")
#else
nonisolated(unsafe)lethelper=try_SignalHelperRunner()
do{
try helper.start()
}catch{
XCTFail("Cant run xdgTestHelper: \(error)")
return
}
if !helper.waitForReady(){
XCTFail("Didnt receive Ready from sub-process")
return
}
letnow=DispatchTime.now().uptimeNanoseconds
lettimeout=DispatchTime(uptimeNanoseconds: now +2_000_000_000)
func waitForSemaphore()->Bool{
guard helper.semaphore.wait(timeout: timeout)==.success else{
helper.process.terminate()
XCTFail("Timedout waiting for signal")
returnfalse
}
returntrue
}
XCTAssertTrue(helper.process.isRunning)
XCTAssertTrue(helper.process.suspend())
XCTAssertTrue(helper.process.isRunning)
XCTAssertTrue(helper.process.resume())
ifwaitForSemaphore()==false{return}
XCTAssertEqual(helper.sigContCount,1)
XCTAssertTrue(helper.process.resume())
XCTAssertTrue(helper.process.suspend())
XCTAssertTrue(helper.process.resume())
XCTAssertEqual(helper.sigContCount,1)
XCTAssertTrue(helper.process.suspend())
XCTAssertTrue(helper.process.suspend())
XCTAssertTrue(helper.process.resume())
ifwaitForSemaphore()==false{return}
_ = helper.process.suspend()
_ = helper.process.resume()
ifwaitForSemaphore()==false{return}
XCTAssertEqual(helper.sigContCount,3)
helper.process.terminate()
helper.process.waitUntilExit()
XCTAssertFalse(helper.process.isRunning)
XCTAssertFalse(helper.process.suspend())
XCTAssertTrue(helper.process.resume())
XCTAssertTrue(helper.process.resume())
#endif
}
func test_redirect_stdin_using_null()throws{
lettask=Process()
task.executableURL =tryxdgTestHelperURL()
task.arguments =["--cat"]
task.standardInput =FileHandle.nullDevice
XCTAssertNoThrow(try task.run())
task.waitUntilExit()
}
func test_redirect_stdout_using_null()throws{
lettask=Process()
task.executableURL =tryxdgTestHelperURL()
task.arguments =["--env"]
task.standardOutput =FileHandle.nullDevice
XCTAssertNoThrow(try task.run())
task.waitUntilExit()
}
func test_redirect_stdin_stdout_using_null()throws{
lettask=Process()
task.executableURL =tryxdgTestHelperURL()
task.arguments =["--cat"]
task.standardInput =FileHandle.nullDevice
task.standardOutput =FileHandle.nullDevice
XCTAssertNoThrow(try task.run())
task.waitUntilExit()
}
func test_redirect_stderr_using_null()throws{
lettask=Process()
task.executableURL =tryxdgTestHelperURL()
task.arguments =["--env"]
task.standardError =FileHandle.nullDevice
XCTAssertNoThrow(try task.run())
task.waitUntilExit()
}
func test_redirect_all_using_null()throws{
lettask=Process()
task.executableURL =tryxdgTestHelperURL()
task.arguments =["--cat"]
task.standardInput =FileHandle.nullDevice
task.standardOutput =FileHandle.nullDevice
task.standardError =FileHandle.nullDevice
XCTAssertNoThrow(try task.run())
task.waitUntilExit()
}
func test_redirect_all_using_nil()throws{
lettask=Process()
task.executableURL =tryxdgTestHelperURL()
task.arguments =["--cat"]
task.standardInput =nil
task.standardOutput =nil
task.standardError =nil
XCTAssertNoThrow(try task.run())
task.waitUntilExit()
}
func test_plutil()throws{
#if os(Windows)
// See explanation in xdgTestHelperURL() as to why this is unsupported
throwXCTSkip("Running plutil as part of unit tests is not supported on Windows")
#else
lettask=Process()
guardlet url =testBundle(executable:true).url(forAuxiliaryExecutable:"plutil")else{
throwError.ExternalBinaryNotFound("plutil")
}
task.executableURL = url
task.arguments =[]
letstdoutPipe=Pipe()
letstdoutData=Mutex(Data())
task.standardError = stdoutPipe
stdoutPipe.fileHandleForReading.readabilityHandler ={ fh in
stdoutData.withLock{
$0.append(fh.availableData)
}
}
try task.run()
task.waitUntilExit()
stdoutPipe.fileHandleForReading.readabilityHandler =nil
try stdoutData.withLock{
iflet d =try stdoutPipe.fileHandleForReading.readToEnd(){
$0.append(d)
}
XCTAssertEqual(String(data: $0, encoding:.utf8)?.trimmingCharacters(in:.whitespacesAndNewlines),"No files specified.")
}
#endif
}
@available(*, deprecated) // test of deprecated API, suppress deprecation warning
func test_currentDirectory()throws{
letprocess=Process()
XCTAssertNil(process.executableURL)
XCTAssertNotNil(process.currentDirectoryURL)
// Test currentDirectoryURL cannot be set to nil even though it is a URL?
letcwd=URL(fileURLWithPath:FileManager.default.currentDirectoryPath, isDirectory:true)
process.currentDirectoryURL =nil
XCTAssertNotNil(process.currentDirectoryURL)
XCTAssertEqual(process.currentDirectoryURL, cwd)
letaFileURL=URL(fileURLWithPath:"/a_file", isDirectory:false)
XCTAssertFalse(aFileURL.hasDirectoryPath)
XCTAssertEqual(aFileURL.path,"/a_file")
process.currentDirectoryURL = aFileURL
XCTAssertNotEqual(process.currentDirectoryURL, aFileURL)
XCTAssertEqual(process.currentDirectoryPath,"/a_file")
XCTAssertTrue(tryXCTUnwrap(process.currentDirectoryURL).hasDirectoryPath)
XCTAssertEqual(tryXCTUnwrap(process.currentDirectoryURL).absoluteString,"file:///a_file/")
letaDirURL=URL(fileURLWithPath:"/a_dir", isDirectory:true)
XCTAssertTrue(aDirURL.hasDirectoryPath)
XCTAssertEqual(aDirURL.path,"/a_dir")
process.currentDirectoryURL = aDirURL
XCTAssertEqual(process.currentDirectoryURL, aDirURL)
XCTAssertEqual(process.currentDirectoryPath,"/a_dir")
XCTAssertTrue(tryXCTUnwrap(process.currentDirectoryURL).hasDirectoryPath)
XCTAssertEqual(tryXCTUnwrap(process.currentDirectoryURL).absoluteString,"file:///a_dir/")
process.currentDirectoryPath =""
XCTAssertEqual(process.currentDirectoryPath,"")
XCTAssertNil(process.currentDirectoryURL)
process.currentDirectoryURL =nil
XCTAssertEqual(process.currentDirectoryPath, cwd.withUnsafeFileSystemRepresentation{String(cString: $0!)})
process.executableURL =URL(fileURLWithPath:"/some_file_that_doesnt_exist", isDirectory:false)
XCTAssertThrowsError(try process.run()){
letcode=CocoaError.Code(rawValue:($0 asNSError).code)
XCTAssertEqual(code,.fileReadNoSuchFile)
}
do{
let(stdout, _)=tryrunTask([tryxdgTestHelperURL().path,"--getcwd"], currentDirectoryPath:"/")
vardirectory= stdout.trimmingCharacters(in:CharacterSet(["\n","\r"]))
#if os(Windows)
letzero:String.Index= directory.startIndex
letone:String.Index= directory.index(zero, offsetBy:1)
XCTAssertTrue(directory[zero].isLetter)
XCTAssertEqual(directory[one],":")
directory ="/"+ String(directory.dropFirst(2))
#endif
XCTAssertEqual(URL(fileURLWithPath: directory).absoluteURL,
URL(fileURLWithPath:"/").absoluteURL)
}
do{
// NOTE: Windows does have an environment variable called `PWD`.
// The closed thing is %CD% which is a property of the shell rather
// than the environment. Simply ignore this test on Windows.
#if !os(Windows)
XCTAssertNotEqual("/",FileManager.default.currentDirectoryPath)
XCTAssertNotEqual(FileManager.default.currentDirectoryPath,"/")
let(stdout, _)=tryrunTask([tryxdgTestHelperURL().path,"--echo-PWD"], currentDirectoryPath:"/")
letdirectory= stdout.trimmingCharacters(in:CharacterSet(["\n","\r"]))
XCTAssertEqual(directory,ProcessInfo.processInfo.environment["PWD"])
XCTAssertNotEqual(directory,"/")
#endif
}
do{
letprocess=Process()
process.executableURL =tryxdgTestHelperURL()
process.arguments =["--getcwd"]
process.currentDirectoryPath =""
letstdoutPipe=Pipe()
process.standardOutput = stdoutPipe
try process.run()
process.waitUntilExit()
guard process.terminationStatus ==0else{
throwError.TerminationStatus(process.terminationStatus)
}
varstdoutData=Data()
iflet d =try stdoutPipe.fileHandleForReading.readToEnd(){
stdoutData.append(d)
}
guardlet stdout =String(data: stdoutData, encoding:.utf8)else{
throwError.UnicodeDecodingError(stdoutData)
}
letdirectory= stdout.trimmingCharacters(in:CharacterSet(["\n","\r"]))
XCTAssertEqual(directory,FileManager.default.currentDirectoryPath)
}
XCTAssertThrowsError(tryrunTask([tryxdgTestHelperURL().path,"--getcwd"], currentDirectoryPath:"/some_directory_that_doesnt_exsit")){ error in
letcode=CocoaError.Code(rawValue:(error asNSError).code)
XCTAssertEqual(code,.fileReadNoSuchFile)
}
}
#if !os(Windows)
func test_fileDescriptorsAreNotInherited()throws{
lettask=Process()
letsomeExtraFDs=[dup(1),dup(1),dup(1),dup(1),dup(1),dup(1),dup(1)]
task.executableURL =tryxdgTestHelperURL()
task.arguments =["--print-open-file-descriptors"]
task.standardInput =FileHandle.nullDevice
letstdoutPipe=Pipe()
task.standardOutput = stdoutPipe.fileHandleForWriting
task.standardError =FileHandle.nullDevice
XCTAssertNoThrow(try task.run())
try stdoutPipe.fileHandleForWriting.close()
letstdoutData=try stdoutPipe.fileHandleForReading.readToEnd()
task.waitUntilExit()
letstdoutString=String(decoding: stdoutData ??Data(), as:Unicode.UTF8.self)
#if os(macOS)
XCTAssertEqual("0\n1\n2\n", stdoutString)
#else
// on Linux we may also have a /dev/urandom open as well as some socket that Process uses for something.
// we should definitely have stdin (0), stdout (1), and stderr (2) open
XCTAssert(stdoutString.utf8.starts(with:"0\n1\n2\n".utf8))
// in total we should have 6 or fewer lines:
// 1. stdin
// 2. stdout
// 3. stderr
// 4. /dev/urandom (optional)
// 5. communication socket (optional)
// 6. trailing new line
XCTAssertLessThanOrEqual(stdoutString.components(separatedBy:"\n").count,6,"\(stdoutString)")
#endif
forfdin someExtraFDs {
close(fd)
}
}
#endif
func test_pipeCloseBeforeLaunch()throws{
letprocess=Process()
letstdInput=Pipe()
letstdOutput=Pipe()
process.executableURL =tryxdgTestHelperURL()
process.arguments =["--cat"]
process.standardInput = stdInput
process.standardOutput = stdOutput
letstring="Hello, World"
letstdInputPipe= stdInput.fileHandleForWriting
XCTAssertNoThrow(try stdInputPipe.write(XCTUnwrap(string.data(using:.utf8))))
stdInputPipe.closeFile()
XCTAssertNoThrow(try process.run())
process.waitUntilExit()
letstdOutputPipe= stdOutput.fileHandleForReading
do{
letreadData=tryXCTUnwrap(stdOutputPipe.readToEnd())
letreadString=String(data: readData, encoding:.utf8)
XCTAssertEqual(string, readString)
}catch{
XCTFail("\(error)")
}
}
func test_multiProcesses()throws{
letsource=Process()
source.executableURL =tryxdgTestHelperURL()
source.arguments =["--getcwd"]
letcat1=Process()
cat1.executableURL =tryxdgTestHelperURL()
cat1.arguments =["--cat"]
letcat2=Process()
cat2.executableURL =tryxdgTestHelperURL()
cat2.arguments =["--cat"]
letpipe1=Pipe()
source.standardOutput = pipe1
cat1.standardInput = pipe1
letpipe2=Pipe()
cat1.standardOutput = pipe2
cat2.standardInput = pipe2
letpipe3=Pipe()
cat2.standardOutput = pipe3
XCTAssertNoThrow(try source.run())
XCTAssertNoThrow(try cat1.run())
XCTAssertNoThrow(try cat2.run())
cat2.waitUntilExit()
cat1.waitUntilExit()
source.waitUntilExit()
do{
letdata=tryXCTUnwrap(pipe3.fileHandleForReading.readToEnd())
letpwd=String.init(decoding: data, as:UTF8.self).trimmingCharacters(in:CharacterSet(["\n","\r"]))
XCTAssertEqual(pwd,FileManager.default.currentDirectoryPath)
}catch{
XCTFail("\(error)")
}
}
#if !os(Windows)
func test_processGroup()throws{
// The process group of the child process should be different to the parent's.
letprocess=Process()
process.executableURL =tryxdgTestHelperURL()
process.arguments =["--pgrp"]
letpipe=Pipe()
process.standardOutput = pipe
process.standardError =nil
try process.run()
process.waitUntilExit()
XCTAssertEqual(process.terminationStatus,0)
letdata= pipe.fileHandleForReading.availableData
guardlet string =String(data: data, encoding:.ascii)else{
XCTFail("Could not read stdout")
return
}
letparts= string.trimmingCharacters(in:.newlines).components(separatedBy:": ")
guard parts.count ==2,parts[0]=="pgrp",let childPgrp =Int(parts[1])else{
XCTFail("Could not pgrp fron stdout")
return
}
letparentPgrp=Int(getpgrp())
XCTAssertNotEqual(parentPgrp, childPgrp,"Child process group \(parentPgrp) should not equal parent process group \(childPgrp)")
}
#endif
}
privateenumError:Swift.Error{
case TerminationStatus(Int32)
case UnicodeDecodingError(Data)
case InvalidEnvironmentVariable(String)
case ExternalBinaryNotFound(String)
}
// Run xdgTestHelper, wait for 'Ready' from the sub-process, then signal a semaphore.
// Read lines from a pipe and store in a queue.
class_SignalHelperRunner{
letprocess=Process()
letsemaphore=DispatchSemaphore(value:0)
privateletoutputPipe=Pipe()
privateletsQueue=DispatchQueue(label:"signal queue")
privatevargotReady=false
privatevarbytesIn=Data()
privatevar_sigIntCount=0
privatevar_sigContCount=0
varsigIntCount:Int{return sQueue.sync{return _sigIntCount }}
varsigContCount:Int{return sQueue.sync{return _sigContCount }}
init()throws{
process.executableURL =tryxdgTestHelperURL()
process.environment =ProcessInfo.processInfo.environment
process.arguments =["--signal-test"]
process.standardOutput = outputPipe.fileHandleForWriting
nonisolated(unsafe)letnonisolatedSelf=self
outputPipe.fileHandleForReading.readabilityHandler ={ fh in
letnewLine=UInt8(ascii:"\n")
nonisolatedSelf.bytesIn.append(fh.availableData)
if nonisolatedSelf.bytesIn.isEmpty {
return
}
// Split the incoming data into lines.
whilelet index = nonisolatedSelf.bytesIn.firstIndex(of: newLine){
if index >= nonisolatedSelf.bytesIn.startIndex {
// don't include the newline when converting to string
letline=String(data: nonisolatedSelf.bytesIn[nonisolatedSelf.bytesIn.startIndex..<index], encoding:String.Encoding.utf8)??""
nonisolatedSelf.bytesIn.removeSubrange(nonisolatedSelf.bytesIn.startIndex...index)
if nonisolatedSelf.gotReady ==false && line =="Ready"{
nonisolatedSelf.semaphore.signal()
nonisolatedSelf.gotReady =true;
}
elseif nonisolatedSelf.gotReady ==true{
if line =="Signal: SIGINT"{
nonisolatedSelf.sQueue.sync{ nonisolatedSelf._sigIntCount +=1}
nonisolatedSelf.semaphore.signal()
}
elseif line =="Signal: SIGCONT"{
nonisolatedSelf.sQueue.sync{ nonisolatedSelf._sigContCount +=1}
nonisolatedSelf.semaphore.signal()
}
}
}
}
}
}
deinit{
process.terminate()
process.waitUntilExit()
}
func start()throws{
try process.run()
}
func waitForReady()->Bool{
letnow=DispatchTime.now().uptimeNanoseconds
lettimeout=DispatchTime(uptimeNanoseconds: now +2_000_000_000)
guard semaphore.wait(timeout: timeout)==.success else{
process.terminate()
returnfalse
}
returntrue
}
}
@discardableResult
internalfunc runTask(_ arguments:[String], environment:[String:String]?=nil, currentDirectoryPath:String?=nil)throws->(String,String){
letprocess=Process()
vararguments= arguments
letfirstArg= arguments.removeFirst()
process.executableURL =URL(fileURLWithPath: firstArg)
process.arguments = arguments
// Darwin Foundation doesnt allow .environment to be set to nil although the documentation
// says it is an optional. https://developer.apple.com/documentation/foundation/process/1409412-environment
ifvar e = environment {
#if os(Android)
// In Android, we have to provide at least an LD_LIBRARY_PATH, or
// xdgTestHelper will not be able to find the Swift libraries.
ife["LD_LIBRARY_PATH"]==nil{
iflet ldLibraryPath =ProcessInfo.processInfo.environment["LD_LIBRARY_PATH"]{
e["LD_LIBRARY_PATH"]= ldLibraryPath
}
}
#endif
process.environment = e
}
iflet dirPath = currentDirectoryPath {
process.currentDirectoryURL =URL(fileURLWithPath: dirPath, isDirectory:true)
}
letstdoutPipe=Pipe()
letstderrPipe=Pipe()
structOutput{
varstdoutData=Data()
varstderrData=Data()
}
letdataLock=Mutex(Output())
process.standardOutput = stdoutPipe
process.standardError = stderrPipe
stdoutPipe.fileHandleForReading.readabilityHandler ={ fh in
dataLock.withLock{
$0.stdoutData.append(fh.availableData)
}
}
stderrPipe.fileHandleForReading.readabilityHandler ={ fh in
dataLock.withLock{
$0.stderrData.append(fh.availableData)
}
}
try process.run()
process.waitUntilExit()
stdoutPipe.fileHandleForReading.readabilityHandler =nil
stderrPipe.fileHandleForReading.readabilityHandler =nil
guard process.terminationStatus ==0else{
throwError.TerminationStatus(process.terminationStatus)
}
returntry dataLock.withLock{
// Drain any data remaining in the pipes
iflet d =try stdoutPipe.fileHandleForReading.readToEnd(){
$0.stdoutData.append(d)
}
iflet d =try stderrPipe.fileHandleForReading.readToEnd(){
$0.stderrData.append(d)
}
guardlet stdout =String(data: $0.stdoutData, encoding:.utf8)else{
throwError.UnicodeDecodingError($0.stdoutData)
}
guardlet stderr =String(data: $0.stderrData, encoding:.utf8)else{
throwError.UnicodeDecodingError($0.stderrData)
}
return(stdout, stderr)
}
}
privatefunc parseEnv(_ env:String)throws->[String:String]{
varresult=[String: String]()
forlinein env.components(separatedBy:.newlines)where line !=""{
guardlet range = line.range(of:"=")else{
throwError.InvalidEnvironmentVariable(line)
}