How to use spec method of var class

Best Quick code snippet using var.spec

main.swift

Source:main.swift Github

copy

Full Screen

...9 *10 * Unless required by applicable law or agreed to in writing, software11 * distributed under the License is distributed on an "AS IS" BASIS,12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13 * See the License for the specific language governing permissions and14 * limitations under the License.15 */16import ArgumentParser17import Foundation18private enum Constants {}19extension Constants {20 static let specDependencyLabel = "dependency"21 static let skipLinesWithWords = ["unit_tests", "test_spec"]22 static let dependencyLineSeparators = CharacterSet(charactersIn: " ,/")23 static let podSources = [24 "https://${BOT_TOKEN}@github.com/FirebasePrivate/SpecsTesting",25 "https://github.com/firebase/SpecsStaging.git",26 "https://cdn.cocoapods.org/",27 ]28 static let exclusivePods: [String] = ["FirebaseSegmentation"]29}30// flags for 'pod push'31extension Constants {32 static let flags = ["--skip-tests", "--allow-warnings"]33 static let umbrellaPodFlags = Constants.flags + ["--skip-import-validation", "--use-json"]34}35// SpecFiles is a wraper of dict mapping from required pods to their path. This36// will also contain a sequence of installing podspecs.37class SpecFiles {38 private var specFilesDict: [String: URL]39 var depInstallOrder: [String]40 var specSource: String41 init(_ specDict: [String: URL], from specSourcePath: String) {42 specFilesDict = specDict43 depInstallOrder = []44 specSource = specSourcePath45 }46 func removePod(_ key: String) {47 specFilesDict.removeValue(forKey: key)48 }49 subscript(key: String) -> URL? {50 return specFilesDict[key]51 }52 func contains(_ key: String) -> Bool {53 return specFilesDict[key] != nil54 }55 func isEmpty() -> Bool {56 return specFilesDict.isEmpty57 }58}59struct Shell {60 static let shared = Shell()61 @discardableResult62 func run(_ command: String, displayCommand: Bool = true,63 displayFailureResult: Bool = true) -> Int32 {64 let task = Process()65 let pipe = Pipe()66 task.standardOutput = pipe67 task.launchPath = "/bin/bash"68 task.arguments = ["-c", command]69 task.launch()70 if displayCommand {71 print("[SpecRepoBuilder] Command:\(command)\n")72 }73 task.waitUntilExit()74 let data = pipe.fileHandleForReading.readDataToEndOfFile()75 let log = String(data: data, encoding: .utf8)!76 if displayFailureResult, task.terminationStatus != 0 {77 print("-----Exit code: \(task.terminationStatus)")78 print("-----Log:\n \(log)")79 }80 return task.terminationStatus81 }82}83// Error types84enum SpecRepoBuilderError: Error {85 // Error occurs when circular dependencies are detected and deps will be86 // displayed.87 case circularDependencies(pods: Set<String>)88 // Error occurs when there exist specs that failed to push to a spec repo. All89 // specs failed to push should be displayed.90 case failedToPush(pods: [String])91 // Error occurs when a podspec is not found in the repo.92 case podspecNotFound(_ podspec: String, from: String)93}94struct SpecRepoBuilder: ParsableCommand {95 @Option(help: "The root of the firebase-ios-sdk checked out git repo.")96 var sdkRepo: String = FileManager().currentDirectoryPath97 @Option(help: "A list of podspec sources in Podfiles.")98 var podSources: [String] = Constants.podSources99 @Option(help: "Podspecs that will not be pushed to repo.")100 var excludePods: [String] = Constants.exclusivePods101 @Option(help: "Github Account Name.")102 var githubAccount: String = "FirebasePrivate"103 @Option(help: "Github Repo Name.")104 var sdkRepoName: String = "SpecsTesting"105 @Option(help: "Local Podspec Repo Name.")106 var localSpecRepoName: String107 @Flag(help: "Raise error while circular dependency detected.")108 var raiseCircularDepError: Bool = false109 // This will track down dependencies of pods and keep the sequence of110 // dependency installation in specFiles.depInstallOrder.111 func generateOrderOfInstallation(pods: [String], specFiles: SpecFiles,112 parentDeps: inout Set<String>) {113 // pods are dependencies will be tracked down.114 // specFiles includes required pods and their URLs.115 // parentDeps will record the path of tracking down dependencies to avoid116 // duplications and circular dependencies.117 // Stop tracking down when the parent pod does not have any required deps.118 if pods.isEmpty {119 return120 }121 for pod in pods {122 guard specFiles.contains(pod) else { continue }123 let deps = getTargetedDeps(of: pod, from: specFiles)124 // parentDeps will have all dependencies the current pod supports. If the125 // current pod were in the parent dependencies, that means it was tracked126 // before and it is circular dependency.127 if parentDeps.contains(pod) {128 print("Circular dependency is detected in \(pod) and \(parentDeps)")129 if raiseCircularDepError {130 Self131 .exit(withError: SpecRepoBuilderError132 .circularDependencies(pods: parentDeps))133 }134 continue135 }136 // Record the pod as a parent and use depth-first-search to track down137 // dependencies of this pod.138 parentDeps.insert(pod)139 generateOrderOfInstallation(140 pods: deps,141 specFiles: specFiles,142 parentDeps: &parentDeps143 )144 // When pod does not have required dep or its required deps are recorded,145 // the pod itself will be recorded into the depInstallOrder.146 if !specFiles.depInstallOrder.contains(pod) {147 print("\(pod) depends on \(deps).")148 specFiles.depInstallOrder.append(pod)149 }150 // When track back from a lower level, parentDep should track back by151 // removing one pod.152 parentDeps.remove(pod)153 }154 }155 // Scan a podspec file and find and return all dependencies in this podspec.156 func searchDeps(ofPod podName: String, from podSpecFiles: SpecFiles) -> [String] {157 var deps: [String] = []158 var fileContents = ""159 guard let podSpecURL = podSpecFiles[podName] else {160 Self161 .exit(withError: SpecRepoBuilderError162 .podspecNotFound(podName, from: podSpecFiles.specSource))163 }164 do {165 fileContents = try String(contentsOfFile: podSpecURL.path, encoding: .utf8)166 } catch {167 fatalError("Could not read \(podName) podspec from \(podSpecURL.path).")168 }169 // Get all the lines containing `dependency` but don't contain words we170 // want to ignore.171 let depLines: [String] = fileContents172 .components(separatedBy: .newlines)173 .filter { $0.contains("dependency") }174 // Skip lines with words in Constants.skipLinesWithWords175 .filter { !Constants.skipLinesWithWords.contains(where: $0.contains)176 }177 for line in depLines {178 let newLine = line.trimmingCharacters(in: .whitespacesAndNewlines)179 // This is to avoid pushing umbrellapods like Firebase/Core.180 let tokens = newLine.components(separatedBy: Constants.dependencyLineSeparators)181 if let depPrefix = tokens.first {182 if depPrefix.hasSuffix(Constants.specDependencyLabel) {183 // e.g. In Firebase.podspec, Firebase/Core will not be considered a184 // dependency.185 // "ss.dependency 'Firebase/Core'" will be splited in186 // ["ss.dependency", "'Firebase", "Core'"]187 let podNameRaw = String(tokens[1]).replacingOccurrences(of: "'", with: "")188 // In the example above, deps here will not include Firebase since189 // it is the same as the pod name.190 if podNameRaw != podName { deps.append(podNameRaw) }191 }192 }193 }194 return deps195 }196 // Filter and get a list of required dependencies found in the repo.197 func filterTargetDeps(_ deps: [String], with targets: SpecFiles) -> [String] {198 var targetedDeps: [String] = []199 for dep in deps {200 // Only get unique and required dep in the output list.201 if targets.contains(dep), !targetedDeps.contains(dep) {202 targetedDeps.append(dep)203 }204 }205 return targetedDeps206 }207 func getTargetedDeps(of pod: String, from specFiles: SpecFiles) -> [String] {208 let deps = searchDeps(ofPod: pod, from: specFiles)209 return filterTargetDeps(deps, with: specFiles)210 }211 func pushPodspec(forPod pod: String, sdkRepo: String, sources: [String],212 flags: [String], shell: Shell = Shell.shared) -> Int32 {213 let podPath = sdkRepo + "/" + pod + ".podspec"214 let sourcesArg = sources.joined(separator: ",")215 let flagsArg = flags.joined(separator: " ")216 let outcome =217 shell218 .run(219 "pod repo push \(localSpecRepoName) \(podPath) --sources=\(sourcesArg) \(flagsArg)"220 )221 shell.run("pod repo update")222 return outcome223 }224 // This will commit and push to erase the entire remote spec repo.225 func eraseRemoteRepo(repoPath: String, from githubAccount: String, _ sdkRepoName: String,226 shell: Shell = Shell.shared) {227 shell228 .run(229 "git clone --quiet https://${BOT_TOKEN}@github.com/\(githubAccount)/\(sdkRepoName).git"230 )231 let fileManager = FileManager.default232 do {233 let dirs = try fileManager.contentsOfDirectory(atPath: "\(repoPath)/\(sdkRepoName)")234 for dir in dirs {235 if dir != ".git" {236 shell.run("cd \(sdkRepoName); git rm -r \(dir)")237 }238 }239 shell.run("cd \(sdkRepoName); git commit -m 'Empty repo'; git push")240 } catch {241 print("Error while enumerating files \(repoPath): \(error.localizedDescription)")242 }243 do {244 try fileManager.removeItem(at: URL(fileURLWithPath: "\(repoPath)/\(sdkRepoName)"))245 } catch {246 print("Error occurred while removing \(repoPath)/\(sdkRepoName): \(error)")247 }248 }249 mutating func run() throws {250 let fileManager = FileManager.default251 let curDir = FileManager().currentDirectoryPath252 var podSpecFiles: [String: URL] = [:]253 let documentsURL = URL(fileURLWithPath: sdkRepo)254 do {255 let fileURLs = try fileManager.contentsOfDirectory(256 at: documentsURL,257 includingPropertiesForKeys: nil258 )259 let podspecURLs = fileURLs.filter { $0.pathExtension == "podspec" }260 for podspecURL in podspecURLs {261 let podName = podspecURL.deletingPathExtension().lastPathComponent262 if !Constants.exclusivePods.contains(podName) {263 podSpecFiles[podName] = podspecURL264 }265 }266 } catch {267 print(268 "Error while enumerating files \(documentsURL.path): \(error.localizedDescription)"269 )270 }271 // This set is used to keep parent dependencies and help detect circular272 // dependencies.273 var tmpSet: Set<String> = []274 print("Detect podspecs: \(podSpecFiles.keys)")275 let specFileDict = SpecFiles(podSpecFiles, from: sdkRepo)276 generateOrderOfInstallation(277 pods: Array(podSpecFiles.keys),278 specFiles: specFileDict,279 parentDeps: &tmpSet280 )281 print("Podspec push order:\n", specFileDict.depInstallOrder.joined(separator: "->\t"))282 do {283 if fileManager.fileExists(atPath: "\(curDir)/\(sdkRepoName)") {284 print("remove \(sdkRepoName) dir.")285 try fileManager.removeItem(at: URL(fileURLWithPath: "\(curDir)/\(sdkRepoName)"))286 }287 eraseRemoteRepo(repoPath: "\(curDir)", from: githubAccount, sdkRepoName)288 } catch {289 print("error occurred. \(error)")290 }291 var exitCode: Int32 = 0292 var failedPods: [String] = []293 for pod in specFileDict.depInstallOrder {294 var podExitCode: Int32 = 0295 print("----------\(pod)-----------")296 switch pod {297 case "Firebase":298 podExitCode = pushPodspec(299 forPod: pod,300 sdkRepo: sdkRepo,301 sources: podSources,302 flags: Constants.umbrellaPodFlags303 )304 default:305 podExitCode = pushPodspec(306 forPod: pod,307 sdkRepo: sdkRepo,308 sources: podSources,309 flags: Constants.flags310 )311 }312 if podExitCode != 0 {313 exitCode = 1314 failedPods.append(pod)315 }316 }317 if exitCode != 0 {318 Self.exit(withError: SpecRepoBuilderError.failedToPush(pods: failedPods))319 }...

