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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504
|
//===----------------------------------------------------------------------===//
//
// 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 Basics.AsyncProcess
import var TSCBasic.stdoutStream
import class TSCBasic.SynchronizedQueue
import class TSCBasic.Thread
#if os(Windows)
import WinSDK // for ERROR_NOT_FOUND
#endif
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 TestEventStreamOptions: ParsableArguments {
/// Legacy equivalent of ``configurationPath``.
@Option(name: .customLong("experimental-configuration-path"),
help: .private)
var experimentalConfigurationPath: AbsolutePath?
/// Path where swift-testing's JSON configuration should be read.
@Option(name: .customLong("configuration-path"),
help: .hidden)
var configurationPath: AbsolutePath?
/// Legacy equivalent of ``eventStreamOutputPath``.
@Option(name: .customLong("experimental-event-stream-output"),
help: .private)
var experimentalEventStreamOutputPath: AbsolutePath?
/// Path where swift-testing's JSON output should be written.
@Option(name: .customLong("event-stream-output-path"),
help: .hidden)
var eventStreamOutputPath: AbsolutePath?
/// Legacy equivalent of ``eventStreamVersion``.
@Option(name: .customLong("experimental-event-stream-version"),
help: .private)
var experimentalEventStreamVersion: Int?
/// The schema version of swift-testing's JSON input/output.
@Option(name: .customLong("event-stream-version"),
help: .hidden)
var eventStreamVersion: Int?
}
struct TestCommandOptions: ParsableArguments {
@OptionGroup()
var globalOptions: GlobalOptions
@OptionGroup()
var sharedOptions: SharedOptions
/// Which testing libraries to use (and any related options.)
@OptionGroup()
var testLibraryOptions: TestLibraryOptions
/// Options for Swift Testing's event stream.
@OptionGroup()
var testEventStreamOptions: TestEventStreamOptions
/// 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
}
}
/// 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
private func run(_ swiftCommandState: SwiftCommandState, buildParameters: BuildParameters, testProducts: [BuiltTestProduct]) async throws {
// Remove test output from prior runs and validate priors.
if self.options.enableExperimentalTestOutput && buildParameters.triple.supportsTestSummary {
_ = try? localFileSystem.removeFileTree(buildParameters.testOutputPath)
}
var results = [TestRunner.Result]()
// Run XCTest.
if options.testLibraryOptions.isEnabled(.xctest, swiftCommandState: swiftCommandState) {
// Validate XCTest is available on Darwin-based systems. If it's not available and we're hitting this code
// path, that means the developer must have explicitly passed --enable-xctest (or the toolchain is
// corrupt, I suppose.)
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
}
if !self.options.shouldRunInParallel {
let (xctestArgs, testCount) = try xctestArgs(for: testProducts, swiftCommandState: swiftCommandState)
let result = try await runTestProducts(
testProducts,
additionalArguments: xctestArgs,
productsBuildParameters: buildParameters,
swiftCommandState: swiftCommandState,
library: .xctest
)
if result == .success, testCount == 0 {
results.append(.noMatchingTests)
} else {
results.append(result)
}
} 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))
let result: TestRunner.Result
let testResults: [ParallelTestRunner.TestResult]
if tests.isEmpty {
testResults = []
result = .noMatchingTests
} else {
// 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: buildParameters,
shouldOutputSuccess: swiftCommandState.logLevel <= .info,
observabilityScope: swiftCommandState.observabilityScope
)
testResults = try runner.run(tests)
result = runner.ranSuccessfully ? .success : .failure
}
try generateXUnitOutputIfRequested(for: testResults, swiftCommandState: swiftCommandState)
results.append(result)
}
}
// Run Swift Testing (parallel or not, it has a single entry point.)
if options.testLibraryOptions.isEnabled(.swiftTesting, swiftCommandState: swiftCommandState) {
lazy var testEntryPointPath = testProducts.lazy.compactMap(\.testEntryPointPath).first
if options.testLibraryOptions.isExplicitlyEnabled(.swiftTesting, swiftCommandState: swiftCommandState) || testEntryPointPath == nil {
results.append(
try await runTestProducts(
testProducts,
additionalArguments: [],
productsBuildParameters: buildParameters,
swiftCommandState: swiftCommandState,
library: .swiftTesting
)
)
} else if let testEntryPointPath {
// Cannot run Swift Testing because an entry point file was used and the developer
// didn't explicitly enable Swift Testing.
swiftCommandState.observabilityScope.emit(
debug: "Skipping automatic Swift Testing invocation because a test entry point path is present: \(testEntryPointPath)"
)
}
}
switch results.reduce() {
case .success:
// Nothing to do here.
break
case .failure:
swiftCommandState.executionStatus = .failure
if self.options.enableExperimentalTestOutput {
try Self.handleTestOutput(productsBuildParameters: buildParameters, packagePath: testProducts[0].packagePath)
}
case .noMatchingTests:
swiftCommandState.observabilityScope.emit(.noMatchingTests)
}
}
private func xctestArgs(for testProducts: [BuiltTestProduct], swiftCommandState: SwiftCommandState) throws -> (arguments: [String], testCount: Int?) {
switch options.testCaseSpecifier {
case .none:
if case .skip = options.skippedTests(fileSystem: swiftCommandState.fileSystem) {
fallthrough
} else {
return ([], nil)
}
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))
return (TestRunner.xctestArguments(forTestSpecifiers: tests.map(\.specifier)), tests.count)
}
}
/// 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: - Common implementation
public func run(_ swiftCommandState: SwiftCommandState) async throws {
do {
// Validate commands arguments
try self.validateArguments(swiftCommandState: swiftCommandState)
} 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 {
let (productsBuildParameters, _) = try swiftCommandState.buildParametersForTest(options: self.options)
let testProducts = try buildTestsIfNeeded(swiftCommandState: swiftCommandState)
// 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)
}
try await run(swiftCommandState, buildParameters: productsBuildParameters, testProducts: testProducts)
// process code Coverage if request
if self.options.enableCodeCoverage, swiftCommandState.executionStatus != .failure {
try await processCodeCoverage(testProducts, swiftCommandState: swiftCommandState)
}
}
}
private func runTestProducts(
_ testProducts: [BuiltTestProduct],
additionalArguments: [String],
productsBuildParameters: BuildParameters,
swiftCommandState: SwiftCommandState,
library: BuildParameters.Testing.Library
) async throws -> TestRunner.Result {
// Pass through all arguments from the command line to Swift Testing.
var additionalArguments = additionalArguments
if library == .swiftTesting {
// Reconstruct the arguments list. If an xUnit path was specified, remove it.
var commandLineArguments = [String]()
var originalCommandLineArguments = CommandLine.arguments.dropFirst().makeIterator()
while let arg = originalCommandLineArguments.next() {
if arg == "--xunit-output" {
_ = originalCommandLineArguments.next()
} else {
commandLineArguments.append(arg)
}
}
additionalArguments += commandLineArguments
if var xunitPath = options.xUnitOutput, options.testLibraryOptions.isEnabled(.xctest, swiftCommandState: swiftCommandState) {
// We are running Swift Testing, XCTest is also running in this session, and an xUnit path
// was specified. Make sure we don't stomp on XCTest's XML output by having Swift Testing
// write to a different path.
var xunitFileName = "\(xunitPath.basenameWithoutExt)-swift-testing"
if let ext = xunitPath.extension {
xunitFileName = "\(xunitFileName).\(ext)"
}
xunitPath = xunitPath.parentDirectory.appending(xunitFileName)
additionalArguments += ["--xunit-output", xunitPath.pathString]
}
}
let toolchain = try swiftCommandState.getTargetToolchain()
let testEnv = try TestingSupport.constructTestEnvironment(
toolchain: toolchain,
buildParameters: productsBuildParameters,
sanitizers: globalOptions.build.sanitizers,
library: library
)
let runnerPaths: [AbsolutePath] = switch library {
case .xctest:
testProducts.map(\.bundlePath)
case .swiftTesting:
testProducts.map(\.binaryPath)
}
let runner = TestRunner(
bundlePaths: runnerPaths,
additionalArguments: additionalArguments,
cancellator: swiftCommandState.cancellator,
toolchain: toolchain,
testEnv: testEnv,
observabilityScope: swiftCommandState.observabilityScope,
library: library
)
// Finally, run the tests.
return runner.test(outputHandler: {
// command's result output goes on stdout
// ie "swift test" should output to stdout
print($0, terminator: "")
})
}
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
) 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)
let (productsBuildParameters, _) = try swiftCommandState.buildParametersForTest(options: self.options)
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)
}
}
/// Merges all profraw profiles in codecoverage directory into default.profdata file.
private func mergeCodeCovRawDataFiles(swiftCommandState: SwiftCommandState) throws {
// Get the llvm-prof tool.
let llvmProf = try swiftCommandState.getTargetToolchain().getLLVMProf()
// Get the profraw files.
let (productsBuildParameters, _) = try swiftCommandState.buildParametersForTest(options: self.options)
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 AsyncProcess.checkNonZeroExit(arguments: args)
}
/// Exports profdata as a JSON file.
private func exportCodeCovAsJSON(
to path: AbsolutePath,
testBinary: AbsolutePath,
swiftCommandState: SwiftCommandState
) throws {
// Export using the llvm-cov tool.
let llvmCov = try swiftCommandState.getTargetToolchain().getLLVMCov()
let (productsBuildParameters, _) = try swiftCommandState.buildParametersForTest(options: self.options)
let args = [
llvmCov.pathString,
"export",
"-instr-profile=\(productsBuildParameters.codeCovDataFile)",
testBinary.pathString
]
let result = try AsyncProcess.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
) throws -> [BuiltTestProduct] {
let (productsBuildParameters, toolsBuildParameters) = try swiftCommandState.buildParametersForTest(options: self.options)
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(swiftCommandState: SwiftCommandState) 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")
}
guard options.testLibraryOptions.isEnabled(.xctest, swiftCommandState: swiftCommandState) else {
throw StringError("'--num-workers' is only supported when testing with XCTest")
}
}
if options._deprecated_shouldListTests {
swiftCommandState.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)
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
/// Options for Swift Testing's event stream.
@OptionGroup()
var testEventStreamOptions: TestEventStreamOptions
// for deprecated passthrough from SwiftTestTool (parse will fail otherwise)
@Flag(name: [.customLong("list-tests"), .customShort("l")], help: .hidden)
var _deprecated_passthrough: Bool = false
func run(_ swiftCommandState: SwiftCommandState) throws {
let (productsBuildParameters, toolsBuildParameters) = try swiftCommandState.buildParametersForTest(
enableCodeCoverage: false,
shouldSkipBuilding: sharedOptions.shouldSkipBuilding
)
let testProducts = try buildTestsIfNeeded(
swiftCommandState: swiftCommandState,
productsBuildParameters: productsBuildParameters,
toolsBuildParameters: toolsBuildParameters
)
let toolchain = try swiftCommandState.getTargetToolchain()
let testEnv = try TestingSupport.constructTestEnvironment(
toolchain: toolchain,
buildParameters: productsBuildParameters,
sanitizers: globalOptions.build.sanitizers,
library: .swiftTesting
)
if testLibraryOptions.isEnabled(.xctest, swiftCommandState: swiftCommandState) {
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)
}
}
if testLibraryOptions.isEnabled(.swiftTesting, swiftCommandState: swiftCommandState) {
lazy var testEntryPointPath = testProducts.lazy.compactMap(\.testEntryPointPath).first
if testLibraryOptions.isExplicitlyEnabled(.swiftTesting, swiftCommandState: swiftCommandState) || testEntryPointPath == nil {
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 result = runner.test(outputHandler: {
// command's result output goes on stdout
// ie "swift test" should output to stdout
print($0, terminator: "")
})
if result == .failure {
swiftCommandState.executionStatus = .failure
}
} else if let testEntryPointPath {
// Cannot run Swift Testing because an entry point file was used and the developer
// didn't explicitly enable Swift Testing.
swiftCommandState.observabilityScope.emit(
debug: "Skipping automatic Swift Testing invocation (list) because a test entry point path is present: \(testEntryPointPath)"
)
}
}
}
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: Environment
/// 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: Environment,
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
}
/// The result of running the test(s).
enum Result: Equatable {
/// The test(s) ran successfully.
case success
/// The test(s) failed.
case failure
/// There were no matching tests to run.
///
/// XCTest does not report this result. It is used by Swift Testing only.
case noMatchingTests
}
/// Executes and returns execution status. Prints test output on standard streams if requested
/// - Returns: Result of spawning and running the test process, and the output stream result
func test(outputHandler: @escaping (String) -> Void) -> Result {
var results = [Result]()
for path in self.bundlePaths {
let testSuccess = self.test(at: path, outputHandler: outputHandler)
results.append(testSuccess)
}
return results.reduce()
}
/// Constructs arguments to execute XCTest.
private func args(forTestAt testPath: AbsolutePath) throws -> [String] {
var args: [String] = []
#if os(macOS)
switch library {
case .xctest:
guard let xctestPath = self.toolchain.xctestPath else {
throw TestError.xcodeNotInstalled
}
args += [xctestPath.pathString]
case .swiftTesting:
let helper = try self.toolchain.getSwiftTestingHelper()
args += [helper.pathString, "--test-bundle-path", testPath.pathString]
}
args += additionalArguments
args += [testPath.pathString]
#else
args += [testPath.pathString]
args += additionalArguments
#endif
if library == .swiftTesting {
// HACK: tell the test bundle/executable that we want to run Swift Testing, not XCTest.
// XCTest doesn't understand this argument (yet), so don't pass it there.
args += ["--testing-library", "swift-testing"]
}
return args
}
private func test(at path: AbsolutePath, outputHandler: @escaping (String) -> Void) -> Result {
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 = AsyncProcess.OutputRedirection.stream(
stdout: outputHandler,
stderr: outputHandler
)
let process = AsyncProcess(arguments: try args(forTestAt: path), environment: self.testEnv, outputRedirection: outputRedirection)
guard let terminationKey = self.cancellator.register(process) else {
return .failure // terminating
}
defer { self.cancellator.deregister(terminationKey) }
try process.launch()
let result = try process.waitUntilExit()
switch result.exitStatus {
case .terminated(code: 0):
return .success
case .terminated(code: EXIT_NO_TESTS_FOUND) where library == .swiftTesting:
return .noMatchingTests
#if !os(Windows)
case .signalled(let signal) where ![SIGINT, SIGKILL, SIGTERM].contains(signal):
testObservabilityScope.emit(error: "Exited with unexpected signal code \(signal)")
return .failure
#endif
default:
return .failure
}
} catch {
testObservabilityScope.emit(error)
return .failure
}
}
}
extension Collection where Element == TestRunner.Result {
/// Reduce all results in this collection into a single result.
func reduce() -> Element {
if contains(.failure) {
return .failure
} else if isEmpty || contains(.success) {
return .success
} else {
return .noMatchingTests
}
}
}
/// 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 Environment.current["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.
for test in tests {
pendingTests.enqueue(test)
}
self.numTests = tests.count
self.numCurrentTest = 0
// Enqueue the sentinels, we stop a thread when it encounters a sentinel in the queue.
for _ in 0..<numJobs {
pendingTests.enqueue(nil)
}
}
/// Executes the tests spawning parallel workers. Blocks calling thread until all workers are finished.
func run(_ tests: [UnitTest]) throws -> [TestResult] {
assert(!tests.isEmpty, "There should be at least one test to execute.")
let testEnv = try TestingSupport.constructTestEnvironment(
toolchain: self.toolchain,
buildParameters: self.productsBuildParameters,
sanitizers: self.buildOptions.sanitizers,
library: .xctest // swift-testing does not use ParallelTestRunner
)
// Enqueue all the tests.
try enqueueTests(tests)
// Create the worker threads.
let workers: [Thread] = (0..<numJobs).map({ _ in
let thread = Thread {
// Dequeue a specifier and run it till we encounter nil.
while let test = self.pendingTests.dequeue() {
let additionalArguments = TestRunner.xctestArguments(forTestSpecifiers: CollectionOfOne(test.specifier))
let testRunner = TestRunner(
bundlePaths: [test.productPath],
additionalArguments: additionalArguments,
cancellator: self.cancellator,
toolchain: self.toolchain,
testEnv: testEnv,
observabilityScope: self.observabilityScope,
library: .xctest // swift-testing does not use ParallelTestRunner
)
var output = ""
let outputLock = NSLock()
let start = DispatchTime.now()
let result = testRunner.test(outputHandler: { _output in outputLock.withLock{ output += _output }})
let duration = start.distance(to: .now())
if result == .failure {
self.ranSuccessfully = false
}
self.finishedTests.enqueue(TestResult(
unitTest: test,
output: output,
success: result != .failure,
duration: duration
))
}
}
thread.start()
return thread
})
// List of processed tests.
let processedTests = ThreadSafeArrayStore<TestResult>()
// Report (consume) the tests which have finished running.
while let result = finishedTests.dequeue() {
updateProgress(for: result.unitTest)
// Store the result.
processedTests.append(result)
// We can't enqueue a sentinel into finished tests queue because we won't know
// which test is last one so exit this when all the tests have finished running.
if numCurrentTest == numTests {
break
}
}
// Wait till all threads finish execution.
workers.forEach { $0.join() }
// Report the completion.
progressAnimation.complete(success: processedTests.get().contains(where: { !$0.success }))
// Print test results.
for test in processedTests.get() {
if (!test.success || shouldOutputSuccess) && !productsBuildParameters.testingParameters.experimentalTestOutput {
// command's result output goes on stdout
// ie "swift test" should output to stdout
print(test.output)
}
}
return processedTests.get()
}
}
/// A struct to hold the XCTestSuite data.
struct TestSuite {
/// A struct to hold a XCTestCase data.
struct TestCase {
/// Name of the test case.
let name: String
/// Array of test methods in this test case.
let tests: [String]
}
/// The name of the test suite.
let name: String
/// Array of test cases in this test suite.
let tests: [TestCase]
/// Parses a JSON String to array of TestSuite.
///
/// - Parameters:
/// - jsonString: JSON string to be parsed.
/// - context: the commandline which produced the given JSON.
///
/// - Throws: JSONDecodingError, TestError
///
/// - Returns: Array of TestSuite.
static func parse(jsonString: String, context: String) throws -> [TestSuite] {
let json: JSON
do {
json = try JSON(string: jsonString)
} catch {
throw TestError.invalidListTestJSONData(context: context, underlyingError: error)
}
return try TestSuite.parse(json: json, context: context)
}
/// Parses the JSON object into array of TestSuite.
///
/// - Parameters:
/// - json: An object of JSON.
/// - context: the commandline which produced the given JSON.
///
/// - Throws: TestError
///
/// - Returns: Array of TestSuite.
static func parse(json: JSON, context: String) throws -> [TestSuite] {
guard case let .dictionary(contents) = json,
case let .array(testSuites)? = contents["tests"] else {
throw TestError.invalidListTestJSONData(context: context)
}
return try testSuites.map({ testSuite in
guard case let .dictionary(testSuiteData) = testSuite,
case let .string(name)? = testSuiteData["name"],
case let .array(allTestsData)? = testSuiteData["tests"] else {
throw TestError.invalidListTestJSONData(context: context)
}
let testCases: [TestSuite.TestCase] = try allTestsData.map({ testCase in
guard case let .dictionary(testCaseData) = testCase,
case let .string(name)? = testCaseData["name"],
case let .array(tests)? = testCaseData["tests"] else {
throw TestError.invalidListTestJSONData(context: context)
}
let testMethods: [String] = try tests.map({ test in
guard case let .dictionary(testData) = test,
case let .string(testMethod)? = testData["name"] else {
throw TestError.invalidListTestJSONData(context: context)
}
return testMethod
})
return TestSuite.TestCase(name: name, tests: testMethods)
})
return TestSuite(name: name, tests: testCases)
})
}
}
fileprivate extension Dictionary where Key == AbsolutePath, Value == [TestSuite] {
/// Returns all the unit tests of the test suites.
var allTests: [UnitTest] {
var allTests: [UnitTest] = []
for (bundlePath, testSuites) in self {
for testSuite in testSuites {
for testCase in testSuite.tests {
for test in testCase.tests {
allTests.append(UnitTest(productPath: bundlePath, name: test, testCase: testCase.name))
}
}
}
}
return allTests
}
/// Return tests matching the provided specifier
func filteredTests(specifier: TestCaseSpecifier) throws -> [UnitTest] {
switch specifier {
case .none:
return allTests
case .regex(let patterns):
return allTests.filter({ test in
patterns.contains { pattern in
test.specifier.range(of: pattern,
options: .regularExpression) != nil
}
})
case .specific(let name):
return allTests.filter{ $0.specifier == name }
case .skip:
throw InternalError("Tests to skip should never have been passed here.")
}
}
}
fileprivate extension Array where Element == UnitTest {
/// Skip tests matching the provided specifier
func skippedTests(specifier: TestCaseSpecifier) throws -> [UnitTest] {
switch specifier {
case .none:
return self
case .skip(let skippedTests):
var result = self
for skippedTest in skippedTests {
result = result.filter{
$0.specifier.range(of: skippedTest, options: .regularExpression) == nil
}
}
return result
case .regex, .specific:
throw InternalError("Tests to filter should never have been passed here.")
}
}
}
/// xUnit XML file generator for a swift-test run.
final class XUnitGenerator {
typealias TestResult = ParallelTestRunner.TestResult
/// The file system to use
let fileSystem: FileSystem
/// The test results.
let results: [TestResult]
init(fileSystem: FileSystem, results: [TestResult]) {
self.fileSystem = fileSystem
self.results = results
}
/// Generate the file at the given path.
func generate(at path: AbsolutePath) throws {
var content =
"""
<?xml version="1.0" encoding="UTF-8"?>
<testsuites>
"""
// Get the failure count.
let failures = results.filter({ !$0.success }).count
let duration = results.compactMap({ $0.duration.timeInterval() }).reduce(0.0, +)
// We need better output reporting from XCTest.
content +=
"""
<testsuite name="TestResults" errors="0" tests="\(results.count)" failures="\(failures)" time="\(duration)">
"""
// Generate a testcase entry for each result.
//
// FIXME: This is very minimal right now. We should allow including test output etc.
for result in results {
let test = result.unitTest
let duration = result.duration.timeInterval() ?? 0.0
content +=
"""
<testcase classname="\(test.testCase)" name="\(test.name)" time="\(duration)">
"""
if !result.success {
content += "<failure message=\"failed\"></failure>\n"
}
content += "</testcase>\n"
}
content +=
"""
</testsuite>
</testsuites>
"""
try self.fileSystem.writeFileContents(path, string: content)
}
}
extension SwiftCommandState {
func buildParametersForTest(
options: TestCommandOptions
) throws -> (productsBuildParameters: BuildParameters, toolsBuildParameters: BuildParameters) {
try self.buildParametersForTest(
enableCodeCoverage: options.enableCodeCoverage,
enableTestability: options.enableTestableImports,
shouldSkipBuilding: options.sharedOptions.shouldSkipBuilding,
experimentalTestOutput: options.enableExperimentalTestOutput
)
}
}
extension TestCommandOptions {
func skippedTests(fileSystem: FileSystem) -> TestCaseSpecifier {
// TODO: Remove this once the environment variable is no longer used.
if let override = skippedTestsOverride(fileSystem: fileSystem) {
return override
}
return self._testCaseSkip.isEmpty
? .none
: .skip(self._testCaseSkip)
}
/// Returns the test case specifier if overridden in the env.
private func skippedTestsOverride(fileSystem: FileSystem) -> TestCaseSpecifier? {
guard let override = Environment.current["_SWIFTPM_SKIP_TESTS_LIST"] else {
return nil
}
do {
let skipTests: [String.SubSequence]
// Read from the file if it exists.
if let path = try? AbsolutePath(validating: override), fileSystem.exists(path) {
let contents: String = try fileSystem.readFileContents(path)
skipTests = contents.split(separator: "\n", omittingEmptySubsequences: true)
} else {
// Otherwise, read the env variable.
skipTests = override.split(separator: ":", omittingEmptySubsequences: true)
}
return .skip(skipTests.map(String.init))
} catch {
// FIXME: We should surface errors from here.
}
return nil
}
}
extension BuildParameters {
fileprivate func codeCovAsJSONPath(packageName: String) -> AbsolutePath {
return self.codeCovPath.appending(component: packageName + ".json")
}
}
private extension Basics.Diagnostic {
static var noMatchingTests: Self {
.warning("No matching test cases were run")
}
}
/// The exit code returned to Swift Package Manager by Swift Testing when no
/// tests matched the inputs specified by the developer (or, for the case of
/// `swift test list`, when no tests were found.)
///
/// Because Swift Package Manager does not directly link to the testing library,
/// it duplicates the definition of this constant in its own source. Any changes
/// to this constant in either package must be mirrored in the other.
private var EXIT_NO_TESTS_FOUND: CInt {
#if os(macOS) || os(Linux)
EX_UNAVAILABLE
#elseif os(Windows)
ERROR_NOT_FOUND
#else
#warning("Platform-specific implementation missing: value for EXIT_NO_TESTS_FOUND unavailable")
return 2 // We're assuming that EXIT_SUCCESS = 0 and EXIT_FAILURE = 1.
#endif
}
/// Builds the "test" target if enabled in options.
///
/// - Returns: The paths to the build test products.
private func buildTestsIfNeeded(
swiftCommandState: SwiftCommandState,
productsBuildParameters: BuildParameters,
toolsBuildParameters: BuildParameters,
testProduct: String?
) throws -> [BuiltTestProduct] {
let buildSystem = try swiftCommandState.createBuildSystem(
productsBuildParameters: productsBuildParameters,
toolsBuildParameters: toolsBuildParameters
)
let subset: BuildSubset = if let testProduct {
.product(testProduct)
} else {
.allIncludingTests
}
try buildSystem.build(subset: subset)
// Find the test product.
let testProducts = buildSystem.builtTestProducts
guard !testProducts.isEmpty else {
if let testProduct {
throw TestError.productIsNotTest(productName: testProduct)
} else {
throw TestError.testsNotFound
}
}
if let testProductName = testProduct {
guard let selectedTestProduct = testProducts.first(where: { $0.productName == testProductName }) else {
throw TestError.testProductNotFound(productName: testProductName)
}
return [selectedTestProduct]
} else {
return testProducts
}
}
|