-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathDeft.swift
1289 lines (1008 loc) · 39.9 KB
/
Deft.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
// MARK: - Matcher
/**
This object is used to verify results using `expect().to()`.
New matchers are made by providing a global function that returns this type
- Actual: The expected type passed into the `expect()` function.
- Expected: The expected type passed into the global function.
## Global Matcher Function Example ##
```swift
public func equal<T: Equatable>(_ expected: T) -> Matcher<T?, T> {
return Matcher { actual in
return actual == expected
}
}
```
*/
public class Matcher<Actual, Expected> {
let evaluator: (Actual) -> Bool
/**
Creates a new Matcher.
- Parameter evaluator: the closure that is executed during tests. Return true or false to indicate whether or not the actual value passed validation.
*/
public init(_ evaluator: @escaping (Actual) -> Bool) {
self.evaluator = evaluator
}
func execute(actual: Actual) -> Bool {
return evaluator(actual)
}
}
// MARK: - Built-in Matcher Functions
/**
Equal Matcher
Validates that two objects are equal using the `Equatable` protocol.
## Example ##
```swift
expect("value").to(equal("value"))
```
- Parameter expected: The object to be compared to the actual value.
*/
public func equal<T: Equatable>(_ expected: T) -> Matcher<T?, T> {
return Matcher { actual in
return actual == expected
}
}
/**
Be True Matcher
Validates that the actual value is true.
## Example ##
```swift
expect(true).to(beTrue())
```
*/
public func beTrue() -> Matcher<Bool, Void> {
return Matcher { actual in
return actual
}
}
/**
Be False Matcher
Validates that the actual value is false.
## Example ##
```swift
expect(false).to(beFalse())
```
*/
public func beFalse() -> Matcher<Bool, Void> {
return Matcher { actual in
return !actual
}
}
/**
Be Nil Matcher
Validates that the actual value is nil.
## Example ##
```swift
let myClass: MyClass? = nil
expect(myClass).to(beNil())
```
*/
public func beNil<T>() -> Matcher<T?, Void> {
return Matcher { actual in
return actual == nil
}
}
/**
Be Matcher
Validates that two objects are the same instance.
## Example ##
```swift
let myClass = MyClass()
expect(myClass).to(be(myClass))
```
- Parameter expected: The object to be compared to the actual value.
*/
public func be<T: AnyObject>(_ expected: T) -> Matcher<T, T> {
return Matcher { actual in
return actual === expected
}
}
/**
Be Close To Matcher
Validates that the actual value is close to expected value.
## Example ##
```swift
expect(5.0).to(beCloseTo(5.0))
expect(5.0).to(beCloseTo(5.0, maxDelta: 0.1))
```
- Parameter expected: The object to be compared to the actual value.
- Parameter maxDelta: The maximum difference that the actual value can be from the expected value and still pass validation. Defaults to 0.0001
*/
public func beCloseTo(_ expected: Double, maxDelta: Double = 0.0001) -> Matcher<Double, Double> {
return Matcher { actual in
return abs(actual - expected) <= maxDelta
}
}
/**
Be Close To Matcher
Validates that the actual value is close to expected value.
## Example ##
```swift
expect(5.0).to(beCloseTo(5.0))
expect(5.0).to(beCloseTo(5.0, maxDelta: 0.1))
```
- Parameter expected: The object to be compared to the actual value.
- Parameter maxDelta: The maximum difference that the actual value can be from the expected value and still pass validation. Defaults to 0.0001
*/
public func beCloseTo(_ expected: Float, maxDelta: Float = 0.0001) -> Matcher<Float, Float> {
return Matcher { actual in
return abs(actual - expected) <= maxDelta
}
}
/**
Pass Comparison Matcher
Validates that the comparison function returns true when the acutal value is passed in as the left/first argument and the expected value as the right/second argument.
## Example ##
```swift
expect(5).to(passComparison(<=, 10))
```
- Parameter comparisonFunction: The object to be compared to the actual value.
- Parameter expected: The left/second argument to passed into the comparison function.
*/
public func passComparison<T: Comparable>(_ comparisonFunction: @escaping (T, T) -> Bool, _ expected: T) -> Matcher<T, T> {
return Matcher { actual in
return comparisonFunction(actual, expected)
}
}
/**
Have Count Matcher
Validates that the `Collection` has the expected count.
## Example ##
```swift
expect([1, 2, 3]).to(haveCount(3))
```
- Parameter expectedCount: The expected count
*/
public func haveCount<C: Collection>(_ expectedCount: Int) -> Matcher<C, Int> {
return Matcher { actual in
return actual.count == expectedCount
}
}
/**
Have Count Matcher
Validates that the string's `CharacterView` has the expected count.
## Example ##
```swift
expect("value").to(haveCount(5))
```
- Parameter expectedCount: The expected count
*/
public func haveCount(_ expectedCount: Int) -> Matcher<String, Int> {
return Matcher { actual in
return actual.count == expectedCount
}
}
/**
Contain Matcher
Validates that the `Collection` contains the expected value.
## Example ##
```swift
expect([1, 2, 3]).to(contain(2))
```
- Parameter expectedValue: The expected value
*/
public func contain<T: Equatable>(_ expectedValue: T) -> Matcher<[T], T> {
return Matcher { actual in
return actual.contains(expectedValue)
}
}
/**
Contain Matcher
Validates that the `Collection` contains an element that satisfies the predicate.
## Example ##
```swift
let person = Person(age: 21)
expect([person]).to(contain { $0.age == 21 })
```
- Parameter predicate: the closure used to determine in an element satisfies the predicate
*/
public func contain<T>(where predicate: @escaping (T) -> Bool) -> Matcher<[T], T> {
return Matcher { actual in
return actual.contains(where: predicate)
}
}
/**
Be Empty Matcher
Validates that the `Collection` has a count of 0.
## Example ##
```swift
expect([]).to(beEmpty())
```
*/
public func beEmpty<C: Collection>() -> Matcher<C, Void> {
return Matcher { actual in
return actual.count == 0
}
}
/**
Be Empty Matcher
Validates that the string's `CharacterView` has a count of 0.
## Example ##
```swift
expect("").to(beEmpty())
```
*/
public func beEmpty() -> Matcher<String, Void> {
return Matcher { actual in
return actual.isEmpty
}
}
/**
Throw Error Matcher
Validates that wrapping function throws an error.
Can also validate the error using the optionally passed in function. If the error validator function is nil, then matcher will ONLY validate if an error was thrown.
## Example ##
```swift
expect({
try subject.throwingFunction()
}).to(throwError())
expect({
try subject.throwingFunction()
}).to(throwError(errorVerifier: { error in
let actualError = error as! MyError
return actual.name == "expected name"
}))
```
- Parameter errorVerifier: The closure used to determine if the error thrown is the expected error. Defaults to nil.
*/
public func throwError(errorVerifier: ((Error) -> Bool)? = nil) -> Matcher<() throws -> Void, Void> {
return Matcher { actual in
do {
try actual()
} catch let error {
if let errorVerifier = errorVerifier {
return errorVerifier(error)
}
return true
}
return false
}
}
/**
Throw Error Matcher
Validates that wrapping function throws an error equal to the expected error.
- Note: This matcher will also fail validation if the actual error thrown is NOT the same type as the expected error.
## Example ##
```swift
expect({
try subject.throwingFunction()
}).to(throwError(error: MyError()))
```
- Parameter error: The error to be compared to the actual error thrown.
*/
public func throwError<T: Error & Equatable>(error: T) -> Matcher<() throws -> Void, T> {
return Matcher { actual in
do {
try actual()
} catch let actualError {
if let actualError = actualError as? T {
return actualError == error
}
return false
}
return false
}
}
/**
Succeed Matcher
Validates that passed function returns true.
## Example ##
```swift
expect({
if case .one = myEnum {
return true
}
return false
}).to(succeed())
```
- Parameter error: The error to be compared to the actual error thrown.
*/
public func succeed() -> Matcher<() -> Bool, Void> {
return Matcher { actual in
return actual()
}
}
/**
Log Matcher
This matcher is only used for debugging purposes. This matcher exists because of the nature of timing during tests and since breakpoints are not yet available in playgrounds. This matcher allows you to call print statements at the time the enclosing `it` scope executes it's `expect().to()`.
If a print statement is executed directly in the enclosing `it` scope then it will NOT be executed at the same time the `expect().to()`s are evaluated but instead during Deft's scope capturing process. During this capturing process no `beforeEach`s, `afterEach`s, and `expect().to()`s are executed.
## Example ##
```swift
it("should ...") {
print("this is too early and will not reflect any changes made when `beforeEach` scopes are executed.")
expect({
print("useful debugging information is printed here as all `beforeEach` scopes for this `it` scope have executed and none of the `afterEach` scopes have been executed.")
}).to(log())
}
```
*/
public func log() -> Matcher<() -> Void, Void> {
return Matcher { actual in
actual()
return true
}
}
// MARK: - TDD Framework
private struct Constant {
static let levelSpace = " "
static let emptyTitle = ""
struct OutPutPrefix {
static let topLevel = "Test: "
static let describe = "Describe: "
static let context = "Context: "
static let group = "Group: "
static let it = "It: "
static let focused = "F-"
static let pending = "X-"
}
struct SingleCharacter {
static let blank = " "
static let success = "."
static let failure = "F"
static let pending = ">"
}
}
private struct I18n {
enum Key {
case tooManySubjectActions
case newScopesWhileExecuting
case stepOutsideOfScope(StepType)
case itOutsideOfScope
case expectOutsideOfIt
case notAllowedInIt(String)
case lineOutput(text: String, level: Int, firstCharacter: String)
case endLine(totalCount: Int, succeeded: Int, pending: Int)
case failureOutputLine(failureLines: [Int])
}
static func t(_ key: Key) -> String {
switch key {
case .tooManySubjectActions:
return "Only one \"subjectAction()\" per `it`."
case .newScopesWhileExecuting:
return "Tried to add a scope during a test. This is probably caused be a test block (describe, it, beforeEach, etc.) is defined inside an `it` block."
case .stepOutsideOfScope(let type):
return "`\(type)`s must be inside a `describe` or `context` scope."
case .itOutsideOfScope:
return "`it`s must be inside a `describe` or `context` scope."
case .expectOutsideOfIt:
return "`expects`s must be inside an `it` scope."
case .notAllowedInIt(let string):
return "`\(string)` not allowed in `it` scope."
case .lineOutput(let text, let level, let firstCharacter):
let space = String(repeating: Constant.levelSpace, count: level)
return firstCharacter + space + text + "\n"
case .endLine(let totalCount, let succeeded, let pending):
let testText = totalCount == 1 ? "test" : "tests"
return "\n Executed \(totalCount) \(testText)\n |- \(succeeded) succeeded\n |- \(totalCount - succeeded - pending) failed\n |- \(pending) pending\n\n"
case .failureOutputLine(let failureLines):
guard !failureLines.isEmpty else { return "" }
let linesString = failureLines.count == 1 ? "line" : "lines"
return "\n Failed on " + linesString + ": [" + failureLines.map{"\($0)"}.joined(separator: ", ") + "]\n"
}
}
}
private protocol TrackedScope {
func add(_ scope: Scope)
func add(_ step: Step)
func add(_ it: It)
}
private enum StepType {
case beforeEach
case subjectAction
case afterEach
}
private enum ScopeType {
case topLevel
case describe
case context
case group
var outputPrefix: String {
switch self {
case .topLevel: return Constant.OutPutPrefix.topLevel
case .describe: return Constant.OutPutPrefix.describe
case .context: return Constant.OutPutPrefix.context
case .group: return Constant.OutPutPrefix.group
}
}
}
private enum Mark {
case none
case focused
case pending
}
private class TestResult {
let description: String
let total: Int
let succeeded: Int
let pending: Int
let failureLines: [Int]
init(description: String = "", total: Int = 0, succeeded: Int = 0, pending: Int = 0, failureLines: [Int] = []) {
self.description = description
self.total = total
self.succeeded = succeeded
self.pending = pending
self.failureLines = failureLines
}
static func + (lhs: TestResult, rhs: TestResult) -> TestResult {
return TestResult(description: lhs.description + rhs.description,
total: lhs.total + rhs.total,
succeeded: lhs.succeeded + rhs.succeeded,
pending: lhs.pending + rhs.pending,
failureLines: lhs.failureLines + rhs.failureLines)
}
}
private class Expect {
private let captured: () -> Bool
private let line: Int
private let negativeTest: Bool
init<A, E>(actual: A, matcher: Matcher<A, E>, line: Int, negativeTest: Bool) {
self.captured = { matcher.execute(actual: actual) }
self.line = line
self.negativeTest = negativeTest
}
private func execute() -> Bool {
let result = captured()
return result && !negativeTest || !result && negativeTest
}
static func execute(_ expects: [Expect]) -> (Bool, [Int]) {
var failedLines = [Int]()
var allSucceeded = true
for expect in expects {
let success = expect.execute()
if !success {
failedLines.append(expect.line)
allSucceeded = false
}
}
return (allSucceeded, failedLines)
}
}
/**
This type is used to capture the actual value passed into `expect()` and the matcher passed into `to()`.
This type should NOT be used directly. Use `expect().to()` instead.
*/
public class ExpectPartOne<A, E> {
let actual: A
let line: Int
init(actual: A, line: Int) {
self.actual = actual
self.line = line
}
/**
Captures the matcher to be used for this expectation.
- Parameter matcher: The matcher to be used for validation.
*/
public func to(_ matcher: Matcher<A, E>) {
guard let currentScope = TestScope.currentTestScope else {
fatalError(I18n.t(.expectOutsideOfIt))
}
let expect = Expect(actual: actual, matcher: matcher, line: line, negativeTest: false)
currentScope.intake(expect)
}
/**
Captures the matcher to be used for this expectation.
Used to reverse the validation of a matcher. If the matcher passes validation then the test will fail and vise versa.
- Note: Exactly the same as `notTo()`
- Parameter matcher: The matcher to be used for validation.
*/
public func toNot(_ matcher: Matcher<A, E>) {
guard let currentScope = TestScope.currentTestScope else {
fatalError(I18n.t(.expectOutsideOfIt))
}
let expect = Expect(actual: actual, matcher: matcher, line: line, negativeTest: true)
currentScope.intake(expect)
}
/**
Captures the matcher to be used for this expectation.
Used to reverse the validation of a matcher. If the matcher passes validation then the test will fail and vise versa.
- Note: Exactly the same as `toNot()`
- Parameter matcher: The matcher to be used for validation.
*/
public func notTo(_ matcher: Matcher<A, E>) {
toNot(matcher)
}
}
private class It {
private let title: String
private let mark: Mark
let closure: () -> Void
var expects: [Expect] = []
var underFocus: Bool = false
var underPending: Bool = false
var actingFocused: Bool {
return mark == .focused || underFocus
}
var actingPending: Bool {
return mark == .pending || underPending
}
var displayableTitle: String {
let prePrefix: String
switch mark {
case .none: prePrefix = ""
case .focused: prePrefix = Constant.OutPutPrefix.focused
case .pending: prePrefix = Constant.OutPutPrefix.pending
}
return prePrefix + Constant.OutPutPrefix.it + (title.isEmpty ? Constant.emptyTitle : title)
}
init(title: String, mark: Mark, closure: @escaping () -> Void) {
self.title = title
self.mark = mark
self.closure = closure
}
func process(underFocus: Bool, underPending: Bool) {
self.underFocus = underFocus
self.underPending = underPending
}
func add(_ expect: Expect) {
expects.append(expect)
}
// MARK: - Private
private func shouldExecute(isSomethingFocused: Bool) -> Bool {
if actingPending {
return false
}
if isSomethingFocused {
return actingFocused
}
return true
}
// MARK: - Static
static func execute(_ its: [It], level: Int, steps: [Step], isSomethingFocused: Bool, inGroup: Bool) -> TestResult {
if inGroup {
return executeGroup(its, level: level, steps: steps, isSomethingFocused: isSomethingFocused)
} else {
return its.reduce(TestResult()) { $0 + executeGroup([$1], level: level, steps: steps, isSomethingFocused: isSomethingFocused) }
}
}
// MARK: - Private Static
private static func executeGroup(_ its: [It], level: Int, steps: [Step], isSomethingFocused: Bool) -> TestResult {
let hasTestsToRun = its.reduce(false) { $0 || $1.shouldExecute(isSomethingFocused: isSomethingFocused) }
guard hasTestsToRun else {
return its.reduce(TestResult()) {
let testDescription = I18n.t(.lineOutput(text: $1.displayableTitle, level: level, firstCharacter: Constant.SingleCharacter.pending))
return $0 + TestResult(description: testDescription, total: 1, pending: 1)
}
}
guard let currentScope = TestScope.currentTestScope else {
fatalError(I18n.t(.itOutsideOfScope))
}
let beforeEachs = steps.filter { $0.type == .beforeEach }
let subjectActions = steps.filter { $0.type == .subjectAction }
let afterEachs = steps.filter { $0.type == .afterEach }
guard subjectActions.count <= 1 else {
fatalError(I18n.t(.tooManySubjectActions))
}
beforeEachs.forEach { $0.closure() }
subjectActions.forEach { $0.closure() }
its.forEach { currentScope.process($0) }
let result = its.reduce(TestResult()) {
guard $1.shouldExecute(isSomethingFocused: isSomethingFocused) else {
let testDescription = I18n.t(.lineOutput(text: $1.displayableTitle, level: level, firstCharacter: Constant.SingleCharacter.pending))
return $0 + TestResult(description: testDescription, total: 1, pending: 1)
}
let (success, failureLines) = Expect.execute($1.expects)
let outcomeSymbol = success ? Constant.SingleCharacter.success : Constant.SingleCharacter.failure
let testDescription = I18n.t(.lineOutput(text: $1.displayableTitle, level: level, firstCharacter: outcomeSymbol))
return $0 + TestResult(description: testDescription, total: 1, succeeded: success ? 1 : 0, failureLines: failureLines)
}
afterEachs.reversed().forEach { $0.closure() }
return result
}
}
private class Step {
let type: StepType
let closure: () -> Void
init(type: StepType, _ closure: @escaping () -> Void) {
self.type = type
self.closure = closure
}
}
private class Scope: TrackedScope {
private let title: String
private let mark: Mark
let type: ScopeType
private var underFocus: Bool = false
private var underPending: Bool = false
private var steps: [Step] = []
private var its: [It] = []
private var subScopes: [Scope] = []
private var actingFocused: Bool {
return mark == .focused || underFocus
}
private var actingPending: Bool {
return mark == .pending || underPending
}
private var displayableTitle: String {
let prePrefix: String
switch mark {
case .none: prePrefix = ""
case .focused: prePrefix = Constant.OutPutPrefix.focused
case .pending: prePrefix = Constant.OutPutPrefix.pending
}
let prefix: String
switch type {
case .topLevel: prefix = prePrefix + Constant.OutPutPrefix.topLevel
case .describe: prefix = prePrefix + Constant.OutPutPrefix.describe
case .context: prefix = prePrefix + Constant.OutPutPrefix.context
case .group: prefix = prePrefix + Constant.OutPutPrefix.group
}
let displayableDescription = title.isEmpty ? Constant.emptyTitle : title
return prefix + displayableDescription
}
var hasActiveFocus: Bool {
if actingPending {
return false
} else {
let subScopeHasFocus = subScopes.reduce(false) { $0 || $1.hasActiveFocus }
let itHasFocus = its.reduce(false) { $0 || $1.actingFocused }
return subScopeHasFocus || itHasFocus || actingFocused
}
}
init(type: ScopeType, title: String, mark: Mark) {
self.type = type
self.title = title
self.mark = mark
}
func process(underFocus: Bool, underPending: Bool) {
self.underFocus = underFocus
self.underPending = underPending
its.forEach { $0.process(underFocus: actingFocused, underPending: actingPending) }
subScopes.forEach { $0.process(underFocus: actingFocused, underPending: actingPending) }
}
// MARK: - TrackerScope Protocol
func add(_ step: Step) {
steps.append(step)
}
func add(_ it: It) {
its.append(it)
}
func add(_ scope: Scope) {
subScopes.append(scope)
}
// MARK: - Static
static func execute(_ scopes: [Scope], isSomethingFocused: Bool, level: Int = 0, accumulatedSteps: [Step] = []) -> TestResult {
return scopes.reduce(TestResult()) {
let aggregatedSteps = accumulatedSteps + $1.steps
let scopeDescriptionResult = TestResult(description: I18n.t(.lineOutput(text: $1.displayableTitle, level: level, firstCharacter: Constant.SingleCharacter.blank)))
let itsResult = It.execute($1.its, level: level + 1, steps: aggregatedSteps, isSomethingFocused: isSomethingFocused, inGroup: $1.type == .group)
let subScopesResult = execute($1.subScopes, isSomethingFocused: isSomethingFocused, level: level + 1, accumulatedSteps: aggregatedSteps)
return $0 + scopeDescriptionResult + itsResult + subScopesResult
}
}
}
private class Tracker {
var scopes: [TrackedScope]
var it: It?
init(rootScope: TrackedScope) {
self.scopes = [rootScope]
}
var currentScope: TrackedScope {
return scopes.last!
}
func intake(_ scope: Scope, closure: () -> Void) {
scopes.last!.add(scope)
scopes.append(scope)
closure()
scopes.removeLast()
}
func intake(_ it: It) {
scopes.last!.add(it)
}
func intake(_ step: Step) {
scopes.last!.add(step)
}
func process(_ it: It) {
self.it = it
it.closure()
self.it = nil
}
func intake(_ expect: Expect) {
guard let it = it else {
fatalError(I18n.t(.expectOutsideOfIt))
}
it.add(expect)
}
}
private class TestScope: TrackedScope {
static var currentTestScope: TestScope?
private let tracker: Tracker
private let rootScope: Scope
private var isExecuting = false
init(title: String, closure: () -> Void, mark: Mark) {
rootScope = Scope(type: .topLevel, title: title, mark: mark)
self.tracker = Tracker(rootScope: rootScope)
TestScope.currentTestScope = self
closure()
}
func intake(_ scope: Scope, closure: () -> Void) {
ensureNotExecuting()
tracker.intake(scope, closure: closure)
}
func intake(_ it: It) {
ensureNotExecuting()
tracker.intake(it)
}
func intake(_ step: Step) {
ensureNotExecuting()
tracker.intake(step)
}
func intake(_ expect: Expect) {
guard isExecuting else {
fatalError(I18n.t(.expectOutsideOfIt))
}
tracker.intake(expect)
}
func process(_ it: It) {
tracker.process(it)
}
func execute() {
isExecuting = true
rootScope.process(underFocus: false, underPending: false)
let result = Scope.execute([rootScope], isSomethingFocused: rootScope.hasActiveFocus)
let failureLine = I18n.t(.failureOutputLine(failureLines: result.failureLines))
let endLine = I18n.t(.endLine(totalCount: result.total, succeeded: result.succeeded, pending: result.pending))
print(result.description + failureLine + endLine)
isExecuting = false
}
// MARK: - Private
private func ensureNotExecuting() {
guard !isExecuting else {
fatalError(I18n.t(.newScopesWhileExecuting))
}
}
// MARK: - TrackedScope Protocol
func add(_ scope: Scope) {
rootScope.add(scope)
}
func add(_ step: Step) {
rootScope.add(step)
}
func add(_ it: It) {
rootScope.add(it)
}
}
// MARK: - Scopes
/**
Adds a describe scope.
Describe scopes are normally used to encompass the subject under test or a specific behavior of the subject under test.
- Parameter title: The `describe`'s title that is included in the test output.
- Parameter closure: The `describe` scope to be executed during testing.
*/
public func describe(_ title: String, _ closure: () -> Void) {
intakeScope(type: .describe, title, closure, mark: .none)
}
/**
Adds a focused describe scope.
Describe scopes are normally used to encompass the subject under test or a specific behavior of the subject under test.
- Warning: If one or more focused tests/scopes are added, all non-focused tests/scopes outside of this `fdescribe()` will be treated as pending.
- Note: This has the same function signature as `describe()` for ease of use.
- Parameter title: The `describe`'s title that is included in the test output.
- Parameter closure: The `describe` scope to be executed during testing.
*/
public func fdescribe(_ title: String, _ closure: () -> Void) {
intakeScope(type: .describe, title, closure, mark: .focused)
}
/**
Adds a pending describe scope.
Describe scopes are normally used to encompass the subject under test or a specific behavior of the subject under test.
- Warning: Tests within this `xdescribe()` will be marked as pending regardless of any focus.
- Note: This has the same function signature as `describe()` for ease of use.
- Parameter title: The `describe`'s title that is included in the test output.
- Parameter closure: The `describe` scope to be executed during testing.
*/
public func xdescribe(_ title: String, _ closure: () -> Void) {