- Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathTestBundle.swift
609 lines (505 loc) · 24.3 KB
/
TestBundle.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 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
//
#if NS_FOUNDATION_ALLOWS_TESTABLE_IMPORT
#if canImport(SwiftFoundation) && !DEPLOYMENT_RUNTIME_OBJC
@testableimport SwiftFoundation
#else
@testableimport Foundation
#endif
#endif
internalfunc testBundle(executable:Bool=false)->Bundle{
#if DARWIN_COMPATIBILITY_TESTS
forbundleinBundle.allBundles {
iflet bundleId = bundle.bundleIdentifier, bundleId =="org.swift.DarwinCompatibilityTests", bundle.resourcePath !=nil{
return bundle
}
}
fatalError("Cant find test bundle")
#else
return executable ?Bundle.main :Bundle.module
#endif
}
#if DARWIN_COMPATIBILITY_TESTS
extensionBundle{
staticlet_supportsFreestandingBundles=false
staticlet_supportsFHSBundles=false
}
#endif
internalfunc testBundleName()->String{
// Either 'TestFoundation' or 'DarwinCompatibilityTests'
returntestBundle().infoDictionary!["CFBundleName"]as!String
}
internalfunc xdgTestHelperURL()throws->URL{
#if os(Windows)
// Adding the xdgTestHelper as a dependency of TestFoundation causes its object files (including the main function) to be linked into the test runner executable as well
// While this works on Linux due to special linker functionality, this doesn't work on Windows and results in a collision between the two main symbols
// SwiftPM also cannot support depending on this executable (to ensure it is built) without also linking its objects into the test runner
// For those reasons, using the xdgTestHelper on Windows is currently unsupported and tests that rely on it must be skipped
throwXCTSkip("xdgTestHelper is not supported during testing on Windows (test executables are not supported by SwiftPM on Windows)")
#else
testBundle().bundleURL.deletingLastPathComponent().appendingPathComponent("xdgTestHelper")
#endif
}
classBundlePlayground{
enumExecutableType:CaseIterable{
case library
case executable
varpathExtension:String?{
switchself{
case.library:
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
return"dylib"
#elseif os(Windows)
return"dll"
#else
return"so"
#endif
case.executable:
#if os(Windows)
return"exe"
#else
returnnil
#endif
}
}
varfileNameSuffix:String?{
#if os(Windows) && DEBUG
"_debug"
#else
nil
#endif
}
varflatPathExtension:String?{
#if os(Windows)
returnself.pathExtension
#else
returnnil
#endif
}
varfhsPrefix:String{
switchself{
case.executable:
return"bin"
case.library:
return"lib"
}
}
varnonFlatFilePrefix:String{
switchself{
case.executable:
return""
case.library:
#if os(Windows)
return""
#else
return"lib"
#endif
}
}
}
enumLayout{
case flat(ExecutableType)
case fhs(ExecutableType)
case freestanding(ExecutableType)
staticvarallApplicable:[Layout]{
letlayouts:[Layout]=[
.flat(.library),
.flat(.executable),
.fhs(.library),
.fhs(.executable),
.freestanding(.library),
.freestanding(.executable),
]
return layouts.filter{ $0.isSupported }
}
varisFreestanding:Bool{
switchself{
case.freestanding(_):
returntrue
default:
returnfalse
}
}
varisFHS:Bool{
switchself{
case.fhs(_):
returntrue
default:
returnfalse
}
}
varisFlat:Bool{
switchself{
case.flat(_):
returntrue
default:
returnfalse
}
}
varisSupported:Bool{
switchself{
case.flat(_):
returntrue
case.freestanding(_):
returnBundle._supportsFreestandingBundles
case.fhs(_):
returnBundle._supportsFHSBundles
}
}
}
letbundleName:String
letbundleExtension:String
letresourceFilenames:[String]
letresourceSubdirectory:String
letsubdirectoryResourcesFilenames:[String]
letauxiliaryExecutableName:String
letlayout:Layout
private(set)varbundlePath:String!
private(set)varmainExecutableURL:URL!
privatevarplaygroundPath:String?
init?(bundleName:String,
bundleExtension:String,
resourceFilenames:[String],
resourceSubdirectory:String,
subdirectoryResourcesFilenames:[String],
auxiliaryExecutableName:String,
layout:Layout){
self.bundleName = bundleName
self.bundleExtension = bundleExtension
self.resourceFilenames = resourceFilenames
self.resourceSubdirectory = resourceSubdirectory
self.subdirectoryResourcesFilenames = subdirectoryResourcesFilenames
self.auxiliaryExecutableName = auxiliaryExecutableName
self.layout = layout
if !_create(){
destroy()
returnnil
}
}
privatefunc _create()->Bool{
// Make sure the directory is uniquely named
lettemporaryDirectory=FileManager.default.temporaryDirectory.appendingPathComponent("TestFoundation_Playground_"+ UUID().uuidString)
switch layout {
case.flat(let executableType):
do{
tryFileManager.default.createDirectory(atPath: temporaryDirectory.path, withIntermediateDirectories:false, attributes:nil)
// Make a flat bundle in the playground
letbundleURL= temporaryDirectory.appendingPathComponent(bundleName).appendingPathExtension(self.bundleExtension)
tryFileManager.default.createDirectory(atPath: bundleURL.path, withIntermediateDirectories:false, attributes:nil)
// Make a main and an auxiliary executable:
self.mainExecutableURL = bundleURL
.appendingPathComponent(bundleName +(executableType.fileNameSuffix ??""))
iflet ext = executableType.flatPathExtension {
self.mainExecutableURL.appendPathExtension(ext)
}
guardFileManager.default.createFile(atPath: mainExecutableURL.path, contents:nil)else{
returnfalse
}
varauxiliaryExecutableURL= bundleURL
.appendingPathComponent(auxiliaryExecutableName +(executableType.fileNameSuffix ??""))
iflet ext = executableType.flatPathExtension {
auxiliaryExecutableURL.appendPathExtension(ext)
}
guardFileManager.default.createFile(atPath: auxiliaryExecutableURL.path, contents:nil)else{
returnfalse
}
// Put some resources in the bundle
forresourceNamein resourceFilenames {
guardFileManager.default.createFile(atPath: bundleURL.appendingPathComponent(resourceName).path, contents:nil, attributes:nil)else{
returnfalse
}
}
// Add a resource into a subdirectory
letsubdirectoryURL= bundleURL.appendingPathComponent(resourceSubdirectory)
tryFileManager.default.createDirectory(atPath: subdirectoryURL.path, withIntermediateDirectories:false, attributes:nil)
forresourceNamein subdirectoryResourcesFilenames {
guardFileManager.default.createFile(atPath: subdirectoryURL.appendingPathComponent(resourceName).path, contents:nil, attributes:nil)else{
returnfalse
}
}
self.bundlePath = bundleURL.path
}catch{
returnfalse
}
case.fhs(let executableType):
do{
// Create a FHS /usr/local-style hierarchy:
tryFileManager.default.createDirectory(atPath: temporaryDirectory.path, withIntermediateDirectories:false, attributes:nil)
tryFileManager.default.createDirectory(atPath: temporaryDirectory.appendingPathComponent("share").path, withIntermediateDirectories:false, attributes:nil)
tryFileManager.default.createDirectory(atPath: temporaryDirectory.appendingPathComponent("lib").path, withIntermediateDirectories:false, attributes:nil)
// Make a main and an auxiliary executable:
self.mainExecutableURL = temporaryDirectory
.appendingPathComponent(executableType.fhsPrefix)
.appendingPathComponent(executableType.nonFlatFilePrefix + bundleName +(executableType.fileNameSuffix ??""))
iflet ext = executableType.pathExtension {
self.mainExecutableURL.appendPathExtension(ext)
}
guardFileManager.default.createFile(atPath: mainExecutableURL.path, contents:nil)else{returnfalse}
letexecutablesDirectory= temporaryDirectory.appendingPathComponent("libexec").appendingPathComponent("\(bundleName).executables")
tryFileManager.default.createDirectory(atPath: executablesDirectory.path, withIntermediateDirectories:true, attributes:nil)
varauxiliaryExecutableURL= executablesDirectory
.appendingPathComponent(executableType.nonFlatFilePrefix + auxiliaryExecutableName +(executableType.fileNameSuffix ??""))
iflet ext = executableType.pathExtension {
auxiliaryExecutableURL.appendPathExtension(ext)
}
guardFileManager.default.createFile(atPath: auxiliaryExecutableURL.path, contents:nil)else{returnfalse}
// Make a .resources directory in …/share:
letresourcesDirectory= temporaryDirectory.appendingPathComponent("share").appendingPathComponent("\(bundleName).resources")
tryFileManager.default.createDirectory(atPath: resourcesDirectory.path, withIntermediateDirectories:false, attributes:nil)
// Put some resources in the bundle
forresourceNamein resourceFilenames {
guardFileManager.default.createFile(atPath: resourcesDirectory.appendingPathComponent(resourceName).path, contents:nil, attributes:nil)else{returnfalse}
}
// Add a resource into a subdirectory
letsubdirectoryURL= resourcesDirectory.appendingPathComponent(resourceSubdirectory)
tryFileManager.default.createDirectory(atPath: subdirectoryURL.path, withIntermediateDirectories:false, attributes:nil)
forresourceNamein subdirectoryResourcesFilenames {
guardFileManager.default.createFile(atPath: subdirectoryURL.appendingPathComponent(resourceName).path, contents:nil, attributes:nil)else{returnfalse}
}
self.bundlePath = resourcesDirectory.path
}catch{
returnfalse
}
case.freestanding(let executableType):
do{
letbundleName=URL(string:self.bundleName)!.deletingPathExtension().path
tryFileManager.default.createDirectory(atPath: temporaryDirectory.path, withIntermediateDirectories:false, attributes:nil)
// Make a main executable:
self.mainExecutableURL = temporaryDirectory
.appendingPathComponent(executableType.nonFlatFilePrefix + bundleName +(executableType.fileNameSuffix ??""))
iflet ext = executableType.pathExtension {
self.mainExecutableURL.appendPathExtension(ext)
}
guardFileManager.default.createFile(atPath: mainExecutableURL.path, contents:nil)else{returnfalse}
// Make a .resources directory:
letresourcesDirectory= temporaryDirectory.appendingPathComponent("\(bundleName).resources")
tryFileManager.default.createDirectory(atPath: resourcesDirectory.path, withIntermediateDirectories:false, attributes:nil)
// Make an auxiliary executable:
varauxiliaryExecutableURL= resourcesDirectory
.appendingPathComponent(executableType.nonFlatFilePrefix + auxiliaryExecutableName +(executableType.fileNameSuffix ??""))
iflet ext = executableType.pathExtension {
auxiliaryExecutableURL.appendPathExtension(ext)
}
guardFileManager.default.createFile(atPath: auxiliaryExecutableURL.path, contents:nil)else{returnfalse}
// Put some resources in the bundle
forresourceNamein resourceFilenames {
guardFileManager.default.createFile(atPath: resourcesDirectory.appendingPathComponent(resourceName).path, contents:nil, attributes:nil)else{returnfalse}
}
// Add a resource into a subdirectory
letsubdirectoryURL= resourcesDirectory.appendingPathComponent(resourceSubdirectory)
tryFileManager.default.createDirectory(atPath: subdirectoryURL.path, withIntermediateDirectories:false, attributes:nil)
forresourceNamein subdirectoryResourcesFilenames {
guardFileManager.default.createFile(atPath: subdirectoryURL.appendingPathComponent(resourceName).path, contents:nil, attributes:nil)else{returnfalse}
}
self.bundlePath = resourcesDirectory.path
}catch{
returnfalse
}
}
self.playgroundPath = temporaryDirectory.path
returntrue
}
func destroy(){
guardlet path =self.playgroundPath else{return}
self.playgroundPath =nil
try?FileManager.default.removeItem(atPath: path)
}
deinit{
assert(playgroundPath ==nil,"All playgrounds should have .destroy() invoked on them before they go out of scope.")
}
}
classTestBundle:XCTestCase{
func test_paths(){
letbundle=testBundle()
// bundlePath
XCTAssert(!bundle.bundlePath.isEmpty)
XCTAssertEqual(bundle.bundleURL.path, bundle.bundlePath)
letpath= bundle.bundlePath
// etc
#if os(macOS)
XCTAssertEqual("\(path)/Contents/Resources", bundle.resourcePath)
#if DARWIN_COMPATIBILITY_TESTS
XCTAssertEqual("\(path)/Contents/MacOS/DarwinCompatibilityTests", bundle.executablePath)
#else
XCTAssertEqual("\(path)/Contents/MacOS/TestFoundation", bundle.executablePath)
#endif
XCTAssertEqual("\(path)/Contents/Frameworks", bundle.privateFrameworksPath)
XCTAssertEqual("\(path)/Contents/SharedFrameworks", bundle.sharedFrameworksPath)
XCTAssertEqual("\(path)/Contents/SharedSupport", bundle.sharedSupportPath)
#endif
XCTAssertNil(bundle.path(forAuxiliaryExecutable:"no_such_file"))
#if !DARWIN_COMPATIBILITY_TESTS
XCTAssertNil(bundle.appStoreReceiptURL)
#endif
}
func test_resources(){
letbundle=testBundle()
// bad resources
XCTAssertNil(bundle.url(forResource:nil, withExtension:nil, subdirectory:nil))
XCTAssertNil(bundle.url(forResource:"", withExtension:"", subdirectory:nil))
XCTAssertNil(bundle.url(forResource:"no_such_file", withExtension:nil, subdirectory:nil))
// test file
lettestPlist= bundle.url(forResource:"Test", withExtension:"plist")
XCTAssertNotNil(testPlist)
XCTAssertEqual("Test.plist", testPlist!.lastPathComponent)
XCTAssert(FileManager.default.fileExists(atPath: testPlist!.path))
// aliases, paths
XCTAssertEqual(testPlist!.path, bundle.url(forResource:"Test", withExtension:"plist", subdirectory:nil)!.path)
XCTAssertEqual(testPlist!.path, bundle.path(forResource:"Test", ofType:"plist"))
XCTAssertEqual(testPlist!.path, bundle.path(forResource:"Test", ofType:"plist", inDirectory:nil))
}
func test_infoPlist(){
letbundle=testBundle()
// bundleIdentifier
#if DARWIN_COMPATIBILITY_TESTS
XCTAssertEqual("org.swift.DarwinCompatibilityTests", bundle.bundleIdentifier)
#else
XCTAssertEqual("org.swift.TestFoundation", bundle.bundleIdentifier)
#endif
// infoDictionary
letinfo= bundle.infoDictionary
XCTAssertNotNil(info)
#if DARWIN_COMPATIBILITY_TESTS
XCTAssert("DarwinCompatibilityTests"== info!["CFBundleName"]as!String)
XCTAssert("org.swift.DarwinCompatibilityTests"== info!["CFBundleIdentifier"]as!String)
#else
XCTAssert("TestFoundation"== info!["CFBundleName"]as!String)
XCTAssert("org.swift.TestFoundation"== info!["CFBundleIdentifier"]as!String)
#endif
// localizedInfoDictionary
XCTAssertNil(bundle.localizedInfoDictionary) // FIXME: Add a localized Info.plist for testing
}
func test_localizations(){
letbundle=testBundle()
XCTAssertEqual(["en"], bundle.localizations)
XCTAssertEqual(["en"], bundle.preferredLocalizations)
XCTAssertEqual(["en"],Bundle.preferredLocalizations(from:["en","pl","es"]))
}
privatelet_bundleName="MyBundle"
privatelet_bundleExtension="bundle"
privatelet_bundleResourceNames=["hello.world","goodbye.world","swift.org"]
privatelet_subDirectory="Sources"
privatelet_main="main"
privatelet_type="swift"
privatelet_auxiliaryExecutable="auxiliaryExecutable"
privatefunc _setupPlayground(layout:BundlePlayground.Layout)->BundlePlayground?{
returnBundlePlayground(bundleName: _bundleName,
bundleExtension: _bundleExtension,
resourceFilenames: _bundleResourceNames,
resourceSubdirectory: _subDirectory,
subdirectoryResourcesFilenames:["\(_main).\(_type)"],
auxiliaryExecutableName: _auxiliaryExecutable,
layout: layout)
}
privatefunc _withEachPlaygroundLayout(execute:(BundlePlayground)throws->Void)rethrows{
forlayoutinBundlePlayground.Layout.allApplicable {
iflet playground =_setupPlayground(layout: layout){
tryexecute(playground)
playground.destroy()
}
}
}
privatefunc _cleanupPlayground(_ location:String){
try?FileManager.default.removeItem(atPath: location)
}
func test_URLsForResourcesWithExtension(){
_withEachPlaygroundLayout{(playground)in
letbundle=Bundle(path: playground.bundlePath)!
XCTAssertNotNil(bundle)
letworldResources= bundle.urls(forResourcesWithExtension:"world", subdirectory:nil)
XCTAssertNotNil(worldResources)
XCTAssertEqual(worldResources?.count,2)
letpath= bundle.path(forResource: _main, ofType: _type, inDirectory: _subDirectory)
XCTAssertNotNil(path)
}
}
func test_bundleLoad(){
letbundle=testBundle(executable:true)
let _ = bundle.load()
XCTAssertTrue(bundle.isLoaded)
}
func test_bundleLoadWithError(){
letbundleValid=testBundle(executable:true)
// Test valid load using loadAndReturnError
do{
try bundleValid.loadAndReturnError()
}
catch{
XCTFail("should not fail to load")
}
// This causes a dialog box to appear on Windows which will suspend the tests, so skip testing this on Windows for now
#if !os(Windows)
// Executable cannot be located
try!_withEachPlaygroundLayout{(playground)in
letbundle=Bundle(path: playground.bundlePath)
XCTAssertThrowsError(try bundle!.loadAndReturnError())
}
#endif
}
func test_bundleWithInvalidPath(){
letbundleInvalid=Bundle(path:NSTemporaryDirectory()+"test.playground")
XCTAssertNil(bundleInvalid)
}
func test_bundlePreflight(){
XCTAssertNoThrow(trytestBundle(executable:true).preflight())
// Windows DLL bundles are always executable
#if !os(Windows)
try!_withEachPlaygroundLayout{(playground)in
letbundle=Bundle(path: playground.bundlePath)!
// Must throw as the main executable is a dummy empty file.
XCTAssertThrowsError(try bundle.preflight())
}
#endif
}
func test_bundleFindExecutable(){
XCTAssertNotNil(testBundle(executable:true).executableURL)
_withEachPlaygroundLayout{(playground)in
letbundle=Bundle(path: playground.bundlePath)!
XCTAssertNotNil(bundle.executableURL)
}
}
func test_bundleFindAuxiliaryExecutables(){
_withEachPlaygroundLayout{(playground)in
letbundle=Bundle(path: playground.bundlePath)!
XCTAssertNotNil(bundle.url(forAuxiliaryExecutable: _auxiliaryExecutable))
XCTAssertNil(bundle.url(forAuxiliaryExecutable:"does_not_exist_at_all"))
}
}
#if NS_FOUNDATION_ALLOWS_TESTABLE_IMPORT
func test_bundleReverseBundleLookup(){
_withEachPlaygroundLayout{(playground)in
#if !os(Windows)
if playground.layout.isFreestanding {
// TODO: Freestanding bundles reverse lookup pending to be implemented on non-Windows platforms.
return
}
#endif
if playground.layout.isFHS {
// TODO: FHS bundles reverse lookup pending to be implemented on all platforms.
return
}
letbundle=Bundle(_executableURL: playground.mainExecutableURL)
XCTAssertNotNil(bundle)
XCTAssertEqual(bundle?.bundlePath, playground.bundlePath)
}
}
func test_mainBundleExecutableURL(){
letmaybeURL=Bundle.main.executableURL
XCTAssertNotNil(maybeURL)
guardlet url = maybeURL else{return}
letpath= url.withUnsafeFileSystemRepresentation{
String(cString: $0!)
}
XCTAssertEqual(path,ProcessInfo.processInfo._processPath)
}
#endif
func test_bundleForClass(){
XCTAssertEqual(testBundle(executable:true),Bundle(for:type(of:self)))
}
}