forked from apple/swift-package-manager
-
Notifications
You must be signed in to change notification settings - Fork 0
/
BuildToolTests.swift
386 lines (334 loc) · 18.4 KB
/
BuildToolTests.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
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift open source project
//
// Copyright (c) 2014-2021 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
//
//===----------------------------------------------------------------------===//
@testable import Commands
import PackageGraph
import PackageLoading
import PackageModel
import SPMBuildCore
import SPMTestSupport
import TSCBasic
import Workspace
import XCTest
struct BuildResult {
let binPath: AbsolutePath
let output: String
let binContents: [String]
}
final class BuildToolTests: CommandsTestCase {
@discardableResult
private func execute(
_ args: [String],
environment: [String : String]? = nil,
packagePath: AbsolutePath? = nil
) throws -> (stdout: String, stderr: String) {
return try SwiftPMProduct.SwiftBuild.execute(args, packagePath: packagePath, env: environment)
}
func build(_ args: [String], packagePath: AbsolutePath? = nil) throws -> BuildResult {
let (output, _) = try execute(args, packagePath: packagePath)
defer { try! SwiftPMProduct.SwiftPackage.execute(["clean"], packagePath: packagePath) }
let (binPathOutput, _) = try execute(["--show-bin-path"], packagePath: packagePath)
let binPath = AbsolutePath(binPathOutput.trimmingCharacters(in: .whitespacesAndNewlines))
let binContents = try localFileSystem.getDirectoryContents(binPath)
return BuildResult(binPath: binPath, output: output, binContents: binContents)
}
func testUsage() throws {
let stdout = try execute(["-help"]).stdout
XCTAssertMatch(stdout, .contains("USAGE: swift build"))
}
func testSeeAlso() throws {
let stdout = try execute(["--help"]).stdout
XCTAssertMatch(stdout, .contains("SEE ALSO: swift run, swift package, swift test"))
}
func testVersion() throws {
let stdout = try execute(["--version"]).stdout
XCTAssertMatch(stdout, .contains("Swift Package Manager"))
}
func testCreatingSanitizers() throws {
for sanitizer in Sanitizer.allCases {
XCTAssertEqual(sanitizer, try Sanitizer(argument: sanitizer.shortName))
}
}
func testInvalidSanitizer() throws {
do {
_ = try Sanitizer(argument: "invalid")
XCTFail("Should have failed to create Sanitizer")
} catch let error as StringError {
XCTAssertEqual(error.description, "valid sanitizers: address, thread, undefined, scudo")
}
}
func testImportOfMissedDepWarning() throws {
#if swift(<5.5)
try XCTSkipIf(true, "skipping because host compiler doesn't support '-import-prescan'")
#endif
// Verify the warning flow
try fixture(name: "Miscellaneous/ImportOfMissingDependency") { path in
let fullPath = resolveSymlinks(path)
XCTAssertThrowsError(try build(["--explicit-target-dependency-import-check=warn"], packagePath: fullPath)) { error in
guard case SwiftPMProductError.executionFailure(_, _, let stderr) = error else {
XCTFail()
return
}
XCTAssertTrue(stderr.contains("warning: Target A imports another target (B) in the package without declaring it a dependency."))
}
}
// Verify the error flow
try fixture(name: "Miscellaneous/ImportOfMissingDependency") { path in
let fullPath = resolveSymlinks(path)
XCTAssertThrowsError(try build(["--explicit-target-dependency-import-check=error"], packagePath: fullPath)) { error in
guard case SwiftPMProductError.executionFailure(_, _, let stderr) = error else {
XCTFail()
return
}
XCTAssertTrue(stderr.contains("error: Target A imports another target (B) in the package without declaring it a dependency."))
}
}
// Verify that the default does not run the check
try fixture(name: "Miscellaneous/ImportOfMissingDependency") { path in
let fullPath = resolveSymlinks(path)
XCTAssertThrowsError(try build([], packagePath: fullPath)) { error in
guard case SwiftPMProductError.executionFailure(_, _, let stderr) = error else {
XCTFail()
return
}
XCTAssertFalse(stderr.contains("warning: Target A imports another target (B) in the package without declaring it a dependency."))
}
}
}
func testBinPathAndSymlink() throws {
try fixture(name: "ValidLayouts/SingleModule/ExecutableNew") { fixturePath in
let fullPath = resolveSymlinks(fixturePath)
let targetPath = fullPath.appending(components: ".build", UserToolchain.default.triple.platformBuildPathComponent())
let xcbuildTargetPath = fullPath.appending(components: ".build", "apple")
XCTAssertEqual(try execute(["--show-bin-path"], packagePath: fullPath).stdout,
"\(targetPath.appending(component: "debug").pathString)\n")
XCTAssertEqual(try execute(["-c", "release", "--show-bin-path"], packagePath: fullPath).stdout,
"\(targetPath.appending(component: "release").pathString)\n")
// Print correct path when building with XCBuild.
let xcodeDebugOutput = try execute(["--build-system", "xcode", "--show-bin-path"], packagePath: fullPath).stdout
let xcodeReleaseOutput = try execute(["--build-system", "xcode", "-c", "release", "--show-bin-path"], packagePath: fullPath).stdout
#if os(macOS)
XCTAssertEqual(xcodeDebugOutput, "\(xcbuildTargetPath.appending(components: "Products", "Debug").pathString)\n")
XCTAssertEqual(xcodeReleaseOutput, "\(xcbuildTargetPath.appending(components: "Products", "Release").pathString)\n")
#else
XCTAssertEqual(xcodeDebugOutput, "\(targetPath.appending(component: "debug").pathString)\n")
XCTAssertEqual(xcodeReleaseOutput, "\(targetPath.appending(component: "release").pathString)\n")
#endif
// Test symlink.
_ = try execute([], packagePath: fullPath)
XCTAssertEqual(resolveSymlinks(fullPath.appending(components: ".build", "debug")),
targetPath.appending(component: "debug"))
_ = try execute(["-c", "release"], packagePath: fullPath)
XCTAssertEqual(resolveSymlinks(fullPath.appending(components: ".build", "release")),
targetPath.appending(component: "release"))
}
}
func testProductAndTarget() throws {
try fixture(name: "Miscellaneous/MultipleExecutables") { fixturePath in
let fullPath = resolveSymlinks(fixturePath)
do {
let result = try build(["--product", "exec1"], packagePath: fullPath)
XCTAssertMatch(result.binContents, ["exec1"])
XCTAssertNoMatch(result.binContents, ["exec2.build"])
}
do {
let (_, stderr) = try execute(["--product", "lib1"], packagePath: fullPath)
try SwiftPMProduct.SwiftPackage.execute(["clean"], packagePath: fullPath)
XCTAssertMatch(stderr, .contains("'--product' cannot be used with the automatic product 'lib1'; building the default target instead"))
}
do {
let result = try build(["--target", "exec2"], packagePath: fullPath)
XCTAssertMatch(result.binContents, ["exec2.build"])
XCTAssertNoMatch(result.binContents, ["exec1"])
}
XCTAssertThrowsCommandExecutionError(try execute(["--product", "exec1", "--target", "exec2"], packagePath: fixturePath)) { error in
XCTAssertMatch(error.stderr, .contains("error: '--product' and '--target' are mutually exclusive"))
}
XCTAssertThrowsCommandExecutionError(try execute(["--product", "exec1", "--build-tests"], packagePath: fixturePath)) { error in
XCTAssertMatch(error.stderr, .contains("error: '--product' and '--build-tests' are mutually exclusive"))
}
XCTAssertThrowsCommandExecutionError(try execute(["--build-tests", "--target", "exec2"], packagePath: fixturePath)) { error in
XCTAssertMatch(error.stderr, .contains("error: '--target' and '--build-tests' are mutually exclusive"))
}
XCTAssertThrowsCommandExecutionError(try execute(["--build-tests", "--target", "exec2", "--product", "exec1"], packagePath: fixturePath)) { error in
XCTAssertMatch(error.stderr, .contains("error: '--product', '--target', and '--build-tests' are mutually exclusive"))
}
XCTAssertThrowsCommandExecutionError(try execute(["--product", "UnkownProduct"], packagePath: fixturePath)){ error in
XCTAssertMatch(error.stderr, .contains("error: no product named 'UnkownProduct'"))
}
XCTAssertThrowsCommandExecutionError(try execute(["--target", "UnkownTarget"], packagePath: fixturePath)) { error in
XCTAssertMatch(error.stderr, .contains("error: no target named 'UnkownTarget'"))
}
}
}
func testAtMainSupport() throws {
try fixture(name: "Miscellaneous/AtMainSupport") { fixturePath in
let fullPath = resolveSymlinks(fixturePath)
do {
let result = try build(["--product", "ClangExecSingleFile"], packagePath: fullPath)
XCTAssertMatch(result.binContents, ["ClangExecSingleFile"])
}
do {
let result = try build(["--product", "SwiftExecSingleFile"], packagePath: fullPath)
XCTAssertMatch(result.binContents, ["SwiftExecSingleFile"])
}
do {
let result = try build(["--product", "SwiftExecMultiFile"], packagePath: fullPath)
XCTAssertMatch(result.binContents, ["SwiftExecMultiFile"])
}
}
}
func testNonReachableProductsAndTargetsFunctional() throws {
try fixture(name: "Miscellaneous/UnreachableTargets") { fixturePath in
let aPath = fixturePath.appending(component: "A")
do {
let result = try build([], packagePath: aPath)
XCTAssertNoMatch(result.binContents, ["bexec"])
XCTAssertNoMatch(result.binContents, ["BTarget2.build"])
XCTAssertNoMatch(result.binContents, ["cexec"])
XCTAssertNoMatch(result.binContents, ["CTarget.build"])
}
// Dependency contains a dependent product
do {
let result = try build(["--product", "bexec"], packagePath: aPath)
XCTAssertMatch(result.binContents, ["BTarget2.build"])
XCTAssertMatch(result.binContents, ["bexec"])
XCTAssertNoMatch(result.binContents, ["aexec"])
XCTAssertNoMatch(result.binContents, ["ATarget.build"])
XCTAssertNoMatch(result.binContents, ["BLibrary.a"])
// FIXME: We create the modulemap during build planning, hence this uglyness.
let bTargetBuildDir = ((try? localFileSystem.getDirectoryContents(result.binPath.appending(component: "BTarget1.build"))) ?? []).filter{ $0 != moduleMapFilename }
XCTAssertTrue(bTargetBuildDir.isEmpty, "bTargetBuildDir should be empty")
XCTAssertNoMatch(result.binContents, ["cexec"])
XCTAssertNoMatch(result.binContents, ["CTarget.build"])
// Also make sure we didn't emit parseable module interfaces
// (do this here to avoid doing a second build in
// testParseableInterfaces().
XCTAssertNoMatch(result.binContents, ["ATarget.swiftinterface"])
XCTAssertNoMatch(result.binContents, ["BTarget.swiftinterface"])
XCTAssertNoMatch(result.binContents, ["CTarget.swiftinterface"])
}
}
}
func testParseableInterfaces() throws {
try fixture(name: "Miscellaneous/ParseableInterfaces") { fixturePath in
do {
let result = try build(["--enable-parseable-module-interfaces"], packagePath: fixturePath)
XCTAssertMatch(result.binContents, ["A.swiftinterface"])
XCTAssertMatch(result.binContents, ["B.swiftinterface"])
} catch SwiftPMProductError.executionFailure(_, _, let stderr) {
XCTFail(stderr)
}
}
}
func testAutomaticParseableInterfacesWithLibraryEvolution() throws {
try fixture(name: "Miscellaneous/LibraryEvolution") { fixturePath in
do {
let result = try build([], packagePath: fixturePath)
XCTAssertMatch(result.binContents, ["A.swiftinterface"])
XCTAssertMatch(result.binContents, ["B.swiftinterface"])
}
}
}
func testBuildCompleteMessage() throws {
try fixture(name: "DependencyResolution/Internal/Simple") { fixturePath in
do {
let result = try execute([], packagePath: fixturePath)
XCTAssertMatch(result.stdout, .regex("\\[[1-9][0-9]*\\/[1-9][0-9]*\\] Compiling"))
let lines = result.stdout.split(separator: "\n")
XCTAssertMatch(String(lines.last!), .regex("Build complete! \\([0-9]*\\.[0-9]*s\\)"))
}
do {
// test second time, to make sure message is presented even when nothing to build (cached)
let result = try execute([], packagePath: fixturePath)
XCTAssertNoMatch(result.stdout, .regex("\\[[1-9][0-9]*\\/[1-9][0-9]*\\] Compiling"))
let lines = result.stdout.split(separator: "\n")
XCTAssertMatch(String(lines.last!), .regex("Build complete! \\([0-9]*\\.[0-9]*s\\)"))
}
}
}
func testBuildStartMessage() throws {
try fixture(name: "DependencyResolution/Internal/Simple") { fixturePath in
do {
let result = try execute(["-c", "debug"], packagePath: fixturePath)
XCTAssertMatch(result.stdout, .prefix("Building for debugging"))
}
do {
let result = try execute(["-c", "release"], packagePath: fixturePath)
XCTAssertMatch(result.stdout, .prefix("Building for production"))
}
}
}
func testXcodeBuildSystemDefaultSettings() throws {
#if !os(macOS)
try XCTSkipIf(true, "test requires `xcbuild` and is therefore only supported on macOS")
#endif
try fixture(name: "ValidLayouts/SingleModule/ExecutableNew") { fixturePath in
// Try building using XCBuild with default parameters. This should succeed. We build verbosely so we get full command lines.
let defaultOutput = try execute(["-c", "debug", "-v"], packagePath: fixturePath).stdout
// Look for certain things in the output from XCBuild.
XCTAssertMatch(defaultOutput, .contains("-target \(UserToolchain.default.triple.tripleString(forPlatformVersion: ""))"))
}
}
func testXcodeBuildSystemWithAdditionalBuildFlags() throws {
try XCTSkipIf(true, "Disabled for now because it is hitting 'IR generation failure: Cannot read legacy layout file' in CI (rdar://88828632)")
#if !os(macOS)
try XCTSkipIf(true, "test requires `xcbuild` and is therefore only supported on macOS")
#endif
try fixture(name: "ValidLayouts/SingleModule/ExecutableMixed") { fixturePath in
// Try building using XCBuild with additional flags. This should succeed. We build verbosely so we get full command lines.
let defaultOutput = try execute(
[
"--build-system", "xcode",
"-c", "debug", "-v",
"-Xlinker", "-rpath", "-Xlinker", "/fakerpath",
"-Xcc", "-I/cfakepath",
"-Xcxx", "-I/cxxfakepath",
"-Xswiftc", "-I/swiftfakepath",
],
packagePath: fixturePath
).stdout
// Look for certain things in the output from XCBuild.
XCTAssertMatch(defaultOutput, .contains("/fakerpath"))
XCTAssertMatch(defaultOutput, .contains("-I/cfakepath"))
XCTAssertMatch(defaultOutput, .contains("-I/cxxfakepath"))
XCTAssertMatch(defaultOutput, .contains("-I/swiftfakepath"))
}
}
func testXcodeBuildSystemOverrides() throws {
#if !os(macOS)
try XCTSkipIf(true, "test requires `xcbuild` and is therefore only supported on macOS")
#endif
try fixture(name: "ValidLayouts/SingleModule/ExecutableNew") { fixturePath in
// Try building using XCBuild without specifying overrides. This should succeed, and should use the default compiler path.
let defaultOutput = try execute(["-c", "debug", "--vv"], packagePath: fixturePath).stdout
XCTAssertMatch(defaultOutput, .contains(UserToolchain.default.swiftCompilerPath.pathString))
// Now try building using XCBuild while specifying a faulty compiler override. This should fail. Note that we need to set the executable to use for the manifest itself to the default one, since it defaults to SWIFT_EXEC if not provided.
var overriddenOutput = ""
XCTAssertThrowsCommandExecutionError(
try execute(
["-c", "debug", "--vv"],
environment: ["SWIFT_EXEC": "/usr/bin/false", "SWIFT_EXEC_MANIFEST": UserToolchain.default.swiftCompilerPath.pathString],
packagePath: fixturePath
)
) { error in
overriddenOutput = error.stderr
}
XCTAssertMatch(overriddenOutput, .contains("/usr/bin/false"))
}
}
func testPrintLLBuildManifestJobGraph() throws {
try fixture(name: "DependencyResolution/Internal/Simple") { fixturePath in
let output = try execute(["--print-manifest-job-graph"], packagePath: fixturePath).stdout
XCTAssertMatch(output, .prefix("digraph Jobs {"))
}
}
}