Full Screen

Full Screen

World.swift

Source:World.swift Github

copy

Full Screen

...49 internal var isRunningAdditionalSuites = false50#else51 internal var isRunningAdditionalSuites = false52#endif53 private var specs: [String: ExampleGroup] = [:]54 private var sharedExamples: [String: SharedExampleClosure] = [:]55 private let configuration = Configuration()56 internal private(set) var isConfigurationFinalized = false57 internal var exampleHooks: ExampleHooks {return configuration.exampleHooks }58 internal var suiteHooks: SuiteHooks { return configuration.suiteHooks }59 // MARK: Singleton Constructor60 private override init() {}61 static private(set) var sharedWorld = World()62 static func anotherWorld<T>(block: (World) -> T) -> T {63 let previous = sharedWorld64 defer { sharedWorld = previous }65 let newWorld = World()66 sharedWorld = newWorld67 return block(newWorld)68 }69 // MARK: Public Interface70 /**71 Exposes the World's Configuration object within the scope of the closure72 so that it may be configured. This method must not be called outside of73 an overridden +[QuickConfiguration configure:] method.74 - parameter closure: A closure that takes a Configuration object that can75 be mutated to change Quick's behavior.76 */77 internal func configure(_ closure: QuickConfigurer) {78 assert(!isConfigurationFinalized,79 "Quick cannot be configured outside of a +[QuickConfiguration configure:] method. You should not call -[World configure:] directly. Instead, subclass QuickConfiguration and override the +[QuickConfiguration configure:] method.")80 closure(configuration)81 }82 /**83 Finalizes the World's configuration.84 Any subsequent calls to World.configure() will raise.85 */86 internal func finalizeConfiguration() {87 isConfigurationFinalized = true88 }89 /**90 Returns an internally constructed root example group for the given91 QuickSpec class.92 A root example group with the description "root example group" is lazily93 initialized for each QuickSpec class. This root example group wraps the94 top level of a -[QuickSpec spec] method--it's thanks to this group that95 users can define beforeEach and it closures at the top level, like so:96 override func spec() {97 // These belong to the root example group98 beforeEach {}99 it("is at the top level") {}100 }101 - parameter specClass: The QuickSpec class for which to retrieve the root example group.102 - returns: The root example group for the class.103 */104 internal func rootExampleGroup(forSpecClass specClass: QuickSpec.Type) -> ExampleGroup {105 let name = String(describing: specClass)106 if let group = specs[name] {107 return group108 } else {109 let group = ExampleGroup(110 description: "root example group",111 flags: [:],112 isInternalRootExampleGroup: true113 )114 specs[name] = group115 return group116 }117 }118 /**119 Returns all examples that should be run for a given spec class.120 There are two filtering passes that occur when determining which examples should be run.121 That is, these examples are the ones that are included by inclusion filters, and are122 not excluded by exclusion filters.123 - parameter specClass: The QuickSpec subclass for which examples are to be returned.124 - returns: A list of examples to be run as test invocations.125 */126 internal func examples(forSpecClass specClass: QuickSpec.Type) -> [Example] {127 // 1. Grab all included examples.128 let included = includedExamples129 // 2. Grab the intersection of (a) examples for this spec, and (b) included examples.130 let spec = rootExampleGroup(forSpecClass: specClass).examples.filter { included.contains($0) }131 // 3. Remove all excluded examples.132 return spec.filter { example in133 !self.configuration.exclusionFilters.contains { $0(example) }134 }135 }136 // MARK: Internal137 internal func registerSharedExample(_ name: String, closure: @escaping SharedExampleClosure) {138 raiseIfSharedExampleAlreadyRegistered(name)139 sharedExamples[name] = closure140 }141 internal func sharedExample(_ name: String) -> SharedExampleClosure {142 raiseIfSharedExampleNotRegistered(name)143 return sharedExamples[name]!144 }145 internal var includedExampleCount: Int {146 return includedExamples.count147 }148 internal lazy var cachedIncludedExampleCount: Int = self.includedExampleCount149 internal var beforesCurrentlyExecuting: Bool {150 let suiteBeforesExecuting = suiteHooks.phase == .beforesExecuting151 let exampleBeforesExecuting = exampleHooks.phase == .beforesExecuting152 var groupBeforesExecuting = false153 if let runningExampleGroup = currentExampleMetadata?.example.group {154 groupBeforesExecuting = runningExampleGroup.phase == .beforesExecuting155 }156 return suiteBeforesExecuting || exampleBeforesExecuting || groupBeforesExecuting157 }158 internal var aftersCurrentlyExecuting: Bool {159 let suiteAftersExecuting = suiteHooks.phase == .aftersExecuting160 let exampleAftersExecuting = exampleHooks.phase == .aftersExecuting161 var groupAftersExecuting = false162 if let runningExampleGroup = currentExampleMetadata?.example.group {163 groupAftersExecuting = runningExampleGroup.phase == .aftersExecuting164 }165 return suiteAftersExecuting || exampleAftersExecuting || groupAftersExecuting166 }167 internal func performWithCurrentExampleGroup(_ group: ExampleGroup, closure: () -> Void) {168 let previousExampleGroup = currentExampleGroup169 currentExampleGroup = group170 closure()171 currentExampleGroup = previousExampleGroup172 }173 private var allExamples: [Example] {174 var all: [Example] = []175 for (_, group) in specs {176 group.walkDownExamples { all.append($0) }177 }178 return all179 }180 private var includedExamples: [Example] {181 let all = allExamples182 let included = all.filter { example in183 return self.configuration.inclusionFilters.contains { $0(example) }184 }185 if included.isEmpty && configuration.runAllWhenEverythingFiltered {186 return all187 } else {188 return included189 }...

