forked from openedx/openedx-app-ios
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MockTemplate.swifttemplate
2133 lines (1928 loc) · 93 KB
/
MockTemplate.swifttemplate
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
<%_
let mockTypeName = "Mock"
func swiftLintRules(_ arguments: [String: Any]) -> [String] {
return stringArray(fromArguments: arguments, forKey: "excludedSwiftLintRules").map { rule in
return "//swiftlint:disable \(rule)"
}
}
func projectImports(_ arguments: [String: Any]) -> [String] {
return imports(arguments) + testableImports(arguments)
}
func imports(_ arguments: [String: Any]) -> [String] {
return stringArray(fromArguments: arguments, forKey: "import")
.map { return "import \($0)" }
}
func testableImports(_ arguments: [String: Any]) -> [String] {
return stringArray(fromArguments: arguments, forKey: "testable")
.map { return "@testable import \($0)" }
}
/// [Internal] Get value from dictionary
/// - Parameters:
/// - fromArguments: dictionary
/// - forKey: dictionary key
/// - Returns: array of strings, if key not found, returns empty array.
/// - Note: If sourcery arguments containts only one element, then single value is stored, otherwise array of elements. This method always gets array of elements.
func stringArray(fromArguments arguments: [String: Any], forKey key: String) -> [String] {
if let argument = arguments[key] as? String {
return [argument]
} else if let manyArguments = arguments[key] as? [String] {
return manyArguments
} else {
return []
}
}
_%>
// Generated with SwiftyMocky 4.2.0
// Required Sourcery: 1.8.0
<%_ for rule in swiftLintRules(argument) { -%>
<%_ %><%= rule %>
<%_ } -%>
import SwiftyMocky
import XCTest
<%# ================================================== IMPORTS -%><%_ -%>
<%_ for projectImport in projectImports(argument) { -%>
<%_ %><%= projectImport %>
<%_ } -%>
<%# ============================ IMPORTS InAPP (aggregated argument) -%><%_ -%>
<%_ if let swiftyMockyArgs = argument["swiftyMocky"] as? [String: Any] { -%>
<%_ for projectImport in projectImports(swiftyMockyArgs) { -%>
<%_ %><%= projectImport %>
<%_ } -%>
<%_ } -%>
<%_
class Current {
static var selfType: String = "Self"
static var accessModifier: String = "open"
}
// Collision management
func areThereCollisions(between methods: [MethodWrapper]) -> Bool {
let givenSet = Set<String>(methods.map({ $0.givenConstructorName(prefix: "") }))
guard givenSet.count == methods.count else { return true } // there would be conflicts in Given
let verifySet = Set<String>(methods.map({ $0.verificationProxyConstructorName(prefix: "") }))
guard verifySet.count == methods.count else { return true } // there would be conflicts in Verify
return false
}
// herlpers
func uniques(methods: [SourceryRuntime.Method]) -> [SourceryRuntime.Method] {
func returnTypeStripped(_ method: SourceryRuntime.Method) -> String {
let returnTypeRaw = "\(method.returnTypeName)"
var stripped: String = {
guard let range = returnTypeRaw.range(of: "where") else { return returnTypeRaw }
var stripped = returnTypeRaw
stripped.removeSubrange((range.lowerBound)...)
return stripped
}()
stripped = stripped.trimmingCharacters(in: CharacterSet(charactersIn: " "))
return stripped
}
func areSameParams(_ p1: SourceryRuntime.MethodParameter, _ p2: SourceryRuntime.MethodParameter) -> Bool {
guard p1.argumentLabel == p2.argumentLabel else { return false }
guard p1.name == p2.name else { return false }
guard p1.argumentLabel == p2.argumentLabel else { return false }
guard p1.typeName.name == p2.typeName.name else { return false }
guard p1.actualTypeName?.name == p2.actualTypeName?.name else { return false }
return true
}
func areSameMethods(_ m1: SourceryRuntime.Method, _ m2: SourceryRuntime.Method) -> Bool {
guard m1.name != m2.name else { return m1.returnTypeName == m2.returnTypeName }
guard m1.selectorName == m2.selectorName else { return false }
guard m1.parameters.count == m2.parameters.count else { return false }
let p1 = m1.parameters
let p2 = m2.parameters
for i in 0..<p1.count {
if !areSameParams(p1[i],p2[i]) { return false }
}
return m1.returnTypeName == m2.returnTypeName
}
return methods.reduce([], { (result, element) -> [SourceryRuntime.Method] in
guard !result.contains(where: { areSameMethods($0,element) }) else { return result }
return result + [element]
})
}
func uniquesWithoutGenericConstraints(methods: [SourceryRuntime.Method]) -> [SourceryRuntime.Method] {
func returnTypeStripped(_ method: SourceryRuntime.Method) -> String {
let returnTypeRaw = "\(method.returnTypeName)"
var stripped: String = {
guard let range = returnTypeRaw.range(of: "where") else { return returnTypeRaw }
var stripped = returnTypeRaw
stripped.removeSubrange((range.lowerBound)...)
return stripped
}()
stripped = stripped.trimmingCharacters(in: CharacterSet(charactersIn: " "))
return stripped
}
func areSameParams(_ p1: SourceryRuntime.MethodParameter, _ p2: SourceryRuntime.MethodParameter) -> Bool {
guard p1.argumentLabel == p2.argumentLabel else { return false }
guard p1.name == p2.name else { return false }
guard p1.argumentLabel == p2.argumentLabel else { return false }
guard p1.typeName.name == p2.typeName.name else { return false }
guard p1.actualTypeName?.name == p2.actualTypeName?.name else { return false }
return true
}
func areSameMethods(_ m1: SourceryRuntime.Method, _ m2: SourceryRuntime.Method) -> Bool {
guard m1.name != m2.name else { return returnTypeStripped(m1) == returnTypeStripped(m2) }
guard m1.selectorName == m2.selectorName else { return false }
guard m1.parameters.count == m2.parameters.count else { return false }
let p1 = m1.parameters
let p2 = m2.parameters
for i in 0..<p1.count {
if !areSameParams(p1[i],p2[i]) { return false }
}
return returnTypeStripped(m1) == returnTypeStripped(m2)
}
return methods.reduce([], { (result, element) -> [SourceryRuntime.Method] in
guard !result.contains(where: { areSameMethods($0,element) }) else { return result }
return result + [element]
})
}
func uniques(variables: [SourceryRuntime.Variable]) -> [SourceryRuntime.Variable] {
return variables.reduce([], { (result, element) -> [SourceryRuntime.Variable] in
guard !result.contains(where: { $0.name == element.name }) else { return result }
return result + [element]
})
}
func wrapMethod(_ method: SourceryRuntime.Method) -> MethodWrapper {
return MethodWrapper(method)
}
func wrapSubscript(_ wrapped: SourceryRuntime.Subscript) -> SubscriptWrapper {
return SubscriptWrapper(wrapped)
}
func justWrap(_ variable: SourceryRuntime.Variable) -> VariableWrapper { return wrapProperty(variable) }
func wrapProperty(_ variable: SourceryRuntime.Variable, _ scope: String = "") -> VariableWrapper {
return VariableWrapper(variable, scope: scope)
}
func stubProperty(_ variable: SourceryRuntime.Variable, _ scope: String) -> String {
let wrapper = VariableWrapper(variable, scope: scope)
return "\(wrapper.prototype)\n\t\(wrapper.privatePrototype)"
}
func propertyTypes(_ variable: SourceryRuntime.Variable) -> String {
let wrapper = VariableWrapper(variable, scope: "scope")
return "\(wrapper.propertyGet())" + (wrapper.readonly ? "" : "\n\t\t\(wrapper.propertySet())")
}
func propertyMethodTypes(_ variable: SourceryRuntime.Variable) -> String {
let wrapper = VariableWrapper(variable, scope: "")
return "\(wrapper.propertyCaseGet())" + (wrapper.readonly ? "" : "\n\t\t\(wrapper.propertyCaseSet())")
}
func propertyMethodTypesIntValue(_ variable: SourceryRuntime.Variable) -> String {
let wrapper = VariableWrapper(variable, scope: "")
return "\(wrapper.propertyCaseGetIntValue())" + (wrapper.readonly ? "" : "\n\t\t\t\(wrapper.propertyCaseSetIntValue())")
}
func propertyRegister(_ variable: SourceryRuntime.Variable) {
let wrapper = VariableWrapper(variable, scope: "")
MethodWrapper.register(wrapper.propertyCaseGetName,wrapper.propertyCaseGetName,wrapper.propertyCaseGetName)
guard !wrapper.readonly else { return }
MethodWrapper.register(wrapper.propertyCaseSetName,wrapper.propertyCaseSetName,wrapper.propertyCaseGetName)
}
class Helpers {
static func split(_ string: String, byFirstOccurenceOf word: String) -> (String, String) {
guard let wordRange = string.range(of: word) else { return (string, "") }
let selfRange = string.range(of: string)!
let before = String(string[selfRange.lowerBound..<wordRange.lowerBound])
let after = String(string[wordRange.upperBound..<selfRange.upperBound])
return (before, after)
}
static func extractAssociatedTypes(from annotated: SourceryRuntime.Annotated) -> [String]? {
if let types = annotated.annotations["associatedtype"] as? [String] {
return types.reversed()
} else if let type = annotated.annotations["associatedtype"] as? String {
return [type]
} else {
return nil
}
}
static func extractWhereClause(from annotated: SourceryRuntime.Annotated) -> String? {
if let constraints = annotated.annotations["where"] as? [String] {
return " where \(constraints.reversed().joined(separator: ", "))"
} else if let constraint = annotated.annotations["where"] as? String {
return " where \(constraint)"
} else {
return nil
}
}
/// Extract all typealiases from "annotations"
static func extractTypealiases(from annotated: SourceryRuntime.Annotated) -> [String] {
if let types = annotated.annotations["typealias"] as? [String] {
return types.reversed()
} else if let type = annotated.annotations["typealias"] as? String {
return [type]
} else {
return []
}
}
static func extractGenericsList(_ associatedTypes: [String]?) -> [String] {
return associatedTypes?.flatMap {
split($0, byFirstOccurenceOf: " where ").0.replacingOccurrences(of: " ", with: "").split(separator: ":").map(String.init).first
}.map { "\($0)" } ?? []
}
static func extractGenericTypesModifier(_ associatedTypes: [String]?) -> String {
let all = extractGenericsList(associatedTypes)
guard !all.isEmpty else { return "" }
return "<\(all.joined(separator: ","))>"
}
static func extractGenericTypesConstraints(_ associatedTypes: [String]?) -> String {
guard let all = associatedTypes else { return "" }
let constraints = all.flatMap { t -> String? in
let splitted = split(t, byFirstOccurenceOf: " where ")
let constraint = splitted.0.replacingOccurrences(of: " ", with: "").split(separator: ":").map(String.init)
guard constraint.count == 2 else { return nil }
let adopts = constraint[1].split(separator: ",").map(String.init)
var mapped = adopts.map { "\(constraint[0]): \($0)" }
if !splitted.1.isEmpty {
mapped.append(splitted.1)
}
return mapped.joined(separator: ", ")
}
.joined(separator: ", ")
guard !constraints.isEmpty else { return "" }
return " where \(constraints)"
}
static func extractAttributes(
from attributes: [String: [SourceryRuntime.Attribute]],
filterOutStartingWith disallowedPrefixes: [String] = []
) -> String {
return attributes
.reduce([SourceryRuntime.Attribute]()) { $0 + $1.1 }
.map { $0.description }
.filter { !["private", "internal", "public", "open", "optional"].contains($0) }
.filter { element in
!disallowedPrefixes.contains(where: element.hasPrefix)
}
.sorted()
.joined(separator: " ")
}
}
class ParameterWrapper {
let parameter: MethodParameter
var isVariadic = false
var wrappedForCall: String {
let typeString = "\(type.actualTypeName ?? type)"
let isEscaping = typeString.contains("@escaping")
let isOptional = (type.actualTypeName ?? type).isOptional
if parameter.isClosure && !isEscaping && !isOptional {
return "\(nestedType).any"
} else {
return "\(nestedType).value(\(escapedName))"
}
}
var nestedType: String {
return "\(TypeWrapper(type, isVariadic).nestedParameter)"
}
var justType: String {
return "\(TypeWrapper(type, isVariadic).replacingSelf())"
}
var justPerformType: String {
return "\(TypeWrapper(type, isVariadic).replacingSelfRespectingVariadic())".replacingOccurrences(of: "!", with: "?")
}
var genericType: String {
return isVariadic ? "Parameter<[GenericAttribute]>" : "Parameter<GenericAttribute>"
}
var typeErasedType: String {
return isVariadic ? "Parameter<[TypeErasedAttribute]>" : "Parameter<TypeErasedAttribute>"
}
var type: SourceryRuntime.TypeName {
return parameter.typeName
}
var name: String {
return parameter.name
}
var escapedName: String {
return "`\(parameter.name)`"
}
var comparator: String {
return "guard Parameter.compare(lhs: lhs\(parameter.name.capitalized), rhs: rhs\(parameter.name.capitalized), with: matcher) else { return false }"
}
func comparatorResult() -> String {
let lhsName = "lhs\(parameter.name.capitalized)"
let rhsName = "rhs\(parameter.name.capitalized)"
return "results.append(Matcher.ParameterComparisonResult(Parameter.compare(lhs: \(lhsName), rhs: \(rhsName), with: matcher), \(lhsName), \(rhsName), \"\(labelAndName())\"))"
}
init(_ parameter: SourceryRuntime.MethodParameter, _ variadics: [String] = []) {
self.parameter = parameter
self.isVariadic = !variadics.isEmpty && variadics.contains(parameter.name)
}
func isGeneric(_ types: [String]) -> Bool {
return TypeWrapper(type).isGeneric(types)
}
func wrappedForProxy(_ generics: [String], _ availability: Bool = false) -> String {
if isGeneric(generics) {
return "\(escapedName).wrapAsGeneric()"
}
if (availability) {
return "\(escapedName).typeErasedAttribute()"
}
return "\(escapedName)"
}
func wrappedForCalls(_ generics: [String], _ availability: Bool = false) -> String {
if isGeneric(generics) {
return "\(wrappedForCall).wrapAsGeneric()"
}
if (availability) {
return "\(wrappedForCall).typeErasedAttribute()"
}
return "\(wrappedForCall)"
}
func asMethodArgument() -> String {
if parameter.argumentLabel != parameter.name {
return "\(parameter.argumentLabel ?? "_") \(parameter.name): \(parameter.typeName)"
} else {
return "\(parameter.name): \(parameter.typeName)"
}
}
func labelAndName() -> String {
let label = parameter.argumentLabel ?? "_"
return label != parameter.name ? "\(label) \(parameter.name)" : label
}
func sanitizedForEnumCaseName() -> String {
if let label = parameter.argumentLabel, label != parameter.name {
return "\(label)_\(parameter.name)".replacingOccurrences(of: "`", with: "")
} else {
return "\(parameter.name)".replacingOccurrences(of: "`", with: "")
}
}
}
class TypeWrapper {
let type: SourceryRuntime.TypeName
let isVariadic: Bool
var vPref: String { return isVariadic ? "[" : "" }
var vSuff: String { return isVariadic ? "]" : "" }
var unwrapped: String {
return type.unwrappedTypeName
}
var unwrappedReplacingSelf: String {
return replacingSelf(unwrap: true)
}
var stripped: String {
if type.isImplicitlyUnwrappedOptional {
return "\(vPref)\(unwrappedReplacingSelf)?\(vSuff)"
} else if type.isOptional {
return "\(vPref)\(unwrappedReplacingSelf)?\(vSuff)"
} else {
return "\(vPref)\(unwrappedReplacingSelf)\(vSuff)"
}
}
var nestedParameter: String {
if type.isImplicitlyUnwrappedOptional {
return "Parameter<\(vPref)\(unwrappedReplacingSelf)?\(vSuff)>"
} else if type.isOptional {
return "Parameter<\(vPref)\(unwrappedReplacingSelf)?\(vSuff)>"
} else {
return "Parameter<\(vPref)\(unwrappedReplacingSelf)\(vSuff)>"
}
}
var isSelfType: Bool {
return unwrapped == "Self"
}
func isSelfTypeRecursive() -> Bool {
if let tuple = type.tuple {
for element in tuple.elements {
guard !TypeWrapper(element.typeName).isSelfTypeRecursive() else { return true }
}
} else if let array = type.array {
return TypeWrapper(array.elementTypeName).isSelfTypeRecursive()
} else if let dictionary = type.dictionary {
guard !TypeWrapper(dictionary.valueTypeName).isSelfTypeRecursive() else { return true }
guard !TypeWrapper(dictionary.keyTypeName).isSelfTypeRecursive() else { return true }
} else if let closure = type.closure {
guard !TypeWrapper(closure.actualReturnTypeName).isSelfTypeRecursive() else { return true }
for parameter in closure.parameters {
guard !TypeWrapper(parameter.typeName).isSelfTypeRecursive() else { return true }
}
}
return isSelfType
}
init(_ type: SourceryRuntime.TypeName, _ isVariadic: Bool = false) {
self.type = type
self.isVariadic = isVariadic
}
func isGeneric(_ types: [String]) -> Bool {
guard !type.isVoid else { return false }
return isGeneric(name: unwrapped, generics: types)
}
private func isGeneric(name: String, generics: [String]) -> Bool {
let name = "(\(name.replacingOccurrences(of: " ", with: "")))"
let modifiers = "[\\?\\!]*"
return generics.contains(where: { generic in
let wrapped = "([\\(]\(generic)\(modifiers)[\\)\\.])"
let constraint = "([<,]\(generic)\(modifiers)[>,\\.])"
let arrays = "([\\[:]\(generic)\(modifiers)[\\],\\.:])"
let tuples = "([\\(,]\(generic)\(modifiers)[,\\.\\)])"
let closures = "((\\-\\>)\(generic)\(modifiers)[,\\.\\)])"
let pattern = "\(wrapped)|\(constraint)|\(arrays)|\(tuples)|\(closures)"
guard let regex = try? NSRegularExpression(pattern: pattern) else { return false }
return regex.firstMatch(in: name, options: [], range: NSRange(location: 0, length: (name as NSString).length)) != nil
})
}
func replacingSelf(unwrap: Bool = false) -> String {
guard isSelfTypeRecursive() else {
return unwrap ? self.unwrapped : "\(type)"
}
if isSelfType {
let optionality: String = {
if type.isImplicitlyUnwrappedOptional {
return "!"
} else if type.isOptional {
return "?"
} else {
return ""
}
}()
return unwrap ? Current.selfType : Current.selfType + optionality
} else if let tuple = type.tuple {
let inner = tuple.elements.map({ TypeWrapper($0.typeName).replacingSelf() }).joined(separator: ",")
let value = "(\(inner))"
return value
} else if let array = type.array {
let value = "[\(TypeWrapper(array.elementTypeName).replacingSelf())]"
return value
} else if let dictionary = type.dictionary {
let value = "[" +
"\(TypeWrapper(dictionary.valueTypeName).replacingSelf())"
+ ":" +
"\(TypeWrapper(dictionary.keyTypeName).replacingSelf())"
+ "]"
return value
} else if let closure = type.closure {
let returnType = TypeWrapper(closure.actualReturnTypeName).replacingSelf()
let inner = closure.parameters
.map { TypeWrapper($0.typeName).replacingSelf() }
.joined(separator: ",")
let throwing = closure.throws ? "throws " : ""
let value = "(\(inner)) \(throwing)-> \(returnType)"
return value
} else {
return (unwrap ? self.unwrapped : "\(type)")
}
}
func replacingSelfRespectingVariadic() -> String {
return "\(vPref)\(replacingSelf())\(vSuff)"
}
}
func replacingSelf(_ value: String) -> String {
return value
// TODO: proper regex here
// default < case >
.replacingOccurrences(of: "<Self>", with: "<\(Current.selfType)>")
.replacingOccurrences(of: "<Self ", with: "<\(Current.selfType) ")
.replacingOccurrences(of: "<Self.", with: "<\(Current.selfType).")
.replacingOccurrences(of: "<Self,", with: "<\(Current.selfType),")
.replacingOccurrences(of: "<Self?", with: "<\(Current.selfType)?")
.replacingOccurrences(of: " Self>", with: " \(Current.selfType)>")
.replacingOccurrences(of: ",Self>", with: ",\(Current.selfType)>")
// (Self) -> Case
.replacingOccurrences(of: "(Self)", with: "(\(Current.selfType))")
.replacingOccurrences(of: "(Self ", with: "(\(Current.selfType) ")
.replacingOccurrences(of: "(Self.", with: "(\(Current.selfType).")
.replacingOccurrences(of: "(Self,", with: "(\(Current.selfType),")
.replacingOccurrences(of: "(Self?", with: "(\(Current.selfType)?")
.replacingOccurrences(of: " Self)", with: " \(Current.selfType))")
.replacingOccurrences(of: ",Self)", with: ",\(Current.selfType))")
// literals
.replacingOccurrences(of: "[Self]", with: "[\(Current.selfType)]")
// right
.replacingOccurrences(of: "[Self ", with: "[\(Current.selfType) ")
.replacingOccurrences(of: "[Self.", with: "[\(Current.selfType).")
.replacingOccurrences(of: "[Self,", with: "[\(Current.selfType),")
.replacingOccurrences(of: "[Self:", with: "[\(Current.selfType):")
.replacingOccurrences(of: "[Self?", with: "[\(Current.selfType)?")
// left
.replacingOccurrences(of: " Self]", with: " \(Current.selfType)]")
.replacingOccurrences(of: ",Self]", with: ",\(Current.selfType)]")
.replacingOccurrences(of: ":Self]", with: ":\(Current.selfType)]")
// unknown
.replacingOccurrences(of: " Self ", with: " \(Current.selfType) ")
.replacingOccurrences(of: " Self.", with: " \(Current.selfType).")
.replacingOccurrences(of: " Self,", with: " \(Current.selfType),")
.replacingOccurrences(of: " Self:", with: " \(Current.selfType):")
.replacingOccurrences(of: " Self?", with: " \(Current.selfType)?")
.replacingOccurrences(of: ",Self ", with: ",\(Current.selfType) ")
.replacingOccurrences(of: ",Self,", with: ",\(Current.selfType),")
.replacingOccurrences(of: ",Self?", with: ",\(Current.selfType)?")
}
class MethodWrapper {
private var noStubDefinedMessage: String {
let methodName = method.name.condenseWhitespace()
.replacingOccurrences(of: "( ", with: "(")
.replacingOccurrences(of: " )", with: ")")
return "Stub return value not specified for \(methodName). Use given"
}
private static var registered: [String: Int] = [:]
private static var suffixes: [String: Int] = [:]
private static var suffixesWithoutReturnType: [String: Int] = [:]
let method: SourceryRuntime.Method
var accessModifier: String {
guard !method.isStatic else { return "public static" }
guard !returnsGenericConstrainedToSelf else { return "public" }
guard !parametersContainsSelf else { return "public" }
return Current.accessModifier
}
var hasAvailability: Bool { method.attributes["available"]?.isEmpty == false }
var isAsync: Bool {
self.method.annotations["async"] != nil
}
private var registrationName: String {
var rawName = (method.isStatic ? "sm*\(method.selectorName)" : "m*\(method.selectorName)")
.replacingOccurrences(of: "_", with: "")
.replacingOccurrences(of: "(", with: "__")
.replacingOccurrences(of: ")", with: "")
var parametersNames = method.parameters.map { "\($0.name)" }
while let range = rawName.range(of: ":"), let name = parametersNames.first {
parametersNames.removeFirst()
rawName.replaceSubrange(range, with: "_\(name)")
}
let trimSet = CharacterSet(charactersIn: "_")
return rawName
.replacingOccurrences(of: ":", with: "")
.replacingOccurrences(of: "m*", with: "m_")
.replacingOccurrences(of: "___", with: "__").trimmingCharacters(in: trimSet)
}
private var uniqueName: String {
var rawName = (method.isStatic ? "sm_\(method.selectorName)" : "m_\(method.selectorName)")
var parametersNames = method.parameters.map { "\($0.name)_of_\($0.typeName.name)" }
while let range = rawName.range(of: ":"), let name = parametersNames.first {
parametersNames.removeFirst()
rawName.replaceSubrange(range, with: "_\(name)")
}
return rawName.trimmingCharacters(in: CharacterSet(charactersIn: "_"))
}
private var uniqueNameWithReturnType: String {
let returnTypeRaw = "\(method.returnTypeName)"
var returnTypeStripped: String = {
guard let range = returnTypeRaw.range(of: "where") else { return returnTypeRaw }
var stripped = returnTypeRaw
stripped.removeSubrange((range.lowerBound)...)
return stripped
}()
returnTypeStripped = returnTypeStripped.trimmingCharacters(in: CharacterSet(charactersIn: " "))
return "\(uniqueName)->\(returnTypeStripped)"
}
private var nameSuffix: String {
guard let count = MethodWrapper.registered[registrationName] else { return "" }
guard count > 1 else { return "" }
guard let index = MethodWrapper.suffixes[uniqueNameWithReturnType] else { return "" }
return "_\(index)"
}
private var methodAttributes: String {
return Helpers.extractAttributes(from: self.method.attributes, filterOutStartingWith: ["mutating", "@inlinable"])
}
private var methodAttributesNonObjc: String {
return Helpers.extractAttributes(from: self.method.attributes, filterOutStartingWith: ["mutating", "@inlinable", "@objc"])
}
var prototype: String {
return "\(registrationName)\(nameSuffix)".replacingOccurrences(of: "`", with: "")
}
var parameters: [ParameterWrapper] {
return filteredParameters.map { ParameterWrapper($0, self.getVariadicParametersNames()) }
}
var filteredParameters: [MethodParameter] {
return method.parameters.filter { $0.name != "" }
}
var functionPrototype: String {
let throwing: String = {
if method.throws {
return "throws "
} else if method.rethrows {
return "rethrows "
} else {
return ""
}
}()
let staticModifier: String = "\(accessModifier) "
let params = replacingSelf(parametersForStubSignature())
var attributes = self.methodAttributes
attributes = attributes.isEmpty ? "" : "\(attributes)\n\t"
var asyncModifier = self.isAsync ? "async " : ""
if method.isInitializer {
return "\(attributes)public required \(method.name) \(asyncModifier)\(throwing)"
} else if method.returnTypeName.isVoid {
let wherePartIfNeeded: String = {
if method.returnTypeName.name.hasPrefix("Void") {
let range = method.returnTypeName.name.range(of: "Void")!
return "\(method.returnTypeName.name[range.upperBound...])"
} else {
return !method.returnTypeName.name.isEmpty ? "\(method.returnTypeName.name) " : ""
}
}()
return "\(attributes)\(staticModifier)func \(method.shortName)\(params) \(asyncModifier)\(throwing)\(wherePartIfNeeded)"
} else if returnsGenericConstrainedToSelf {
return "\(attributes)\(staticModifier)func \(method.shortName)\(params) \(asyncModifier)\(throwing)-> \(returnTypeReplacingSelf) "
} else {
return "\(attributes)\(staticModifier)func \(method.shortName)\(params) \(asyncModifier)\(throwing)-> \(method.returnTypeName.name) "
}
}
var invocation: String {
guard !method.isInitializer else { return "" }
if filteredParameters.isEmpty {
return "addInvocation(.\(prototype))"
} else {
return "addInvocation(.\(prototype)(\(parametersForMethodCall())))"
}
}
var givenValue: String {
guard !method.isInitializer else { return "" }
guard method.throws || !method.returnTypeName.isVoid else { return "" }
let methodType = filteredParameters.isEmpty ? ".\(prototype)" : ".\(prototype)(\(parametersForMethodCall()))"
let returnType: String = returnsSelf ? "__Self__" : "\(TypeWrapper(method.returnTypeName).stripped)"
if method.returnTypeName.isVoid {
return """
\n\t\tdo {
\t\t _ = try methodReturnValue(\(methodType)).casted() as Void
\t\t}\(" ")
"""
} else {
let defaultValue = method.returnTypeName.isOptional ? " = nil" : ""
return """
\n\t\tvar __value: \(returnType)\(defaultValue)
\t\tdo {
\t\t __value = try methodReturnValue(\(methodType)).casted()
\t\t}\(" ")
"""
}
}
var throwValue: String {
guard !method.isInitializer else { return "" }
guard method.throws || !method.returnTypeName.isVoid else { return "" }
let safeFailure = method.isStatic ? "" : "\t\t\tonFatalFailure(\"\(noStubDefinedMessage)\")\n"
// For Void and Returning optionals - we allow not stubbed case to happen, as we are still able to return
let noStubHandling = method.returnTypeName.isVoid || method.returnTypeName.isOptional ? "\t\t\t// do nothing" : "\(safeFailure)\t\t\tFailure(\"\(noStubDefinedMessage)\")"
guard method.throws else {
return """
catch {
\(noStubHandling)
\t\t}
"""
}
return """
catch MockError.notStubed {
\(noStubHandling)
\t\t} catch {
\t\t throw error
\t\t}
"""
}
var returnValue: String {
guard !method.isInitializer else { return "" }
guard !method.returnTypeName.isVoid else { return "" }
return "\n\t\treturn __value"
}
var equalCase: String {
guard !method.isInitializer else { return "" }
if filteredParameters.isEmpty {
return "case (.\(prototype), .\(prototype)):"
} else {
let lhsParams = filteredParameters.map { "let lhs\($0.name.capitalized)" }.joined(separator: ", ")
let rhsParams = filteredParameters.map { "let rhs\($0.name.capitalized)" }.joined(separator: ", ")
return "case (.\(prototype)(\(lhsParams)), .\(prototype)(\(rhsParams))):"
}
}
func equalCases() -> String {
var results = self.equalCase
guard !parameters.isEmpty else {
results += " return .match"
return results
}
results += "\n\t\t\t\tvar results: [Matcher.ParameterComparisonResult] = []\n"
results += parameters.map { "\t\t\t\t\($0.comparatorResult())" }.joined(separator: "\n")
results += "\n\t\t\t\treturn Matcher.ComparisonResult(results)"
return results
}
var intValueCase: String {
if filteredParameters.isEmpty {
return "case .\(prototype): return 0"
} else {
let params = filteredParameters.enumerated().map { offset, _ in
return "p\(offset)"
}
let definitions = params.joined(separator: ", ")
let paramsSum = params.map({ "\($0).intValue" }).joined(separator: " + ")
return "case let .\(prototype)(\(definitions)): return \(paramsSum)"
}
}
var assertionName: String {
return "case .\(prototype): return \".\(method.selectorName)\(method.parameters.isEmpty ? "()" : "")\""
}
var returnsSelf: Bool {
guard !returnsGenericConstrainedToSelf else { return true }
return !method.returnTypeName.isVoid && TypeWrapper(method.returnTypeName).isSelfType
}
var returnsGenericConstrainedToSelf: Bool {
let defaultReturnType = "\(method.returnTypeName.name) "
return defaultReturnType != returnTypeReplacingSelf
}
var returnTypeReplacingSelf: String {
return replacingSelf("\(method.returnTypeName.name) ")
}
var parametersContainsSelf: Bool {
return replacingSelf(parametersForStubSignature()) != parametersForStubSignature()
}
var replaceSelf: String {
return Current.selfType
}
init(_ method: SourceryRuntime.Method) {
self.method = method
}
public static func clear() -> String {
MethodWrapper.registered = [:]
MethodWrapper.suffixes = [:]
MethodWrapper.suffixesWithoutReturnType = [:]
return ""
}
func register() {
MethodWrapper.register(registrationName,uniqueName,uniqueNameWithReturnType)
}
static func register(_ name: String, _ uniqueName: String, _ uniqueNameWithReturnType: String) {
if let count = MethodWrapper.registered[name] {
MethodWrapper.registered[name] = count + 1
MethodWrapper.suffixes[uniqueNameWithReturnType] = count + 1
} else {
MethodWrapper.registered[name] = 1
MethodWrapper.suffixes[uniqueNameWithReturnType] = 1
}
if let count = MethodWrapper.suffixesWithoutReturnType[uniqueName] {
MethodWrapper.suffixesWithoutReturnType[uniqueName] = count + 1
} else {
MethodWrapper.suffixesWithoutReturnType[uniqueName] = 1
}
}
func returnTypeMatters() -> Bool {
let count = MethodWrapper.suffixesWithoutReturnType[uniqueName] ?? 0
return count > 1
}
func wrappedInMethodType() -> Bool {
return !method.isInitializer
}
func returningParameter(_ multiple: Bool, _ front: Bool) -> String {
guard returnTypeMatters() else { return "" }
let returning: String = "returning: \(returnTypeStripped(method, type: true))"
guard multiple else { return returning }
return front ? ", \(returning)" : "\(returning), "
}
// Stub
func stubBody() -> String {
let body: String = {
if method.isInitializer || !returnsSelf {
return invocation + performCall() + givenValue + throwValue + returnValue
} else {
return wrappedStubPrefix()
+ "\t\t" + invocation
+ performCall()
+ givenValue
+ throwValue
+ returnValue
+ wrappedStubPostfix()
}
}()
return replacingSelf(body)
}
func wrappedStubPrefix() -> String {
guard !method.isInitializer, returnsSelf else {
return ""
}
let throwing: String = {
if method.throws {
return "throws "
} else if method.rethrows {
return "rethrows "
} else {
return ""
}
}()
return "func _wrapped<__Self__>() \(throwing)-> __Self__ {\n"
}
func wrappedStubPostfix() -> String {
guard !method.isInitializer, returnsSelf else {
return ""
}
let throwing: String = (method.throws || method.rethrows) ? "try ": ""
return "\n\t\t}"
+ "\n\t\treturn \(throwing)_wrapped()"
}
// Method Type
func methodTypeDeclarationWithParameters() -> String {
if filteredParameters.isEmpty {
return "case \(prototype)"
} else {
return "case \(prototype)(\(parametersForMethodTypeDeclaration(availability: hasAvailability)))"
}
}
// Given
func containsEmptyArgumentLabels() -> Bool {
return parameters.contains(where: { $0.parameter.argumentLabel == nil })
}
func givenReturnTypeString() -> String {
let returnTypeString: String = {
guard !returnsGenericConstrainedToSelf else { return returnTypeReplacingSelf }
guard !returnsSelf else { return replaceSelf }
return TypeWrapper(method.returnTypeName).stripped
}()
return returnTypeString
}
func givenConstructorName(prefix: String = "") -> String {
let returnTypeString = givenReturnTypeString()
let (annotation, _, _) = methodInfo()
let clauseConstraints = whereClauseExpression()
if filteredParameters.isEmpty {
return "\(annotation)public static func \(method.shortName)(willReturn: \(returnTypeString)...) -> \(prefix)MethodStub" + clauseConstraints
} else {
return "\(annotation)public static func \(method.shortName)(\(parametersForProxySignature()), willReturn: \(returnTypeString)...) -> \(prefix)MethodStub" + clauseConstraints
}
}
func givenConstructorNameThrows(prefix: String = "") -> String {
let (annotation, _, _) = methodInfo()
let clauseConstraints = whereClauseExpression()
let genericsArray = getGenericsConstraints(getGenericsAmongParameters(), filterSingle: false)
let generics = genericsArray.isEmpty ? "" : "<\(genericsArray.joined(separator: ", "))>"
if filteredParameters.isEmpty {
return "\(annotation)public static func \(method.callName)\(generics)(willThrow: Error...) -> \(prefix)MethodStub" + clauseConstraints
} else {
return "\(annotation)public static func \(method.callName)\(generics)(\(parametersForProxySignature()), willThrow: Error...) -> \(prefix)MethodStub" + clauseConstraints
}
}
func givenConstructor(prefix: String = "") -> String {
if filteredParameters.isEmpty {
return "return \(prefix)Given(method: .\(prototype), products: willReturn.map({ StubProduct.return($0 as Any) }))"
} else {
return "return \(prefix)Given(method: .\(prototype)(\(parametersForProxyInit())), products: willReturn.map({ StubProduct.return($0 as Any) }))"
}
}
func givenConstructorThrows(prefix: String = "") -> String {
if filteredParameters.isEmpty {
return "return \(prefix)Given(method: .\(prototype), products: willThrow.map({ StubProduct.throw($0) }))"
} else {
return "return \(prefix)Given(method: .\(prototype)(\(parametersForProxyInit())), products: willThrow.map({ StubProduct.throw($0) }))"
}
}
// Given willProduce
func givenProduceConstructorName(prefix: String = "") -> String {
let returnTypeString = givenReturnTypeString()
let (annotation, _, _) = methodInfo()
let produceClosure = "(Stubber<\(returnTypeString)>) -> Void"
let clauseConstraints = whereClauseExpression()
if filteredParameters.isEmpty {
return "\(annotation)public static func \(method.shortName)(willProduce: \(produceClosure)) -> \(prefix)MethodStub" + clauseConstraints
} else {
return "\(annotation)public static func \(method.shortName)(\(parametersForProxySignature()), willProduce: \(produceClosure)) -> \(prefix)MethodStub" + clauseConstraints
}
}
func givenProduceConstructorNameThrows(prefix: String = "") -> String {
let returnTypeString = givenReturnTypeString()
let (annotation, _, _) = methodInfo()
let produceClosure = "(StubberThrows<\(returnTypeString)>) -> Void"
let clauseConstraints = whereClauseExpression()
if filteredParameters.isEmpty {
return "\(annotation)public static func \(method.shortName)(willProduce: \(produceClosure)) -> \(prefix)MethodStub" + clauseConstraints
} else {
return "\(annotation)public static func \(method.shortName)(\(parametersForProxySignature()), willProduce: \(produceClosure)) -> \(prefix)MethodStub" + clauseConstraints
}
}
func givenProduceConstructor(prefix: String = "") -> String {
let returnTypeString = givenReturnTypeString()
return """
let willReturn: [\(returnTypeString)] = []
\t\t\tlet given: \(prefix)Given = { \(givenConstructor(prefix: prefix)) }()
\t\t\tlet stubber = given.stub(for: (\(returnTypeString)).self)
\t\t\twillProduce(stubber)
\t\t\treturn given
"""
}
func givenProduceConstructorThrows(prefix: String = "") -> String {
let returnTypeString = givenReturnTypeString()
return """
let willThrow: [Error] = []
\t\t\tlet given: \(prefix)Given = { \(givenConstructorThrows(prefix: prefix)) }()
\t\t\tlet stubber = given.stubThrows(for: (\(returnTypeString)).self)
\t\t\twillProduce(stubber)
\t\t\treturn given
"""
}
// Verify
func verificationProxyConstructorName(prefix: String = "") -> String {
let (annotation, methodName, genericConstrains) = methodInfo()