-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
StdlibUnittest.swift
3682 lines (3264 loc) · 110 KB
/
StdlibUnittest.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
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
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2020 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 SwiftPrivate
import SwiftPrivateThreadExtras
import SwiftPrivateLibcExtras
#if canImport(Darwin)
#if _runtime(_ObjC)
import Foundation
#endif
import Darwin
#elseif canImport(Glibc)
import Glibc
#elseif canImport(Musl)
import Musl
#elseif os(WASI)
import WASILibc
#elseif os(Windows)
import CRT
import WinSDK
#endif
#if _runtime(_ObjC)
import ObjectiveC
#endif
#if SWIFT_ENABLE_EXPERIMENTAL_CONCURRENCY
import _Concurrency
#endif
#if os(WASI)
let platformSupportsChildProcesses = false
#else
let platformSupportsChildProcesses = true
#endif
extension String {
/// Returns the lines in `self`.
public var _lines : [String] {
return _split(separator: "\n")
}
/// Splits `self` at occurrences of `separator`.
public func _split(separator: Unicode.Scalar) -> [String] {
let scalarSlices = unicodeScalars.split { $0 == separator }
return scalarSlices.map { String(String.UnicodeScalarView($0)) }
}
}
public struct SourceLoc {
public let file: String
public let line: UInt
public let comment: String?
public init(_ file: String, _ line: UInt, comment: String? = nil) {
self.file = file
self.line = line
self.comment = comment
}
public func withCurrentLoc(
_ file: String = #file, line: UInt = #line
) -> SourceLocStack {
return SourceLocStack(self).with(SourceLoc(file, line))
}
}
public struct SourceLocStack {
let locs: [SourceLoc]
public init() {
locs = []
}
public init(_ loc: SourceLoc) {
locs = [loc]
}
init(_locs: [SourceLoc]) {
locs = _locs
}
var isEmpty: Bool {
return locs.isEmpty
}
public func with(_ loc: SourceLoc) -> SourceLocStack {
var locs = self.locs
locs.append(loc)
return SourceLocStack(_locs: locs)
}
public func pushIf(
_ showFrame: Bool, file: String, line: UInt
) -> SourceLocStack {
return showFrame ? self.with(SourceLoc(file, line)) : self
}
public func withCurrentLoc(
file: String = #file, line: UInt = #line
) -> SourceLocStack {
return with(SourceLoc(file, line))
}
public func print() {
let top = locs.first!
Swift.print("check failed at \(top.file), line \(top.line)")
_printStackTrace(SourceLocStack(_locs: Array(locs.dropFirst())))
}
}
fileprivate struct AtomicBool {
private var _value: _stdlib_AtomicInt
init(_ b: Bool) { self._value = _stdlib_AtomicInt(b ? 1 : 0) }
func store(_ b: Bool) { _value.store(b ? 1 : 0) }
func load() -> Bool { return _value.load() != 0 }
@discardableResult
func orAndFetch(_ b: Bool) -> Bool {
return _value.orAndFetch(b ? 1 : 0) != 0
}
func fetchAndClear() -> Bool {
return _value.fetchAndAnd(0) != 0
}
}
func _printStackTrace(_ stackTrace: SourceLocStack?) {
guard let s = stackTrace, !s.locs.isEmpty else { return }
print("stacktrace:")
for (i, loc) in s.locs.reversed().enumerated() {
let comment = (loc.comment != nil) ? " ; \(loc.comment!)" : ""
print(" #\(i): \(loc.file):\(loc.line)\(comment)")
}
}
fileprivate var _anyExpectFailed = AtomicBool(false)
fileprivate var _seenExpectCrash = AtomicBool(false)
/// Run `body` and expect a failure to happen.
///
/// The check passes iff `body` triggers one or more failures.
public func expectFailure(
_ message: @autoclosure () -> String = "",
stackTrace: SourceLocStack = SourceLocStack(),
showFrame: Bool = true,
file: String = #file, line: UInt = #line, invoking body: () -> Void) {
let startAnyExpectFailed = _anyExpectFailed.fetchAndClear()
body()
let endAnyExpectFailed = _anyExpectFailed.fetchAndClear()
expectTrue(
endAnyExpectFailed, "running `body` should produce an expected failure",
stackTrace: stackTrace.pushIf(showFrame, file: file, line: line)
)
_anyExpectFailed.orAndFetch(startAnyExpectFailed)
}
/// An opaque function that ignores its argument and returns nothing.
public func noop<T>(_ value: T) {}
/// An opaque function that simply returns its argument.
public func identity<T>(_ value: T) -> T {
return value
}
public func identity(_ element: OpaqueValue<Int>) -> OpaqueValue<Int> {
return element
}
public func identityEq(_ element: MinimalEquatableValue) -> MinimalEquatableValue {
return element
}
public func identityComp(_ element: MinimalComparableValue)
-> MinimalComparableValue {
return element
}
public func expectEqual<T : Equatable>(
_ first: T,
_ second: T,
_ message: @autoclosure () -> String = "",
stackTrace: SourceLocStack = SourceLocStack(),
showFrame: Bool = true,
file: String = #file, line: UInt = #line
) {
expectEqualTest(first, second, message(),
stackTrace: stackTrace.pushIf(showFrame, file: file, line: line), showFrame: false) {$0 == $1}
}
public func expectEqual<T : Equatable, U : Equatable>(
_ first: (T, U),
_ second: (T, U),
_ message: @autoclosure () -> String = "",
stackTrace: SourceLocStack = SourceLocStack(),
showFrame: Bool = true,
file: String = #file, line: UInt = #line
) {
expectEqualTest(first.0, second.0, message(),
stackTrace: stackTrace.pushIf(showFrame, file: file, line: line), showFrame: false) {$0 == $1}
expectEqualTest(first.1, second.1, message(),
stackTrace: stackTrace.pushIf(showFrame, file: file, line: line), showFrame: false) {$0 == $1}
}
public func expectEqual<T : Equatable, U : Equatable, V : Equatable>(
_ first: (T, U, V),
_ second: (T, U, V),
_ message: @autoclosure () -> String = "",
stackTrace: SourceLocStack = SourceLocStack(),
showFrame: Bool = true,
file: String = #file, line: UInt = #line
) {
expectEqualTest(first.0, second.0, message(),
stackTrace: stackTrace.pushIf(showFrame, file: file, line: line), showFrame: false) {$0 == $1}
expectEqualTest(first.1, second.1, message(),
stackTrace: stackTrace.pushIf(showFrame, file: file, line: line), showFrame: false) {$0 == $1}
expectEqualTest(first.2, second.2, message(),
stackTrace: stackTrace.pushIf(showFrame, file: file, line: line), showFrame: false) {$0 == $1}
}
public func expectEqual<T : Equatable, U : Equatable, V : Equatable, W : Equatable>(
_ first: (T, U, V, W),
_ second: (T, U, V, W),
_ message: @autoclosure () -> String = "",
stackTrace: SourceLocStack = SourceLocStack(),
showFrame: Bool = true,
file: String = #file, line: UInt = #line
) {
expectEqualTest(first.0, second.0, message(),
stackTrace: stackTrace.pushIf(showFrame, file: file, line: line), showFrame: false) {$0 == $1}
expectEqualTest(first.1, second.1, message(),
stackTrace: stackTrace.pushIf(showFrame, file: file, line: line), showFrame: false) {$0 == $1}
expectEqualTest(first.2, second.2, message(),
stackTrace: stackTrace.pushIf(showFrame, file: file, line: line), showFrame: false) {$0 == $1}
expectEqualTest(first.3, second.3, message(),
stackTrace: stackTrace.pushIf(showFrame, file: file, line: line), showFrame: false) {$0 == $1}
}
public func expectEqual(
_ first: String,
_ second: Substring,
_ message: @autoclosure () -> String = "",
stackTrace: SourceLocStack = SourceLocStack(),
showFrame: Bool = true,
file: String = #file, line: UInt = #line
) {
if !(first == second) {
expectationFailure(
"""
first: \(String(reflecting: first)) (of type \(String(reflecting: type(of: first))))
second: \(String(reflecting: second)) (of type \(String(reflecting: type(of: second))))
""",
trace: message(),
stackTrace: stackTrace.pushIf(showFrame, file: file, line: line)
)
}
}
public func expectEqual(
_ first: Substring,
_ second: String,
_ message: @autoclosure () -> String = "",
stackTrace: SourceLocStack = SourceLocStack(),
showFrame: Bool = true,
file: String = #file, line: UInt = #line
) {
if !(first == second) {
expectationFailure(
"""
first: \(String(reflecting: first)) (of type \(String(reflecting: type(of: first))))
second: \(String(reflecting: second)) (of type \(String(reflecting: type(of: second))))
""",
trace: message(),
stackTrace: stackTrace.pushIf(showFrame, file: file, line: line)
)
}
}
public func expectEqual(
_ first: String,
_ second: String,
_ message: @autoclosure () -> String = "",
stackTrace: SourceLocStack = SourceLocStack(),
showFrame: Bool = true,
file: String = #file, line: UInt = #line
) {
if !(first == second) {
expectationFailure(
"""
first: \(String(reflecting: first)) (of type \(String(reflecting: type(of: first))))
second: \(String(reflecting: second)) (of type \(String(reflecting: type(of: second))))
""",
trace: message(),
stackTrace: stackTrace.pushIf(showFrame, file: file, line: line)
)
}
}
public func expectEqualReference(
_ first: AnyObject?,
_ second: AnyObject?,
_ message: @autoclosure () -> String = "",
stackTrace: SourceLocStack = SourceLocStack(),
showFrame: Bool = true,
file: String = #file, line: UInt = #line
) {
expectEqualTest(first, second, message(),
stackTrace: stackTrace.pushIf(showFrame, file: file, line: line), showFrame: false) {$0 === $1}
}
public func expectationFailure(
_ reason: String,
trace message: String,
stackTrace: SourceLocStack) {
_anyExpectFailed.store(true)
stackTrace.print()
print(reason, terminator: reason == "" ? "" : "\n")
print(message, terminator: message == "" ? "" : "\n")
}
// Renamed to avoid collision with expectEqual(_, _, TRACE).
// See <rdar://26058520> Generic type constraints incorrectly applied to
// functions with the same name
public func expectEqualTest<T>(
_ first: T,
_ second: T,
_ message: @autoclosure () -> String = "",
stackTrace: SourceLocStack = SourceLocStack(),
showFrame: Bool = true,
file: String = #file, line: UInt = #line,
sameValue equal: (T, T) -> Bool
) {
if !equal(first, second) {
expectationFailure(
"""
first: \(String(reflecting: first)) (of type \(String(reflecting: type(of: first))))
second: \(String(reflecting: second)) (of type \(String(reflecting: type(of: second))))
""",
trace: message(),
stackTrace: stackTrace.pushIf(showFrame, file: file, line: line)
)
}
}
public func expectNotEqual<T : Equatable>(
_ first: T,
_ second: T,
_ message: @autoclosure () -> String = "",
stackTrace: SourceLocStack = SourceLocStack(),
showFrame: Bool = true,
file: String = #file, line: UInt = #line
) {
if first == second {
expectationFailure(
"unexpected value: \"\(second)\" (of type \(String(reflecting: type(of: second))))",
trace: message(),
stackTrace: stackTrace.pushIf(showFrame, file: file, line: line)
)
}
}
public func expectOptionalEqual<T>(
_ first: T,
_ second: T?,
_ message: @autoclosure () -> String = "",
stackTrace: SourceLocStack = SourceLocStack(),
showFrame: Bool = true,
file: String = #file, line: UInt = #line,
sameValue equal: (T, T) -> Bool
) {
if (second == nil) || !equal(first, second!) {
expectationFailure(
"""
first: \"\(first)\" (of type \(String(reflecting: type(of: first))))
second: \"\(second.debugDescription)\" (of type \(String(reflecting: type(of: second))))
""",
trace: message(),
stackTrace: stackTrace.pushIf(showFrame, file: file, line: line))
}
}
public func expectEqual(
_ first: Any.Type, _ second: Any.Type,
_ message: @autoclosure () -> String = "",
stackTrace: SourceLocStack = SourceLocStack(),
showFrame: Bool = true,
file: String = #file, line: UInt = #line
) {
expectEqualTest(
first, second, message(),
stackTrace: stackTrace.pushIf(showFrame, file: file, line: line), showFrame: false
) { $0 == $1 }
}
public func expectLT<T : Comparable>(_ lhs: T, _ rhs: T,
_ message: @autoclosure () -> String = "",
stackTrace: SourceLocStack = SourceLocStack(),
showFrame: Bool = true,
file: String = #file, line: UInt = #line) {
if !(lhs < rhs) {
expectationFailure("\(lhs) < \(rhs)", trace: message(),
stackTrace: stackTrace.pushIf(showFrame, file: file, line: line))
} else if !(rhs > lhs) {
expectationFailure("\(lhs) < \(rhs) (flipped)", trace: message(),
stackTrace: stackTrace.pushIf(showFrame, file: file, line: line))
}
}
public func expectLE<T : Comparable>(_ lhs: T, _ rhs: T,
_ message: @autoclosure () -> String = "",
stackTrace: SourceLocStack = SourceLocStack(),
showFrame: Bool = true,
file: String = #file, line: UInt = #line) {
if !(lhs <= rhs) {
expectationFailure("\(lhs) <= \(rhs)", trace: message(),
stackTrace: stackTrace.pushIf(showFrame, file: file, line: line))
} else if !(rhs >= lhs) {
expectationFailure("\(lhs) <= \(rhs) (flipped)", trace: message(),
stackTrace: stackTrace.pushIf(showFrame, file: file, line: line))
}
}
public func expectGT<T : Comparable>(_ lhs: T, _ rhs: T,
_ message: @autoclosure () -> String = "",
stackTrace: SourceLocStack = SourceLocStack(),
showFrame: Bool = true,
file: String = #file, line: UInt = #line) {
if !(lhs > rhs) {
expectationFailure("\(lhs) > \(rhs)", trace: message(),
stackTrace: stackTrace.pushIf(showFrame, file: file, line: line))
} else if !(rhs < lhs) {
expectationFailure("\(lhs) > \(rhs) (flipped)", trace: message(),
stackTrace: stackTrace.pushIf(showFrame, file: file, line: line))
}
}
public func expectGE<T : Comparable>(_ lhs: T, _ rhs: T,
_ message: @autoclosure () -> String = "",
stackTrace: SourceLocStack = SourceLocStack(),
showFrame: Bool = true,
file: String = #file, line: UInt = #line) {
if !(lhs >= rhs) {
expectationFailure("\(lhs) >= \(rhs)", trace: message(),
stackTrace: stackTrace.pushIf(showFrame, file: file, line: line))
} else if !(rhs <= lhs) {
expectationFailure("\(lhs) >= \(rhs) (flipped)", trace: message(),
stackTrace: stackTrace.pushIf(showFrame, file: file, line: line))
}
}
extension Range {
internal func _contains(_ other: Range<Bound>) -> Bool {
if other.lowerBound < lowerBound { return false }
if upperBound < other.upperBound { return false }
return true
}
}
extension Range {
internal func _contains(_ other: ClosedRange<Bound>) -> Bool {
if other.lowerBound < lowerBound { return false }
if upperBound <= other.upperBound { return false }
return true
}
}
public func expectTrapping<Bound>(
_ point: Bound, in range: Range<Bound>,
_ message: @autoclosure () -> String = "",
stackTrace: SourceLocStack = SourceLocStack(),
showFrame: Bool = true,
file: String = #file, line: UInt = #line
) {
if !range.contains(point) {
expectationFailure("\(point) in \(range)", trace: message(),
stackTrace: stackTrace.pushIf(showFrame, file: file, line: line))
_trappingExpectationFailedCallback()
}
}
public func expectTrapping<Bound>(
_ subRange: Range<Bound>, in range: Range<Bound>,
_ message: @autoclosure () -> String = "",
stackTrace: SourceLocStack = SourceLocStack(),
showFrame: Bool = true,
file: String = #file, line: UInt = #line
) {
if !range._contains(subRange) {
expectationFailure("\(subRange) in \(range)", trace: message(),
stackTrace: stackTrace.pushIf(showFrame, file: file, line: line))
_trappingExpectationFailedCallback()
}
}
public func expectTrapping<Bound>(
_ point: Bound, in range: ClosedRange<Bound>,
_ message: @autoclosure () -> String = "",
stackTrace: SourceLocStack = SourceLocStack(),
showFrame: Bool = true,
file: String = #file, line: UInt = #line
) {
if !range.contains(point) {
expectationFailure("\(point) in \(range)", trace: message(),
stackTrace: stackTrace.pushIf(showFrame, file: file, line: line))
_trappingExpectationFailedCallback()
}
}
public func expectTrapping<Bound>(
_ subRange: ClosedRange<Bound>, in range: Range<Bound>,
_ message: @autoclosure () -> String = "",
stackTrace: SourceLocStack = SourceLocStack(),
showFrame: Bool = true,
file: String = #file, line: UInt = #line
) {
if !range._contains(subRange) {
expectationFailure("\(subRange) in \(range)", trace: message(),
stackTrace: stackTrace.pushIf(showFrame, file: file, line: line))
_trappingExpectationFailedCallback()
}
}
extension ClosedRange {
internal func _contains(_ other: ClosedRange<Bound>) -> Bool {
if other.lowerBound < lowerBound { return false }
if upperBound < other.upperBound { return false }
return true
}
}
public func expectTrapping<Bound>(
_ subRange: ClosedRange<Bound>, in range: ClosedRange<Bound>,
_ message: @autoclosure () -> String = "",
stackTrace: SourceLocStack = SourceLocStack(),
showFrame: Bool = true,
file: String = #file, line: UInt = #line
) {
if !range._contains(subRange) {
expectationFailure("\(subRange) in \(range)", trace: message(),
stackTrace: stackTrace.pushIf(showFrame, file: file, line: line))
_trappingExpectationFailedCallback()
}
}
public func expectType<T>(_: T.Type, _ x: inout T) {}
public func expectEqualType<T>(_: T.Type, _: T.Type) {}
public func expectSequenceType<X : Sequence>(_ x: X) -> X {
return x
}
public func expectCollectionType<X : Collection>(
_ x: X.Type
) {}
public func expectMutableCollectionType<X : MutableCollection>(
_ x: X.Type
) {}
/// A slice is a `Collection` that when sliced returns an instance of
/// itself.
public func expectSliceType<X : Collection>(
_ sliceType: X.Type
) where X.SubSequence == X {}
/// A mutable slice is a `MutableCollection` that when sliced returns an
/// instance of itself.
public func expectMutableSliceType<X : MutableCollection>(
_ mutableSliceType: X.Type
) where X.SubSequence == X {}
/// Check that all associated types of a `Sequence` are what we expect them
/// to be.
public func expectSequenceAssociatedTypes<X : Sequence>(
sequenceType: X.Type,
iteratorType: X.Iterator.Type
) {}
/// Check that all associated types of a `Collection` are what we expect them
/// to be.
public func expectCollectionAssociatedTypes<X : Collection>(
collectionType: X.Type,
iteratorType: X.Iterator.Type,
subSequenceType: X.SubSequence.Type,
indexType: X.Index.Type,
indicesType: X.Indices.Type
) {}
/// Check that all associated types of a `BidirectionalCollection` are what we
/// expect them to be.
public func expectBidirectionalCollectionAssociatedTypes<X : BidirectionalCollection>(
collectionType: X.Type,
iteratorType: X.Iterator.Type,
subSequenceType: X.SubSequence.Type,
indexType: X.Index.Type,
indicesType: X.Indices.Type
) {}
/// Check that all associated types of a `RandomAccessCollection` are what we
/// expect them to be.
public func expectRandomAccessCollectionAssociatedTypes<X : RandomAccessCollection>(
collectionType: X.Type,
iteratorType: X.Iterator.Type,
subSequenceType: X.SubSequence.Type,
indexType: X.Index.Type,
indicesType: X.Indices.Type
) {}
public struct AssertionResult : CustomStringConvertible {
init(isPass: Bool) {
self._isPass = isPass
}
public func withDescription(_ description: String) -> AssertionResult {
var result = self
result.description += description
return result
}
let _isPass: Bool
public var description: String = ""
}
public func assertionSuccess() -> AssertionResult {
return AssertionResult(isPass: true)
}
public func assertionFailure() -> AssertionResult {
return AssertionResult(isPass: false)
}
public func expectUnreachable(
_ message: @autoclosure () -> String = "",
stackTrace: SourceLocStack = SourceLocStack(),
showFrame: Bool = true,
file: String = #file, line: UInt = #line) {
expectationFailure("this code should not be executed", trace: message(),
stackTrace: stackTrace.pushIf(showFrame, file: file, line: line))
}
public func expectUnreachableCatch(_ error: Error,
_ message: @autoclosure () -> String = "",
stackTrace: SourceLocStack = SourceLocStack(),
showFrame: Bool = true,
file: String = #file, line: UInt = #line) {
expectationFailure(
"error should not be thrown: \"\(error)\"", trace: message(),
stackTrace: stackTrace.pushIf(showFrame, file: file, line: line))
}
public func expectTrue(_ actual: AssertionResult,
_ message: @autoclosure () -> String = "",
stackTrace: SourceLocStack = SourceLocStack(),
showFrame: Bool = true,
file: String = #file, line: UInt = #line) {
if !actual._isPass {
expectationFailure(
"expected: passed assertion\n\(actual.description)", trace: message(),
stackTrace: stackTrace.pushIf(showFrame, file: file, line: line))
}
}
public func expectFalse(_ actual: AssertionResult,
_ message: @autoclosure () -> String = "",
stackTrace: SourceLocStack = SourceLocStack(),
showFrame: Bool = true,
file: String = #file, line: UInt = #line) {
if actual._isPass {
expectationFailure(
"expected: failed assertion\n\(actual.description)", trace: message(),
stackTrace: stackTrace.pushIf(showFrame, file: file, line: line))
}
}
public func expectTrue(_ actual: Bool,
_ message: @autoclosure () -> String = "",
stackTrace: SourceLocStack = SourceLocStack(),
showFrame: Bool = true,
file: String = #file, line: UInt = #line) {
if !actual {
expectationFailure("expected: true", trace: message(),
stackTrace: stackTrace.pushIf(showFrame, file: file, line: line))
}
}
public func expectFalse(_ actual: Bool,
_ message: @autoclosure () -> String = "",
stackTrace: SourceLocStack = SourceLocStack(),
showFrame: Bool = true,
file: String = #file, line: UInt = #line) {
if actual {
expectationFailure("expected: false", trace: message(),
stackTrace: stackTrace.pushIf(showFrame, file: file, line: line))
}
}
public func expectThrows<ErrorType: Error & Equatable>(
_ expectedError: ErrorType? = nil, _ test: () throws -> Void,
_ message: @autoclosure () -> String = "",
stackTrace: SourceLocStack = SourceLocStack(),
showFrame: Bool = true,
file: String = #file, line: UInt = #line) {
do {
try test()
} catch let error as ErrorType {
if let expectedError = expectedError {
expectEqual(expectedError, error)
}
} catch {
expectationFailure("unexpected error thrown: \"\(error)\"", trace: message(),
stackTrace: stackTrace.pushIf(showFrame, file: file, line: line))
}
}
public func expectDoesNotThrow(_ test: () throws -> Void,
_ message: @autoclosure () -> String = "",
stackTrace: SourceLocStack = SourceLocStack(),
showFrame: Bool = true,
file: String = #file, line: UInt = #line) {
do {
try test()
} catch {
expectationFailure("unexpected error thrown: \"\(error)\"", trace: message(),
stackTrace: stackTrace.pushIf(showFrame, file: file, line: line))
}
}
public func expectNil<T>(_ value: T?,
_ message: @autoclosure () -> String = "",
stackTrace: SourceLocStack = SourceLocStack(),
showFrame: Bool = true,
file: String = #file, line: UInt = #line) {
if value != nil {
expectationFailure(
"expected optional to be nil\nactual: \"\(value!)\"", trace: message(),
stackTrace: stackTrace.pushIf(showFrame, file: file, line: line))
}
}
@discardableResult
public func expectNotNil<T>(_ value: T?,
_ message: @autoclosure () -> String = "",
stackTrace: SourceLocStack = SourceLocStack(),
showFrame: Bool = true,
file: String = #file, line: UInt = #line) -> T? {
if value == nil {
expectationFailure("expected optional to be non-nil", trace: message(),
stackTrace: stackTrace.pushIf(showFrame, file: file, line: line))
}
return value
}
public func expectCrashLater(withMessage message: String = "") {
print("\(_stdlibUnittestStreamPrefix);expectCrash;\(_anyExpectFailed.load())")
var stderr = _Stderr()
print("\(_stdlibUnittestStreamPrefix);expectCrash;\(message)", to: &stderr)
_seenExpectCrash.store(true)
}
public func expectCrash(withMessage message: String = "", executing: () -> Void) -> Never {
expectCrashLater(withMessage: message)
executing()
expectUnreachable()
fatalError()
}
func _defaultTestSuiteFailedCallback() {
abort()
}
var _testSuiteFailedCallback: () -> Void = _defaultTestSuiteFailedCallback
public func _setTestSuiteFailedCallback(_ callback: @escaping () -> Void) {
_testSuiteFailedCallback = callback
}
func _defaultTrappingExpectationFailedCallback() {
abort()
}
var _trappingExpectationFailedCallback: () -> Void
= _defaultTrappingExpectationFailedCallback
public func _setTrappingExpectationFailedCallback(callback: @escaping () -> Void) {
_trappingExpectationFailedCallback = callback
}
extension ProcessTerminationStatus {
var isSwiftTrap: Bool {
switch self {
case .signal(let signal):
#if os(Windows)
return CInt(signal) == SIGILL
#elseif os(WASI)
// No signals support on WASI yet, see https://github.com/WebAssembly/WASI/issues/166.
return false
#else
return CInt(signal) == SIGILL || CInt(signal) == SIGTRAP
#endif
default:
// This default case is needed for standard library builds where
// resilience is enabled.
// FIXME: Add the .exit case when there is a way to suppress when not.
// case .exit: return false
return false
}
}
}
func _stdlib_getline() -> String? {
var result: [UInt8] = []
while true {
let c = getchar()
if c == EOF {
if result.isEmpty {
return nil
}
return String(decoding: result, as: UTF8.self)
}
if c == CInt(Unicode.Scalar("\n").value) {
return String(decoding: result, as: UTF8.self)
}
result.append(UInt8(c))
}
}
func _printDebuggingAdvice(_ fullTestName: String) {
print("To debug, run:")
var invocation = [CommandLine.arguments[0]]
#if os(Windows)
var buffer: UnsafeMutablePointer<CChar>?
var length: Int = 0
if _dupenv_s(&buffer, &length, "SWIFT_INTERPRETER") != 0, let buffer = buffer {
invocation.insert(String(cString: buffer), at: 0)
free(buffer)
}
#else
let interpreter = getenv("SWIFT_INTERPRETER")
if interpreter != nil {
if let interpreterCmd = String(validatingCString: interpreter!) {
invocation.insert(interpreterCmd, at: 0)
}
}
#endif
print("$ \(invocation.joined(separator: " ")) " +
"--stdlib-unittest-in-process --stdlib-unittest-filter \"\(fullTestName)\"")
}
var _allTestSuites: [TestSuite] = []
var _testSuiteNameToIndex: [String : Int] = [:]
let _stdlibUnittestStreamPrefix = "__STDLIB_UNITTEST__"
let _crashedPrefix = "CRASHED:"
@_silgen_name("installTrapInterceptor")
func _installTrapInterceptor()
#if _runtime(_ObjC)
@objc protocol _StdlibUnittestNSException {
@objc optional var name: AnyObject { get }
}
#endif
// Avoid serializing references to objc_setUncaughtExceptionHandler in SIL.
@inline(never)
func _childProcess() {
_installTrapInterceptor()
#if _runtime(_ObjC)
objc_setUncaughtExceptionHandler {
let exception = ($0 as Optional)! as AnyObject
var stderr = _Stderr()
let maybeNSException =
unsafeBitCast(exception, to: _StdlibUnittestNSException.self)
if let name = maybeNSException.name {
print("*** [StdlibUnittest] Terminating due to uncaught exception " +
"\(name): \(exception)",
to: &stderr)
} else {
print("*** [StdlibUnittest] Terminating due to uncaught exception: " +
"\(exception)",
to: &stderr)
}
}
#endif
while let line = _stdlib_getline() {
let parts = line._split(separator: ";")
if parts[0] == _stdlibUnittestStreamPrefix {
precondition(parts[1] == "shutdown")
return
}
let testSuiteName = parts[0]
let testName = parts[1]
var testParameter: Int?
if parts.count > 2 {
testParameter = Int(parts[2])!
} else {
testParameter = nil
}
let testSuite = _allTestSuites[_testSuiteNameToIndex[testSuiteName]!]
_anyExpectFailed.store(false)
testSuite._runTest(name: testName, parameter: testParameter)
print("\(_stdlibUnittestStreamPrefix);end;\(_anyExpectFailed.load())")
var stderr = _Stderr()
print("\(_stdlibUnittestStreamPrefix);end", to: &stderr)
if testSuite._shouldShutDownChildProcess(forTestNamed: testName) {
return
}
}
}
#if SWIFT_ENABLE_EXPERIMENTAL_CONCURRENCY
@available(SwiftStdlib 5.1, *)
@inline(never)
func _childProcessAsync() async {
_installTrapInterceptor()
#if _runtime(_ObjC)
objc_setUncaughtExceptionHandler {
let exception = ($0 as Optional)! as AnyObject
var stderr = _Stderr()
let maybeNSException =
unsafeBitCast(exception, to: _StdlibUnittestNSException.self)
if let name = maybeNSException.name {
print("*** [StdlibUnittest] Terminating due to uncaught exception " +
"\(name): \(exception)",
to: &stderr)
} else {
print("*** [StdlibUnittest] Terminating due to uncaught exception: " +
"\(exception)",
to: &stderr)
}
}
#endif
while let line = _stdlib_getline() {
let parts = line._split(separator: ";")
if parts[0] == _stdlibUnittestStreamPrefix {
precondition(parts[1] == "shutdown")
return
}
let testSuiteName = parts[0]
let testName = parts[1]
var testParameter: Int?
if parts.count > 2 {
testParameter = Int(parts[2])!
} else {
testParameter = nil
}
let testSuite = _allTestSuites[_testSuiteNameToIndex[testSuiteName]!]
_anyExpectFailed.store(false)
await testSuite._runTestAsync(name: testName, parameter: testParameter)
print("\(_stdlibUnittestStreamPrefix);end;\(_anyExpectFailed.load())")
var stderr = _Stderr()
print("\(_stdlibUnittestStreamPrefix);end", to: &stderr)
if testSuite._shouldShutDownChildProcess(forTestNamed: testName) {
return
}
}
}
#endif
class _ParentProcess {
#if os(Windows)
internal var _process: HANDLE = INVALID_HANDLE_VALUE
internal var _childStdin: _FDOutputStream =
_FDOutputStream(handle: INVALID_HANDLE_VALUE)
internal var _childStdout: _FDInputStream =
_FDInputStream(handle: INVALID_HANDLE_VALUE)
internal var _childStderr: _FDInputStream =
_FDInputStream(handle: INVALID_HANDLE_VALUE)
#else
internal var _pid: pid_t?
internal var _childStdin: _FDOutputStream = _FDOutputStream(fd: -1)