Full Screen

Full Screen

QuickSpec.swift

Source:QuickSpec.swift Github

copy

Full Screen

...8#else9public typealias QuickSpecBase = XCTestCase10#endif11open class QuickSpec: QuickSpecBase {12 /// Returns the currently executing spec. Use in specs that require XCTestCase13 /// methods, e.g. expectation(description:).14 public private(set) static var current: QuickSpec!15 private var example: Example? {16 didSet {17 QuickSpec.current = self18 }19 }20 open func spec() {}21#if !canImport(Darwin)22 public required init() {23 super.init(name: "", testClosure: { _ in })24 }25 public required init(name: String, testClosure: @escaping (XCTestCase) throws -> Swift.Void) {26 super.init(name: name, testClosure: testClosure)27 }28#else29 public required override init() {30 super.init()31 }32 /// This method is used as a hook for the following two purposes33 ///34 /// 1. Performing all configurations35 /// 2. Gathering examples for each spec classes36 ///37 /// On Linux, those are done in `LinuxMain.swift` and `Quick.QCKMain`. But38 /// SwiftPM on macOS does not have the mechanism (test cases are automatically39 /// discovered powered by Objective-C runtime), so we needed the alternative40 /// way.41 override open class var defaultTestSuite: XCTestSuite {42 QuickConfiguration.configureSubclassesIfNeeded(world: World.sharedWorld)43 // Let's gather examples for each spec classes. This has the same effect44 // as listing spec classes in `LinuxMain.swift` on Linux.45 gatherExamplesIfNeeded()46 return super.defaultTestSuite47 }48 override open class func _qck_testMethodSelectors() -> [String] {49 let examples = World.sharedWorld.examples(forSpecClass: self)50 var selectorNames = Set<String>()51 return examples.map { example in52 let selector = addInstanceMethod(for: example, classSelectorNames: &selectorNames)53 return NSStringFromSelector(selector)54 }55 }56 private static func addInstanceMethod(for example: Example, classSelectorNames selectorNames : inout Set<String>) -> Selector {57 let block: @convention(block) (QuickSpec) -> Void = { spec in58 spec.example = example59 example.run()60 }61 let implementation = imp_implementationWithBlock(block as Any)62 let originalName = example.name.c99ExtendedIdentifier63 var selectorName = originalName64 var i: UInt = 265 while selectorNames.contains(selectorName) {66 selectorName = String(format: "%@_%tu", originalName, i)67 i += 168 }69 selectorNames.insert(selectorName)70 let selector = NSSelectorFromString(selectorName)71 class_addMethod(self, selector, implementation, "v@:")72 return selector73 }74#endif75#if !canImport(Darwin)76 public class var allTests: [(String, (QuickSpec) -> () throws -> Void)] {77 gatherExamplesIfNeeded()78 let examples = World.sharedWorld.examples(forSpecClass: self)79 let result = examples.map { example -> (String, (QuickSpec) -> () throws -> Void) in80 return (example.name, { spec in81 return {82 spec.example = example83 example.run()84 }85 })86 }87 return result88 }89#endif90 internal static func gatherExamplesIfNeeded() {91 let world = World.sharedWorld92 let rootExampleGroup = world.rootExampleGroup(forSpecClass: self)93 guard rootExampleGroup.examples.isEmpty else {94 return95 }96 world.performWithCurrentExampleGroup(rootExampleGroup) {97 self.init().spec()98 }99 }100}101#endif...

Full Screen

Full Screen

spec

Using AI Code Generation

copy

Full Screen

1import Foundation2print("sum is \(c)")3import Foundation4print("sum is \(c)")5import Foundation6print("sum is \(c)")7import Foundation8print("sum is \(c)")9import Foundation10print("sum is \(c)")11import Foundation12print("sum is \(c)")13import Foundation14print("sum is \(c)")15import Foundation16print("sum is \(c)")17import Foundation18print("sum is \(c)")19import Foundation20print("sum is \(c)")21import Foundation22print("sum is \(c)")23import Foundation

Full Screen

Full Screen

spec

Using AI Code Generation

copy

Full Screen

1struct A {2}3 var a = A(x: 1 )4struct A {5}6 var a = A(x: 1 )7struct A {8}9 var a = A(x: 1 )10struct A {11}12 var a = A(x: 1 )13struct A {14}15 var a = A(x: 1 )16struct A {17}18 var a = A(x: 1 )19struct A {20}21 var a = A(x: 1 )22struct A {23}24 var a = A(x: 1 )25struct A {26}27 var a = A(x: 1 )28struct A {29}30 var a = A(x: 1 )31struct A {

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Quick automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful