From c8ae80d70370f6b0a1d8d8eb1e613a04f5db71fa Mon Sep 17 00:00:00 2001 From: Leonardo Cardoso Date: Sun, 23 Sep 2018 19:24:51 +0200 Subject: [PATCH] Remove extraneous lines --- .../AlamofireSource.swift | 16 +-- .../Delegates/AppDelegate.swift | 19 ++- Package.swift | 2 +- Sources/Cache.swift | 33 +++--- Sources/NSURLSessionExtension.swift | 12 +- Sources/Regex.swift | 70 ++++++------ Sources/StringExtension.swift | 74 ++++++------ SwiftLinkPreviewTests/BodyTests.swift | 100 ++++++++-------- SwiftLinkPreviewTests/Constants.swift | 20 ++-- SwiftLinkPreviewTests/File.swift | 8 +- SwiftLinkPreviewTests/HugeTests.swift | 23 ++-- SwiftLinkPreviewTests/IconTests.swift | 2 - SwiftLinkPreviewTests/ImageTests.swift | 63 +++++----- SwiftLinkPreviewTests/IntExtension.swift | 4 +- SwiftLinkPreviewTests/MemoryLeaks.swift | 16 +-- SwiftLinkPreviewTests/MetaTests.swift | 108 +++++++++--------- SwiftLinkPreviewTests/RegexTests.swift | 33 +++--- .../StringTestExtension.swift | 54 ++++----- SwiftLinkPreviewTests/TitleTests.swift | 39 +++---- SwiftLinkPreviewTests/URLs.swift | 5 +- 20 files changed, 345 insertions(+), 356 deletions(-) diff --git a/Example/SwiftLinkPreviewExample/AlamofireSource.swift b/Example/SwiftLinkPreviewExample/AlamofireSource.swift index d5a70b4..91143fb 100644 --- a/Example/SwiftLinkPreviewExample/AlamofireSource.swift +++ b/Example/SwiftLinkPreviewExample/AlamofireSource.swift @@ -11,14 +11,14 @@ import AlamofireImage import ImageSlideshow public class AlamofireSource: NSObject, InputSource { - + var url: NSURL? - + public init(url: NSURL) { self.url = url super.init() } - + public init?(urlString: String) { if let validUrl = NSURL(string: urlString) { self.url = validUrl @@ -28,7 +28,7 @@ public class AlamofireSource: NSObject, InputSource { return nil } } - + public func load(to imageView: UIImageView, with callback: @escaping (UIImage?) -> Void) { guard let url = self.url as URL? else { return } @@ -36,12 +36,12 @@ public class AlamofireSource: NSObject, InputSource { placeholderImage: nil, filter: nil, progress: nil) { (response) in - + imageView.image = response.result.value - + if let value = response.result.value { callback(value) } - + } } - + } diff --git a/Example/SwiftLinkPreviewExample/Delegates/AppDelegate.swift b/Example/SwiftLinkPreviewExample/Delegates/AppDelegate.swift index 0312f04..64447f0 100644 --- a/Example/SwiftLinkPreviewExample/Delegates/AppDelegate.swift +++ b/Example/SwiftLinkPreviewExample/Delegates/AppDelegate.swift @@ -10,37 +10,34 @@ import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { - + var window: UIWindow? - - + func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } - + func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } - + func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } - + func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } - + func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } - + func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } - - -} +} diff --git a/Package.swift b/Package.swift index fe1f233..96b2a3b 100644 --- a/Package.swift +++ b/Package.swift @@ -10,4 +10,4 @@ import PackageDescription let package = Package( name: "SwiftLinkPreview" -) \ No newline at end of file +) diff --git a/Sources/Cache.swift b/Sources/Cache.swift index 7bdb52b..6550594 100644 --- a/Sources/Cache.swift +++ b/Sources/Cache.swift @@ -9,44 +9,43 @@ import Foundation public protocol Cache { - + func slp_getCachedResponse(url: String) -> SwiftLinkPreview.Response? - + func slp_setCachedResponse(url: String, response: SwiftLinkPreview.Response?) } public class DisabledCache: Cache { - + public static let instance = DisabledCache() - + public func slp_getCachedResponse(url: String) -> SwiftLinkPreview.Response? { return nil; } - + public func slp_setCachedResponse(url: String, response: SwiftLinkPreview.Response?) { } } - open class InMemoryCache: Cache { private var cache = Dictionary() private let invalidationTimeout: TimeInterval private let cleanupTimer: DispatchSource? - + //High priority queue for quick responses private static let cacheQueue = DispatchQueue(label: "SwiftLinkPreviewInMemoryCacheQueue", qos: .userInitiated, target: DispatchQueue.global(qos: .userInitiated)) - + public init(invalidationTimeout: TimeInterval = 300.0, cleanupInterval: TimeInterval = 10.0) { self.invalidationTimeout = invalidationTimeout - - self.cleanupTimer = DispatchSource.makeTimerSource(queue: type(of:self).cacheQueue) as? DispatchSource + + self.cleanupTimer = DispatchSource.makeTimerSource(queue: type(of: self).cacheQueue) as? DispatchSource self.cleanupTimer?.schedule(deadline: .now() + cleanupInterval, repeating: cleanupInterval) - + self.cleanupTimer?.setEventHandler { [weak self] in guard let sself = self else {return} sself.cleanup() } - + self.cleanupTimer?.resume() } - + open func cleanup() { type(of: self).cacheQueue.async { for (url, data) in self.cache { @@ -56,11 +55,11 @@ open class InMemoryCache: Cache { } } } - + open func slp_getCachedResponse(url: String) -> SwiftLinkPreview.Response? { return type(of: self).cacheQueue.sync { guard let response = cache[url] else { return nil } - + if response.date.timeIntervalSinceNow >= invalidationTimeout { slp_setCachedResponse(url: url, response: nil) return nil @@ -68,7 +67,7 @@ open class InMemoryCache: Cache { return response.response } } - + open func slp_setCachedResponse(url: String, response: SwiftLinkPreview.Response?) { type(of: self).cacheQueue.sync { if let response = response { @@ -78,7 +77,7 @@ open class InMemoryCache: Cache { } } } - + deinit { self.cleanupTimer?.cancel() } diff --git a/Sources/NSURLSessionExtension.swift b/Sources/NSURLSessionExtension.swift index 282e15d..68ba6b5 100644 --- a/Sources/NSURLSessionExtension.swift +++ b/Sources/NSURLSessionExtension.swift @@ -8,21 +8,21 @@ import Foundation public extension URLSession { - + public func synchronousDataTask(with url: URL) -> (Data?, URLResponse?, NSError?) { - + var data: Data?, response: URLResponse?, error: NSError? let semaphore = DispatchSemaphore(value: 0) - + dataTask(with: url, completionHandler: { data = $0; response = $1; error = $2 as NSError? semaphore.signal() - + }) .resume() - + _ = semaphore.wait(timeout: DispatchTime.distantFuture) - + return (data, response, error) } diff --git a/Sources/Regex.swift b/Sources/Regex.swift index f056202..dc39c24 100644 --- a/Sources/Regex.swift +++ b/Sources/Regex.swift @@ -9,7 +9,7 @@ import Foundation // MARK: - Regular expressions class Regex { - + static let imagePattern = "(.+?)\\.(gif|jpg|jpeg|png|bmp)$" static let imageTagPattern = "" static let titlePattern = "(.*?)" @@ -23,45 +23,45 @@ class Regex { static let scriptPattern = "" static let commentPattern = "" static let hrefPattern = ".*href=\"(.*?)\".*" - + // Test regular expression static func test(_ string: String, regex: String) -> Bool { - + return Regex.pregMatchFirst(string, regex: regex) != nil - + } - + // Match first occurrency static func pregMatchFirst(_ string: String, regex: String, index: Int = 0) -> String? { - - do{ - + + do { + let rx = try NSRegularExpression(pattern: regex, options: [.caseInsensitive]) - - if let match = rx.firstMatch(in: string, options: [], range: NSMakeRange(0, string.count)) { - + + if let match = rx.firstMatch(in: string, options: [], range: NSRange(location: 0, length: string.count)) { + var result: [String] = Regex.stringMatches([match], text: string, index: index) return result.count == 0 ? nil : result[0] - + } else { - + return nil - + } - + } catch { - + return nil - + } - + } - + // Match all occurrencies static func pregMatchAll(_ string: String, regex: String, index: Int = 0) -> [String] { - - do{ - + + do { + let rx = try NSRegularExpression(pattern: regex, options: [.caseInsensitive]) var matches: [NSTextCheckingResult] = [] @@ -70,22 +70,22 @@ class Regex { if string.count > limit { string.split(by: limit).forEach { - matches.append(contentsOf: rx.matches(in: string, options: [], range: NSMakeRange(0, $0.count))) + matches.append(contentsOf: rx.matches(in: string, options: [], range: NSRange(location: 0, length: $0.count))) } } else { - matches.append(contentsOf: rx.matches(in: string, options: [], range: NSMakeRange(0, string.count))) + matches.append(contentsOf: rx.matches(in: string, options: [], range: NSRange(location: 0, length: string.count))) } - + return !matches.isEmpty ? Regex.stringMatches(matches, text: string, index: index) : [] - + } catch { - + return [] - + } - + } - + // Extract matches from string static func stringMatches(_ results: [NSTextCheckingResult], text: String, index: Int = 0) -> [String] { @@ -97,14 +97,14 @@ class Regex { return "" } } - + } - + // Return tag pattern static func tagPattern(_ tag: String) -> String { - + return "<" + tag + "(.*?)>(.*?)" - + } - + } diff --git a/Sources/StringExtension.swift b/Sources/StringExtension.swift index 3af8363..2bac552 100644 --- a/Sources/StringExtension.swift +++ b/Sources/StringExtension.swift @@ -8,79 +8,79 @@ import Foundation #if os(iOS) || os(watchOS) || os(tvOS) - + import UIKit - + #elseif os(OSX) - + import Cocoa - + #endif extension String { - + // Trim var trim: String { - + return self.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) - + } - + // Remove extra white spaces var extendedTrim: String { - + let components = self.components(separatedBy: CharacterSet.whitespacesAndNewlines) return components.filter { !$0.isEmpty }.joined(separator: " ").trim - + } - + // Decode HTML entities var decoded: String { - + let encodedData = self.data(using: String.Encoding.utf8)! let attributedOptions: [NSAttributedString.DocumentReadingOptionKey: Any] = [ .documentType: NSAttributedString.DocumentType.html, .characterEncoding: NSNumber(value: String.Encoding.utf8.rawValue) ] - + do { - + let attributedString = try NSAttributedString(data: encodedData, options: attributedOptions, documentAttributes: nil) - + return attributedString.string - + } catch _ { - + return self - + } - + } - + // Strip tags var tagsStripped: String { - + return self.deleteTagByPattern(Regex.rawTagPattern) - + } - + // Delete tab by pattern func deleteTagByPattern(_ pattern: String) -> String { - + return self.replacingOccurrences(of: pattern, with: "", options: .regularExpression, range: nil) - + } - + // Replace func replace(_ search: String, with: String) -> String { - + let replaced: String = self.replacingOccurrences(of: search, with: with) - + return replaced.isEmpty ? self : replaced - + } - + // Substring func substring(_ start: Int, end: Int) -> String { @@ -89,19 +89,19 @@ extension String { } func substring(_ range: NSRange) -> String { - + var end = range.location + range.length end = end > self.count ? self.count - 1 : end - + return self.substring(range.location, end: end) - + } - + // Check if url is an image func isImage() -> Bool { - + return Regex.test(self, regex: Regex.imagePattern) - + } // Split into substring of equal length @@ -117,5 +117,5 @@ extension String { return results.map { String($0) } } - + } diff --git a/SwiftLinkPreviewTests/BodyTests.swift b/SwiftLinkPreviewTests/BodyTests.swift index d17f9a2..33b3e82 100644 --- a/SwiftLinkPreviewTests/BodyTests.swift +++ b/SwiftLinkPreviewTests/BodyTests.swift @@ -11,142 +11,142 @@ import XCTest // This class tests body texts class BodyTests: XCTestCase { - + // MARK: - Vars var spanTemplate = "" var pTemplate = "" var divTemplate = "" let slp = SwiftLinkPreview() - + // MARK: - SetUps // Those setup functions get that template, and fulfil determinated areas with rand texts, images and tags override func setUp() { super.setUp() - + self.spanTemplate = File.toString(Constants.bodyTextSpan) self.divTemplate = File.toString(Constants.bodyTextDiv) self.pTemplate = File.toString(Constants.bodyTextP) - + } - + // MARK: - Span func setUpSpan() { - + var metaData = [ Constants.random1: String.randomText(), Constants.random2: String.randomText() ] - + var template = self.spanTemplate template = template.replace(Constants.headRandom, with: String.randomText()) - + template = template.replace(Constants.random1, with: metaData[Constants.random1]!) template = template.replace(Constants.random2, with: metaData[Constants.random2]!) - + template = template.replace(Constants.tag1, with: String.randomText()) template = template.replace(Constants.tag2, with: String.randomText()) - + template = template.replace(Constants.bodyRandomPre, with: String.randomText()) template = template.replace(Constants.bodyRandomMiddle, with: String.randomText()) template = template.replace(Constants.bodyRandomPos, with: String.randomText()).extendedTrim - + let response = self.slp.crawlDescription(template, result: SwiftLinkPreview.Response()) - + let comparable = (response.result[.description] as! String) - + XCTAssert(comparable == metaData[Constants.random1]!.decoded || comparable == metaData[Constants.random2]!.decoded) - + } - + func testSpan() { - + for _ in 0 ..< 100 { - + self.setUpSpan() - + } - + } - + // MARK: - Div func setUpDiv() { - + let metaData = [ Constants.random1: String.randomText(), Constants.random2: String.randomText() ] - + var template = self.divTemplate template = template.replace(Constants.headRandom, with: String.randomText()) - + template = template.replace(Constants.random1, with: metaData[Constants.random1]!) template = template.replace(Constants.random2, with: metaData[Constants.random2]!) - + template = template.replace(Constants.tag1, with: String.randomText()) template = template.replace(Constants.tag2, with: String.randomText()) - + template = template.replace(Constants.bodyRandomPre, with: String.randomText()) template = template.replace(Constants.bodyRandomMiddle, with: String.randomText()) template = template.replace(Constants.bodyRandomPos, with: String.randomText()).extendedTrim - + let response = self.slp.crawlDescription(template, result: SwiftLinkPreview.Response()) - + let comparable = (response.result[.description] as! String) - + XCTAssert(comparable == metaData[Constants.random1]!.decoded || comparable == metaData[Constants.random2]!.decoded) - + } - + func testDiv() { - + for _ in 0 ..< 100 { - + self.setUpDiv() - + } - + } - + // MARK: - P func setUpP() { - + let metaData = [ Constants.random1: String.randomText(), Constants.random2: String.randomText() ] - + var template = self.pTemplate template = template.replace(Constants.headRandom, with: String.randomText()) - + template = template.replace(Constants.random1, with: metaData[Constants.random1]!) template = template.replace(Constants.random2, with: metaData[Constants.random2]!) - + template = template.replace(Constants.tag1, with: String.randomText()) template = template.replace(Constants.tag2, with: String.randomText()) - + template = template.replace(Constants.bodyRandomPre, with: String.randomText()) template = template.replace(Constants.bodyRandomMiddle, with: String.randomText()) template = template.replace(Constants.bodyRandomPos, with: String.randomText()).extendedTrim - + let response = self.slp.crawlDescription(template, result: SwiftLinkPreview.Response()) - + let comparable = (response.result[.description] as! String) - + XCTAssert(comparable == metaData[Constants.random1]!.decoded || comparable == metaData[Constants.random2]!.decoded) - + } - + func testP() { - + for _ in 0 ..< 100 { - + self.setUpP() - + } - + } - + } diff --git a/SwiftLinkPreviewTests/Constants.swift b/SwiftLinkPreviewTests/Constants.swift index 9b201a5..db15838 100644 --- a/SwiftLinkPreviewTests/Constants.swift +++ b/SwiftLinkPreviewTests/Constants.swift @@ -9,7 +9,7 @@ import Foundation struct Constants { - + static let huge = "huge" static let bodyTitle = "body-text-span" static let bodyTextSpan = "body-text-span" @@ -23,44 +23,44 @@ struct Constants { static let headMetaItemprop = "head-meta-itemprop" static let headMetaFacebook = "head-meta-facebook" static let headTitle = "head-title" - + static let headRandom = "[:head-random]" static let headRandomPre = "[:head-random-pre]" static let headRandomPos = "[:head-random-pos]" - + static let bodyRandom = "[:body-random]" static let bodyRandomPre = "[:body-random-pre]" static let bodyRandomMiddle = "[:body-random-middle]" static let bodyRandomPos = "[:body-random-pos]" - + static let twitterTitle = "[:twitter-title]" static let twitterSite = "[:twitter-site]" static let twitterImageSrc = "[:twitter-image-src]" static let twitterDescription = "[:twitter-description]" - + static let facebookTitle = "[:og-title]" static let facebookSite = "[:og-url]" static let facebookImage = "[:og-image]" static let facebookDescription = "[:og-description]" - + static let title = "[:title]" static let site = "[:site]" static let image = "[:image]" static let description = "[:description]" - + static let image1 = "[:image-1]" static let image2 = "[:image-2]" static let image3 = "[:image-3]" - + static let random1 = "[:random-1]" static let random2 = "[:random-2]" static let random3 = "[:random-3]" - + static let tag1 = "[:tag-1]" static let tag2 = "[:tag-2]" static let tag3 = "[:tag-3]" static let href = "[:href]" static let rel = "[:rel]" - + } diff --git a/SwiftLinkPreviewTests/File.swift b/SwiftLinkPreviewTests/File.swift index cb592c0..32e8a8f 100644 --- a/SwiftLinkPreviewTests/File.swift +++ b/SwiftLinkPreviewTests/File.swift @@ -9,14 +9,14 @@ import Foundation class File { - + // Read local html files static func toString(_ file: String) -> String { - + let path = Bundle(for: object_getClass(self)!).path(forResource: file, ofType: "html") let fileHtml = try! NSString(contentsOfFile: path!, encoding: String.Encoding.utf8.rawValue) return String(fileHtml) - + } - + } diff --git a/SwiftLinkPreviewTests/HugeTests.swift b/SwiftLinkPreviewTests/HugeTests.swift index bc107c1..70d504a 100644 --- a/SwiftLinkPreviewTests/HugeTests.swift +++ b/SwiftLinkPreviewTests/HugeTests.swift @@ -11,31 +11,30 @@ import XCTest // This class tests head meta info class HugeTests: XCTestCase { - + // MARK: - Vars let slp = SwiftLinkPreview() - + // MARK: - Huge func testHuge() { - + do { - + // Get youtube.com becaus it contains a huge HTML let source = try String(contentsOf: URL(string: "https://youtube.com")!).extendedTrim - + let title = self.slp.crawlCode(source, minimum: SwiftLinkPreview.titleMinimumRelevant) let description = self.slp.crawlCode(source, minimum: SwiftLinkPreview.decriptionMinimumRelevant) - + XCTAssert(!title.trim.isEmpty) XCTAssert(!description.trim.isEmpty) - + } catch let err as NSError { - + print("\(err)") - + } - + } - - + } diff --git a/SwiftLinkPreviewTests/IconTests.swift b/SwiftLinkPreviewTests/IconTests.swift index 742884b..a315539 100644 --- a/SwiftLinkPreviewTests/IconTests.swift +++ b/SwiftLinkPreviewTests/IconTests.swift @@ -39,8 +39,6 @@ class IconTests: XCTestCase { template = File.toString(Constants.bodyIcon) } - - func testLink() { for _ in 1..<1000 { let icon = random(array: iconList) diff --git a/SwiftLinkPreviewTests/ImageTests.swift b/SwiftLinkPreviewTests/ImageTests.swift index cfd3414..ec3b250 100644 --- a/SwiftLinkPreviewTests/ImageTests.swift +++ b/SwiftLinkPreviewTests/ImageTests.swift @@ -11,89 +11,88 @@ import XCTest // This class tests body images class ImageTests: XCTestCase { - + // MARK: - Vars var singleImageTemplate = "" var galleryImageTemplate = "" let slp = SwiftLinkPreview() - + // MARK: - SetUps // Those setup functions get that template, and fulfil determinated areas with rand texts, images and tags override func setUp() { super.setUp() - + self.singleImageTemplate = File.toString(Constants.bodyImageSingle) self.galleryImageTemplate = File.toString(Constants.bodyImageGallery) - + } - + // MARK: - Single func setUpSingle() { - + let data = [Constants.image: String.randomImage()] - + var singleImageTemplate = self.singleImageTemplate singleImageTemplate = singleImageTemplate.replace(Constants.headRandom, with: String.randomTag()) singleImageTemplate = singleImageTemplate.replace(Constants.bodyRandomPre, with: String.randomTag()) singleImageTemplate = singleImageTemplate.replace(Constants.bodyRandomPos, with: String.randomTag()) - + singleImageTemplate = singleImageTemplate.replace(Constants.image, with: data[Constants.image]!) - + singleImageTemplate = singleImageTemplate.replace(Constants.bodyRandom, with: String.randomTag()).extendedTrim - - + let result = self.slp.crawlImages(singleImageTemplate, result: SwiftLinkPreview.Response()) - + XCTAssertEqual((result[.image] as! String), data[Constants.image]) - + } - + func testSingle() { - + for _ in 0 ..< 100 { - + self.setUpSingle() - + } - + } - + // MARK: - Gallery func setUpGallery() { - + let data = [ Constants.image1: String.randomImage(), Constants.image2: String.randomImage(), Constants.image3: String.randomImage() ] - + var galleryImageTemplate = self.galleryImageTemplate galleryImageTemplate = galleryImageTemplate.replace(Constants.headRandom, with: String.randomTag()) galleryImageTemplate = galleryImageTemplate.replace(Constants.bodyRandomPre, with: String.randomTag()) galleryImageTemplate = galleryImageTemplate.replace(Constants.bodyRandomPos, with: String.randomTag()) - + galleryImageTemplate = galleryImageTemplate.replace(Constants.image1, with: data[Constants.image1]!) galleryImageTemplate = galleryImageTemplate.replace(Constants.image2, with: data[Constants.image2]!) galleryImageTemplate = galleryImageTemplate.replace(Constants.image3, with: data[Constants.image3]!) - + galleryImageTemplate = galleryImageTemplate.replace(Constants.bodyRandom, with: String.randomTag()).extendedTrim - + let result = self.slp.crawlImages(galleryImageTemplate, result: SwiftLinkPreview.Response()) - + XCTAssertEqual((result[.images] as! [String])[0], data[Constants.image1]) XCTAssertEqual((result[.images] as! [String])[1], data[Constants.image2]) XCTAssertEqual((result[.images] as! [String])[2], data[Constants.image3]) - + } - + func testGallery() { - + for _ in 0 ..< 100 { - + self.setUpGallery() - + } - + } - + } diff --git a/SwiftLinkPreviewTests/IntExtension.swift b/SwiftLinkPreviewTests/IntExtension.swift index 40b2f04..cb71b14 100644 --- a/SwiftLinkPreviewTests/IntExtension.swift +++ b/SwiftLinkPreviewTests/IntExtension.swift @@ -9,9 +9,9 @@ import Foundation public extension Int { - + public static func random(_ lower: Int = 0, upper: Int = 100) -> Int { return lower + Int(arc4random_uniform(UInt32(upper - 1 - lower + 1))) } - + } diff --git a/SwiftLinkPreviewTests/MemoryLeaks.swift b/SwiftLinkPreviewTests/MemoryLeaks.swift index 48c21d4..0ca6e2c 100644 --- a/SwiftLinkPreviewTests/MemoryLeaks.swift +++ b/SwiftLinkPreviewTests/MemoryLeaks.swift @@ -11,31 +11,31 @@ import XCTest class Counter { private var val: Int - + init(_ count: Int) { val = count } - + func dec() { val -= 1 } - + var isZero: Bool { return val == 0 } } -class MemoryCheckedSwiftLinkPrefiew : SwiftLinkPreview { - +class MemoryCheckedSwiftLinkPrefiew: SwiftLinkPreview { + let expectation: XCTestExpectation let counter: Counter - + init(expectation: XCTestExpectation, counter: Counter) { self.expectation = expectation self.counter = counter super.init() } - + deinit { counter.dec() if counter.isZero { @@ -45,7 +45,7 @@ class MemoryCheckedSwiftLinkPrefiew : SwiftLinkPreview { } class MemoryLeaks: XCTestCase { - + // func testObjectDestroy() { // let e = expectation(description: "instrument") // let requestCount = 3 diff --git a/SwiftLinkPreviewTests/MetaTests.swift b/SwiftLinkPreviewTests/MetaTests.swift index 60855a6..a91f7ed 100644 --- a/SwiftLinkPreviewTests/MetaTests.swift +++ b/SwiftLinkPreviewTests/MetaTests.swift @@ -11,29 +11,29 @@ import XCTest // This class tests head meta info class MetaTests: XCTestCase { - + // MARK: - Vars var twitterTemplate = "" var facebookTemplate = "" var itempropTemplate = "" var metaTemplate = "" let slp = SwiftLinkPreview() - + // MARK: - SetUps // Those setup functions get that template, and fulfil determinated areas with rand texts, images and tags override func setUp() { super.setUp() - + self.twitterTemplate = File.toString(Constants.headMetaTwitter) self.facebookTemplate = File.toString(Constants.headMetaFacebook) self.itempropTemplate = File.toString(Constants.headMetaItemprop) self.metaTemplate = File.toString(Constants.headMetaMeta) - + } - + // MARK: - Twitter func setUpTwitterAndRun() { - + var twitterData = [ Constants.twitterTitle: String.randomText(), @@ -41,39 +41,39 @@ class MetaTests: XCTestCase { Constants.twitterDescription: String.randomText(), Constants.twitterImageSrc: String.randomImage() ] - + var twitterTemplate = self.twitterTemplate twitterTemplate = twitterTemplate.replace(Constants.headRandomPre, with: String.randomTag()) twitterTemplate = twitterTemplate.replace(Constants.headRandomPos, with: String.randomTag()) - + twitterTemplate = twitterTemplate.replace(Constants.twitterTitle, with: twitterData[Constants.twitterTitle]!) twitterTemplate = twitterTemplate.replace(Constants.twitterSite, with: twitterData[Constants.twitterSite]!) twitterTemplate = twitterTemplate.replace(Constants.twitterDescription, with: twitterData[Constants.twitterDescription]!) twitterTemplate = twitterTemplate.replace(Constants.twitterImageSrc, with: twitterData[Constants.twitterImageSrc]!) - + twitterTemplate = twitterTemplate.replace(Constants.bodyRandom, with: String.randomTag()).extendedTrim - + let result = self.slp.crawlMetaTags(twitterTemplate, result: SwiftLinkPreview.Response()) - + XCTAssertEqual((result[.title] as! String), twitterData[Constants.twitterTitle]!.decoded) XCTAssertEqual((result[.description] as! String), twitterData[Constants.twitterDescription]!.decoded) XCTAssertEqual((result[.image] as! String), twitterData[Constants.twitterImageSrc]) - + } - + func testTwitter() { - + for _ in 0 ..< 100 { - + self.setUpTwitterAndRun() - + } - + } - + // MARK: - Facebook func setUpFacebookAndRun() { - + var facebookData = [ Constants.facebookTitle: String.randomText(), @@ -81,38 +81,38 @@ class MetaTests: XCTestCase { Constants.facebookDescription: String.randomText(), Constants.facebookImage: String.randomImage() ] - + var facebookTemplate = self.facebookTemplate facebookTemplate = facebookTemplate.replace(Constants.headRandomPre, with: String.randomTag()) facebookTemplate = facebookTemplate.replace(Constants.headRandomPos, with: String.randomTag()) - + facebookTemplate = facebookTemplate.replace(Constants.facebookTitle, with: facebookData[Constants.facebookTitle]!) facebookTemplate = facebookTemplate.replace(Constants.facebookSite, with: facebookData[Constants.facebookSite]!) facebookTemplate = facebookTemplate.replace(Constants.facebookDescription, with: facebookData[Constants.facebookDescription]!) facebookTemplate = facebookTemplate.replace(Constants.facebookImage, with: facebookData[Constants.facebookImage]!) - + facebookTemplate = facebookTemplate.replace(Constants.bodyRandom, with: String.randomTag()).extendedTrim - + let result = self.slp.crawlMetaTags(facebookTemplate, result: SwiftLinkPreview.Response()) - + XCTAssertEqual((result[.title] as! String), facebookData[Constants.facebookTitle]!.decoded) XCTAssertEqual((result[.description] as! String), facebookData[Constants.facebookDescription]!.decoded) XCTAssertEqual((result[.image] as! String), facebookData[Constants.facebookImage]) } - + func testFacebook() { - + for _ in 0 ..< 100 { - + self.setUpFacebookAndRun() - + } - + } - + // MARK: - Facebook func setUpItempropAndRun() { - + var itempropData = [ Constants.title: String.randomText(), @@ -120,38 +120,38 @@ class MetaTests: XCTestCase { Constants.description: String.randomText(), Constants.image: String.randomImage() ] - + var itempropTemplate = self.itempropTemplate itempropTemplate = itempropTemplate.replace(Constants.headRandomPre, with: String.randomTag()) itempropTemplate = itempropTemplate.replace(Constants.headRandomPos, with: String.randomTag()) - + itempropTemplate = itempropTemplate.replace(Constants.title, with: itempropData[Constants.title]!) itempropTemplate = itempropTemplate.replace(Constants.site, with: itempropData[Constants.site]!) itempropTemplate = itempropTemplate.replace(Constants.description, with: itempropData[Constants.description]!) itempropTemplate = itempropTemplate.replace(Constants.image, with: itempropData[Constants.image]!) - + itempropTemplate = itempropTemplate.replace(Constants.bodyRandom, with: String.randomTag()).extendedTrim - + let result = self.slp.crawlMetaTags(itempropTemplate, result: SwiftLinkPreview.Response()) - + XCTAssertEqual((result[.title] as! String), itempropData[Constants.title]!.decoded) XCTAssertEqual((result[.description] as! String), itempropData[Constants.description]!.decoded) XCTAssertEqual((result[.image] as! String), itempropData[Constants.image]) } - + func testItemprop() { - + for _ in 0 ..< 100 { - + self.setUpItempropAndRun() - + } - + } - + // MARK: - Meta func setUpMetaAndRun() { - + var metaData = [ Constants.title: String.randomText(), @@ -159,33 +159,33 @@ class MetaTests: XCTestCase { Constants.description: String.randomText(), Constants.image: String.randomImage() ] - + var metaTemplate = self.metaTemplate metaTemplate = metaTemplate.replace(Constants.headRandomPre, with: String.randomTag()) metaTemplate = metaTemplate.replace(Constants.headRandomPos, with: String.randomTag()) - + metaTemplate = metaTemplate.replace(Constants.title, with: metaData[Constants.title]!) metaTemplate = metaTemplate.replace(Constants.site, with: metaData[Constants.site]!) metaTemplate = metaTemplate.replace(Constants.description, with: metaData[Constants.description]!) metaTemplate = metaTemplate.replace(Constants.image, with: metaData[Constants.image]!) - + metaTemplate = metaTemplate.replace(Constants.bodyRandom, with: String.randomTag()).extendedTrim - + let result = self.slp.crawlMetaTags(metaTemplate, result: SwiftLinkPreview.Response()) - + XCTAssertEqual((result[.title] as! String), metaData[Constants.title]!.decoded) XCTAssertEqual((result[.description] as! String), metaData[Constants.description]!.decoded) XCTAssertEqual((result[.image] as! String), metaData[Constants.image]) } - + func testMeta() { - + for _ in 0 ..< 100 { - + self.setUpMetaAndRun() - + } - + } - + } diff --git a/SwiftLinkPreviewTests/RegexTests.swift b/SwiftLinkPreviewTests/RegexTests.swift index c2ceb77..8abfdb2 100644 --- a/SwiftLinkPreviewTests/RegexTests.swift +++ b/SwiftLinkPreviewTests/RegexTests.swift @@ -12,39 +12,38 @@ import XCTest // This class tests URLs class RegexTests: XCTestCase { - // MARK: - Vars let slp = SwiftLinkPreview() - + // MARK: - Functions func testURL() { - + for url in URLs.bunch { - + let extracted = slp.extractURL(text: url[0]) - + // print(extracted?.absoluteString, url[1]) - + XCTAssertEqual(extracted?.absoluteString, url[1]) - + } - + } - + func testCanonicalURL() { - + for url in URLs.bunch { - + let finalUrl = URL(string: url[1]) - + let canonical = self.slp.extractCanonicalURL(finalUrl!) - + // print(canonical, url[2]) - + XCTAssertEqual(canonical, url[2]) - + } - + } - + } diff --git a/SwiftLinkPreviewTests/StringTestExtension.swift b/SwiftLinkPreviewTests/StringTestExtension.swift index d468819..9d65d05 100644 --- a/SwiftLinkPreviewTests/StringTestExtension.swift +++ b/SwiftLinkPreviewTests/StringTestExtension.swift @@ -10,7 +10,7 @@ import Foundation import GameplayKit extension String { - + static let loremIpsum = [ "Et harum quidem rerum facilis est et expedita distinctio.", @@ -28,76 +28,76 @@ extension String { "Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur?", "Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?" ] - + static let protocolType = ["http://", "https://"] static let tagType = ["span", "p", "div"] static let imageType = ["gif", "jpg", "jpeg", "png", "bmp"] - + // Random String static func randomString(_ length: Int) -> String { - + let charactersString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" let charactersArray = charactersString.characters.map { String($0) } - + var string = "" for _ in 0.. String { - + return loremIpsum[Int.random(upper: loremIpsum.count)] - + } - + // Random Tag static func randomTag() -> String { - + let tag = tagType[Int.random(upper: tagType.count)] return "<\(tag)>\(randomText())" - + } - + // Random Tag static func randomImageTag() -> String { - + let options = [ "", "", "" ] - + return options[Int.random(upper: options.count)] - + } - + // Random URL static func randomUrl() -> String { - + var rand = Int.random(upper: 30) + 5 let base = String.randomString(rand) - + rand = Int.random(upper: 3) + 2 rand = rand.hashValue > 3 ? 3 : rand let end = String.randomString(rand) - + let prtcl = self.protocolType[Int.random(upper: protocolType.count)] let url = "\(prtcl)\(base).\(end.lowercased())" - + return url - + } - + // Random Image static func randomImage() -> String { - + return "\(randomUrl())/\(String.randomString(Int.random(upper: 15) + 5)).\(imageType[Int.random(upper: imageType.count)])" - + } - + } diff --git a/SwiftLinkPreviewTests/TitleTests.swift b/SwiftLinkPreviewTests/TitleTests.swift index df4cef7..5cf56b9 100644 --- a/SwiftLinkPreviewTests/TitleTests.swift +++ b/SwiftLinkPreviewTests/TitleTests.swift @@ -11,58 +11,57 @@ import XCTest // This class tests head title class TitleTests: XCTestCase { - + // MARK: - Vars var titleTemplate = "" let slp = SwiftLinkPreview() - + // MARK: - SetUps // Those setup functions get that template, and fulfil determinated areas with rand texts, images and tags override func setUp() { super.setUp() - + self.titleTemplate = File.toString(Constants.headTitle) - + } - + // MARK: - Title func setUpTitle() { - + var metaData = [ Constants.title: String.randomText(), Constants.headRandom: String.randomTag(), Constants.bodyRandom: String.randomTag() ] - + var metaTemplate = self.titleTemplate metaTemplate = metaTemplate.replace(Constants.headRandomPre, with: metaData[Constants.headRandom]!) metaTemplate = metaTemplate.replace(Constants.headRandomPos, with: metaData[Constants.headRandom]!) - + metaTemplate = metaTemplate.replace(Constants.title, with: metaData[Constants.title]!) - + metaTemplate = metaTemplate.replace(Constants.bodyRandom, with: metaData[Constants.bodyRandom]!).extendedTrim - - + let response = self.slp.crawlTitle(metaTemplate, result: SwiftLinkPreview.Response()) - + let comparable = (response.result[.title] as! String) let comparison = comparable == metaData[Constants.title]!.decoded.extendedTrim || comparable == metaData[Constants.headRandom]!.decoded.extendedTrim || comparable == metaData[Constants.bodyRandom]!.decoded.extendedTrim - + XCTAssert(comparison) - + } - + func testTitle() { - + for _ in 0 ..< 100 { - + self.setUpTitle() - + } - + } - + } diff --git a/SwiftLinkPreviewTests/URLs.swift b/SwiftLinkPreviewTests/URLs.swift index ccacf74..2b50745 100644 --- a/SwiftLinkPreviewTests/URLs.swift +++ b/SwiftLinkPreviewTests/URLs.swift @@ -9,7 +9,7 @@ import Foundation struct URLs { - + // Please add the text in the format: // [text, expectation, canonical] // ["xxx https://your.url.com/etc#something?else=true xxx", "https://your.url.com/etc#something?else=true", "your.url.com"] @@ -125,6 +125,5 @@ struct URLs { "goo.gl" ] ] - - + }