-
Notifications
You must be signed in to change notification settings - Fork 187
Expand file tree
/
Copy pathBuildOperationTests.swift
More file actions
7932 lines (7114 loc) · 454 KB
/
Copy pathBuildOperationTests.swift
File metadata and controls
7932 lines (7114 loc) · 454 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
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift open source project
//
// Copyright (c) 2025 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 class Foundation.ProcessInfo
import struct Foundation.URL
import struct Foundation.UUID
import Testing
import SwiftBuildTestSupport
import func SWBBuildService.commandLineDisplayString
import SWBBuildSystem
import SWBCore
import struct SWBProtocol.RunDestinationInfo
import struct SWBProtocol.TargetDescription
import struct SWBProtocol.TargetDependencyRelationship
import SWBTestSupport
import SWBTaskExecution
@_spi(Testing) import SWBUtil
import SWBTestSupport
@Suite(.requireXcode16())
fileprivate struct BuildOperationTests: CoreBasedTests {
@Test(.requireSDKs(.host), arguments: [("clang", "-Onone"), ("swiftc", "-Onone"), ("swiftc", "-Owholemodule")])
func commandLineTool(linkerDriver: String, optimizationLevel: String) async throws {
try await withTemporaryDirectory { (tmpDir: Path) in
let testProject = try await TestProject(
"TestProject",
sourceRoot: tmpDir,
groupTree: TestGroup(
"SomeFiles",
children: [
TestFile("main.swift"),
TestFile("dynamic library.swift"),
TestFile("static library.swift"),
]),
buildConfigurations: [
TestBuildConfiguration("Debug", buildSettings: [
"ARCHS": "$(ARCHS_STANDARD)",
"CODE_SIGNING_ALLOWED": ProcessInfo.processInfo.hostOperatingSystem() == .macOS ? "YES" : "NO",
"CODE_SIGN_IDENTITY": "-",
"CODE_SIGN_ENTITLEMENTS": "Entitlements.plist",
"DEFINES_MODULE": "YES",
"PRODUCT_NAME": "$(TARGET_NAME)",
"SDKROOT": "$(HOST_PLATFORM)",
"SUPPORTED_PLATFORMS": "$(HOST_PLATFORM)",
"SWIFT_VERSION": swiftVersion,
"LINKER_DRIVER": linkerDriver,
"SWIFT_OPTIMIZATION_LEVEL": optimizationLevel,
])
],
targets: [
TestStandardTarget(
"tool",
type: .commandLineTool,
buildConfigurations: [
TestBuildConfiguration("Debug", buildSettings: [
"LD_RUNPATH_SEARCH_PATHS": "@loader_path/",
])
],
buildPhases: [
TestSourcesBuildPhase(["main.swift"]),
TestFrameworksBuildPhase([
TestBuildFile(.target("dynamiclib")),
TestBuildFile(.target("staticlib")),
])
],
dependencies: [
"dynamiclib",
"staticlib",
]
),
TestStandardTarget(
"dynamiclib",
type: .dynamicLibrary,
buildConfigurations: [
TestBuildConfiguration("Debug", buildSettings: [
"DYLIB_INSTALL_NAME_BASE": "$ORIGIN",
"DYLIB_INSTALL_NAME_BASE[sdk=macosx*]": "@rpath",
// FIXME: Find a way to make these default
"EXECUTABLE_PREFIX": "lib",
"EXECUTABLE_PREFIX[sdk=windows*]": "",
])
],
buildPhases: [
TestSourcesBuildPhase(["dynamic library.swift"]),
],
productReferenceName: "$(EXECUTABLE_NAME)",
),
TestStandardTarget(
"staticlib",
type: .staticLibrary,
buildConfigurations: [
TestBuildConfiguration("Debug", buildSettings: [
// FIXME: Find a way to make these default
"EXECUTABLE_PREFIX": "lib",
"EXECUTABLE_PREFIX[sdk=windows*]": "",
])
],
buildPhases: [
TestSourcesBuildPhase(["static library.swift"]),
],
productReferenceName: "$(EXECUTABLE_NAME)",
),
])
let core = try await getCore()
let tester = try await BuildOperationTester(core, testProject, simulated: false)
let projectDir = tester.workspace.projects[0].sourceRoot
try await tester.fs.writeFileContents(projectDir.join("main.swift")) { stream in
stream <<< "import dynamiclib\n"
stream <<< "import staticlib\n"
stream <<< "dynamicLib()\n"
stream <<< "dynamicLib()\n"
stream <<< "staticLib()\n"
stream <<< "print(\"Hello world\")\n"
}
try await tester.fs.writeFileContents(projectDir.join("dynamic library.swift")) { stream in
stream <<< "public func dynamicLib() { }"
}
try await tester.fs.writeFileContents(projectDir.join("static library.swift")) { stream in
stream <<< "public func staticLib() { }"
}
try await tester.fs.writePlist(projectDir.join("Entitlements.plist"), .plDict([:]))
let provisioningInputs = [
"dynamiclib": ProvisioningTaskInputs(identityHash: "-", signedEntitlements: .plDict([:]), simulatedEntitlements: .plDict([:])),
"staticlib": ProvisioningTaskInputs(identityHash: "-", signedEntitlements: .plDict([:]), simulatedEntitlements: .plDict([:])),
"tool": ProvisioningTaskInputs(identityHash: "-", signedEntitlements: .plDict([:]), simulatedEntitlements: .plDict([:]))
]
let destination: RunDestinationInfo = .host
try await tester.checkBuild(runDestination: destination, signableTargets: Set(provisioningInputs.keys), signableTargetInputs: provisioningInputs) { results in
results.checkNoErrors()
let executionResult = try await Process.getOutput(url: URL(fileURLWithPath: projectDir.join("build").join("Debug\(destination.builtProductsDirSuffix)").join(core.hostOperatingSystem.imageFormat.executableName(basename: "tool")).str), arguments: [], environment: destination.hostRuntimeEnvironment(core))
#expect(executionResult.exitStatus == .exit(0))
if core.hostOperatingSystem == .windows {
#expect(String(decoding: executionResult.stdout, as: UTF8.self) == "Hello world\r\n")
} else {
#expect(String(decoding: executionResult.stdout, as: UTF8.self) == "Hello world\n")
}
#expect(String(decoding: executionResult.stderr, as: UTF8.self) == "")
}
}
}
@Test(.requireSDKs(.host))
func commandLineToolAutolinkingFoundation() async throws {
try await withTemporaryDirectory { (tmpDir: Path) in
let testProject = try await TestProject(
"TestProject",
sourceRoot: tmpDir,
groupTree: TestGroup(
"SomeFiles",
children: [
TestFile("main.swift"),
]),
buildConfigurations: [
TestBuildConfiguration("Debug", buildSettings: [
"ARCHS": "$(ARCHS_STANDARD)",
"CODE_SIGNING_ALLOWED": ProcessInfo.processInfo.hostOperatingSystem() == .macOS ? "YES" : "NO",
"CODE_SIGN_IDENTITY": "-",
"CODE_SIGN_ENTITLEMENTS": "Entitlements.plist",
"DEFINES_MODULE": "YES",
"PRODUCT_NAME": "$(TARGET_NAME)",
"SDKROOT": "$(HOST_PLATFORM)",
"SUPPORTED_PLATFORMS": "$(HOST_PLATFORM)",
"SWIFT_VERSION": swiftVersion,
])
],
targets: [
TestStandardTarget(
"tool",
type: .commandLineTool,
buildConfigurations: [
TestBuildConfiguration("Debug")
],
buildPhases: [
TestSourcesBuildPhase(["main.swift"]),
]
),
])
let core = try await getCore()
let tester = try await BuildOperationTester(core, testProject, simulated: false)
let projectDir = tester.workspace.projects[0].sourceRoot
try await tester.fs.writeFileContents(projectDir.join("main.swift")) { stream in
stream <<< "import Foundation\n"
stream <<< "let x = JSONDecoder()\n"
}
try await tester.fs.writePlist(projectDir.join("Entitlements.plist"), .plDict([:]))
let provisioningInputs = [
"tool": ProvisioningTaskInputs(identityHash: "-", signedEntitlements: .plDict([:]), simulatedEntitlements: .plDict([:]))
]
let destination: RunDestinationInfo = .host
try await tester.checkBuild(runDestination: destination, signableTargets: Set(provisioningInputs.keys), signableTargetInputs: provisioningInputs) { results in
results.checkNoErrors()
}
}
}
@Test(.requireSDKs(.host))
func debuggableCommandLineTool() async throws {
try await withTemporaryDirectory { (tmpDir: Path) in
let testProject = try await TestProject(
"TestProject",
sourceRoot: tmpDir,
groupTree: TestGroup(
"SomeFiles",
children: [
TestFile("main.swift"),
TestFile("dynamic.swift"),
TestFile("static.swift"),
]),
buildConfigurations: [
TestBuildConfiguration("Debug", buildSettings: [
"ARCHS": "$(ARCHS_STANDARD)",
"CODE_SIGNING_ALLOWED": ProcessInfo.processInfo.hostOperatingSystem() == .macOS ? "YES" : "NO",
"CODE_SIGN_IDENTITY": "-",
"CODE_SIGN_ENTITLEMENTS": "Entitlements.plist",
"DEFINES_MODULE": "YES",
"PRODUCT_NAME": "$(TARGET_NAME)",
"SDKROOT": "$(HOST_PLATFORM)",
"SUPPORTED_PLATFORMS": "$(HOST_PLATFORM)",
"SWIFT_VERSION": swiftVersion,
"GCC_GENERATE_DEBUGGING_SYMBOLS": "YES",
])
],
targets: [
TestStandardTarget(
"tool",
type: .commandLineTool,
buildConfigurations: [
TestBuildConfiguration("Debug", buildSettings: [
"LD_RUNPATH_SEARCH_PATHS": "@loader_path/",
])
],
buildPhases: [
TestSourcesBuildPhase(["main.swift"]),
TestFrameworksBuildPhase([
TestBuildFile(.target("dynamiclib")),
TestBuildFile(.target("staticlib")),
])
],
dependencies: [
"dynamiclib",
"staticlib",
]
),
TestStandardTarget(
"dynamiclib",
type: .dynamicLibrary,
buildConfigurations: [
TestBuildConfiguration("Debug", buildSettings: [
"DYLIB_INSTALL_NAME_BASE": "$ORIGIN",
"DYLIB_INSTALL_NAME_BASE[sdk=macosx*]": "@rpath",
// FIXME: Find a way to make these default
"EXECUTABLE_PREFIX": "lib",
"EXECUTABLE_PREFIX[sdk=windows*]": "",
])
],
buildPhases: [
TestSourcesBuildPhase(["dynamic.swift"]),
],
productReferenceName: "$(EXECUTABLE_NAME)",
),
TestStandardTarget(
"staticlib",
type: .staticLibrary,
buildConfigurations: [
TestBuildConfiguration("Debug", buildSettings: [
// FIXME: Find a way to make these default
"EXECUTABLE_PREFIX": "lib",
"EXECUTABLE_PREFIX[sdk=windows*]": "",
])
],
buildPhases: [
TestSourcesBuildPhase(["static.swift"]),
],
productReferenceName: "$(EXECUTABLE_NAME)",
),
])
let core = try await getCore()
let tester = try await BuildOperationTester(core, testProject, simulated: false)
let projectDir = tester.workspace.projects[0].sourceRoot
try await tester.fs.writeFileContents(projectDir.join("main.swift")) { stream in
stream <<< "import dynamiclib\n"
stream <<< "import staticlib\n"
stream <<< "dynamicLib()\n"
stream <<< "dynamicLib()\n"
stream <<< "staticLib()\n"
stream <<< "print(\"Hello world\")\n"
}
try await tester.fs.writeFileContents(projectDir.join("dynamic.swift")) { stream in
stream <<< "public func dynamicLib() { }"
}
try await tester.fs.writeFileContents(projectDir.join("static.swift")) { stream in
stream <<< "public func staticLib() { }"
}
try await tester.fs.writePlist(projectDir.join("Entitlements.plist"), .plDict([:]))
let provisioningInputs = [
"dynamiclib": ProvisioningTaskInputs(identityHash: "-", signedEntitlements: .plDict([:]), simulatedEntitlements: .plDict([:])),
"staticlib": ProvisioningTaskInputs(identityHash: "-", signedEntitlements: .plDict([:]), simulatedEntitlements: .plDict([:])),
"tool": ProvisioningTaskInputs(identityHash: "-", signedEntitlements: .plDict([:]), simulatedEntitlements: .plDict([:]))
]
let destination: RunDestinationInfo = .host
try await tester.checkBuild(runDestination: destination, persistent: true, signableTargets: Set(provisioningInputs.keys), signableTargetInputs: provisioningInputs) { results in
results.checkNoErrors()
if core.hostOperatingSystem.imageFormat.requiresSwiftModulewrap {
let toolWrap = try #require(results.getTask(.matchTargetName("tool"), .matchRuleType("SwiftModuleWrap")))
try results.checkTask(.matchTargetName("tool"), .matchRuleType("Ld")) { task in
try results.checkTaskFollows(task, toolWrap)
}
let dylibWrap = try #require(results.getTask(.matchTargetName("dynamiclib"), .matchRuleType("SwiftModuleWrap")))
try results.checkTask(.matchTargetName("dynamiclib"), .matchRuleType("Ld")) { task in
try results.checkTaskFollows(task, dylibWrap)
}
let staticWrap = try #require(results.getTask(.matchTargetName("staticlib"), .matchRuleType("SwiftModuleWrap")))
try results.checkTask(.matchTargetName("staticlib"), .matchRuleType("Libtool")) { task in
try results.checkTaskFollows(task, staticWrap)
}
}
let executionResult = try await Process.getOutput(url: URL(fileURLWithPath: projectDir.join("build").join("Debug\(destination.builtProductsDirSuffix)").join(core.hostOperatingSystem.imageFormat.executableName(basename: "tool")).str), arguments: [], environment: destination.hostRuntimeEnvironment(core))
#expect(executionResult.exitStatus == .exit(0))
if core.hostOperatingSystem == .windows {
#expect(String(decoding: executionResult.stdout, as: UTF8.self) == "Hello world\r\n")
} else {
#expect(String(decoding: executionResult.stdout, as: UTF8.self) == "Hello world\n")
}
#expect(String(decoding: executionResult.stderr, as: UTF8.self) == "")
}
}
}
@Test(.requireSDKs(.host))
func commandLineTool_whitespaceEscaping() async throws {
try await withTemporaryDirectory { (tmpDir: Path) in
let tmpDir = tmpDir.join("has whitespace")
let testProject = try await TestProject(
"TestProject",
sourceRoot: tmpDir,
groupTree: TestGroup(
"SomeFiles",
children: [
TestFile("main.swift"),
TestFile("dynamic.swift"),
TestFile("static.swift"),
]),
buildConfigurations: [
TestBuildConfiguration("Debug", buildSettings: [
"ARCHS": "$(ARCHS_STANDARD)",
"CODE_SIGNING_ALLOWED": ProcessInfo.processInfo.hostOperatingSystem() == .macOS ? "YES" : "NO",
"CODE_SIGN_IDENTITY": "-",
"CODE_SIGN_ENTITLEMENTS": "Entitlements.plist",
"DEFINES_MODULE": "YES",
"PRODUCT_NAME": "$(TARGET_NAME)",
"SDKROOT": "$(HOST_PLATFORM)",
"SUPPORTED_PLATFORMS": "$(HOST_PLATFORM)",
"SWIFT_VERSION": swiftVersion,
"GCC_GENERATE_DEBUGGING_SYMBOLS": "YES",
])
],
targets: [
TestStandardTarget(
"tool",
type: .commandLineTool,
buildConfigurations: [
TestBuildConfiguration("Debug", buildSettings: [
"LD_RUNPATH_SEARCH_PATHS": "@loader_path/",
])
],
buildPhases: [
TestSourcesBuildPhase(["main.swift"]),
TestFrameworksBuildPhase([
TestBuildFile(.target("dynamiclib")),
TestBuildFile(.target("staticlib")),
])
],
dependencies: [
"dynamiclib",
"staticlib",
]
),
TestStandardTarget(
"dynamiclib",
type: .dynamicLibrary,
buildConfigurations: [
TestBuildConfiguration("Debug", buildSettings: [
"DYLIB_INSTALL_NAME_BASE": "$ORIGIN",
"DYLIB_INSTALL_NAME_BASE[sdk=macosx*]": "@rpath",
// FIXME: Find a way to make these default
"EXECUTABLE_PREFIX": "lib",
"EXECUTABLE_PREFIX[sdk=windows*]": "",
])
],
buildPhases: [
TestSourcesBuildPhase(["dynamic.swift"]),
],
productReferenceName: "$(EXECUTABLE_NAME)",
),
TestStandardTarget(
"staticlib",
type: .staticLibrary,
buildConfigurations: [
TestBuildConfiguration("Debug", buildSettings: [
// FIXME: Find a way to make these default
"EXECUTABLE_PREFIX": "lib",
"EXECUTABLE_PREFIX[sdk=windows*]": "",
])
],
buildPhases: [
TestSourcesBuildPhase(["static.swift"]),
],
productReferenceName: "$(EXECUTABLE_NAME)",
),
])
let core = try await getCore()
let tester = try await BuildOperationTester(core, testProject, simulated: false)
let projectDir = tester.workspace.projects[0].sourceRoot
try await tester.fs.writeFileContents(projectDir.join("main.swift")) { stream in
stream <<< "import dynamiclib\n"
stream <<< "import staticlib\n"
stream <<< "dynamicLib()\n"
stream <<< "dynamicLib()\n"
stream <<< "staticLib()\n"
stream <<< "print(\"Hello world\")\n"
}
try await tester.fs.writeFileContents(projectDir.join("dynamic.swift")) { stream in
stream <<< "public func dynamicLib() { }"
}
try await tester.fs.writeFileContents(projectDir.join("static.swift")) { stream in
stream <<< "public func staticLib() { }"
}
try await tester.fs.writePlist(projectDir.join("Entitlements.plist"), .plDict([:]))
let provisioningInputs = [
"dynamiclib": ProvisioningTaskInputs(identityHash: "-", signedEntitlements: .plDict([:]), simulatedEntitlements: .plDict([:])),
"staticlib": ProvisioningTaskInputs(identityHash: "-", signedEntitlements: .plDict([:]), simulatedEntitlements: .plDict([:])),
"tool": ProvisioningTaskInputs(identityHash: "-", signedEntitlements: .plDict([:]), simulatedEntitlements: .plDict([:]))
]
let destination: RunDestinationInfo = .host
try await tester.checkBuild(runDestination: destination, persistent: true, signableTargets: Set(provisioningInputs.keys), signableTargetInputs: provisioningInputs) { results in
results.checkNoErrors()
}
}
}
@Test(.requireSDKs(.macOS))
func unitTestWithGeneratedEntryPointViaMacOSOverride() async throws {
try await withTemporaryDirectory(removeTreeOnDeinit: false) { (tmpDir: Path) in
let testProject = try await TestProject(
"TestProject",
sourceRoot: tmpDir,
groupTree: TestGroup(
"SomeFiles",
children: [
TestFile("test.swift"),
]),
buildConfigurations: [
TestBuildConfiguration("Debug", buildSettings: [
"ARCHS": "$(ARCHS_STANDARD)",
"CODE_SIGNING_ALLOWED": "NO",
"PRODUCT_NAME": "$(TARGET_NAME)",
"SDKROOT": "$(HOST_PLATFORM)",
"SUPPORTED_PLATFORMS": "$(HOST_PLATFORM)",
"SWIFT_VERSION": swiftVersion,
"INDEX_DATA_STORE_DIR": "\(tmpDir.join("index").str)",
"LINKER_DRIVER": "swiftc"
])
],
targets: [
TestStandardTarget(
"MyTests",
type: .unitTest,
buildConfigurations: [
TestBuildConfiguration("Debug", buildSettings: [
"GENERATE_TEST_ENTRYPOINTS_FOR_BUNDLES": "YES"
])
],
buildPhases: [
TestSourcesBuildPhase(["test.swift"]),
],
),
])
let core = try await getCore()
let tester = try await BuildOperationTester(core, testProject, simulated: false)
try localFS.createDirectory(tmpDir.join("index"))
let projectDir = tester.workspace.projects[0].sourceRoot
try await tester.fs.writeFileContents(projectDir.join("test.swift")) { stream in
stream <<< """
import Testing
import XCTest
@Suite struct MySuite {
@Test func myTest() {
#expect(42 == 42)
}
}
final class MYXCTests: XCTestCase {
func testFoo() {
XCTAssertTrue(true)
}
}
"""
}
let destination: RunDestinationInfo = .host
try await tester.checkBuild(runDestination: destination, persistent: true) { results in
results.checkNoErrors()
results.checkTask(.matchRuleType("GenerateTestEntryPoint")) { task in
task.checkCommandLineMatches(["builtin-generateTestEntryPoint", "--output", .suffix("test_entry_point.swift")])
}
}
}
}
@Test(.requireSDKs(.host), .skipHostOS(.macOS))
func unitTestWithGeneratedEntryPoint() async throws {
try await withTemporaryDirectory(removeTreeOnDeinit: false) { (tmpDir: Path) in
let testProject = try await TestProject(
"TestProject",
sourceRoot: tmpDir,
groupTree: TestGroup(
"SomeFiles",
children: [
TestFile("library.swift"),
TestFile("test.swift"),
]),
buildConfigurations: [
TestBuildConfiguration("Debug", buildSettings: [
"ARCHS": "$(ARCHS_STANDARD)",
"CODE_SIGNING_ALLOWED": "NO",
"PRODUCT_NAME": "$(TARGET_NAME)",
"SDKROOT": "$(HOST_PLATFORM)",
"SUPPORTED_PLATFORMS": "$(HOST_PLATFORM)",
"SWIFT_VERSION": swiftVersion,
"INDEX_DATA_STORE_DIR": "\(tmpDir.join("index").str)",
"LINKER_DRIVER": "swiftc"
])
],
targets: [
TestStandardTarget(
"UnitTestRunner",
type: .swiftpmTestRunner,
buildConfigurations: [
TestBuildConfiguration("Debug", buildSettings: [
"LD_RUNPATH_SEARCH_PATHS": "$(RPATH_ORIGIN)",
]),
],
buildPhases: [
TestSourcesBuildPhase(),
TestFrameworksBuildPhase([
TestBuildFile(.target("MyTests"))
])
],
dependencies: ["MyTests"]
),
TestStandardTarget(
"MyTests",
type: .unitTest,
buildConfigurations: [
TestBuildConfiguration("Debug", buildSettings: [
"LD_RUNPATH_SEARCH_PATHS": "$(RPATH_ORIGIN)",
"LD_DYLIB_INSTALL_NAME": "$(EXECUTABLE_NAME)"
])
],
buildPhases: [
TestSourcesBuildPhase(["test.swift"]),
TestFrameworksBuildPhase([
TestBuildFile(.target("library")),
])
], dependencies: [
"library"
],
productReferenceName: "$(EXECUTABLE_NAME)"
),
TestStandardTarget(
"library",
type: .dynamicLibrary,
buildConfigurations: [
TestBuildConfiguration("Debug", buildSettings: [
"LD_RUNPATH_SEARCH_PATHS": "$(RPATH_ORIGIN)",
// FIXME: Find a way to make these default
"EXECUTABLE_PREFIX": "lib",
"EXECUTABLE_PREFIX[sdk=windows*]": "",
"LD_DYLIB_INSTALL_NAME": "$(EXECUTABLE_NAME)",
])
],
buildPhases: [
TestSourcesBuildPhase(["library.swift"]),
],
productReferenceName: "$(EXECUTABLE_NAME)",
)
])
let core = try await getCore()
let tester = try await BuildOperationTester(core, testProject, simulated: false)
try localFS.createDirectory(tmpDir.join("index"))
let projectDir = tester.workspace.projects[0].sourceRoot
try await tester.fs.writeFileContents(projectDir.join("library.swift")) { stream in
stream <<< "public func foo() -> Int { 42 }\n"
}
try await tester.fs.writeFileContents(projectDir.join("test.swift")) { stream in
stream <<< """
import Testing
import XCTest
import library
@Suite struct MySuite {
@Test func myTest() {
#expect(foo() == 42)
}
}
final class MYXCTests: XCTestCase {
func testFoo() {
XCTAssertTrue(true)
}
}
"""
}
let destination: RunDestinationInfo = .host
try await tester.checkBuild(runDestination: destination, persistent: true) { results in
results.checkNoErrors()
let environment = try destination.hostRuntimeEnvironment(core)
do {
let executionResult = try await Process.getOutput(url: URL(fileURLWithPath: projectDir.join("build").join("Debug\(destination.builtProductsDirSuffix)").join(core.hostOperatingSystem.imageFormat.executableName(basename: "UnitTestRunner")).str), arguments: [], environment: environment)
#expect(executionResult.exitStatus == .exit(0))
#expect(String(decoding: executionResult.stdout, as: UTF8.self).contains("Executed 1 test"))
}
do {
let executionResult = try await Process.getOutput(url: URL(fileURLWithPath: projectDir.join("build").join("Debug\(destination.builtProductsDirSuffix)").join(core.hostOperatingSystem.imageFormat.executableName(basename: "UnitTestRunner")).str), arguments: ["--testing-library", "swift-testing"], environment: environment)
#expect(executionResult.exitStatus == .exit(0))
#expect(String(decoding: executionResult.stderr, as: UTF8.self).contains("Test run with 1 test "))
}
}
}
}
@Test(.requireSDKs(.host), .skipHostOS(.macOS))
func unitTestWithGeneratedEntryPoint_testabilityDisabled() async throws {
try await withTemporaryDirectory(removeTreeOnDeinit: false) { (tmpDir: Path) in
let testProject = try await TestProject(
"TestProject",
sourceRoot: tmpDir,
groupTree: TestGroup(
"SomeFiles",
children: [
TestFile("library.swift"),
TestFile("test.swift"),
]),
buildConfigurations: [
TestBuildConfiguration("Debug", buildSettings: [
"ARCHS": "$(ARCHS_STANDARD)",
"CODE_SIGNING_ALLOWED": "NO",
"PRODUCT_NAME": "$(TARGET_NAME)",
"SDKROOT": "$(HOST_PLATFORM)",
"SUPPORTED_PLATFORMS": "$(HOST_PLATFORM)",
"SWIFT_VERSION": swiftVersion,
"INDEX_DATA_STORE_DIR": "\(tmpDir.join("index").str)",
"LINKER_DRIVER": "swiftc",
"ENABLE_TESTABILITY": "NO",
"SWIFT_ENABLE_TESTABILITY": "NO",
])
],
targets: [
TestStandardTarget(
"UnitTestRunner",
type: .swiftpmTestRunner,
buildConfigurations: [
TestBuildConfiguration("Debug", buildSettings: [
"LD_RUNPATH_SEARCH_PATHS": "$(RPATH_ORIGIN)",
]),
],
buildPhases: [
TestSourcesBuildPhase(),
TestFrameworksBuildPhase([
TestBuildFile(.target("MyTests"))
])
],
dependencies: ["MyTests"]
),
TestStandardTarget(
"MyTests",
type: .unitTest,
buildConfigurations: [
TestBuildConfiguration("Debug", buildSettings: [
"LD_RUNPATH_SEARCH_PATHS": "$(RPATH_ORIGIN)",
"LD_DYLIB_INSTALL_NAME": "$(EXECUTABLE_NAME)"
])
],
buildPhases: [
TestSourcesBuildPhase(["test.swift"]),
TestFrameworksBuildPhase([
TestBuildFile(.target("library")),
])
], dependencies: [
"library"
],
productReferenceName: "$(EXECUTABLE_NAME)"
),
TestStandardTarget(
"library",
type: .dynamicLibrary,
buildConfigurations: [
TestBuildConfiguration("Debug", buildSettings: [
"LD_RUNPATH_SEARCH_PATHS": "$(RPATH_ORIGIN)",
// FIXME: Find a way to make these default
"EXECUTABLE_PREFIX": "lib",
"EXECUTABLE_PREFIX[sdk=windows*]": "",
"LD_DYLIB_INSTALL_NAME": "$(EXECUTABLE_NAME)",
])
],
buildPhases: [
TestSourcesBuildPhase(["library.swift"]),
],
productReferenceName: "$(EXECUTABLE_NAME)",
)
])
let core = try await getCore()
let tester = try await BuildOperationTester(core, testProject, simulated: false)
try localFS.createDirectory(tmpDir.join("index"))
let projectDir = tester.workspace.projects[0].sourceRoot
try await tester.fs.writeFileContents(projectDir.join("library.swift")) { stream in
stream <<< "public func foo() -> Int { 42 }\n"
}
try await tester.fs.writeFileContents(projectDir.join("test.swift")) { stream in
stream <<< """
import Testing
import XCTest
import library
@Suite struct MySuite {
@Test func myTest() {
#expect(foo() == 42)
}
}
final class MYXCTests: XCTestCase {
func testFoo() {
XCTAssertTrue(true)
}
}
"""
}
let destination: RunDestinationInfo = .host
try await tester.checkBuild(runDestination: destination, persistent: true) { results in
results.checkWarning(.prefix("Skipping XCTest discovery for 'MyTests' because it was not built for testing"))
results.checkNoErrors()
let environment = try destination.hostRuntimeEnvironment(core)
do {
let executionResult = try await Process.getOutput(url: URL(fileURLWithPath: projectDir.join("build").join("Debug\(destination.builtProductsDirSuffix)").join(core.hostOperatingSystem.imageFormat.executableName(basename: "UnitTestRunner")).str), arguments: [], environment: environment)
#expect(executionResult.exitStatus == .exit(0))
#expect(String(decoding: executionResult.stdout, as: UTF8.self).contains("Executed 0 tests"))
}
do {
let executionResult = try await Process.getOutput(url: URL(fileURLWithPath: projectDir.join("build").join("Debug\(destination.builtProductsDirSuffix)").join(core.hostOperatingSystem.imageFormat.executableName(basename: "UnitTestRunner")).str), arguments: ["--testing-library", "swift-testing"], environment: environment)
withKnownIssue("On windows the test output indicates no tests ran, needs investigation") {
#expect(executionResult.exitStatus == .exit(0))
#expect(String(decoding: executionResult.stderr, as: UTF8.self).contains("Test run with 1 test "))
} when: {
core.hostOperatingSystem == .windows
}
}
}
}
}
/// Check that environment variables are propagated from the user environment correctly.
@Test(.requireSDKs(.host), .skipHostOS(.windows), .requireSystemPackages(apt: "yacc", yum: "byacc"))
func userEnvironment() async throws {
try await withTemporaryDirectory { tmpDirPath async throws -> Void in
let testWorkspace = TestWorkspace(
"Test",
sourceRoot: tmpDirPath.join("Test"),
projects: [
TestProject(
"aProject",
groupTree: TestGroup(
"Sources", children: [
TestFile("Foo.y")]),
buildConfigurations: [TestBuildConfiguration(
"Debug",
buildSettings: [
"USE_HEADERMAP": "NO",
"YACC": tmpDirPath.join("yacc-script").str,
])],
targets: [
TestStandardTarget(
"Foo", type: .staticLibrary,
buildPhases: [
TestSourcesBuildPhase(["Foo.y"]),
]),
])
])
let tester = try await BuildOperationTester(getCore(), testWorkspace, simulated: false)
try await tester.fs.writeFileContents(testWorkspace.sourceRoot.join("aProject/Foo.y")) { stream in
stream <<<
"""
%{
static int yylex() { return 0; }
static int yyerror(const char *format) { return 0; }
%}
%%
list:
;
%%
"""
}
guard let yaccPath = tester.findExecutable(basename: "yacc") else {
Issue.record("couldn't find yacc executable")
return
}
try await tester.fs.writeFileContents(tmpDirPath.join("yacc-script")) {
let codec = UNIXShellCommandCodec(encodingStrategy: .backslashes, encodingBehavior: .fullCommandLine)
// We filter out any variables that are automatically added by the shell or llbuild
$0 <<< "#!/bin/bash\n"
$0 <<< "/usr/bin/env -u DEVELOPER_DIR | /usr/bin/sort | grep -v PWD= | grep -v SHLVL= | grep -v LLBUILD_ | grep -v ANDROID_ | grep -v _= \n"
$0 <<< codec.encode([yaccPath.str]) <<< " \"$@\"\n"
}
try tester.fs.setFilePermissions(tmpDirPath.join("yacc-script"), permissions: 0o755)
tester.userInfo = UserInfo(user: "exampleUser", group: "exampleGroup", uid: 1234, gid:12345, home: Path("/Users/exampleUser"), environment: [
"ENV_KEY": "ENV_VALUE"])
tester.workspaceContext.updateUserInfo(tester.userInfo)
try await tester.checkBuild(runDestination: .host) { results in
// We expect one task with one line of output.
results.checkTask(.matchRuleType("Yacc")) { task in
results.checkTaskOutput(task) { taskOutput in
#expect(taskOutput == "ENV_KEY=ENV_VALUE\n")
}
}
results.checkNoDiagnostics()
}
}
}
// MARK: Simulated Project Builds
@Test(.requireSDKs(.host), .skipHostOS(.windows)) // FIXME: Windows: Need to implement /usr/bin/true support for skipped tasks in tests
func simulatedEmptyTarget() async throws {
try await withTemporaryDirectory { tmpDirPath async throws -> Void in
let testWorkspace = TestWorkspace(
"Test",
sourceRoot: tmpDirPath.join("Test"),
projects: [
TestProject(
"aProject",
groupTree: TestGroup("Sources"),
targets: [
TestAggregateTarget(
"mock",
buildPhases: [])
])
])
try await BuildOperationTester(getCore(), testWorkspace, simulated: true).checkBuild(runDestination: .host) { results in
// Check that the delegate was passed build started and build ended events in the right place.
results.checkCapstoneEvents()
}
}
}
/// Check the handling of shell scripts in different targets which produce the same output files.
@Test(.requireSDKs(.macOS))
func multipleProducersEmptyTarget() async throws {
try await withTemporaryDirectory { tmpDirPath async throws -> Void in
let testWorkspace = TestWorkspace(
"Test",
sourceRoot: tmpDirPath.join("Test"),
projects: [
TestProject(
"aProject",
groupTree: TestGroup("Sources", children: [TestFile("foo.c")]),
buildConfigurations: [
TestBuildConfiguration("Debug", buildSettings: [
"GENERATE_INFOPLIST_FILE": "YES",
"PRODUCT_NAME": "$(TARGET_NAME)"
])
],
targets: [
TestAggregateTarget(
"combo",
buildPhases: [],
dependencies: ["agg1", "agg2", "agg3"]),
TestAggregateTarget(
"agg1",
buildPhases: [
TestShellScriptBuildPhase(
name: "Script1", originalObjectID: "Script1", contents: "echo Script1", inputs: [],
outputs: [
"/tmp/script-output"
])
]),
TestAggregateTarget(
"agg2",
buildPhases: [
TestShellScriptBuildPhase(
name: "Script2", originalObjectID: "Script2", contents: "echo Script2", inputs: [],
outputs: [
"/tmp/script-output",
"/tmp/script-output2",
])
]),
TestStandardTarget(
"agg3",
type: .application,
buildConfigurations: [
TestBuildConfiguration("Debug", buildSettings: ["BUILD_VARIANTS": "normal debug"])
],
buildPhases: [
TestSourcesBuildPhase(["foo.c"])
],
buildRules: [
TestBuildRule(filePattern: "*.c", script: "cp $INPUT_FILE_PATH /tmp/b", outputs: ["/tmp/b"])
])
])
])
let tester = try await BuildOperationTester(getCore(), testWorkspace, simulated: true)
try await tester.checkBuild(runDestination: .macOS) { results in
// Check that there were was a warning about the duplicate.
results.checkWarning(.contains("duplicate output file '/tmp/b'"))
results.checkWarning(.contains("duplicate output file '/tmp/script-output'"))
results.checkNoWarnings()
results.checkError("""
Multiple commands produce \'/tmp/b\'
Target \'agg3\' (project \'aProject\') has custom build rule with input \'\(tmpDirPath.str)/Test/aProject/foo.c\'
Target \'agg3\' (project \'aProject\') has custom build rule with input \'\(tmpDirPath.str)/Test/aProject/foo.c\'
Consider making this custom build rule architecture-neutral by unchecking \'Run once per architecture\' in Build Rules, or ensure that it produces distinct output file paths for each architecture and variant combination.
""")
results.checkError("""
Multiple commands produce '/tmp/script-output'
That command depends on command in Target 'agg1' (project \'aProject\'): script phase “Script1”
That command depends on command in Target 'agg2' (project \'aProject\'): script phase “Script2”
""")
results.checkNoErrors()
// Find the two script tasks.
guard let _ = results.tasks.filter({ (task: ExecutableTask) -> Bool in task.ruleInfo.prefix(2) == ["PhaseScriptExecution", "Script1"] }).first else { Issue.record(); return }
guard let _ = results.tasks.filter({ (task: ExecutableTask) -> Bool in task.ruleInfo.prefix(2) == ["PhaseScriptExecution", "Script2"] }).first else { Issue.record(); return }
// Check that the delegate was passed build started and build ended events in the right place.
results.checkCapstoneEvents()
}
}
}
@Test(.requireSDKs(.macOS))
func wishfullySimulatedMinimalFramework() async throws {