Best Mockingbird code snippet using MethodTemplate.modifiers
MethodTemplate.swift
Source:MethodTemplate.swift
...152 return String(lines: methods, spacing: 2)153 }154 155 /// Modifiers specifically for stubbing and verification methods.156 lazy var regularModifiers: String = { return modifiers(allowOverride: false) }()157 /// Modifiers for mocked methods.158 lazy var overridableModifiers: String = { return modifiers(allowOverride: true) }()159 func modifiers(allowOverride: Bool = true) -> String {160 let isRequired = method.attributes.contains(.required)161 let required = (isRequired || method.isInitializer ? "required " : "")162 let shouldOverride = method.isOverridable && !isRequired && allowOverride163 let override = shouldOverride ? "override " : ""164 let `static` = method.kind.typeScope.isStatic ? "static " : ""165 return "\(required)\(override)\(`static`)"166 }167 168 lazy var genericTypes: [String] = {169 return method.genericTypes.map({ $0.flattenedDeclaration })170 }()171 172 lazy var genericConstraints: String = {173 guard !method.whereClauses.isEmpty else { return "" }174 return " where \(separated: method.whereClauses.map({ context.specializeTypeName("\($0)") }))"175 }()176 177 enum FunctionVariant {178 case function, subscriptGetter, subscriptSetter179 180 var isSubscript: Bool {181 switch self {182 case .function: return false183 case .subscriptGetter, .subscriptSetter: return true184 }185 }186 }187 188 enum FullNameMode {189 case mocking(variant: FunctionVariant)190 case matching(useVariadics: Bool, variant: FunctionVariant)191 case initializerProxy192 193 var isMatching: Bool {194 switch self {195 case .matching: return true196 case .mocking, .initializerProxy: return false197 }198 }199 200 var isInitializerProxy: Bool {201 switch self {202 case .matching, .mocking: return false203 case .initializerProxy: return true204 }205 }206 207 var useVariadics: Bool {208 switch self {209 case .matching(let useVariadics, _): return useVariadics210 case .mocking, .initializerProxy: return false211 }212 }213 214 var variant: FunctionVariant {215 switch self {216 case .matching(_, let variant), .mocking(let variant): return variant217 case .initializerProxy: return .function218 }219 }220 }221 222 func shortName(for mode: FullNameMode) -> String {223 let failable: String224 if mode.isInitializerProxy {225 failable = ""226 } else if method.attributes.contains(.failable) {227 failable = "?"228 } else if method.attributes.contains(.unwrappedFailable) {229 failable = "!"230 } else {231 failable = ""232 }233 234 // Don't escape initializers, subscripts, and special functions with reserved tokens like `==`.235 let shouldEscape = !method.isInitializer236 && method.kind != .functionSubscript237 && (method.shortName.first?.isLetter == true238 || method.shortName.first?.isNumber == true239 || method.shortName.first == "_")240 let escapedShortName = mode.isInitializerProxy ? "initialize" :241 (shouldEscape ? method.shortName.backtickWrapped : method.shortName)242 243 return genericTypes.isEmpty244 ? "\(escapedShortName)\(failable)"245 : "\(escapedShortName)\(failable)<\(separated: genericTypes)>"246 }247 248 lazy var fullNameForMocking: String = {249 return fullName(for: .mocking(variant: .function))250 }()251 lazy var fullNameForMatching: String = {252 return fullName(for: .matching(useVariadics: false, variant: .function))253 }()254 /// It's not possible to have an autoclosure with variadics. However, since a method can only have255 /// one variadic parameter, we can generate one method for wildcard matching using an argument256 /// matcher, and another for specific matching using variadics.257 lazy var fullNameForMatchingVariadics: String = {258 return fullName(for: .matching(useVariadics: true, variant: .function))259 }()260 func fullName(for mode: FullNameMode) -> String {261 let additionalParameters: [String]262 if mode.isInitializerProxy {263 additionalParameters = ["__file: StaticString = #file", "__line: UInt = #line"]264 } else if mode.variant == .subscriptSetter {265 let closureType = mode.isMatching ? "@autoclosure () -> " : ""266 additionalParameters = ["`newValue`: \(closureType)\(matchableReturnType)"]267 } else {268 additionalParameters = []269 }270 271 let parameterNames = method.parameters.map({ parameter -> String in272 let typeName: String273 if mode.isMatching && (!mode.useVariadics || !parameter.attributes.contains(.variadic)) {274 typeName = "@autoclosure () -> \(parameter.matchableTypeName(in: self))"275 } else {276 typeName = parameter.mockableTypeName(context: self)277 }278 let argumentLabel = parameter.argumentLabel ?? "_"279 let parameterName = parameter.name.backtickWrapped280 if argumentLabel.backtickUnwrapped != parameter.name {281 return "\(argumentLabel) \(parameterName): \(typeName)"282 } else if mode.isMatching && mode.variant.isSubscript {283 // Synthesized declarations for subscripts don't use argument labels (unless the parameter284 // name differs) for parity with bracket syntax.285 return "_ \(parameterName): \(typeName)"286 } else {287 return "\(parameterName): \(typeName)"288 }289 }) + additionalParameters290 291 let actualShortName = shortName(for: mode)292 let shortName: String293 if mode.isMatching, let resolvedShortName = Constants.reservedNamesMap[actualShortName] {294 shortName = resolvedShortName295 } else {296 shortName = actualShortName297 }298 299 return "\(shortName)(\(separated: parameterNames))"300 }301 302 lazy var mockableInvocation: String = {303 return ObjectInitializationTemplate(304 name: "Mockingbird.SwiftInvocation",305 arguments: [306 ("selectorName", "\(doubleQuoted: uniqueDeclaration)"),307 ("selectorType", "Mockingbird.SelectorType.method"),308 ("arguments", "[\(separated: mockArgumentMatchers)]"),309 ("returnType", "Swift.ObjectIdentifier(\(parenthetical: matchableReturnType).self)"),310 ]).render()311 }()312 313 func matchableInvocation(isVariadic: Bool = false) -> String {314 let matchers = isVariadic ? resolvedVariadicArgumentMatchers : resolvedArgumentMatchers315 return ObjectInitializationTemplate(316 name: "Mockingbird.SwiftInvocation",317 arguments: [318 ("selectorName", "\(doubleQuoted: uniqueDeclaration)"),319 ("selectorType", "Mockingbird.SelectorType.method"),320 ("arguments", "[\(matchers)]"),321 ("returnType", "Swift.ObjectIdentifier(\(parenthetical: matchableReturnType).self)"),322 ]).render()323 }324 325 lazy var resolvedArgumentMatchers: String = {326 return self.resolvedArgumentMatchers(for: method.parameters.map({ ($0.name, true) }))327 }()328 329 /// Variadic parameters cannot be resolved indirectly using `resolve()`.330 lazy var resolvedVariadicArgumentMatchers: String = {331 let parameters = method.parameters.map({ ($0.name, !$0.attributes.contains(.variadic)) })332 return resolvedArgumentMatchers(for: parameters)333 }()334 335 /// Can create argument matchers via resolving (shouldResolve = true) or by direct initialization.336 func resolvedArgumentMatchers(for parameters: [(name: String, shouldResolve: Bool)]) -> String {337 return String(list: parameters.map({ (name, shouldResolve) in338 let type = shouldResolve ? "resolve" : "ArgumentMatcher"339 return "Mockingbird.\(type)(\(name.backtickWrapped))"340 }))341 }342 343 lazy var returnTypeAttributesForMocking: String = {344 if method.attributes.contains(.rethrows) { return " rethrows" }345 if method.attributes.contains(.throws) { return " throws" }346 return ""347 }()348 349 lazy var returnTypeAttributesForMatching: String = {350 return method.isThrowing ? "throws " : ""351 }()352 353 lazy var declarationTypeForMocking: String = {354 if method.attributes.contains(.throws) {355 return "\(Declaration.throwingFunctionDeclaration)"356 } else {357 return "\(Declaration.functionDeclaration)"358 }359 }()360 361 lazy var mockArgumentMatchers: [String] = {362 return method.parameters.map({ parameter -> String in363 guard !parameter.isNonEscapingClosure else {364 // Can't save the argument in the invocation because it's a non-escaping closure type.365 return ObjectInitializationTemplate(366 name: "Mockingbird.ArgumentMatcher",367 arguments: [368 (nil, ObjectInitializationTemplate(369 name: "Mockingbird.NonEscapingClosure",370 genericTypes: [parameter.matchableTypeName(in: self)]).render())371 ]).render()372 }373 return ObjectInitializationTemplate(374 name: "Mockingbird.ArgumentMatcher",375 arguments: [(nil, "\(backticked: parameter.name)")]).render()376 })377 }()378 379 lazy var mockObject: String = {380 return method.kind.typeScope.isStatic ? "self.staticMock" : "self"381 }()382 383 /// Original function signature for casting to a matchable signature (variadics support).384 lazy var originalSignature: String = {385 let modifiers = method.isThrowing ? " throws" : ""386 let parameterTypes = method.parameters.map({387 $0.matchableTypeName(context: self, bridgeVariadics: false)388 })389 return "(\(separated: parameterTypes))\(modifiers) -> \(matchableReturnType)"390 }()391 392 /// General function signature for matching.393 lazy var longSignature: String = {394 let modifiers = method.isThrowing ? " throws" : ""395 return "(\(separated: matchableParameterTypes))\(modifiers) -> \(matchableReturnType)"396 }()397 398 /// Convenience function signature for matching without any arguments.399 lazy var shortSignature: String = {400 let modifiers = method.isThrowing ? " throws" : ""401 return "()\(modifiers) -> \(matchableReturnType)"402 }()403 404 lazy var mockableReturnType: String = {405 return context.specializeTypeName(method.returnTypeName)406 }()407 408 lazy var matchableReturnType: String = {409 return mockableReturnType.removingImplicitlyUnwrappedOptionals()410 }()411 412 lazy var mockableParameterTypes: [String] = {413 return method.parameters.map({ $0.mockableTypeName(context: self) })414 }()415 ...
InitializerMethodTemplate.swift
Source:InitializerMethodTemplate.swift
1//2// InitializerMethodTemplate.swift3// MockingbirdGenerator4//5// Created by Andrew Chang on 4/18/20.6//7import Foundation8/// Renders initializer method declarations.9class InitializerMethodTemplate: MethodTemplate {10 /// Synthetic initializer for static/class instances.11 override var classInitializerProxy: String? {12 guard method.isInitializer,13 isClassBound || !context.containsOverridableDesignatedInitializer14 else { return nil }15 16 // We can't usually infer what concrete arguments to pass to the designated initializer.17 guard !method.attributes.contains(.convenience) else { return nil }18 19 let failable = method.attributes.contains(.failable) ? "?" : ""20 let scopedName = mockableScopedName21 let declaration = "public static func \(fullNameForInitializerProxy)\(returnTypeAttributesForMocking) -> \(scopedName)\(failable)\(genericConstraints)"22 23 let body = !context.shouldGenerateThunks ? MockableTypeTemplate.Constants.thunkStub : """24 let mock: \(scopedName)\(failable) = \(FunctionCallTemplate(25 name: scopedName,26 parameters: method.parameters,27 isThrowing: method.isThrowing))28 mock\(failable).mockingbirdContext.sourceLocation = SourceLocation(__file, __line)29 return mock30 """31 32 return FunctionDefinitionTemplate(attributes: method.attributes.safeDeclarations,33 declaration: declaration,34 body: body).render()35 }36 37 override var mockedDeclarations: String {38 // We can't usually infer what concrete arguments to pass to the designated initializer.39 guard !method.attributes.contains(.convenience) else { return "" }40 41 let trivia = "// MARK: Mocked \(fullNameForMocking)"42 let declaration = "public \(overridableModifiers)\(uniqueDeclaration)"43 44 if isClassBound {45 // Class-defined initializer, called from an `InitializerProxy`.46 let body = !context.shouldGenerateThunks ? MockableTypeTemplate.Constants.thunkStub :47 FunctionCallTemplate(name: "super.init",48 parameters: method.parameters,49 isThrowing: method.attributes.contains(.throws)).render()50 return String(lines: [51 trivia,52 FunctionDefinitionTemplate(attributes: method.attributes.safeDeclarations,53 declaration: declaration,54 body: body).render(),55 ])56 } else if !context.containsOverridableDesignatedInitializer {57 // Pure protocol or class-only protocol with no class-defined initializers.58 let body = !context.shouldGenerateThunks ? MockableTypeTemplate.Constants.thunkStub :59 (context.protocolClassConformance == nil ? "" :60 FunctionCallTemplate(name: "super.init").render())61 return String(lines: [62 trivia,63 FunctionDefinitionTemplate(attributes: method.attributes.safeDeclarations,64 declaration: declaration,65 body: body).render(),66 ])67 } else {68 // Unavailable class-only protocol-defined initializer, should not be used directly.69 let initializerSuffix = context.protocolClassConformance != nil ? ".initialize(...)" : ""70 let errorMessage = "Please use 'mock(\(context.mockableType.name).self)\(initializerSuffix)' to initialize a concrete mock instance"71 let deprecated = "@available(*, deprecated, message: \(doubleQuoted: errorMessage))"72 return String(lines: [73 trivia,74 FunctionDefinitionTemplate(attributes: method.attributes.safeDeclarations + [deprecated],75 declaration: declaration,76 body: "fatalError(\(doubleQuoted: errorMessage))").render(),77 ])78 }79 }80 81 override var synthesizedDeclarations: String { return "" }82 83 lazy var fullNameForInitializerProxy: String = {84 return fullName(for: .initializerProxy)85 }()86 87 override var overridableUniqueDeclaration: String {88 return "\(fullNameForMocking)\(returnTypeAttributesForMocking)\(genericConstraints) "89 }90}...
modifiers
Using AI Code Generation
1let template = MethodTemplate()2print(template.render())3let template = MethodTemplate()4print(template.render())5let template = MethodTemplate()6print(template.render())7let template = MethodTemplate()8print(template.render())9let template = MethodTemplate()10print(template.render())11let template = MethodTemplate()12print(template.render())13let template = MethodTemplate()14print(template.render())15let template = MethodTemplate()16print(template.render())17let template = MethodTemplate()18print(template.render())19let template = MethodTemplate()20print(template.render())21let template = MethodTemplate()22print(template.render())23let template = MethodTemplate()24print(template.render())25let template = MethodTemplate()26print(template.render())
modifiers
Using AI Code Generation
1import UIKit2class ViewController: UIViewController {3 override func viewDidLoad() {4 super.viewDidLoad()5 }6 @IBAction func btnTap(_ sender: UIButton) {7 }8}9import UIKit10class ViewController: UIViewController {11 override func viewDidLoad() {12 super.viewDidLoad()13 }14 @IBAction func btnTap(_ sender: UIButton) {15 }16}17import UIKit18class ViewController: UIViewController {19 override func viewDidLoad() {20 super.viewDidLoad()21 }22 @IBAction func btnTap(_ sender: UIButton) {23 }24}25import UIKit26class ViewController: UIViewController {27 override func viewDidLoad() {28 super.viewDidLoad()29 }30 @IBAction func btnTap(_ sender: UIButton) {31 }32}33import UIKit34class ViewController: UIViewController {35 override func viewDidLoad() {36 super.viewDidLoad()37 }38 @IBAction func btnTap(_ sender: UIButton) {39 }40}41import UIKit42class ViewController: UIViewController {43 override func viewDidLoad() {44 super.viewDidLoad()45 }46 @IBAction func btnTap(_ sender: UIButton) {47 }48}49import UIKit50class ViewController: UIViewController {
modifiers
Using AI Code Generation
1import Foundation2public class MethodTemplate {3 public func modifiers(modifiers: [String]) -> MethodTemplate {4 }5}6import Foundation7public class MethodTemplate {8 public func modifiers(modifiers: [String]) -> MethodTemplate {9 }10}11import Foundation12public class MethodTemplate {13 public func modifiers(modifiers: [String]) -> MethodTemplate {14 }15}16import Foundation17public class MethodTemplate {18 public func modifiers(modifiers: [String]) -> MethodTemplate {19 }20}21import Foundation22public class MethodTemplate {23 public func modifiers(modifiers: [String]) -> MethodTemplate {24 }25}26import Foundation27public class MethodTemplate {28 public func modifiers(modifiers: [String]) -> MethodTemplate {29 }30}31import Foundation32public class MethodTemplate {33 public func modifiers(modifiers: [String]) -> MethodTemplate {34 }35}36import Foundation37public class MethodTemplate {38 public func modifiers(modifiers: [String]) -> MethodTemplate {39 }40}41import Foundation42public class MethodTemplate {43 public func modifiers(modifiers: [String]) -> MethodTemplate {44 }45}46import Foundation47public class MethodTemplate {48 public func modifiers(modifiers: [String]) -> MethodTemplate {49 }50}51import Foundation52public class MethodTemplate {53 public func modifiers(modifiers: [String]) -> MethodTemplate {54 }
modifiers
Using AI Code Generation
1import Foundation2class MethodTemplate {3 init(template: String) {4 }5 func modifiers() -> String {6 let words = template.components(separatedBy: " ")7 for word in words {8 if word == "public" || word == "private" || word == "internal" {9 result += "\(word) "10 }11 }12 return result.trimmingCharacters(in: .whitespaces)13 }14}15let template = readLine()!16let method = MethodTemplate(template: template)17print(method.modifiers())18let template = readLine()!19let method = MethodTemplate(template: template)20print(method.modifiers())21let template = readLine()!22let method = MethodTemplate(template: template)23print(method.modifiers())24let template = readLine()!25let method = MethodTemplate(template: template)26print(method.modifiers())
modifiers
Using AI Code Generation
1import Foundation2let template = MethodTemplate()3print("Modifiers: \(template.modifiers)")4import Foundation5let template = MethodTemplate()6print("Name: \(template.name)")7import Foundation8let template = MethodTemplate()9print("Return Type: \(template.returnType)")10import Foundation11let template = MethodTemplate()12print("Arguments: \(template.arguments)")13import Foundation14let template = MethodTemplate()15print("Body: \(template.body)")16import Foundation17let template = MethodTemplate()18print("Description: \(template.description)")19import Foundation20let template = MethodTemplate()21template.generate()
modifiers
Using AI Code Generation
1let template = try MethodTemplate(named: "myTemplate")2let result = try template.render(["name": "Bob"])3print(result)4Hello {{ name|upper }}5let template = try MethodTemplate(named: "myTemplate")6let result = try template.render(["name": "Bob"])7print(result)8Hello {{ name|upper }}9let template = try MethodTemplate(named: "myTemplate")10let result = try template.render(["name": "Bob"])11print(result)12Hello {{ name|upper }}13let template = try MethodTemplate(named: "myTemplate")14let result = try template.render(["name": "Bob"])15print(result)16Hello {{ name|upper }}17let template = try MethodTemplate(named: "myTemplate")18let result = try template.render(["name": "Bob"])19print(result)20Hello {{ name|upper }}21let template = try MethodTemplate(named: "myTemplate")22let result = try template.render(["name": "Bob"])23print(result)24Hello {{ name|upper }}25let template = try MethodTemplate(named: "myTemplate")26let result = try template.render(["name": "Bob"])27print(result)
modifiers
Using AI Code Generation
1import UIKit2class ViewController: UIViewController {3 override func viewDidLoad() {4 super.viewDidLoad()5 let method = MethodTemplate()6 let template = method.getTemplate()7 print(template)8 print(method.getTemplate())9 }10}11import UIKit12class ViewController: UIViewController {13 override func viewDidLoad() {14 super.viewDidLoad()15 let method = MethodTemplate()16 let template = method.getTemplate()17 print(template)18 print(method.getTemplate())19 }20}21import UIKit22class ViewController: UIViewController {23 override func viewDidLoad() {24 super.viewDidLoad()25 let method = MethodTemplate()26 let template = method.getTemplate()27 print(template)28 print(method.getTemplate())29 }30}31import UIKit32class ViewController: UIViewController {33 override func viewDidLoad() {34 super.viewDidLoad()35 let method = MethodTemplate()36 let template = method.getTemplate()37 print(template)38 print(method.getTemplate())39 }40}41import UIKit42class ViewController: UIViewController {43 override func viewDidLoad() {44 super.viewDidLoad()45 let method = MethodTemplate()46 let template = method.getTemplate()47 print(template)48 }49}50import UIKit51class ViewController: UIViewController {52 override func viewDidLoad() {53 super.viewDidLoad()54 let method = MethodTemplate()55 let template = method.getTemplate()56 print(template)57 }58}
modifiers
Using AI Code Generation
1import Foundation2var temp = MethodTemplate()3print(temp.generateCode())4Output: public func hello() {5}6import Foundation7var temp = MethodTemplate()8print(temp.generateCode())9Output: public func hello(name: String) {10}11import Foundation12var temp = MethodTemplate()13print(temp.generateCode())14Output: public func hello() -> String {15}16import Foundation17var temp = MethodTemplate()18temp.body = "print('hello world')"19print(temp.generateCode())20Output: public func hello() {21 print('hello world')22}23import Foundation24var temp = MethodTemplate()25temp.body = "return 'hello \(name)'"26print(temp.generateCode())27Output: public func hello(name: String) -> String {28 return 'hello \(name)'29}30import Foundation31var temp = MethodTemplate()32temp.body = "return 'hello \(name)'"33print(temp.generateCode())34Output: public func hello(name: String) -> String {35 return 'hello \(name)'36}37import Foundation38var temp = MethodTemplate()39temp.body = "return 'hello \(name)'"40print(temp.generateCode())41Output: public func hello(name: String)
modifiers
Using AI Code Generation
1import Foundation2import SwiftKotlinFramework3let template = MethodTemplate(source: source, modifiers: [.public, .static])4print(template.render())5public static func method() {6}7import Foundation8import SwiftKotlinFramework9let template = MethodTemplate(source: source, modifiers: [.public, .static])10print(template.render())11public static func method() {12}13import Foundation14import SwiftKotlinFramework15let template = MethodTemplate(source: source, modifiers: [.public, .static])16print(template.render())17public static func method() {18}19import Foundation20import SwiftKotlinFramework21let template = MethodTemplate(source: source, modifiers: [.public, .static])22print(template.render())23public static func method() {24}25import Foundation26import SwiftKotlinFramework27let template = MethodTemplate(source: source, modifiers: [.public, .static])28print(template.render())29public static func method() {30}31import Foundation32import SwiftKotlinFramework33let template = MethodTemplate(source: source, modifiers: [.public, .static])34print(template.render())35public static func method() {36}37import Foundation38import SwiftKotlinFramework39let template = MethodTemplate(source: source, modifiers: [.public, .static])40print(template.render())41public static func method()
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!