-
Notifications
You must be signed in to change notification settings - Fork 172
Expand file tree
/
Copy pathXcodesKitTests.swift
More file actions
1514 lines (1328 loc) · 65.9 KB
/
XcodesKitTests.swift
File metadata and controls
1514 lines (1328 loc) · 65.9 KB
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
import XCTest
import Version
import PromiseKit
import PMKFoundation
import Path
import AppleAPI
import Rainbow
@testable import XcodesKit
final class XcodesKitTests: XCTestCase {
static let mockXcode = Xcode(version: Version("0.0.0")!, url: URL(string: "https://apple.com/xcode.xip")!, filename: "mock.xip", releaseDate: nil)
var xcodeList: XcodeList!
var xcodeInstaller: XcodeInstaller!
var sessionService: AppleSessionService!
override class func setUp() {
super.setUp()
PromiseKit.conf.Q.map = nil
PromiseKit.conf.Q.return = nil
}
override func setUp() {
Current = .mock
Rainbow.outputTarget = .unknown
Rainbow.enabled = false
sessionService = AppleSessionService(configuration: Configuration())
xcodeList = XcodeList()
xcodeInstaller = XcodeInstaller(xcodeList: xcodeList, sessionService: sessionService)
}
func test_ParseCertificateInfo_Succeeds() throws {
let sampleRawInfo = """
Executable=/Applications/Xcode-10.1.app/Contents/MacOS/Xcode
Identifier=com.apple.dt.Xcode
Format=app bundle with Mach-O thin (x86_64)
CodeDirectory v=20200 size=434 flags=0x2000(library-validation) hashes=6+5 location=embedded
Signature size=4485
Authority=Software Signing
Authority=Apple Code Signing Certification Authority
Authority=Apple Root CA
Info.plist entries=39
TeamIdentifier=59GAB85EFG
Sealed Resources version=2 rules=13 files=253327
Internal requirements count=1 size=68
"""
let info = xcodeInstaller.parseCertificateInfo(sampleRawInfo)
XCTAssertEqual(info.authority, ["Software Signing", "Apple Code Signing Certification Authority", "Apple Root CA"])
XCTAssertEqual(info.teamIdentifier, "59GAB85EFG")
XCTAssertEqual(info.bundleIdentifier, "com.apple.dt.Xcode")
}
func test_DownloadOrUseExistingArchive_ReturnsExistingArchive() {
Current.files.fileExistsAtPath = { _ in return true }
var xcodeDownloadURL: URL?
Current.network.downloadTask = { url, _, _ in
xcodeDownloadURL = url.pmkRequest.url
return (Progress(), Promise(error: PMKError.invalidCallingConvention))
}
let xcode = Xcode(version: Version("0.0.0")!, url: URL(string: "https://apple.com/xcode.xip")!, filename: "mock.xip", releaseDate: nil)
xcodeInstaller.downloadOrUseExistingArchive(for: xcode, downloader: .urlSession, willInstall: true, progressChanged: { _ in })
.tap { result in
guard case .fulfilled(let value) = result else { XCTFail("downloadOrUseExistingArchive rejected."); return }
XCTAssertEqual(value, Path.environmentApplicationSupport.join("com.robotsandpencils.xcodes").join("Xcode-0.0.0.xip").url)
XCTAssertNil(xcodeDownloadURL)
}
.cauterize()
}
func test_DownloadOrUseExistingArchive_DownloadsArchive() {
Current.files.fileExistsAtPath = { _ in return false }
var xcodeDownloadURL: URL?
Current.network.downloadTask = { url, destination, _ in
xcodeDownloadURL = url.pmkRequest.url
return (Progress(), Promise.value((destination, HTTPURLResponse(url: url.pmkRequest.url!, statusCode: 200, httpVersion: nil, headerFields: nil)!)))
}
let xcode = Xcode(version: Version("0.0.0")!, url: URL(string: "https://apple.com/xcode.xip")!, filename: "mock.xip", releaseDate: nil)
xcodeInstaller.downloadOrUseExistingArchive(for: xcode, downloader: .urlSession, willInstall: true, progressChanged: { _ in })
.tap { result in
guard case .fulfilled(let value) = result else { XCTFail("downloadOrUseExistingArchive rejected."); return }
XCTAssertEqual(value, Path.environmentApplicationSupport.join("com.robotsandpencils.xcodes").join("Xcode-0.0.0.xip").url)
XCTAssertEqual(xcodeDownloadURL, URL(string: "https://apple.com/xcode.xip")!)
}
.cauterize()
}
func test_InstallArchivedXcode_SecurityAssessmentFails_Throws() {
Current.shell.spctlAssess = { _ in return Promise(error: Process.PMKError.execution(process: Process(), standardOutput: nil, standardError: nil)) }
let xcode = Xcode(version: Version("0.0.0")!, url: URL(fileURLWithPath: "/"), filename: "mock", releaseDate: nil)
let installedXcode = InstalledXcode(path: Path("/Applications/Xcode-0.0.0.app")!)!
xcodeInstaller.installArchivedXcode(xcode, at: URL(fileURLWithPath: "/Xcode-0.0.0.xip"), to: Path.root.join("Applications"), emptyTrash: false, noSuperuser: false)
.catch { error in XCTAssertEqual(error as! XcodeInstaller.Error, XcodeInstaller.Error.failedSecurityAssessment(xcode: installedXcode, output: "")) }
}
func test_InstallArchivedXcode_VerifySigningCertificateFails_Throws() {
Current.shell.codesignVerify = { _ in return Promise(error: Process.PMKError.execution(process: Process(), standardOutput: nil, standardError: nil)) }
let xcode = Xcode(version: Version("0.0.0")!, url: URL(fileURLWithPath: "/"), filename: "mock", releaseDate: nil)
xcodeInstaller.installArchivedXcode(xcode, at: URL(fileURLWithPath: "/Xcode-0.0.0.xip"), to: Path.root.join("Applications"), emptyTrash: false, noSuperuser: false)
.catch { error in XCTAssertEqual(error as! XcodeInstaller.Error, XcodeInstaller.Error.codesignVerifyFailed(output: "")) }
}
func test_InstallArchivedXcode_VerifySigningCertificateDoesntMatch_Throws() {
Current.shell.codesignVerify = { _ in return Promise.value((0, "", "")) }
let xcode = Xcode(version: Version("0.0.0")!, url: URL(fileURLWithPath: "/"), filename: "mock", releaseDate: nil)
xcodeInstaller.installArchivedXcode(xcode, at: URL(fileURLWithPath: "/Xcode-0.0.0.xip"), to: Path.root.join("Applications"), emptyTrash: false, noSuperuser: false)
.catch { error in XCTAssertEqual(error as! XcodeInstaller.Error, XcodeInstaller.Error.unexpectedCodeSigningIdentity(identifier: "", certificateAuthority: [])) }
}
func test_InstallArchivedXcode_TrashesXIPWhenFinished() {
var trashedItemAtURL: URL?
Current.files.trashItem = { itemURL in
trashedItemAtURL = itemURL
return URL(fileURLWithPath: "\(NSHomeDirectory())/.Trash/\(itemURL.lastPathComponent)")
}
let xcode = Xcode(version: Version("0.0.0")!, url: URL(fileURLWithPath: "/"), filename: "mock", releaseDate: nil)
let xipURL = URL(fileURLWithPath: "/Xcode-0.0.0.xip")
xcodeInstaller.installArchivedXcode(xcode, at: xipURL, to: Path.root.join("Applications"), emptyTrash: false, noSuperuser: false)
.ensure { XCTAssertEqual(trashedItemAtURL, xipURL) }
.cauterize()
}
func test_InstallLogging_FullHappyPath() {
Rainbow.outputTarget = .console
Rainbow.enabled = true
var log = ""
XcodesKit.Current.logging.log = { log.append($0 + "\n") }
// Don't have a valid session
Current.network.validateSession = { Promise(error: AppleAPI.Client.Error.invalidSession) }
// It hasn't been downloaded
Current.files.fileExistsAtPath = { path in
if path == (Path.xcodesApplicationSupport/"Xcode-0.0.0.xip").string {
return false
}
else {
return true
}
}
// It's an available release version
XcodesKit.Current.network.dataTask = { url in
if url.pmkRequest.url! == URLRequest.downloads.url! {
let downloads = Downloads(downloads: [Download(name: "Xcode 0.0.0", files: [Download.File(remotePath: "https://apple.com/xcode.xip")], dateModified: Date())])
let encoder = JSONEncoder()
encoder.dateEncodingStrategy = .formatted(.downloadsDateModified)
let downloadsData = try! encoder.encode(downloads)
return Promise.value((data: downloadsData, response: HTTPURLResponse(url: url.pmkRequest.url!, statusCode: 200, httpVersion: nil, headerFields: nil)!))
}
return Promise.value((data: Data(), response: HTTPURLResponse(url: url.pmkRequest.url!, statusCode: 200, httpVersion: nil, headerFields: nil)!))
}
// It downloads and updates progress
Current.network.downloadTask = { (url, saveLocation, _) -> (Progress, Promise<(saveLocation: URL, response: URLResponse)>) in
let progress = Progress(totalUnitCount: 100)
return (progress,
Promise { resolver in
// Need this to run after the Promise has returned to the caller. This makes the test async, requiring waiting for an expectation.
DispatchQueue.main.async {
for i in 0...100 {
progress.completedUnitCount = Int64(i)
}
resolver.fulfill((saveLocation: saveLocation,
response: HTTPURLResponse(url: url.pmkRequest.url!, statusCode: 200, httpVersion: nil, headerFields: nil)!))
}
})
}
// It's a valid .app
Current.shell.codesignVerify = { _ in
return Promise.value(
ProcessOutput(
status: 0,
out: "",
err: """
TeamIdentifier=\(XcodeInstaller.XcodeTeamIdentifier)
Authority=\(XcodeInstaller.XcodeCertificateAuthority[0])
Authority=\(XcodeInstaller.XcodeCertificateAuthority[1])
Authority=\(XcodeInstaller.XcodeCertificateAuthority[2])
"""))
}
// Don't have superuser privileges the first time
var validateSudoAuthenticationCallCount = 0
XcodesKit.Current.shell.validateSudoAuthentication = {
validateSudoAuthenticationCallCount += 1
if validateSudoAuthenticationCallCount == 1 {
return Promise(error: Process.PMKError.execution(process: Process(), standardOutput: nil, standardError: nil))
}
else {
return Promise.value(Shell.processOutputMock)
}
}
// User enters password
XcodesKit.Current.shell.readSecureLine = { prompt, _ in
XcodesKit.Current.logging.log(prompt)
return "password"
}
// User enters something
XcodesKit.Current.shell.readLine = { prompt in
XcodesKit.Current.logging.log(prompt)
return "asdf"
}
let expectation = self.expectation(description: "Finished")
xcodeInstaller.install(.version("0.0.0"), dataSource: .apple, downloader: .urlSession, destination: Path.root.join("Applications"), emptyTrash: false, noSuperuser: false)
.ensure {
let url = Bundle.module.url(forResource: "LogOutput-FullHappyPath", withExtension: "txt", subdirectory: "Fixtures")!
XCTAssertEqual(log, try! String(contentsOf: url))
expectation.fulfill()
}
.catch {
XCTFail($0.localizedDescription)
}
waitForExpectations(timeout: 1.0)
}
func test_InstallLogging_FullHappyPath_NoColor() {
var log = ""
XcodesKit.Current.logging.log = { log.append($0 + "\n") }
// Don't have a valid session
Current.network.validateSession = { Promise(error: AppleAPI.Client.Error.invalidSession) }
// It hasn't been downloaded
Current.files.fileExistsAtPath = { path in
if path == (Path.xcodesApplicationSupport/"Xcode-0.0.0.xip").string {
return false
}
else {
return true
}
}
// It's an available release version
XcodesKit.Current.network.dataTask = { url in
if url.pmkRequest.url! == URLRequest.downloads.url! {
let downloads = Downloads(downloads: [Download(name: "Xcode 0.0.0", files: [Download.File(remotePath: "https://apple.com/xcode.xip")], dateModified: Date())])
let encoder = JSONEncoder()
encoder.dateEncodingStrategy = .formatted(.downloadsDateModified)
let downloadsData = try! encoder.encode(downloads)
return Promise.value((data: downloadsData, response: HTTPURLResponse(url: url.pmkRequest.url!, statusCode: 200, httpVersion: nil, headerFields: nil)!))
}
return Promise.value((data: Data(), response: HTTPURLResponse(url: url.pmkRequest.url!, statusCode: 200, httpVersion: nil, headerFields: nil)!))
}
// It downloads and updates progress
Current.network.downloadTask = { (url, saveLocation, _) -> (Progress, Promise<(saveLocation: URL, response: URLResponse)>) in
let progress = Progress(totalUnitCount: 100)
return (progress,
Promise { resolver in
// Need this to run after the Promise has returned to the caller. This makes the test async, requiring waiting for an expectation.
DispatchQueue.main.async {
for i in 0...100 {
progress.completedUnitCount = Int64(i)
}
resolver.fulfill((saveLocation: saveLocation,
response: HTTPURLResponse(url: url.pmkRequest.url!, statusCode: 200, httpVersion: nil, headerFields: nil)!))
}
})
}
// It's a valid .app
Current.shell.codesignVerify = { _ in
return Promise.value(
ProcessOutput(
status: 0,
out: "",
err: """
TeamIdentifier=\(XcodeInstaller.XcodeTeamIdentifier)
Authority=\(XcodeInstaller.XcodeCertificateAuthority[0])
Authority=\(XcodeInstaller.XcodeCertificateAuthority[1])
Authority=\(XcodeInstaller.XcodeCertificateAuthority[2])
"""))
}
// Don't have superuser privileges the first time
var validateSudoAuthenticationCallCount = 0
XcodesKit.Current.shell.validateSudoAuthentication = {
validateSudoAuthenticationCallCount += 1
if validateSudoAuthenticationCallCount == 1 {
return Promise(error: Process.PMKError.execution(process: Process(), standardOutput: nil, standardError: nil))
}
else {
return Promise.value(Shell.processOutputMock)
}
}
// User enters password
XcodesKit.Current.shell.readSecureLine = { prompt, _ in
XcodesKit.Current.logging.log(prompt)
return "password"
}
// User enters something
XcodesKit.Current.shell.readLine = { prompt in
XcodesKit.Current.logging.log(prompt)
return "asdf"
}
let expectation = self.expectation(description: "Finished")
xcodeInstaller.install(.version("0.0.0"), dataSource: .apple, downloader: .urlSession, destination: Path.root.join("Applications"), emptyTrash: false, noSuperuser: false)
.ensure {
let url = Bundle.module.url(forResource: "LogOutput-FullHappyPath-NoColor", withExtension: "txt", subdirectory: "Fixtures")!
XCTAssertEqual(log, try! String(contentsOf: url))
expectation.fulfill()
}
.catch {
XCTFail($0.localizedDescription)
}
waitForExpectations(timeout: 1.0)
}
func test_InstallLogging_FullHappyPath_NonInteractiveTerminal() {
Rainbow.outputTarget = .unknown
Rainbow.enabled = false
XcodesKit.Current.shell.isatty = { false }
var log = ""
XcodesKit.Current.logging.log = { log.append($0 + "\n") }
// Don't have a valid session
Current.network.validateSession = { Promise(error: AppleAPI.Client.Error.invalidSession) }
// It hasn't been downloaded
Current.files.fileExistsAtPath = { path in
if path == (Path.xcodesApplicationSupport/"Xcode-0.0.0.xip").string {
return false
}
else {
return true
}
}
// It's an available release version
XcodesKit.Current.network.dataTask = { url in
if url.pmkRequest.url! == URLRequest.downloads.url! {
let downloads = Downloads(downloads: [Download(name: "Xcode 0.0.0", files: [Download.File(remotePath: "https://apple.com/xcode.xip")], dateModified: Date())])
let encoder = JSONEncoder()
encoder.dateEncodingStrategy = .formatted(.downloadsDateModified)
let downloadsData = try! encoder.encode(downloads)
return Promise.value((data: downloadsData, response: HTTPURLResponse(url: url.pmkRequest.url!, statusCode: 200, httpVersion: nil, headerFields: nil)!))
}
return Promise.value((data: Data(), response: HTTPURLResponse(url: url.pmkRequest.url!, statusCode: 200, httpVersion: nil, headerFields: nil)!))
}
// It downloads and updates progress
Current.network.downloadTask = { (url, saveLocation, _) -> (Progress, Promise<(saveLocation: URL, response: URLResponse)>) in
let progress = Progress(totalUnitCount: 100)
return (progress,
Promise { resolver in
// Need this to run after the Promise has returned to the caller. This makes the test async, requiring waiting for an expectation.
DispatchQueue.main.async {
for i in 0...100 {
progress.completedUnitCount = Int64(i)
}
resolver.fulfill((saveLocation: saveLocation,
response: HTTPURLResponse(url: url.pmkRequest.url!, statusCode: 200, httpVersion: nil, headerFields: nil)!))
}
})
}
// It's a valid .app
Current.shell.codesignVerify = { _ in
return Promise.value(
ProcessOutput(
status: 0,
out: "",
err: """
TeamIdentifier=\(XcodeInstaller.XcodeTeamIdentifier)
Authority=\(XcodeInstaller.XcodeCertificateAuthority[0])
Authority=\(XcodeInstaller.XcodeCertificateAuthority[1])
Authority=\(XcodeInstaller.XcodeCertificateAuthority[2])
"""))
}
// Don't have superuser privileges the first time
var validateSudoAuthenticationCallCount = 0
XcodesKit.Current.shell.validateSudoAuthentication = {
validateSudoAuthenticationCallCount += 1
if validateSudoAuthenticationCallCount == 1 {
return Promise(error: Process.PMKError.execution(process: Process(), standardOutput: nil, standardError: nil))
}
else {
return Promise.value(Shell.processOutputMock)
}
}
// User enters password
XcodesKit.Current.shell.readSecureLine = { prompt, _ in
XcodesKit.Current.logging.log(prompt)
return "password"
}
// User enters something
XcodesKit.Current.shell.readLine = { prompt in
XcodesKit.Current.logging.log(prompt)
return "asdf"
}
let expectation = self.expectation(description: "Finished")
xcodeInstaller.install(.version("0.0.0"), dataSource: .apple, downloader: .urlSession, destination: Path.root.join("Applications"), emptyTrash: false, noSuperuser: false)
.ensure {
let url = Bundle.module.url(forResource: "LogOutput-FullHappyPath-NonInteractiveTerminal", withExtension: "txt", subdirectory: "Fixtures")!
XCTAssertEqual(log, try! String(contentsOf: url))
expectation.fulfill()
}
.catch {
XCTFail($0.localizedDescription)
}
waitForExpectations(timeout: 1.0)
}
func test_InstallLogging_AlternativeDirectory() {
var log = ""
XcodesKit.Current.logging.log = { log.append($0 + "\n") }
// Don't have a valid session
Current.network.validateSession = { Promise(error: AppleAPI.Client.Error.invalidSession) }
// It hasn't been downloaded
Current.files.fileExistsAtPath = { path in
if path == (Path.xcodesApplicationSupport/"Xcode-0.0.0.xip").string {
return false
}
else {
return true
}
}
// It's an available release version
XcodesKit.Current.network.dataTask = { url in
if url.pmkRequest.url! == URLRequest.downloads.url! {
let downloads = Downloads(downloads: [Download(name: "Xcode 0.0.0", files: [Download.File(remotePath: "https://apple.com/xcode.xip")], dateModified: Date())])
let encoder = JSONEncoder()
encoder.dateEncodingStrategy = .formatted(.downloadsDateModified)
let downloadsData = try! encoder.encode(downloads)
return Promise.value((data: downloadsData, response: HTTPURLResponse(url: url.pmkRequest.url!, statusCode: 200, httpVersion: nil, headerFields: nil)!))
}
return Promise.value((data: Data(), response: HTTPURLResponse(url: url.pmkRequest.url!, statusCode: 200, httpVersion: nil, headerFields: nil)!))
}
// It downloads and updates progress
Current.network.downloadTask = { (url, saveLocation, _) -> (Progress, Promise<(saveLocation: URL, response: URLResponse)>) in
let progress = Progress(totalUnitCount: 100)
return (progress,
Promise { resolver in
// Need this to run after the Promise has returned to the caller. This makes the test async, requiring waiting for an expectation.
DispatchQueue.main.async {
for i in 0...100 {
progress.completedUnitCount = Int64(i)
}
resolver.fulfill((saveLocation: saveLocation,
response: HTTPURLResponse(url: url.pmkRequest.url!, statusCode: 200, httpVersion: nil, headerFields: nil)!))
}
})
}
// It's a valid .app
Current.shell.codesignVerify = { _ in
return Promise.value(
ProcessOutput(
status: 0,
out: "",
err: """
TeamIdentifier=\(XcodeInstaller.XcodeTeamIdentifier)
Authority=\(XcodeInstaller.XcodeCertificateAuthority[0])
Authority=\(XcodeInstaller.XcodeCertificateAuthority[1])
Authority=\(XcodeInstaller.XcodeCertificateAuthority[2])
"""))
}
// Don't have superuser privileges the first time
var validateSudoAuthenticationCallCount = 0
XcodesKit.Current.shell.validateSudoAuthentication = {
validateSudoAuthenticationCallCount += 1
if validateSudoAuthenticationCallCount == 1 {
return Promise(error: Process.PMKError.execution(process: Process(), standardOutput: nil, standardError: nil))
}
else {
return Promise.value(Shell.processOutputMock)
}
}
// User enters password
XcodesKit.Current.shell.readSecureLine = { prompt, _ in
XcodesKit.Current.logging.log(prompt)
return "password"
}
// User enters something
XcodesKit.Current.shell.readLine = { prompt in
XcodesKit.Current.logging.log(prompt)
return "asdf"
}
let expectation = self.expectation(description: "Finished")
xcodeInstaller.install(.version("0.0.0"), dataSource: .apple, downloader: .urlSession, destination: Path.home.join("Xcode"), emptyTrash: false, noSuperuser: false)
.ensure {
let url = Bundle.module.url(forResource: "LogOutput-AlternativeDirectory", withExtension: "txt", subdirectory: "Fixtures")!
let expectedText = try! String(contentsOf: url).replacingOccurrences(of: "/Users/brandon", with: Path.home.string)
XCTAssertEqual(log, expectedText)
expectation.fulfill()
}
.catch {
XCTFail($0.localizedDescription)
}
waitForExpectations(timeout: 1.0)
}
func test_InstallLogging_IncorrectSavedPassword() {
var log = ""
XcodesKit.Current.logging.log = { log.append($0 + "\n") }
// Don't have a valid session
Current.network.validateSession = { Promise(error: AppleAPI.Client.Error.invalidSession) }
// XCODES_PASSWORD has incorrect password
var passwordEnvCallCount = 0
XcodesKit.Current.shell.env = { key in
if key == "XCODES_PASSWORD" {
passwordEnvCallCount += 1
return "old_password"
} else {
return nil
}
}
var loginCallCount = 0
XcodesKit.Current.network.login = { _, _ in
defer { loginCallCount += 1 }
if loginCallCount == 0 {
return Promise(error: Client.Error.invalidUsernameOrPassword(username: "test@example.com"))
}
return Promise.value(())
}
// It hasn't been downloaded
Current.files.fileExistsAtPath = { path in
if path == (Path.xcodesApplicationSupport/"Xcode-0.0.0.xip").string {
return false
}
else {
return true
}
}
// It's an available release version
XcodesKit.Current.network.dataTask = { url in
if url.pmkRequest.url! == URLRequest.downloads.url! {
let downloads = Downloads(downloads: [Download(name: "Xcode 0.0.0", files: [Download.File(remotePath: "https://apple.com/xcode.xip")], dateModified: Date())])
let encoder = JSONEncoder()
encoder.dateEncodingStrategy = .formatted(.downloadsDateModified)
let downloadsData = try! encoder.encode(downloads)
return Promise.value((data: downloadsData, response: HTTPURLResponse(url: url.pmkRequest.url!, statusCode: 200, httpVersion: nil, headerFields: nil)!))
}
return Promise.value((data: Data(), response: HTTPURLResponse(url: url.pmkRequest.url!, statusCode: 200, httpVersion: nil, headerFields: nil)!))
}
// It downloads and updates progress
Current.network.downloadTask = { (url, saveLocation, _) -> (Progress, Promise<(saveLocation: URL, response: URLResponse)>) in
let progress = Progress(totalUnitCount: 100)
return (progress,
Promise { resolver in
// Need this to run after the Promise has returned to the caller. This makes the test async, requiring waiting for an expectation.
DispatchQueue.main.async {
for i in 0...100 {
progress.completedUnitCount = Int64(i)
}
resolver.fulfill((saveLocation: saveLocation,
response: HTTPURLResponse(url: url.pmkRequest.url!, statusCode: 200, httpVersion: nil, headerFields: nil)!))
}
})
}
// It's a valid .app
Current.shell.codesignVerify = { _ in
return Promise.value(
ProcessOutput(
status: 0,
out: "",
err: """
TeamIdentifier=\(XcodeInstaller.XcodeTeamIdentifier)
Authority=\(XcodeInstaller.XcodeCertificateAuthority[0])
Authority=\(XcodeInstaller.XcodeCertificateAuthority[1])
Authority=\(XcodeInstaller.XcodeCertificateAuthority[2])
"""))
}
// Don't have superuser privileges the first time
var validateSudoAuthenticationCallCount = 0
XcodesKit.Current.shell.validateSudoAuthentication = {
validateSudoAuthenticationCallCount += 1
if validateSudoAuthenticationCallCount == 1 {
return Promise(error: Process.PMKError.execution(process: Process(), standardOutput: nil, standardError: nil))
}
else {
return Promise.value(Shell.processOutputMock)
}
}
// User enters password
var readSecureLineCallCount = 0
XcodesKit.Current.shell.readSecureLine = { prompt, _ in
XcodesKit.Current.logging.log(prompt)
readSecureLineCallCount += 1
return "password"
}
// User enters something
XcodesKit.Current.shell.readLine = { prompt in
XcodesKit.Current.logging.log(prompt)
return "test@example.com"
}
let expectation = self.expectation(description: "Finished")
xcodeInstaller.install(.version("0.0.0"), dataSource: .apple, downloader: .urlSession, destination: Path.root.join("Applications"), emptyTrash: false, noSuperuser: false)
.ensure {
let url = Bundle.module.url(forResource: "LogOutput-IncorrectSavedPassword", withExtension: "txt", subdirectory: "Fixtures")!
XCTAssertEqual(log, try! String(contentsOf: url))
expectation.fulfill()
XCTAssertEqual(passwordEnvCallCount, 2)
XCTAssertEqual(readSecureLineCallCount, 2)
}
.catch {
XCTFail($0.localizedDescription)
}
waitForExpectations(timeout: 1.0)
}
func test_InstallLogging_DamagedXIP() {
var log = ""
XcodesKit.Current.logging.log = { log.append($0 + "\n") }
// Don't have a valid session
var validateSessionCallCount = 0
Current.network.validateSession = {
validateSessionCallCount += 1
if validateSessionCallCount == 1 {
return Promise(error: AppleAPI.Client.Error.invalidSession)
} else {
return Promise.value(())
}
}
// It has been downloaded
var unxipCallCount = 0
Current.files.fileExistsAtPath = { path in
if path == (Path.xcodesApplicationSupport/"Xcode-0.0.0.xip").string {
if unxipCallCount == 1 {
return false
} else {
return true
}
}
else {
return true
}
}
// It's an available release version
XcodesKit.Current.network.dataTask = { url in
if url.pmkRequest.url! == URLRequest.downloads.url! {
let downloads = Downloads(downloads: [Download(name: "Xcode 0.0.0", files: [Download.File(remotePath: "https://apple.com/xcode.xip")], dateModified: Date())])
let encoder = JSONEncoder()
encoder.dateEncodingStrategy = .formatted(.downloadsDateModified)
let downloadsData = try! encoder.encode(downloads)
return Promise.value((data: downloadsData, response: HTTPURLResponse(url: url.pmkRequest.url!, statusCode: 200, httpVersion: nil, headerFields: nil)!))
}
return Promise.value((data: Data(), response: HTTPURLResponse(url: url.pmkRequest.url!, statusCode: 200, httpVersion: nil, headerFields: nil)!))
}
// It downloads and updates progress
Current.network.downloadTask = { (url, saveLocation, _) -> (Progress, Promise<(saveLocation: URL, response: URLResponse)>) in
let progress = Progress(totalUnitCount: 100)
return (progress,
Promise { resolver in
// Need this to run after the Promise has returned to the caller. This makes the test async, requiring waiting for an expectation.
DispatchQueue.main.async {
for i in 0...100 {
progress.completedUnitCount = Int64(i)
}
resolver.fulfill((saveLocation: saveLocation,
response: HTTPURLResponse(url: url.pmkRequest.url!, statusCode: 200, httpVersion: nil, headerFields: nil)!))
}
})
}
// It's a valid .app
Current.shell.codesignVerify = { _ in
return Promise.value(
ProcessOutput(
status: 0,
out: "",
err: """
TeamIdentifier=\(XcodeInstaller.XcodeTeamIdentifier)
Authority=\(XcodeInstaller.XcodeCertificateAuthority[0])
Authority=\(XcodeInstaller.XcodeCertificateAuthority[1])
Authority=\(XcodeInstaller.XcodeCertificateAuthority[2])
"""))
}
// Don't have superuser privileges the first time
var validateSudoAuthenticationCallCount = 0
Current.shell.validateSudoAuthentication = {
validateSudoAuthenticationCallCount += 1
if validateSudoAuthenticationCallCount == 1 {
return Promise(error: Process.PMKError.execution(process: Process(), standardOutput: nil, standardError: nil))
}
else {
return Promise.value(Shell.processOutputMock)
}
}
// User enters password
Current.shell.readSecureLine = { prompt, _ in
XcodesKit.Current.logging.log(prompt)
return "password"
}
// User enters something
XcodesKit.Current.shell.readLine = { prompt in
XcodesKit.Current.logging.log(prompt)
return "asdf"
}
Current.shell.unxip = { _ in
unxipCallCount += 1
if unxipCallCount == 1 {
return Promise(error: Process.PMKError.execution(process: Process(), standardOutput: nil, standardError: "The file \"Xcode-0.0.0.xip\" is damaged and can’t be expanded."))
} else {
return Promise.value(Shell.processOutputMock)
}
}
let expectation = self.expectation(description: "Finished")
xcodeInstaller.install(.version("0.0.0"), dataSource: .apple, downloader: .urlSession, destination: Path.root.join("Applications"), emptyTrash: false, noSuperuser: false)
.ensure {
let url = Bundle.module.url(forResource: "LogOutput-DamagedXIP", withExtension: "txt", subdirectory: "Fixtures")!
let expectedText = try! String(contentsOf: url).replacingOccurrences(of: "/Users/brandon", with: Path.home.string)
XCTAssertEqual(log, expectedText)
expectation.fulfill()
}
.catch {
XCTFail($0.localizedDescription)
}
waitForExpectations(timeout: 1.0)
}
func test_UninstallXcode() {
// There are installed Xcodes
let installedXcodes = [
InstalledXcode(path: Path("/Applications/Xcode-0.0.0.app")!)!,
InstalledXcode(path: Path("/Applications/Xcode-2.0.0.app")!)!,
InstalledXcode(path: Path("/Applications/Xcode-2.0.1.app")!)!
]
Current.files.installedXcodes = { _ in installedXcodes }
Current.files.contentsAtPath = { path in
if path == "/Applications/Xcode-0.0.0.app/Contents/Info.plist" {
let url = Bundle.module.url(forResource: "Stub-0.0.0.Info", withExtension: "plist", subdirectory: "Fixtures")!
return try? Data(contentsOf: url)
}
else if path == "/Applications/Xcode-2.0.0.app/Contents/Info.plist" {
let url = Bundle.module.url(forResource: "Stub-2.0.0.Info", withExtension: "plist", subdirectory: "Fixtures")!
return try? Data(contentsOf: url)
}
else if path == "/Applications/Xcode-2.0.1.app/Contents/Info.plist" {
let url = Bundle.module.url(forResource: "Stub-2.0.1.Info", withExtension: "plist", subdirectory: "Fixtures")!
return try? Data(contentsOf: url)
}
else if path.contains("version.plist") {
let url = Bundle.module.url(forResource: "Stub.version", withExtension: "plist", subdirectory: "Fixtures")!
return try? Data(contentsOf: url)
}
else {
return nil
}
}
// The one that's going to be deleted is selected
Current.shell.xcodeSelectPrintPath = {
Promise.value((status: 0, out: "/Applications/Xcode-0.0.0.app/Contents/Developer", err: ""))
}
// Trashing succeeds
var trashedItemAtURL: URL?
Current.files.trashItem = { itemURL in
trashedItemAtURL = itemURL
return URL(fileURLWithPath: "\(NSHomeDirectory())/.Trash/\(itemURL.lastPathComponent)")
}
// Switching succeeds
var selectedPaths: [String] = []
Current.shell.xcodeSelectSwitch = { password, path in
selectedPaths.append(path)
return Promise.value((status: 0, out: "", err: ""))
}
xcodeInstaller.uninstallXcode("0.0.0", directory: Path.root.join("Applications"), emptyTrash: false)
.ensure {
XCTAssertEqual(selectedPaths, ["/Applications/Xcode-2.0.1.app"])
XCTAssertEqual(trashedItemAtURL, installedXcodes[0].path.url)
}
.cauterize()
}
func test_UninstallInteractively() {
var log = ""
XcodesKit.Current.logging.log = { log.append($0 + "\n") }
// There are installed Xcodes
let installedXcodes = [
InstalledXcode(path: Path("/Applications/Xcode-0.0.0.app")!, version: Version(0, 0, 0)),
InstalledXcode(path: Path("/Applications/Xcode-2.0.1.app")!, version: Version(2, 0, 1)),
]
Current.files.installedXcodes = { _ in installedXcodes }
// It prints the expected paths
var xcodeSelectPrintPathCallCount = 0
Current.shell.xcodeSelectPrintPath = {
xcodeSelectPrintPathCallCount += 1
if xcodeSelectPrintPathCallCount == 1 {
return Promise.value((status: 0, out: "/Applications/Xcode-2.0.1.app/Contents/Developer", err: ""))
}
else {
return Promise.value((status: 0, out: "/Applications/Xcode-0.0.0.app/Contents/Developer", err: ""))
}
}
// User enters an index
XcodesKit.Current.shell.readLine = { prompt in
XcodesKit.Current.logging.log(prompt)
return "1"
}
// Trashing succeeds
var trashedItemAtURL: URL?
Current.files.trashItem = { itemURL in
trashedItemAtURL = itemURL
return URL(fileURLWithPath: "\(NSHomeDirectory())/.Trash/\(itemURL.lastPathComponent)")
}
xcodeInstaller.uninstallXcode("999", directory: Path.root.join("Applications"), emptyTrash: false)
.ensure {
XCTAssertEqual(trashedItemAtURL, installedXcodes[0].path.url)
}
.cauterize()
XCTAssertEqual(log, """
999.0 is not installed.
Available Xcode versions:
1) 0.0
2) 2.0.1
Enter the number of the Xcode to select:
Xcode 0.0 moved to Trash: \(NSHomeDirectory())/.Trash/Xcode-0.0.0.app
""")
}
func test_VerifySecurityAssessment_Fails() {
Current.shell.spctlAssess = { _ in return Promise(error: Process.PMKError.execution(process: Process(), standardOutput: nil, standardError: nil)) }
let installedXcode = InstalledXcode(path: Path("/Applications/Xcode-0.0.0.app")!)!
xcodeInstaller.verifySecurityAssessment(of: installedXcode)
.tap { result in XCTAssertFalse(result.isFulfilled) }
.cauterize()
}
func test_VerifySecurityAssessment_Succeeds() {
Current.shell.spctlAssess = { _ in return Promise.value((0, "", "")) }
let installedXcode = InstalledXcode(path: Path("/Applications/Xcode-0.0.0.app")!)!
xcodeInstaller.verifySecurityAssessment(of: installedXcode)
.tap { result in XCTAssertTrue(result.isFulfilled) }
.cauterize()
}
func test_MigrateApplicationSupport_NoSupportFiles() {
Current.files.fileExistsAtPath = { _ in return false }
var source: URL?
var destination: URL?
Current.files.moveItem = { source = $0; destination = $1 }
var removedItemAtURL: URL?
Current.files.removeItem = { removedItemAtURL = $0 }
migrateApplicationSupportFiles()
XCTAssertNil(source)
XCTAssertNil(destination)
XCTAssertNil(removedItemAtURL)
}
func test_MigrateApplicationSupport_OnlyOldSupportFiles() {
Current.files.fileExistsAtPath = { return $0.contains("ca.brandonevans") }
var source: URL?
var destination: URL?
Current.files.moveItem = { source = $0; destination = $1 }
var removedItemAtURL: URL?
Current.files.removeItem = { removedItemAtURL = $0 }
migrateApplicationSupportFiles()
XCTAssertEqual(source, Path.environmentApplicationSupport.join("ca.brandonevans.xcodes").url)
XCTAssertEqual(destination, Path.environmentApplicationSupport.join("com.robotsandpencils.xcodes").url)
XCTAssertNil(removedItemAtURL)
}
func test_MigrateApplicationSupport_OldAndNewSupportFiles() {
Current.files.fileExistsAtPath = { _ in return true }
var source: URL?
var destination: URL?
Current.files.moveItem = { source = $0; destination = $1 }
var removedItemAtURL: URL?
Current.files.removeItem = { removedItemAtURL = $0 }
migrateApplicationSupportFiles()
XCTAssertNil(source)
XCTAssertNil(destination)
XCTAssertEqual(removedItemAtURL, Path.environmentApplicationSupport.join("ca.brandonevans.xcodes").url)
}
func test_MigrateApplicationSupport_OnlyNewSupportFiles() {
Current.files.fileExistsAtPath = { return $0.contains("com.robotsandpencils") }
var source: URL?
var destination: URL?
Current.files.moveItem = { source = $0; destination = $1 }
var removedItemAtURL: URL?
Current.files.removeItem = { removedItemAtURL = $0 }
migrateApplicationSupportFiles()
XCTAssertNil(source)
XCTAssertNil(destination)
XCTAssertNil(removedItemAtURL)
}
func test_ParsePrereleaseXcodes() {
let url = Bundle.module.url(forResource: "developer.apple.com-download-19-6-9", withExtension: "html", subdirectory: "Fixtures")!
let data = try! Data(contentsOf: url)
let xcodes = try! XcodeList().parsePrereleaseXcodes(from: data)
XCTAssertEqual(xcodes.count, 1)
XCTAssertEqual(xcodes[0].version, Version("11.0.0-beta+11M336W"))
}
func test_SelectPrint() {
var log = ""
XcodesKit.Current.logging.log = { log.append($0 + "\n") }
Current.files.installedXcodes = { _ in
[InstalledXcode(path: Path("/Applications/Xcode-0.0.0.app")!)!,
InstalledXcode(path: Path("/Applications/Xcode-2.0.0.app")!)!]
}
Current.shell.xcodeSelectPrintPath = { Promise.value((status: 0, out: "/Applications/Xcode-2.0.0.app/Contents/Developer", err: "")) }
selectXcode(shouldPrint: true, pathOrVersion: "", directory: Path.root.join("Applications"))
.cauterize()
XCTAssertEqual(log, """
/Applications/Xcode-2.0.0.app/Contents/Developer
""")
}
func test_SelectPath() {
var log = ""
XcodesKit.Current.logging.log = { log.append($0 + "\n") }
// There are installed Xcodes
Current.files.installedXcodes = { _ in
[InstalledXcode(path: Path("/Applications/Xcode-0.0.0.app")!)!,
InstalledXcode(path: Path("/Applications/Xcode-2.0.1.app")!)!]
}
Current.files.contentsAtPath = { path in
if path == "/Applications/Xcode-0.0.0.app/Contents/Info.plist" {
let url = Bundle.module.url(forResource: "Stub-0.0.0.Info", withExtension: "plist", subdirectory: "Fixtures")!
return try? Data(contentsOf: url)
}
else if path == "/Applications/Xcode-2.0.1.app/Contents/Info.plist" {
let url = Bundle.module.url(forResource: "Stub-2.0.1.Info", withExtension: "plist", subdirectory: "Fixtures")!
return try? Data(contentsOf: url)
}
else if path.contains("version.plist") {
let url = Bundle.module.url(forResource: "Stub.version", withExtension: "plist", subdirectory: "Fixtures")!
return try? Data(contentsOf: url)
}
else {
return nil
}
}
// It prints the expected paths
var xcodeSelectPrintPathCallCount = 0
Current.shell.xcodeSelectPrintPath = {
xcodeSelectPrintPathCallCount += 1
if xcodeSelectPrintPathCallCount == 1 {
return Promise.value((status: 0, out: "/Applications/Xcode-2.0.1.app/Contents/Developer", err: ""))
}
else {
return Promise.value((status: 0, out: "/Applications/Xcode-0.0.0.app/Contents/Developer", err: ""))
}
}
// Don't have superuser privileges the first time
var validateSudoAuthenticationCallCount = 0
Current.shell.validateSudoAuthentication = {
validateSudoAuthenticationCallCount += 1
if validateSudoAuthenticationCallCount == 1 {
return Promise(error: Process.PMKError.execution(process: Process(), standardOutput: nil, standardError: nil))