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
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift open source project
//
// Copyright (c) 2022 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 Basics
import CoreCommands
import PackageModel
import SPMBuildCore
import Workspace
import class Basics.AsyncProcess
import var TSCBasic.stderrStream
import var TSCBasic.stdoutStream
import func TSCBasic.withTemporaryFile
/// Internal helper functionality for the SwiftTestTool command and for the
/// plugin support.
///
/// Note: In the long term this should be factored into a reusable module that
/// can run and report results on tests from both CLI and libSwiftPM API.
enum TestingSupport {
/// Locates XCTestHelper tool inside the libexec directory and bin directory.
/// Note: It is a fatalError if we are not able to locate the tool.
///
/// - Returns: Path to XCTestHelper tool.
static func xctestHelperPath(swiftCommandState: SwiftCommandState) throws -> AbsolutePath {
var triedPaths = [AbsolutePath]()
func findXCTestHelper(swiftBuildPath: AbsolutePath) -> AbsolutePath? {
// XCTestHelper tool is installed in libexec.
let maybePath = swiftBuildPath.parentDirectory.parentDirectory.appending(
components: "libexec", "swift", "pm", "swiftpm-xctest-helper"
)
if swiftCommandState.fileSystem.isFile(maybePath) {
return maybePath
} else {
triedPaths.append(maybePath)
return nil
}
}
if let firstCLIArgument = CommandLine.arguments.first {
let runningSwiftBuildPath = try AbsolutePath(validating: firstCLIArgument, relativeTo: swiftCommandState.originalWorkingDirectory)
if let xctestHelperPath = findXCTestHelper(swiftBuildPath: runningSwiftBuildPath) {
return xctestHelperPath
}
}
// This will be true during swiftpm development or when using swift.org toolchains.
let xcodePath = try AsyncProcess.checkNonZeroExit(args: "/usr/bin/xcode-select", "--print-path").spm_chomp()
let installedSwiftBuildPath = try AsyncProcess.checkNonZeroExit(
args: "/usr/bin/xcrun", "--find", "swift-build",
environment: ["DEVELOPER_DIR": xcodePath]
).spm_chomp()
if let xctestHelperPath = findXCTestHelper(swiftBuildPath: try AbsolutePath(validating: installedSwiftBuildPath)) {
return xctestHelperPath
}
throw InternalError("XCTestHelper binary not found, tried \(triedPaths.map { $0.pathString }.joined(separator: ", "))")
}
static func getTestSuites(
in testProducts: [BuiltTestProduct],
swiftCommandState: SwiftCommandState,
enableCodeCoverage: Bool,
shouldSkipBuilding: Bool,
experimentalTestOutput: Bool,
sanitizers: [Sanitizer]
) throws -> [AbsolutePath: [TestSuite]] {
let testSuitesByProduct = try testProducts
.map {(
$0.bundlePath,
try Self.getTestSuites(
fromTestAt: $0.bundlePath,
swiftCommandState: swiftCommandState,
enableCodeCoverage: enableCodeCoverage,
shouldSkipBuilding: shouldSkipBuilding,
experimentalTestOutput: experimentalTestOutput,
sanitizers: sanitizers
)
)}
return try Dictionary(throwingUniqueKeysWithValues: testSuitesByProduct)
}
/// Runs the corresponding tool to get tests JSON and create TestSuite array.
/// On macOS, we use the swiftpm-xctest-helper tool bundled with swiftpm.
/// On Linux, XCTest can dump the json using `--dump-tests-json` mode.
///
/// - Parameters:
/// - path: Path to the XCTest bundle(macOS) or executable(Linux).
///
/// - Throws: TestError, SystemError, TSCUtility.Error
///
/// - Returns: Array of TestSuite
static func getTestSuites(
fromTestAt path: AbsolutePath,
swiftCommandState: SwiftCommandState,
enableCodeCoverage: Bool,
shouldSkipBuilding: Bool,
experimentalTestOutput: Bool,
sanitizers: [Sanitizer]
) throws -> [TestSuite] {
// Run the correct tool.
var args = [String]()
#if os(macOS)
let data: String = try withTemporaryFile { tempFile in
args = [try Self.xctestHelperPath(swiftCommandState: swiftCommandState).pathString, path.pathString, tempFile.path.pathString]
let env = try Self.constructTestEnvironment(
toolchain: try swiftCommandState.getTargetToolchain(),
buildParameters: swiftCommandState.buildParametersForTest(
enableCodeCoverage: enableCodeCoverage,
shouldSkipBuilding: shouldSkipBuilding,
experimentalTestOutput: experimentalTestOutput
).productsBuildParameters,
sanitizers: sanitizers,
library: .xctest
)
try AsyncProcess.checkNonZeroExit(arguments: args, environment: env)
// Read the temporary file's content.
return try swiftCommandState.fileSystem.readFileContents(AbsolutePath(tempFile.path))
}
#else
let env = try Self.constructTestEnvironment(
toolchain: try swiftCommandState.getTargetToolchain(),
buildParameters: swiftCommandState.buildParametersForTest(
enableCodeCoverage: enableCodeCoverage,
shouldSkipBuilding: shouldSkipBuilding
).productsBuildParameters,
sanitizers: sanitizers,
library: .xctest
)
args = [path.description, "--dump-tests-json"]
let data = try AsyncProcess.checkNonZeroExit(arguments: args, environment: env)
#endif
// Parse json and return TestSuites.
return try TestSuite.parse(jsonString: data, context: args.joined(separator: " "))
}
/// Creates the environment needed to test related tools.
static func constructTestEnvironment(
toolchain: UserToolchain,
buildParameters: BuildParameters,
sanitizers: [Sanitizer],
library: BuildParameters.Testing.Library
) throws -> Environment {
var env = Environment.current
// If the standard output or error stream is NOT a TTY, set the NO_COLOR
// environment variable. This environment variable is a de facto
// standard used to inform downstream processes not to add ANSI escape
// codes to their output. SEE: https://www.no-color.org
if !stdoutStream.isTTY || !stderrStream.isTTY {
env["NO_COLOR"] = "1"
}
// Add the code coverage related variables.
if buildParameters.testingParameters.enableCodeCoverage {
// Defines the path at which the profraw files will be written on test execution.
//
// `%m` will create a pool of profraw files and append the data from
// each execution in one of the files. This doesn't matter for serial
// execution but is required when the tests are running in parallel as
// SwiftPM repeatedly invokes the test binary with the test case name as
// the filter.
let codecovProfile = buildParameters.buildPath.appending(components: "codecov", "\(library)%m.profraw")
env["LLVM_PROFILE_FILE"] = codecovProfile.pathString
}
#if !os(macOS)
#if os(Windows)
if let xctestLocation = toolchain.xctestPath {
env.prependPath(key: .path, value: xctestLocation.pathString)
}
if let swiftTestingLocation = toolchain.swiftTestingPathOnWindows {
env.prependPath(key: .path, value: swiftTestingLocation.pathString)
}
#endif
return env
#else
// Add the sdk platform path if we have it.
if let sdkPlatformFrameworksPath = try? SwiftSDK.sdkPlatformFrameworkPaths() {
// appending since we prefer the user setting (if set) to the one we inject
env.appendPath(key: "DYLD_FRAMEWORK_PATH", value: sdkPlatformFrameworksPath.fwk.pathString)
env.appendPath(key: "DYLD_LIBRARY_PATH", value: sdkPlatformFrameworksPath.lib.pathString)
}
// We aren't using XCTest's harness logic to run Swift Testing tests.
if library == .xctest {
env["SWIFT_TESTING_ENABLED"] = "0"
}
// Fast path when no sanitizers are enabled.
if sanitizers.isEmpty {
return env
}
// Get the runtime libraries.
var runtimes = try sanitizers.map({ sanitizer in
return try toolchain.runtimeLibrary(for: sanitizer).pathString
})
// Append any existing value to the front.
if let existingValue = env["DYLD_INSERT_LIBRARIES"], !existingValue.isEmpty {
runtimes.insert(existingValue, at: 0)
}
env["DYLD_INSERT_LIBRARIES"] = runtimes.joined(separator: ":")
return env
#endif
}
}
extension SwiftCommandState {
func buildParametersForTest(
enableCodeCoverage: Bool,
enableTestability: Bool? = nil,
shouldSkipBuilding: Bool = false,
experimentalTestOutput: Bool = false
) throws -> (productsBuildParameters: BuildParameters, toolsBuildParameters: BuildParameters) {
let productsBuildParameters = buildParametersForTest(
modifying: try productsBuildParameters,
enableCodeCoverage: enableCodeCoverage,
enableTestability: enableTestability,
shouldSkipBuilding: shouldSkipBuilding,
experimentalTestOutput: experimentalTestOutput
)
let toolsBuildParameters = buildParametersForTest(
modifying: try toolsBuildParameters,
enableCodeCoverage: enableCodeCoverage,
enableTestability: enableTestability,
shouldSkipBuilding: shouldSkipBuilding,
experimentalTestOutput: experimentalTestOutput
)
return (productsBuildParameters, toolsBuildParameters)
}
private func buildParametersForTest(
modifying parameters: BuildParameters,
enableCodeCoverage: Bool,
enableTestability: Bool?,
shouldSkipBuilding: Bool,
experimentalTestOutput: Bool
) -> BuildParameters {
var parameters = parameters
var explicitlyEnabledDiscovery = false
var explicitlySpecifiedPath: AbsolutePath?
if case let .entryPointExecutable(
explicitlyEnabledDiscoveryValue,
explicitlySpecifiedPathValue
) = parameters.testingParameters.testProductStyle {
explicitlyEnabledDiscovery = explicitlyEnabledDiscoveryValue
explicitlySpecifiedPath = explicitlySpecifiedPathValue
}
parameters.testingParameters = .init(
configuration: parameters.configuration,
targetTriple: parameters.triple,
forceTestDiscovery: explicitlyEnabledDiscovery,
testEntryPointPath: explicitlySpecifiedPath
)
parameters.testingParameters.enableCodeCoverage = enableCodeCoverage
// for test commands, we normally enable building with testability
// but we let users override this with a flag
parameters.testingParameters.enableTestability = enableTestability ?? true
parameters.shouldSkipBuilding = shouldSkipBuilding
parameters.testingParameters.experimentalTestOutput = experimentalTestOutput
return parameters
}
}
|