-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
SwiftTestCommand.swift
1411 lines (1200 loc) · 53.2 KB
/
SwiftTestCommand.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 open source project
//
// Copyright (c) 2015-2024 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 ArgumentParser
@_spi(SwiftPMInternal)
import Basics
@_spi(SwiftPMInternal)
import CoreCommands
import Dispatch
import Foundation
import PackageGraph
@_spi(SwiftPMInternal)
import PackageModel
import SPMBuildCore
import func TSCLibc.exit
import Workspace
import struct TSCBasic.ByteString
import enum TSCBasic.JSON
import class TSCBasic.Process
import enum TSCBasic.ProcessEnv
import var TSCBasic.stdoutStream
import class TSCBasic.SynchronizedQueue
import class TSCBasic.Thread
private enum TestError: Swift.Error {
case invalidListTestJSONData(context: String, underlyingError: Error? = nil)
case testsNotFound
case testProductNotFound(productName: String)
case productIsNotTest(productName: String)
case multipleTestProducts([String])
case xctestNotAvailable(reason: String)
case xcodeNotInstalled
}
extension TestError: CustomStringConvertible {
var description: String {
switch self {
case .testsNotFound:
return "no tests found; create a target in the 'Tests' directory"
case .testProductNotFound(let productName):
return "there is no test product named '\(productName)'"
case .productIsNotTest(let productName):
return "the product '\(productName)' is not a test"
case .invalidListTestJSONData(let context, let underlyingError):
let underlying = underlyingError != nil ? ", underlying error: \(underlyingError!)" : ""
return "invalid list test JSON structure, produced by \(context)\(underlying)"
case .multipleTestProducts(let products):
return "found multiple test products: \(products.joined(separator: ", ")); use --test-product to select one"
case let .xctestNotAvailable(reason):
return "XCTest not available: \(reason)"
case .xcodeNotInstalled:
return "XCTest not available; download and install Xcode to use XCTest on this platform"
}
}
}
struct SharedOptions: ParsableArguments {
@Flag(name: .customLong("skip-build"),
help: "Skip building the test target")
var shouldSkipBuilding: Bool = false
/// The test product to use. This is useful when there are multiple test products
/// to choose from (usually in multiroot packages).
@Option(help: .hidden)
var testProduct: String?
}
struct TestCommandOptions: ParsableArguments {
@OptionGroup()
var globalOptions: GlobalOptions
@OptionGroup()
var sharedOptions: SharedOptions
/// Which testing libraries to use (and any related options.)
@OptionGroup()
var testLibraryOptions: TestLibraryOptions
/// If tests should run in parallel mode.
@Flag(name: .customLong("parallel"),
inversion: .prefixedNo,
help: "Run the tests in parallel.")
var shouldRunInParallel: Bool = false
/// Number of tests to execute in parallel
@Option(name: .customLong("num-workers"),
help: "Number of tests to execute in parallel.")
var numberOfWorkers: Int?
/// List the tests and exit.
@Flag(name: [.customLong("list-tests"), .customShort("l")],
help: "Lists test methods in specifier format")
var _deprecated_shouldListTests: Bool = false
/// If the path of the exported code coverage JSON should be printed.
@Flag(name: [.customLong("show-codecov-path"), .customLong("show-code-coverage-path"), .customLong("show-coverage-path")],
help: "Print the path of the exported code coverage JSON file")
var shouldPrintCodeCovPath: Bool = false
var testCaseSpecifier: TestCaseSpecifier {
if !filter.isEmpty {
return .regex(filter)
}
return _testCaseSpecifier.map { .specific($0) } ?? .none
}
@Option(name: [.customShort("s"), .customLong("specifier")])
var _testCaseSpecifier: String?
@Option(help: """
Run test cases matching regular expression, Format: <test-target>.<test-case> \
or <test-target>.<test-case>/<test>
""")
var filter: [String] = []
@Option(name: .customLong("skip"),
help: "Skip test cases matching regular expression, Example: --skip PerformanceTests")
var _testCaseSkip: [String] = []
/// Path where the xUnit xml file should be generated.
@Option(name: .customLong("xunit-output"),
help: "Path where the xUnit xml file should be generated.")
var xUnitOutput: AbsolutePath?
/// Generate LinuxMain entries and exit.
@Flag(name: .customLong("testable-imports"), inversion: .prefixedEnableDisable, help: "Enable or disable testable imports. Enabled by default.")
var enableTestableImports: Bool = true
/// Whether to enable code coverage.
@Flag(name: .customLong("code-coverage"),
inversion: .prefixedEnableDisable,
help: "Enable code coverage")
var enableCodeCoverage: Bool = false
/// Configure test output.
@Option(help: ArgumentHelp("", visibility: .hidden))
public var testOutput: TestOutput = .default
var enableExperimentalTestOutput: Bool {
return testOutput == .experimentalSummary
}
/// Path where swift-testing's JSON configuration should be read.
@Option(name: .customLong("experimental-configuration-path"),
help: .hidden)
var configurationPath: AbsolutePath?
/// Path where swift-testing's JSON output should be written.
@Option(name: .customLong("experimental-event-stream-output"),
help: .hidden)
var eventStreamOutputPath: AbsolutePath?
/// The schema version of swift-testing's JSON input/output.
@Option(name: .customLong("experimental-event-stream-version"),
help: .hidden)
var eventStreamVersion: Int?
}
/// Tests filtering specifier, which is used to filter tests to run.
public enum TestCaseSpecifier {
/// No filtering
case none
/// Specify test with fully quantified name
case specific(String)
/// RegEx patterns for tests to run
case regex([String])
/// RegEx patterns for tests to skip
case skip([String])
}
/// Different styles of test output.
public enum TestOutput: String, ExpressibleByArgument {
/// Whatever `xctest` emits to the console.
case `default`
/// Capture XCTest events and provide a summary.
case experimentalSummary
/// Let the test process emit parseable output to the console.
case experimentalParseable
}
/// swift-test tool namespace
public struct SwiftTestCommand: AsyncSwiftCommand {
public static var configuration = CommandConfiguration(
commandName: "test",
_superCommandName: "swift",
abstract: "Build and run tests",
discussion: "SEE ALSO: swift build, swift run, swift package",
version: SwiftVersion.current.completeDisplayString,
subcommands: [
List.self, Last.self
],
helpNames: [.short, .long, .customLong("help", withSingleDash: true)])
public var globalOptions: GlobalOptions {
options.globalOptions
}
@OptionGroup()
var options: TestCommandOptions
// MARK: - XCTest
private func xctestRun(_ swiftCommandState: SwiftCommandState) async throws {
// validate XCTest available on darwin based systems
let toolchain = try swiftCommandState.getTargetToolchain()
if case let .unsupported(reason) = try swiftCommandState.getHostToolchain().swiftSDK.xctestSupport {
if let reason {
throw TestError.xctestNotAvailable(reason: reason)
} else {
throw TestError.xcodeNotInstalled
}
} else if toolchain.targetTriple.isDarwin() && toolchain.xctestPath == nil {
throw TestError.xcodeNotInstalled
}
let (productsBuildParameters, _) = try swiftCommandState.buildParametersForTest(options: self.options, library: .xctest)
// Remove test output from prior runs and validate priors.
if self.options.enableExperimentalTestOutput && productsBuildParameters.triple.supportsTestSummary {
_ = try? localFileSystem.removeFileTree(productsBuildParameters.testOutputPath)
}
let testProducts = try buildTestsIfNeeded(swiftCommandState: swiftCommandState, library: .xctest)
if !self.options.shouldRunInParallel {
let xctestArgs = try xctestArgs(for: testProducts, swiftCommandState: swiftCommandState)
try await runTestProducts(
testProducts,
additionalArguments: xctestArgs,
productsBuildParameters: productsBuildParameters,
swiftCommandState: swiftCommandState,
library: .xctest
)
} else {
let testSuites = try TestingSupport.getTestSuites(
in: testProducts,
swiftCommandState: swiftCommandState,
enableCodeCoverage: options.enableCodeCoverage,
shouldSkipBuilding: options.sharedOptions.shouldSkipBuilding,
experimentalTestOutput: options.enableExperimentalTestOutput,
sanitizers: globalOptions.build.sanitizers
)
let tests = try testSuites
.filteredTests(specifier: options.testCaseSpecifier)
.skippedTests(specifier: options.skippedTests(fileSystem: swiftCommandState.fileSystem))
// If there were no matches, emit a warning and exit.
if tests.isEmpty {
swiftCommandState.observabilityScope.emit(.noMatchingTests)
try generateXUnitOutputIfRequested(for: [], swiftCommandState: swiftCommandState)
return
}
// Clean out the code coverage directory that may contain stale
// profraw files from a previous run of the code coverage tool.
if self.options.enableCodeCoverage {
try swiftCommandState.fileSystem.removeFileTree(productsBuildParameters.codeCovPath)
}
// Run the tests using the parallel runner.
let runner = ParallelTestRunner(
bundlePaths: testProducts.map { $0.bundlePath },
cancellator: swiftCommandState.cancellator,
toolchain: toolchain,
numJobs: options.numberOfWorkers ?? ProcessInfo.processInfo.activeProcessorCount,
buildOptions: globalOptions.build,
productsBuildParameters: productsBuildParameters,
shouldOutputSuccess: swiftCommandState.logLevel <= .info,
observabilityScope: swiftCommandState.observabilityScope
)
let testResults = try runner.run(tests)
try generateXUnitOutputIfRequested(for: testResults, swiftCommandState: swiftCommandState)
// process code Coverage if request
if self.options.enableCodeCoverage, runner.ranSuccessfully {
try await processCodeCoverage(testProducts, swiftCommandState: swiftCommandState, library: .xctest)
}
if !runner.ranSuccessfully {
swiftCommandState.executionStatus = .failure
}
if self.options.enableExperimentalTestOutput, !runner.ranSuccessfully {
try Self.handleTestOutput(productsBuildParameters: productsBuildParameters, packagePath: testProducts[0].packagePath)
}
}
}
private func xctestArgs(for testProducts: [BuiltTestProduct], swiftCommandState: SwiftCommandState) throws -> [String] {
switch options.testCaseSpecifier {
case .none:
if case .skip = options.skippedTests(fileSystem: swiftCommandState.fileSystem) {
fallthrough
} else {
return []
}
case .regex, .specific, .skip:
// If old specifier `-s` option was used, emit deprecation notice.
if case .specific = options.testCaseSpecifier {
swiftCommandState.observabilityScope.emit(warning: "'--specifier' option is deprecated; use '--filter' instead")
}
// Find the tests we need to run.
let testSuites = try TestingSupport.getTestSuites(
in: testProducts,
swiftCommandState: swiftCommandState,
enableCodeCoverage: options.enableCodeCoverage,
shouldSkipBuilding: options.sharedOptions.shouldSkipBuilding,
experimentalTestOutput: options.enableExperimentalTestOutput,
sanitizers: globalOptions.build.sanitizers
)
let tests = try testSuites
.filteredTests(specifier: options.testCaseSpecifier)
.skippedTests(specifier: options.skippedTests(fileSystem: swiftCommandState.fileSystem))
// If there were no matches, emit a warning.
if tests.isEmpty {
swiftCommandState.observabilityScope.emit(.noMatchingTests)
}
return TestRunner.xctestArguments(forTestSpecifiers: tests.map(\.specifier))
}
}
/// Generate xUnit file if requested.
private func generateXUnitOutputIfRequested(
for testResults: [ParallelTestRunner.TestResult],
swiftCommandState: SwiftCommandState
) throws {
guard let xUnitOutput = options.xUnitOutput else {
return
}
let generator = XUnitGenerator(
fileSystem: swiftCommandState.fileSystem,
results: testResults
)
try generator.generate(at: xUnitOutput)
}
// MARK: - swift-testing
private func swiftTestingRun(_ swiftCommandState: SwiftCommandState) async throws {
let (productsBuildParameters, _) = try swiftCommandState.buildParametersForTest(options: self.options, library: .swiftTesting)
let testProducts = try buildTestsIfNeeded(swiftCommandState: swiftCommandState, library: .swiftTesting)
let additionalArguments = Array(CommandLine.arguments.dropFirst())
try await runTestProducts(
testProducts,
additionalArguments: additionalArguments,
productsBuildParameters: productsBuildParameters,
swiftCommandState: swiftCommandState,
library: .swiftTesting
)
}
// MARK: - Common implementation
public func run(_ swiftCommandState: SwiftCommandState) async throws {
do {
// Validate commands arguments
try self.validateArguments(observabilityScope: swiftCommandState.observabilityScope)
} catch {
swiftCommandState.observabilityScope.emit(error)
throw ExitCode.failure
}
if self.options.shouldPrintCodeCovPath {
try printCodeCovPath(swiftCommandState)
} else if self.options._deprecated_shouldListTests {
// backward compatibility 6/2022 for deprecation of flag into a subcommand
let command = try List.parse()
try command.run(swiftCommandState)
} else {
if try options.testLibraryOptions.enableSwiftTestingLibrarySupport(swiftCommandState: swiftCommandState) {
try await swiftTestingRun(swiftCommandState)
}
if options.testLibraryOptions.enableXCTestSupport {
try await xctestRun(swiftCommandState)
}
}
}
private func runTestProducts(
_ testProducts: [BuiltTestProduct],
additionalArguments: [String],
productsBuildParameters: BuildParameters,
swiftCommandState: SwiftCommandState,
library: BuildParameters.Testing.Library
) async throws {
// Clean out the code coverage directory that may contain stale
// profraw files from a previous run of the code coverage tool.
if self.options.enableCodeCoverage {
try swiftCommandState.fileSystem.removeFileTree(productsBuildParameters.codeCovPath)
}
let toolchain = try swiftCommandState.getTargetToolchain()
let testEnv = try TestingSupport.constructTestEnvironment(
toolchain: toolchain,
destinationBuildParameters: productsBuildParameters,
sanitizers: globalOptions.build.sanitizers,
library: library
)
let runner = TestRunner(
bundlePaths: testProducts.map { library == .xctest ? $0.bundlePath : $0.binaryPath },
additionalArguments: additionalArguments,
cancellator: swiftCommandState.cancellator,
toolchain: toolchain,
testEnv: testEnv,
observabilityScope: swiftCommandState.observabilityScope,
library: library
)
// Finally, run the tests.
let ranSuccessfully = runner.test(outputHandler: {
// command's result output goes on stdout
// ie "swift test" should output to stdout
print($0, terminator: "")
})
if !ranSuccessfully {
swiftCommandState.executionStatus = .failure
}
if self.options.enableCodeCoverage, ranSuccessfully {
try await processCodeCoverage(testProducts, swiftCommandState: swiftCommandState, library: library)
}
if self.options.enableExperimentalTestOutput, !ranSuccessfully {
try Self.handleTestOutput(productsBuildParameters: productsBuildParameters, packagePath: testProducts[0].packagePath)
}
}
private static func handleTestOutput(productsBuildParameters: BuildParameters, packagePath: AbsolutePath) throws {
guard localFileSystem.exists(productsBuildParameters.testOutputPath) else {
print("No existing test output found.")
return
}
let lines = try String(contentsOfFile: productsBuildParameters.testOutputPath.pathString).components(separatedBy: "\n")
let events = try lines.map { try JSONDecoder().decode(TestEventRecord.self, from: $0) }
let caseEvents = events.compactMap { $0.caseEvent }
let failureRecords = events.compactMap { $0.caseFailure }
let expectedFailures = failureRecords.filter({ $0.failureKind.isExpected == true })
let unexpectedFailures = failureRecords.filter { $0.failureKind.isExpected == false }.sorted(by: { lhs, rhs in
guard let lhsLocation = lhs.issue.sourceCodeContext.location, let rhsLocation = rhs.issue.sourceCodeContext.location else {
return lhs.description < rhs.description
}
if lhsLocation.file == rhsLocation.file {
return lhsLocation.line < rhsLocation.line
} else {
return lhsLocation.file < rhsLocation.file
}
}).map { $0.description(with: packagePath.pathString) }
let startedTests = caseEvents.filter { $0.event == .start }.count
let finishedTests = caseEvents.filter { $0.event == .finish }.count
let totalFailures = expectedFailures.count + unexpectedFailures.count
print("\nRan \(finishedTests)/\(startedTests) tests, \(totalFailures) failures (\(unexpectedFailures.count) unexpected):\n")
print("\(unexpectedFailures.joined(separator: "\n"))")
}
/// Processes the code coverage data and emits a json.
private func processCodeCoverage(
_ testProducts: [BuiltTestProduct],
swiftCommandState: SwiftCommandState,
library: BuildParameters.Testing.Library
) async throws {
let workspace = try swiftCommandState.getActiveWorkspace()
let root = try swiftCommandState.getWorkspaceRoot()
let rootManifests = try await workspace.loadRootManifests(
packages: root.packages,
observabilityScope: swiftCommandState.observabilityScope
)
guard let rootManifest = rootManifests.values.first else {
throw StringError("invalid manifests at \(root.packages)")
}
// Merge all the profraw files to produce a single profdata file.
try mergeCodeCovRawDataFiles(swiftCommandState: swiftCommandState, library: library)
let (productsBuildParameters, _) = try swiftCommandState.buildParametersForTest(options: self.options, library: library)
for product in testProducts {
// Export the codecov data as JSON.
let jsonPath = productsBuildParameters.codeCovAsJSONPath(packageName: rootManifest.displayName)
try exportCodeCovAsJSON(to: jsonPath, testBinary: product.binaryPath, swiftCommandState: swiftCommandState, library: library)
}
}
/// Merges all profraw profiles in codecoverage directory into default.profdata file.
private func mergeCodeCovRawDataFiles(swiftCommandState: SwiftCommandState, library: BuildParameters.Testing.Library) throws {
// Get the llvm-prof tool.
let llvmProf = try swiftCommandState.getTargetToolchain().getLLVMProf()
// Get the profraw files.
let (productsBuildParameters, _) = try swiftCommandState.buildParametersForTest(options: self.options, library: library)
let codeCovFiles = try swiftCommandState.fileSystem.getDirectoryContents(productsBuildParameters.codeCovPath)
// Construct arguments for invoking the llvm-prof tool.
var args = [llvmProf.pathString, "merge", "-sparse"]
for file in codeCovFiles {
let filePath = productsBuildParameters.codeCovPath.appending(component: file)
if filePath.extension == "profraw" {
args.append(filePath.pathString)
}
}
args += ["-o", productsBuildParameters.codeCovDataFile.pathString]
try TSCBasic.Process.checkNonZeroExit(arguments: args)
}
/// Exports profdata as a JSON file.
private func exportCodeCovAsJSON(
to path: AbsolutePath,
testBinary: AbsolutePath,
swiftCommandState: SwiftCommandState,
library: BuildParameters.Testing.Library
) throws {
// Export using the llvm-cov tool.
let llvmCov = try swiftCommandState.getTargetToolchain().getLLVMCov()
let (productsBuildParameters, _) = try swiftCommandState.buildParametersForTest(options: self.options, library: library)
let args = [
llvmCov.pathString,
"export",
"-instr-profile=\(productsBuildParameters.codeCovDataFile)",
testBinary.pathString
]
let result = try TSCBasic.Process.popen(arguments: args)
if result.exitStatus != .terminated(code: 0) {
let output = try result.utf8Output() + result.utf8stderrOutput()
throw StringError("Unable to export code coverage:\n \(output)")
}
try swiftCommandState.fileSystem.writeFileContents(path, bytes: ByteString(result.output.get()))
}
/// Builds the "test" target if enabled in options.
///
/// - Returns: The paths to the build test products.
private func buildTestsIfNeeded(
swiftCommandState: SwiftCommandState,
library: BuildParameters.Testing.Library
) throws -> [BuiltTestProduct] {
let (productsBuildParameters, toolsBuildParameters) = try swiftCommandState.buildParametersForTest(options: self.options, library: library)
return try Commands.buildTestsIfNeeded(
swiftCommandState: swiftCommandState,
productsBuildParameters: productsBuildParameters,
toolsBuildParameters: toolsBuildParameters,
testProduct: self.options.sharedOptions.testProduct
)
}
/// Private function that validates the commands arguments
///
/// - Throws: if a command argument is invalid
private func validateArguments(observabilityScope: ObservabilityScope) throws {
// Validation for --num-workers.
if let workers = options.numberOfWorkers {
// The --num-worker option should be called with --parallel. Since
// this option does not affect swift-testing at this time, we can
// effectively ignore that it defaults to enabling parallelization.
guard options.shouldRunInParallel else {
throw StringError("--num-workers must be used with --parallel")
}
guard workers > 0 else {
throw StringError("'--num-workers' must be greater than zero")
}
if !options.testLibraryOptions.enableXCTestSupport {
throw StringError("'--num-workers' is only supported when testing with XCTest")
}
}
if options._deprecated_shouldListTests {
observabilityScope.emit(warning: "'--list-tests' option is deprecated; use 'swift test list' instead")
}
}
public init() {}
}
extension SwiftTestCommand {
func printCodeCovPath(_ swiftCommandState: SwiftCommandState) throws {
let workspace = try swiftCommandState.getActiveWorkspace()
let root = try swiftCommandState.getWorkspaceRoot()
let rootManifests = try temp_await {
workspace.loadRootManifests(
packages: root.packages,
observabilityScope: swiftCommandState.observabilityScope,
completion: $0
)
}
guard let rootManifest = rootManifests.values.first else {
throw StringError("invalid manifests at \(root.packages)")
}
let (productsBuildParameters, _) = try swiftCommandState.buildParametersForTest(enableCodeCoverage: true, library: .xctest)
print(productsBuildParameters.codeCovAsJSONPath(packageName: rootManifest.displayName))
}
}
extension SwiftTestCommand {
struct Last: SwiftCommand {
@OptionGroup(visibility: .hidden)
var globalOptions: GlobalOptions
func run(_ swiftCommandState: SwiftCommandState) throws {
try SwiftTestCommand.handleTestOutput(
productsBuildParameters: try swiftCommandState.productsBuildParameters,
packagePath: localFileSystem.currentWorkingDirectory ?? .root // by definition runs in the current working directory
)
}
}
struct List: SwiftCommand {
static let configuration = CommandConfiguration(
abstract: "Lists test methods in specifier format"
)
@OptionGroup(visibility: .hidden)
var globalOptions: GlobalOptions
@OptionGroup()
var sharedOptions: SharedOptions
/// Which testing libraries to use (and any related options.)
@OptionGroup()
var testLibraryOptions: TestLibraryOptions
// for deprecated passthrough from SwiftTestTool (parse will fail otherwise)
@Flag(name: [.customLong("list-tests"), .customShort("l")], help: .hidden)
var _deprecated_passthrough: Bool = false
// MARK: - XCTest
private func xctestRun(_ swiftCommandState: SwiftCommandState) throws {
let (productsBuildParameters, toolsBuildParameters) = try swiftCommandState.buildParametersForTest(
enableCodeCoverage: false,
shouldSkipBuilding: sharedOptions.shouldSkipBuilding,
library: .xctest
)
let testProducts = try buildTestsIfNeeded(
swiftCommandState: swiftCommandState,
productsBuildParameters: productsBuildParameters,
toolsBuildParameters: toolsBuildParameters
)
let testSuites = try TestingSupport.getTestSuites(
in: testProducts,
swiftCommandState: swiftCommandState,
enableCodeCoverage: false,
shouldSkipBuilding: sharedOptions.shouldSkipBuilding,
experimentalTestOutput: false,
sanitizers: globalOptions.build.sanitizers
)
// Print the tests.
for test in testSuites.allTests {
print(test.specifier)
}
}
// MARK: - swift-testing
private func swiftTestingRun(_ swiftCommandState: SwiftCommandState) throws {
let (productsBuildParameters, toolsBuildParameters) = try swiftCommandState.buildParametersForTest(
enableCodeCoverage: false,
shouldSkipBuilding: sharedOptions.shouldSkipBuilding,
library: .swiftTesting
)
let testProducts = try buildTestsIfNeeded(
swiftCommandState: swiftCommandState,
productsBuildParameters: productsBuildParameters,
toolsBuildParameters: toolsBuildParameters
)
let toolchain = try swiftCommandState.getTargetToolchain()
let testEnv = try TestingSupport.constructTestEnvironment(
toolchain: toolchain,
destinationBuildParameters: productsBuildParameters,
sanitizers: globalOptions.build.sanitizers,
library: .swiftTesting
)
let additionalArguments = ["--list-tests"] + CommandLine.arguments.dropFirst()
let runner = TestRunner(
bundlePaths: testProducts.map(\.binaryPath),
additionalArguments: additionalArguments,
cancellator: swiftCommandState.cancellator,
toolchain: toolchain,
testEnv: testEnv,
observabilityScope: swiftCommandState.observabilityScope,
library: .swiftTesting
)
// Finally, run the tests.
let ranSuccessfully = runner.test(outputHandler: {
// command's result output goes on stdout
// ie "swift test" should output to stdout
print($0, terminator: "")
})
if !ranSuccessfully {
swiftCommandState.executionStatus = .failure
}
}
// MARK: - Common implementation
func run(_ swiftCommandState: SwiftCommandState) throws {
if try testLibraryOptions.enableSwiftTestingLibrarySupport(swiftCommandState: swiftCommandState) {
try swiftTestingRun(swiftCommandState)
}
if testLibraryOptions.enableXCTestSupport {
try xctestRun(swiftCommandState)
}
}
private func buildTestsIfNeeded(
swiftCommandState: SwiftCommandState,
productsBuildParameters: BuildParameters,
toolsBuildParameters: BuildParameters
) throws -> [BuiltTestProduct] {
return try Commands.buildTestsIfNeeded(
swiftCommandState: swiftCommandState,
productsBuildParameters: productsBuildParameters,
toolsBuildParameters: toolsBuildParameters,
testProduct: self.sharedOptions.testProduct
)
}
}
}
/// A structure representing an individual unit test.
struct UnitTest {
/// The path to the test product containing the test.
let productPath: AbsolutePath
/// The name of the unit test.
let name: String
/// The name of the test case.
let testCase: String
/// The specifier argument which can be passed to XCTest.
var specifier: String {
return testCase + "/" + name
}
}
/// A class to run tests on a XCTest binary.
///
/// Note: Executes the XCTest with inherited environment as it is convenient to pass sensitive
/// information like username, password etc to test cases via environment variables.
final class TestRunner {
/// Path to valid XCTest binaries.
private let bundlePaths: [AbsolutePath]
/// Arguments to pass to the test runner process, if any.
private let additionalArguments: [String]
private let cancellator: Cancellator
// The toolchain to use.
private let toolchain: UserToolchain
private let testEnv: [String: String]
/// ObservabilityScope to emit diagnostics.
private let observabilityScope: ObservabilityScope
/// Which testing library to use with this test run.
private let library: BuildParameters.Testing.Library
/// Get the arguments used on this platform to pass test specifiers to XCTest.
static func xctestArguments<S>(forTestSpecifiers testSpecifiers: S) -> [String] where S: Collection, S.Element == String {
let testSpecifier: String
if testSpecifiers.isEmpty {
testSpecifier = "''"
} else {
testSpecifier = testSpecifiers.joined(separator: ",")
}
#if os(macOS)
return ["-XCTest", testSpecifier]
#else
return [testSpecifier]
#endif
}
/// Creates an instance of TestRunner.
///
/// - Parameters:
/// - testPaths: Paths to valid XCTest binaries.
/// - additionalArguments: Arguments to pass to the test runner process.
init(
bundlePaths: [AbsolutePath],
additionalArguments: [String],
cancellator: Cancellator,
toolchain: UserToolchain,
testEnv: [String: String],
observabilityScope: ObservabilityScope,
library: BuildParameters.Testing.Library
) {
self.bundlePaths = bundlePaths
self.additionalArguments = additionalArguments
self.cancellator = cancellator
self.toolchain = toolchain
self.testEnv = testEnv
self.observabilityScope = observabilityScope.makeChildScope(description: "Test Runner")
self.library = library
}
/// Executes and returns execution status. Prints test output on standard streams if requested
/// - Returns: Boolean indicating if test execution returned code 0, and the output stream result
public func test(outputHandler: @escaping (String) -> Void) -> Bool {
var success = true
for path in self.bundlePaths {
let testSuccess = self.test(at: path, outputHandler: outputHandler)
success = success && testSuccess
}
return success
}
/// Constructs arguments to execute XCTest.
private func args(forTestAt testPath: AbsolutePath) throws -> [String] {
var args: [String] = []
#if os(macOS)
if library == .xctest {
guard let xctestPath = self.toolchain.xctestPath else {
throw TestError.xcodeNotInstalled
}
args = [xctestPath.pathString]
args += additionalArguments
args += [testPath.pathString]
return args
}
#endif
args += [testPath.description]
args += additionalArguments
return args
}
private func test(at path: AbsolutePath, outputHandler: @escaping (String) -> Void) -> Bool {
let testObservabilityScope = self.observabilityScope.makeChildScope(description: "running test at \(path)")
do {
let outputHandler = { (bytes: [UInt8]) in
if let output = String(bytes: bytes, encoding: .utf8) {
outputHandler(output)
}
}
let outputRedirection = Process.OutputRedirection.stream(
stdout: outputHandler,
stderr: outputHandler
)
let process = TSCBasic.Process(arguments: try args(forTestAt: path), environment: self.testEnv, outputRedirection: outputRedirection)
guard let terminationKey = self.cancellator.register(process) else {
return false // terminating
}
defer { self.cancellator.deregister(terminationKey) }
try process.launch()
let result = try process.waitUntilExit()
switch result.exitStatus {
case .terminated(code: 0):
return true
#if !os(Windows)
case .signalled(let signal) where ![SIGINT, SIGKILL, SIGTERM].contains(signal):
testObservabilityScope.emit(error: "Exited with unexpected signal code \(signal)")
return false
#endif
default:
return false
}
} catch {
testObservabilityScope.emit(error)
return false
}
}
}
/// A class to run tests in parallel.
final class ParallelTestRunner {
/// An enum representing result of a unit test execution.
struct TestResult {
var unitTest: UnitTest
var output: String
var success: Bool
var duration: DispatchTimeInterval
}
/// Path to XCTest binaries.
private let bundlePaths: [AbsolutePath]
/// The queue containing list of tests to run (producer).
private let pendingTests = SynchronizedQueue<UnitTest?>()
/// The queue containing tests which are finished running.
private let finishedTests = SynchronizedQueue<TestResult?>()
/// Instance of a terminal progress animation.
private let progressAnimation: ProgressAnimationProtocol
/// Number of tests that will be executed.
private var numTests = 0
/// Number of the current tests that has been executed.
private var numCurrentTest = 0
/// True if all tests executed successfully.
private(set) var ranSuccessfully = true
private let cancellator: Cancellator
private let toolchain: UserToolchain
private let buildOptions: BuildOptions
private let productsBuildParameters: BuildParameters
/// Number of tests to execute in parallel.
private let numJobs: Int
/// Whether to display output from successful tests.
private let shouldOutputSuccess: Bool
/// ObservabilityScope to emit diagnostics.
private let observabilityScope: ObservabilityScope
init(
bundlePaths: [AbsolutePath],
cancellator: Cancellator,
toolchain: UserToolchain,
numJobs: Int,
buildOptions: BuildOptions,
productsBuildParameters: BuildParameters,
shouldOutputSuccess: Bool,
observabilityScope: ObservabilityScope
) {
self.bundlePaths = bundlePaths
self.cancellator = cancellator
self.toolchain = toolchain
self.numJobs = numJobs
self.shouldOutputSuccess = shouldOutputSuccess
self.observabilityScope = observabilityScope.makeChildScope(description: "Parallel Test Runner")
// command's result output goes on stdout
// ie "swift test" should output to stdout
if ProcessEnv.block["SWIFTPM_TEST_RUNNER_PROGRESS_BAR"] == "lit" {
self.progressAnimation = ProgressAnimation.percent(
stream: TSCBasic.stdoutStream,
verbose: false,
header: "Testing:"
)
} else {
self.progressAnimation = ProgressAnimation.ninja(
stream: TSCBasic.stdoutStream,
verbose: false
)
}
self.buildOptions = buildOptions
self.productsBuildParameters = productsBuildParameters
assert(numJobs > 0, "num jobs should be > 0")
}
/// Updates the progress bar status.
private func updateProgress(for test: UnitTest) {
numCurrentTest += 1
progressAnimation.update(step: numCurrentTest, total: numTests, text: "Testing \(test.specifier)")
}
private func enqueueTests(_ tests: [UnitTest]) throws {
// Enqueue all the tests.