-
Notifications
You must be signed in to change notification settings - Fork 182
/
JobExecutorTests.swift
315 lines (275 loc) · 11.7 KB
/
JobExecutorTests.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
//===--------------- JobExecutorTests.swift - Swift Execution Tests -------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import XCTest
import TSCBasic
import TSCUtility
@_spi(Testing) import SwiftDriver
import SwiftDriverExecution
extension Job.ArgTemplate: ExpressibleByStringLiteral {
public init(stringLiteral value: String) {
self = .flag(value)
}
}
class JobCollectingDelegate: JobExecutionDelegate {
struct StubProcess: ProcessProtocol {
static func launchProcess(arguments: [String], env: [String : String]) throws -> StubProcess {
return .init()
}
var processID: TSCBasic.Process.ProcessID { .init(-1) }
func waitUntilExit() throws -> ProcessResult {
return ProcessResult(
arguments: [],
environment: [:],
exitStatus: .terminated(code: EXIT_SUCCESS),
output: Result.success(ByteString("test").contents),
stderrOutput: Result.success([])
)
}
}
var started: [Job] = []
var finished: [(Job, ProcessResult)] = []
func jobFinished(job: Job, result: ProcessResult, pid: Int) {
finished.append((job, result))
}
func jobStarted(job: Job, arguments: [String], pid: Int) {
started.append(job)
}
}
extension DarwinToolchain {
/// macOS SDK path, for testing only.
var sdk: Result<AbsolutePath, Swift.Error> {
Result {
let result = try executor.checkNonZeroExit(
args: "xcrun", "-sdk", "macosx", "--show-sdk-path",
environment: env
).spm_chomp()
return AbsolutePath(result)
}
}
/// macOS resource directory, for testing only.
var resourcesDirectory: Result<AbsolutePath, Swift.Error> {
return Result {
try getToolPath(.swiftCompiler).appending(RelativePath("../../lib/swift/macosx"))
}
}
var clangRT: Result<AbsolutePath, Error> {
resourcesDirectory.map { $0.appending(RelativePath("../clang/lib/darwin/libclang_rt.osx.a")) }
}
var compatibility50: Result<AbsolutePath, Error> {
resourcesDirectory.map { $0.appending(component: "libswiftCompatibility50.a") }
}
var compatibilityDynamicReplacements: Result<AbsolutePath, Error> {
resourcesDirectory.map { $0.appending(component: "libswiftCompatibilityDynamicReplacements.a") }
}
}
final class JobExecutorTests: XCTestCase {
func testDarwinBasic() throws {
#if os(macOS)
let executor = try SwiftDriverExecutor(diagnosticsEngine: DiagnosticsEngine(),
processSet: ProcessSet(),
fileSystem: localFileSystem,
env: ProcessEnv.vars)
let toolchain = DarwinToolchain(env: ProcessEnv.vars, executor: executor)
try withTemporaryDirectory { path in
let foo = path.appending(component: "foo.swift")
let main = path.appending(component: "main.swift")
try localFileSystem.writeFileContents(foo) {
$0 <<< "let foo = 5"
}
try localFileSystem.writeFileContents(main) {
$0 <<< "print(foo)"
}
let exec = path.appending(component: "main")
let resolver = try ArgsResolver(fileSystem: localFileSystem)
resolver.pathMapping = [
.relative(RelativePath("foo.swift")): foo.pathString,
.relative(RelativePath("main.swift")): main.pathString,
.relative(RelativePath("main")): exec.pathString,
]
let inputs: [String: TypedVirtualPath] = [
"foo" : .init(file: .relative(RelativePath( "foo.swift")), type: .swift),
"main": .init(file: .relative(RelativePath("main.swift")), type: .swift)
]
let compileFoo = Job(
moduleName: "main",
kind: .compile,
tool: .absolute(try toolchain.getToolPath(.swiftCompiler)),
commandLine: [
"-frontend",
"-c",
"-primary-file",
.path(inputs[ "foo"]!.file),
.path(inputs["main"]!.file),
"-target", "x86_64-apple-darwin18.7.0",
"-enable-objc-interop",
"-sdk",
.path(.absolute(try toolchain.sdk.get())),
"-module-name", "main",
"-o", .path(.temporary(RelativePath("foo.o"))),
],
inputs: Array(inputs.values),
primaryInputs: [inputs["foo"]!],
outputs: [.init(file: .temporary(RelativePath("foo.o")), type: .object)]
)
let compileMain = Job(
moduleName: "main",
kind: .compile,
tool: .absolute(try toolchain.getToolPath(.swiftCompiler)),
commandLine: [
"-frontend",
"-c",
.path(.relative(RelativePath("foo.swift"))),
"-primary-file",
.path(inputs["main"]!.file),
"-target", "x86_64-apple-darwin18.7.0",
"-enable-objc-interop",
"-sdk",
.path(.absolute(try toolchain.sdk.get())),
"-module-name", "main",
"-o", .path(.temporary(RelativePath("main.o"))),
],
inputs: Array(inputs.values),
primaryInputs: [inputs["main"]!],
outputs: [.init(file: .temporary(RelativePath("main.o")), type: .object)]
)
let link = Job(
moduleName: "main",
kind: .link,
tool: .absolute(try toolchain.getToolPath(.dynamicLinker)),
commandLine: [
.path(.temporary(RelativePath("foo.o"))),
.path(.temporary(RelativePath("main.o"))),
.path(.absolute(try toolchain.clangRT.get())),
"-syslibroot", .path(.absolute(try toolchain.sdk.get())),
"-lobjc", "-lSystem", "-arch", "x86_64",
"-force_load", .path(.absolute(try toolchain.compatibility50.get())),
"-force_load", .path(.absolute(try toolchain.compatibilityDynamicReplacements.get())),
"-L", .path(.absolute(try toolchain.resourcesDirectory.get())),
"-L", .path(.absolute(try toolchain.sdkStdlib(sdk: toolchain.sdk.get()))),
"-rpath", "/usr/lib/swift", "-macosx_version_min", "10.14.0", "-no_objc_category_merging", "-o",
.path(.relative(RelativePath("main"))),
],
inputs: [
.init(file: .temporary(RelativePath("foo.o")), type: .object),
.init(file: .temporary(RelativePath("main.o")), type: .object),
],
primaryInputs: [],
outputs: [.init(file: .relative(RelativePath("main")), type: .image)]
)
let delegate = JobCollectingDelegate()
let executor = MultiJobExecutor(jobs: [compileFoo, compileMain, link], resolver: resolver, executorDelegate: delegate, diagnosticsEngine: DiagnosticsEngine())
try executor.execute(env: toolchain.env, fileSystem: localFileSystem)
let output = try TSCBasic.Process.checkNonZeroExit(args: exec.pathString)
XCTAssertEqual(output, "5\n")
XCTAssertEqual(delegate.started.count, 3)
let fooObject = try resolver.resolve(.path(.temporary(RelativePath("foo.o"))))
XCTAssertTrue(localFileSystem.exists(AbsolutePath(fooObject)), "expected foo.o to be present in the temporary directory")
try resolver.removeTemporaryDirectory()
XCTAssertFalse(localFileSystem.exists(AbsolutePath(fooObject)), "expected foo.o to be removed from the temporary directory")
}
#endif
}
func testStubProcessProtocol() throws {
// This test fails intermittently on Linux
// rdar://70067844
#if !os(macOS)
throw XCTSkip()
#endif
let job = Job(
moduleName: "main",
kind: .compile,
tool: .absolute(AbsolutePath("/usr/bin/swift")),
commandLine: [.flag("something")],
inputs: [],
primaryInputs: [],
outputs: [.init(file: .temporary(RelativePath("main")), type: .object)]
)
let delegate = JobCollectingDelegate()
let executor = MultiJobExecutor(
jobs: [job], resolver: try ArgsResolver(fileSystem: localFileSystem),
executorDelegate: delegate,
diagnosticsEngine: DiagnosticsEngine(),
processType: JobCollectingDelegate.StubProcess.self
)
try executor.execute(env: ProcessEnv.vars, fileSystem: localFileSystem)
XCTAssertEqual(try delegate.finished[0].1.utf8Output(), "test")
}
func testSwiftDriverExecOverride() throws {
var env = ProcessEnv.vars
let envVarName = "SWIFT_DRIVER_SWIFT_FRONTEND_EXEC"
let dummyPath = "/some/garbage/path/fnord"
let executor = try SwiftDriverExecutor(diagnosticsEngine: DiagnosticsEngine(),
processSet: ProcessSet(),
fileSystem: localFileSystem,
env: env)
// DarwinToolchain
env.removeValue(forKey: envVarName)
let normalSwiftPath = try DarwinToolchain(env: env, executor: executor).getToolPath(.swiftCompiler)
// Match Toolchain temporary shim of a fallback to looking for "swift" before failing.
XCTAssertTrue(normalSwiftPath.basenameWithoutExt == "swift-frontend" ||
normalSwiftPath.basenameWithoutExt == "swift")
env[envVarName] = dummyPath
let overriddenSwiftPath = try DarwinToolchain(env: env, executor: executor).getToolPath(.swiftCompiler)
XCTAssertEqual(overriddenSwiftPath, AbsolutePath(dummyPath))
// GenericUnixToolchain
env.removeValue(forKey: envVarName)
let unixSwiftPath = try GenericUnixToolchain(env: env, executor: executor).getToolPath(.swiftCompiler)
XCTAssertTrue(unixSwiftPath.basenameWithoutExt == "swift-frontend" ||
unixSwiftPath.basenameWithoutExt == "swift")
env[envVarName] = dummyPath
let unixOverriddenSwiftPath = try GenericUnixToolchain(env: env, executor: executor).getToolPath(.swiftCompiler)
XCTAssertEqual(unixOverriddenSwiftPath, AbsolutePath(dummyPath))
}
func testInputModifiedDuringSingleJobBuild() throws {
try withTemporaryDirectory { path in
let main = path.appending(component: "main.swift")
try localFileSystem.writeFileContents(main) {
$0 <<< "let foo = 1"
}
var driver = try Driver(args: ["swift", main.pathString])
let jobs = try driver.planBuild()
XCTAssertTrue(jobs.count == 1 && jobs[0].requiresInPlaceExecution)
// Change the file
try localFileSystem.writeFileContents(main) {
$0 <<< "let foo = 1"
}
XCTAssertThrowsError(try driver.run(jobs: jobs)) {
XCTAssertEqual($0 as? Job.InputError,
.inputUnexpectedlyModified(TypedVirtualPath(file: .absolute(main), type: .swift)))
}
}
}
func testInputModifiedDuringMultiJobBuild() throws {
try withTemporaryDirectory { path in
let main = path.appending(component: "main.swift")
try localFileSystem.writeFileContents(main) {
$0 <<< "let foo = 1"
}
let other = path.appending(component: "other.swift")
try localFileSystem.writeFileContents(other) {
$0 <<< "let bar = 2"
}
try assertDriverDiagnostics(args: ["swiftc", main.pathString, other.pathString]) {driver, verifier in
let jobs = try driver.planBuild()
XCTAssertTrue(jobs.count > 1)
// Change the file
try localFileSystem.writeFileContents(other) {
$0 <<< "let bar = 3"
}
// FIXME: It's unfortunate we diagnose this twice, once for each job which uses the input.
verifier.expect(.error("input file '\(other.description)' was modified during the build"))
verifier.expect(.error("input file '\(other.description)' was modified during the build"))
XCTAssertThrowsError(try driver.run(jobs: jobs))
}
}
}
}